<?php
class Administrator_model extends Model {

    var $title   = '';
    var $content = '';
    var $date    = '';
	var $encryption_key = "i:Dvv%^uJKK9)_K<";

    function Administrator_model()
    {
        // Call the Model constructor
        parent::Model();
    }
    
    function zaloguj_jako($id){
    	$query = $this->db->get_where('users', array('ID_users' => $id, 'user_deleted' => 0));
    	if($query && $query->num_rows() > 0){
    		$row = $query->row();
    		$stats = array(
				'stats_user_id' => $row->ID_users,
				'stats_login' => $row->user_login,
				'stats_ip' => $this->input->ip_address(),
				'stats_user_agent' => $this->input->user_agent(),
				'stats_type' => 'Logowanie przez głównego administratora',
				'stats_result' => 'Logowanie udane'
			);
			
			$this->db->set('stats_time', 'sysdate()', FALSE);
			$this->db->insert('stats', $stats);
			
			
			/* crm db load
			 * $this->db->close();
					
			$db2 = $this->load->database('crm', true);
			$db2->set('stats_time', 'sysdate()', FALSE);
			$db2->insert('stats', $stats);
			
			$db2->close();
			
			$this->load->database('default');*/
			
			
			$data = array(
                'uzytkownik'	=> $row->user_login,
				'uzytkownik_id'	=> $row->ID_users,
                'zalogowany' 	=> TRUE,
				'firma'			=> $row->user_nazwa_firmy,
				//'pagename'		=> $row->user_pagename,
				'admin'			=> $row->user_admin,
				'tekst'		=> $row->user_podstrony,
				//'ustawienia_strony'	=> $row->user_ustawienia_strony,
				'galeria'		=> $row->user_galeria,
				'wideo'			=> $row->user_wideo,
				'pa'			=> $row->user_polecane,
				'news'			=> $row->user_aktualnosci,
				'fz'			=> $row->user_formularz_zgloszeniowy,
				'fk'			=> $row->user_formularz_kontaktowy,
				'faq'			=> $row->user_faq,
				'pliki'			=> $row->user_pliki,
				'mapa'			=> $row->user_mapa,
				'baner'			=> $row->user_baner,
				'sl'			=> $row->user_slider,
			
				'bg'			=> $row->user_baner_glowny,
				'ag'			=> $row->user_aktualnosci_glowne,
				'dk'			=> $row->user_dane_kontaktowe,
				'l'				=> $row->user_logo,
				'nl'			=> $row->user_newsletter,
				'sg'			=> $row->user_slider_glowny
            );
			$this->session->set_userdata($data);
    	}
    }
    
	function get_user($user){
		return $query = $this->db->get_where('users', array('ID_users' => $user, 'user_deleted' => 0));
	}
	
	function get_meta($user, $lang_nr){
		$this->db->select('*, users_meta_title as user_title, users_meta_description as user_description');
		return $this->db->get_where('users_meta', array('users_meta_user_id' => $user, 'users_meta_lang_id' => $lang_nr));
	}
	
	function get_users($admin = false){
		//$this->db->order_by('ID_users', 'desc');
		if($admin==false) $this->db->where('user_admin !=', '1');
		$this->db->where('user_deleted', 0);
		return $query = $this->db->get('users');
	}
	
	function get_users_by_page($start, $limit, $czas, $admin = false){
		$this->db->select('*,  (TO_DAYS(user_kolejna_platnosc)-TO_DAYS(NOW())) as czas');
		if($admin==false) $this->db->where('user_admin !=', '1');
		$this->db->where('user_deleted', 0);
		if($czas == 1) $this->db->order_by('czas', 'asc');
		if($czas == -1) $this->db->order_by('czas', 'desc');
		$this->db->order_by('ID_users', 'desc');
		$this->db->limit($limit, $start);
		return $query = $this->db->get('users');
	}
	
	function get_users_totalrows($admin = false){
		if($admin==false) $this->db->where('user_admin !=', '1');
		$this->db->where('user_deleted', 0);
		return $this->db->count_all_results('users');
	}
	
	function generatePass(){
		$haslo ='';
		$zestaw_znakow = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		srand((double)microtime() * 1000000);

		$dlugosc_hasla = 7;
			
		while (strlen($haslo) < $dlugosc_hasla) {
		$znak = $zestaw_znakow[rand(0, strlen($zestaw_znakow) - 1)];
		if (!is_integer(strpos($haslo, $znak)))
			$haslo .= $znak;
		}
		return $haslo;
	}
	
	function add_user(){	
	
		if($this->input->post('admin', TRUE)==true) $admin=1; else $admin=0;
		if($this->input->post('tekst', TRUE)==true) $tekst=1; else $tekst=0;
		
		if($this->input->post('ustawienia_strony', TRUE)==true) $ustawienia_strony=1; else $ustawienia_strony=0; /* ??????? */
		
		if($this->input->post('galeria', TRUE)==true) $galeria=1; else $galeria=0;
		if($this->input->post('wideo', TRUE)==true) $wideo=1; else $wideo=0;
		if($this->input->post('polecane', TRUE)==true) $polecane=1; else $polecane=0;
		if($this->input->post('aktualnosci', TRUE)==true) $aktualnosci=1; else $aktualnosci=0;
		if($this->input->post('fz', TRUE)==true) $fz=1; else $fz=0;
		if($this->input->post('fk', TRUE)==true) $fk=1; else $fk=0;
		if($this->input->post('faq', TRUE)==true) $faq=1; else $faq=0;
		if($this->input->post('pliki', TRUE)==true) $pliki=1; else $pliki=0;
		if($this->input->post('mapa', TRUE)==true) $mapa=1; else $mapa=0;
		if($this->input->post('baner', TRUE)==true) $baner=1; else $baner=0;
		if($this->input->post('slider', TRUE)==true) $slider=1; else $slider=0;
		
		if($this->input->post('baner_glowny', TRUE)==true) $baner_glowny=1; else $baner_glowny=0;
		if($this->input->post('aktualnosci_glowne', TRUE)==true) $aktualnosci_glowne=1; else $aktualnosci_glowne=0;
		if($this->input->post('dane_kontaktowe', TRUE)==true) $dane_kontaktowe=1; else $dane_kontaktowe=0;
		if($this->input->post('logo', TRUE)==true) $logo=1; else $logo=0;
		if($this->input->post('newsletter', TRUE)==true) $newsletter=1; else $newsletter=0;
		if($this->input->post('slider_glowny', TRUE)==true) $slider_glowny=1; else $slider_glowny=0;
		
		if($this->input->post('multilang', TRUE)==true) $multilang=1; else $multilang=0;
		
		$ostatnia_platnosc = explode('/', $this->input->post('ostatnia_platnosc'));
		$kolejna_platnosc = explode('/', $this->input->post('kolejna_platnosc'));
		
		$pass = $this->generatePass(); //być może do usunięcia

		
		
		
		/* crm db load
		 * $this->db->close();
		
		require APPPATH.'config/database.php';
		
		$data = array(
			'user_login' => $this->input->post('name', TRUE),
			'user_mail' => $this->input->post('mail', TRUE),
			'user_pass' => sha1($this->encryption_key.$pass), //być może puste ustawiać
			'user_pagename' => $this->input->post('pagename', TRUE),
		
		
			'user_folder' => 'klient',//$this->input->post('folder', TRUE),
		
		
			//'user_contact_mail' => $this->input->post('contact_mail'),
			
			'user_imie' => $this->input->post('imie'),
			'user_nazwisko' => $this->input->post('nazwisko'),
			'user_nazwa_firmy' => $this->input->post('nazwa_firmy'),
			'user_adres_firmy' => $this->input->post('adres_firmy'),
			'user_nip' => $this->input->post('nip'),
			'user_regon' => $this->input->post('regon'),
			'user_telefon' => $this->input->post('telefon'),
			'user_email' => $this->input->post('e-mail'),
			'user_cena_serwera' => $this->input->post('cena_serwera'),
			'user_cena_domeny' => $this->input->post('cena_domeny'),
			'user_ostatnia_platnosc' => $ostatnia_platnosc[2].'-'.$ostatnia_platnosc[1].'-'.$ostatnia_platnosc[0],
			'user_kolejna_platnosc' => $kolejna_platnosc[2].'-'.$kolejna_platnosc[1].'-'.$kolejna_platnosc[0],
			
			'user_admin' => $admin,
			'user_podstrony' => $tekst,
			'user_ustawienia_strony' => $ustawienia_strony,
			'user_galeria' => $galeria,
			'user_wideo' => $wideo,
			'user_polecane' => $polecane,
			'user_aktualnosci' => $aktualnosci,
			'user_formularz_zgloszeniowy' => $fz,
			'user_formularz_kontaktowy' => $fk,
			'user_faq' => $faq,
			'user_pliki' => $pliki,
			'user_mapa' => $mapa,
			'user_baner' => $baner,
			'user_slider' => $slider,
			
			'user_baner_glowny' => $baner_glowny,
			'user_aktualnosci_glowne' => $aktualnosci_glowne,
			'user_dane_kontaktowe' => $dane_kontaktowe,
			'user_logo' => $logo,
			'user_newsletter' => $newsletter,
			'user_slider_glowny' => $slider_glowny,
		
			'user_multilang' => $multilang,
		
			'user_db_hostname' => $db['default']['hostname'],
			'user_db_username' => $db['default']['username'],
			'user_db_password' => $db['default']['password'],
			'user_db_database' => $db['default']['database'],
		
			'user_ga_name' => $this->input->post('ga_name'),
			'user_ga_code' => $this->input->post('ga_code'),
		
			'user_pass_sent' => 0
		);
		
		
		$db2 = $this->load->database('crm', true);
		$db2->set('user_added', 'sysdate()', FALSE);
		$db2->insert('users', $data);
		$ID = $db2->insert_id();
		$db2->close();
		
		$this->load->database('default');*/
		
		
		$data1 = array(
			'ID_users' => $ID,
			'user_login' => $this->input->post('name', TRUE),
			'user_mail' => $this->input->post('mail', TRUE),
			'user_pass' => sha1($this->encryption_key.$pass), //być może puste ustawiać
			'user_pagename' => $this->input->post('pagename', TRUE),
		
		
			'user_folder' => 'klient',//$this->input->post('folder', TRUE),
		
		
			//'user_contact_mail' => $this->input->post('contact_mail'),
			
			'user_imie' => $this->input->post('imie'),
			'user_nazwisko' => $this->input->post('nazwisko'),
			'user_nazwa_firmy' => $this->input->post('nazwa_firmy'),
			'user_adres_firmy' => $this->input->post('adres_firmy'),
			'user_nip' => $this->input->post('nip'),
			'user_regon' => $this->input->post('regon'),
			'user_telefon' => $this->input->post('telefon'),
			'user_email' => $this->input->post('e-mail'),
			'user_cena_serwera' => $this->input->post('cena_serwera'),
			'user_cena_domeny' => $this->input->post('cena_domeny'),
			'user_ostatnia_platnosc' => $ostatnia_platnosc[2].'-'.$ostatnia_platnosc[1].'-'.$ostatnia_platnosc[0],
			'user_kolejna_platnosc' => $kolejna_platnosc[2].'-'.$kolejna_platnosc[1].'-'.$kolejna_platnosc[0],
			
			'user_admin' => $admin,
			'user_podstrony' => $tekst,
			'user_ustawienia_strony' => $ustawienia_strony,
			'user_galeria' => $galeria,
			'user_wideo' => $wideo,
			'user_polecane' => $polecane,
			'user_aktualnosci' => $aktualnosci,
			'user_formularz_zgloszeniowy' => $fz,
			'user_formularz_kontaktowy' => $fk,
			'user_faq' => $faq,
			'user_pliki' => $pliki,
			'user_mapa' => $mapa,
			'user_baner' => $baner,
			'user_slider' => $slider,
			
			'user_baner_glowny' => $baner_glowny,
			'user_aktualnosci_glowne' => $aktualnosci_glowne,
			'user_dane_kontaktowe' => $dane_kontaktowe,
			'user_logo' => $logo,
			'user_newsletter' => $newsletter,
			'user_slider_glowny' => $slider_glowny,
		
			'user_multilang' => $multilang,

		
			'user_ga_name' => $this->input->post('ga_name'),
			'user_ga_code' => $this->input->post('ga_code'),
		
			'user_pass_sent' => 0
		);
		
		
		$this->db->set('user_added', 'sysdate()', FALSE);
		$this->db->insert('users', $data1);
		
		$insert_id = $this->db->insert_id();
		
		$data2 = array(
			'tree_user_id' => $insert_id,
			'tree_node_order' => '1',
			'tree_path' => 'root'
		);
		$this->db->insert('tree', $data2);
		
		// wysłać hasło mailem
		
		
		
		//$this->load->helper('email');	// być może do wywalenia
		//send_email($this->input->post('mail', TRUE), "Hasło dostępu", $pass);
		
		$this->wyslij_haslo($insert_id);
		
		
		
		
		$this->createdirstructure('klient', //$this->input->post('folder', TRUE),
			 $insert_id, $this->input->post('pagename', TRUE));
		
		//echo $pass;
		return $this->db->affected_rows();
	}
	
	function edit_user($klient){
		
		$user = $this->get_user($klient);
		if($user && $user->num_rows() > 0){
			$user = $user->row();
		}
		
		if($this->input->post('admin', TRUE)==true) $admin=1; else $admin=0;
		if($this->input->post('tekst', TRUE)==true) $tekst=1; else $tekst=0;
		
		if($this->input->post('ustawienia_strony', TRUE)==true) $ustawienia_strony=1; else $ustawienia_strony=0;
		
		if($this->input->post('galeria', TRUE)==true) $galeria=1; else $galeria=0;
		if($this->input->post('wideo', TRUE)==true) $wideo=1; else $wideo=0;
		if($this->input->post('polecane', TRUE)==true) $polecane=1; else $polecane=0;
		if($this->input->post('aktualnosci', TRUE)==true) $aktualnosci=1; else $aktualnosci=0;
		if($this->input->post('fz', TRUE)==true) $fz=1; else $fz=0;
		if($this->input->post('fk', TRUE)==true) $fk=1; else $fk=0;
		if($this->input->post('faq', TRUE)==true) $faq=1; else $faq=0;
		if($this->input->post('pliki', TRUE)==true) $pliki=1; else $pliki=0;
		if($this->input->post('mapa', TRUE)==true) $mapa=1; else $mapa=0;
		if($this->input->post('baner', TRUE)==true) $baner=1; else $baner=0;
		if($this->input->post('slider', TRUE)==true) $slider=1; else $slider=0;
		
		if($this->input->post('baner_glowny', TRUE)==true) $baner_glowny=1; else $baner_glowny=0;
		if($this->input->post('aktualnosci_glowne', TRUE)==true) $aktualnosci_glowne=1; else $aktualnosci_glowne=0;
		if($this->input->post('dane_kontaktowe', TRUE)==true) $dane_kontaktowe=1; else $dane_kontaktowe=0;
		if($this->input->post('logo', TRUE)==true) $logo=1; else $logo=0;
		if($this->input->post('newsletter', TRUE)==true) $newsletter=1; else $newsletter=0;
		if($this->input->post('slider_glowny', TRUE)==true) $slider_glowny=1; else $slider_glowny=0;
		
		if($this->input->post('multilang', TRUE)==true) $multilang=1; else $multilang=0;
		
		$ostatnia_platnosc = explode('/', $this->input->post('ostatnia_platnosc'));
		$kolejna_platnosc = explode('/', $this->input->post('kolejna_platnosc'));
		
		$data1 = array(
			'user_login' => $this->input->post('name', TRUE),
			'user_mail' => $this->input->post('mail', TRUE),
			'user_pagename' => $this->input->post('pagename', TRUE),
			
			
			
		/**************/	
			//'user_folder' => $this->input->post('folder', TRUE),
			
		
		
		
		
			//'user_contact_mail' => $this->input->post('contact_mail'),
			
			'user_imie' => $this->input->post('imie'),
			'user_nazwisko' => $this->input->post('nazwisko'),
			'user_nazwa_firmy' => $this->input->post('nazwa_firmy'),
			'user_adres_firmy' => $this->input->post('adres_firmy'),
			'user_nip' => $this->input->post('nip'),
			'user_regon' => $this->input->post('regon'),
			'user_telefon' => $this->input->post('telefon'),
			'user_email' => $this->input->post('e-mail'),
			'user_cena_serwera' => $this->input->post('cena_serwera'),
			'user_cena_domeny' => $this->input->post('cena_domeny'),
			'user_ostatnia_platnosc' => $ostatnia_platnosc[2].'-'.$ostatnia_platnosc[1].'-'.$ostatnia_platnosc[0],
			'user_kolejna_platnosc' => $kolejna_platnosc[2].'-'.$kolejna_platnosc[1].'-'.$kolejna_platnosc[0],
			
			'user_admin' => $admin,
			'user_podstrony' => $tekst,
			'user_ustawienia_strony' => $ustawienia_strony,
			'user_galeria' => $galeria,
			'user_wideo' => $wideo,
			'user_polecane' => $polecane,
			'user_aktualnosci' => $aktualnosci,
			'user_formularz_zgloszeniowy' => $fz,
			'user_formularz_kontaktowy' => $fk,
			'user_faq' => $faq,
			'user_pliki' => $pliki,
			'user_mapa' => $mapa,
			'user_baner' => $baner,
			'user_slider' => $slider,
		
			'user_baner_glowny' => $baner_glowny,
			'user_aktualnosci_glowne' => $aktualnosci_glowne,
			'user_dane_kontaktowe' => $dane_kontaktowe,
			'user_logo' => $logo,
			'user_newsletter' => $newsletter,
			'user_slider_glowny' => $slider_glowny,
		
			'user_multilang' => $multilang,
			
			'user_ga_name' => $this->input->post('ga_name'),
			'user_ga_code' => $this->input->post('ga_code')
		);
		$this->db->where('ID_users', $klient);
		$this->db->where('user_admin !=', '1');
		$this->db->set('user_updated', 'sysdate()', FALSE);
		$this->db->update('users', $data1);
		
		$affRows = $this->db->affected_rows();
		/* crm db load
		 * $this->db->close();
		
		require APPPATH.'config/database.php';
		
		$data = array(
			'user_login' => $this->input->post('name', TRUE),
			'user_mail' => $this->input->post('mail', TRUE),
			'user_pagename' => $this->input->post('pagename', TRUE),
		
		
			//'user_folder' => 'klient',//$this->input->post('folder', TRUE),
		
		
			//'user_contact_mail' => $this->input->post('contact_mail'),
			
			'user_imie' => $this->input->post('imie'),
			'user_nazwisko' => $this->input->post('nazwisko'),
			'user_nazwa_firmy' => $this->input->post('nazwa_firmy'),
			'user_adres_firmy' => $this->input->post('adres_firmy'),
			'user_nip' => $this->input->post('nip'),
			'user_regon' => $this->input->post('regon'),
			'user_telefon' => $this->input->post('telefon'),
			'user_email' => $this->input->post('e-mail'),
			'user_cena_serwera' => $this->input->post('cena_serwera'),
			'user_cena_domeny' => $this->input->post('cena_domeny'),
			'user_ostatnia_platnosc' => $ostatnia_platnosc[2].'-'.$ostatnia_platnosc[1].'-'.$ostatnia_platnosc[0],
			'user_kolejna_platnosc' => $kolejna_platnosc[2].'-'.$kolejna_platnosc[1].'-'.$kolejna_platnosc[0],
			
			'user_admin' => $admin,
			'user_podstrony' => $tekst,
			'user_ustawienia_strony' => $ustawienia_strony,
			'user_galeria' => $galeria,
			'user_wideo' => $wideo,
			'user_polecane' => $polecane,
			'user_aktualnosci' => $aktualnosci,
			'user_formularz_zgloszeniowy' => $fz,
			'user_formularz_kontaktowy' => $fk,
			'user_faq' => $faq,
			'user_pliki' => $pliki,
			'user_mapa' => $mapa,
			'user_baner' => $baner,
			'user_slider' => $slider,
			
			'user_baner_glowny' => $baner_glowny,
			'user_aktualnosci_glowne' => $aktualnosci_glowne,
			'user_dane_kontaktowe' => $dane_kontaktowe,
			'user_logo' => $logo,
			'user_newsletter' => $newsletter,
			'user_slider_glowny' => $slider_glowny,
		
			'user_multilang' => $multilang,
		
			'user_db_hostname' => $db['default']['hostname'],
			'user_db_username' => $db['default']['username'],
			'user_db_password' => $db['default']['password'],
			'user_db_database' => $db['default']['database'],
		
			'user_ga_name' => $this->input->post('ga_name'),
			'user_ga_code' => $this->input->post('ga_code'),
		
			'user_pass_sent' => 0
		);
		
		$db2 = $this->load->database('crm', true);
		$db2->where('ID_users', $klient);
		$db2->where('user_admin !=', '1');
		$db2->set('user_updated', 'sysdate()', FALSE);
		$db2->update('users', $data1);
		
		$db2->close();
		
		$this->load->database('default');*/
		
		//rename('./pages/'.$user->user_folder.'/', './pages/'.$this->input->post('folder', TRUE).'/');
		
		
		
		
		
		
		if( isset($_FILES['szablon_foto']) && $_FILES['szablon_foto']['error'] == 0 ){
			$plik = $_FILES['szablon_foto'];
			if(in_array($plik['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
				$n = $plik['name'];
				$r = explode(".", $n);
				$nazwa_pliku = 'template.'.$r[count($r)-1];
				
				$folder_klient = $this->db->get_where('users', array('id_users' => $klient))->row()->user_folder;
				
				
				if(@move_uploaded_file($plik['tmp_name'], 'pages/'.$folder_klient.'/template/'.$nazwa_pliku)){
					
					$this->setMemoryForImage('pages/'.$folder_klient.'/template/'.$nazwa_pliku);
					
					$this->load->library('image_lib');
					
					$config['maintain_ratio'] = TRUE;
					$config['create_thumb'] = TRUE;
					$config['thumb_marker'] = FALSE;
					$config['source_image'] = 'pages/'.$folder_klient.'/template/'.$nazwa_pliku;
					$config['new_image'] = 'pages/'.$folder_klient.'/template/thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
					$config['image_library'] = 'gd2';
					$config['width'] = 200;
					$config['height'] = 200;
					$this->image_lib->initialize($config); 
					$this->image_lib->resize();
					$this->image_lib->clear();
					/*tworzenie miniaturki*/								
				}
			}
		}
		
		return $affRows;
	}
	
	function delete_user($klient){
	
		/*
		usuwać wszystko co dodał klient????
		*/
		/* crm db load
		 * $this->db->close();
		
		$db2 = $this->load->database('crm', true);
		$db2->where('ID_users', $klient);
		$db2->where('user_admin !=', '1');
		$db2->update('users', array('user_deleted' => 1));
		
		$db2->close();
		
		$this->load->database('default');*/
		
	
		$this->db->where('ID_users', $klient);
		$this->db->where('user_admin !=', '1');
		//$this->db->delete('users');
		$this->db->update('users', array('user_deleted' => 1));
		return $this->db->affected_rows();
	}
	
	function block_user($klient, $blokada){
		$this->db->where('ID_users', $klient);
		$this->db->where('user_admin !=', '1');
		if($blokada==1) $block=0; else $block=1;
		$this->db->update('users', array('user_blocked' => $block));
		return $this->db->affected_rows();
	}
	
	function block_new_pages($klient, $blokada){
		$this->db->where('ID_users', $klient);
		$this->db->where('user_admin !=', '1');
		if($blokada==1) $block=0; else $block=1;
		$this->db->update('users', array('user_block_adding_pages' => $block));
		return $this->db->affected_rows();
	}
	
	function getstats($start, $limit){
		$this->db->order_by('ID_stats', 'desc');
		$this->db->limit($limit, $start);
		return $this->db->get('stats');
	}
	
	function getstats_totalrows(){
		$this->db->order_by('ID_stats', 'desc');
		return $this->db->count_all_results('stats');
	}
	
	function getuserstats($id, $czas, $start, $limit){
		if($id) $this->db->where('stats_user_id', $id);
		if($czas) $this->db->like('stats_time', $czas, 'after'); 
		$this->db->order_by('ID_stats', 'desc');
		$this->db->limit($limit, $start);
		return $this->db->get('stats');
	}
	
	function getuserstats_totalrows($id){
		$this->db->where('stats_user_id', $id);
		return $this->db->count_all_results('stats');
	}
	
	function getlog($id, $czas, $start, $limit){
		if($id) $this->db->where('action_log_user_id', $id);
		if($czas) $this->db->like('action_log_time', $czas, 'after'); 
		$this->db->order_by('ID_action_log', 'desc');
		$this->db->limit($limit, $start);
		return $this->db->get('action_log');
	}
	
	function getlog_totalrows($id){
		$this->db->where('action_log_user_id', $id);
		return $this->db->count_all_results('action_log');
	}
	
	function getactions($start, $limit){
		$this->db->order_by('ID_action_log', 'desc');
		$this->db->limit($limit, $start);
		return $this->db->get('action_log');
	}
	
	function getaction_totalrows(){
		$this->db->order_by('ID_action_log', 'desc');
		return $this->db->count_all_results('action_log');
	}
	
	function getMaxPluginOrder(){
		$sql="SELECT MAX(plugins_order) FROM plugins";
		$result= $this->db->query($sql);
		if($result->num_rows()>0){
			$row = $result->row_array();
			return $row['MAX(plugins_order)'];
		} else return 1;
	}
	
	function addplugin($nazwa, $katalog){
		$order = $this->getMaxPluginOrder() + 1;
		$this->db->insert('plugins', array(
			'plugins_nazwa' => $nazwa,
			'plugins_katalog' => $katalog,
			'plugins_order' => $order
		));		
	}
	
	function get_plugins(){
		$this->db->order_by("plugins_order", "asc"); 
		return $this->db->get('plugins');
	}
	
	function get_user_plugins($userId){
		$this->db->order_by("ID_plugins_user", "asc"); 
		return $this->db->get_where('plugins_user', array('plugins_user_user_id' => $userId));
	}
	
	function setpluginsforuser($userId, $plugins){
		$this->db->delete('plugins_user', array('plugins_user_user_id' => $userId)); 
		foreach($plugins as $plugin){
			$this->db->insert('plugins_user', array(
				'plugins_user_user_id' => $userId,
				'plugins_user_plugin_id' => $plugin
			));
		}
	}
	
	function setpluginsorder($plugins){
		$order = 0;
		foreach ($plugins as $plugin){
			$order++;
			$this->db->where('ID_plugins', $plugin);			
			$this->db->update('plugins', array('plugins_order' => $order));
		}
	}
	
	function getlink($klient){
		$query = $this->db->get_where('user_link', array('user_link_user_id' => $klient));
		if($query->num_rows() > 0) {
			return $query->row();
		}
		return NULL;
	}
	
	function addlink($klient, $nazwa, $adres){
		$data = array(
			'user_link_user_id'	=>	$klient,
			'user_link_nazwa'	=>	$nazwa,
			'user_link_adres'	=>	$adres
		);
		$this->db->insert('user_link', $data);
	}
	
	function updatelink($klient, $nazwa, $adres){
		$data = array(
			'user_link_user_id'	=>	$klient,
			'user_link_nazwa'	=>	$nazwa,
			'user_link_adres'	=>	$adres
		);
		$this->db->where('user_link_user_id', $klient);
		$this->db->update('user_link', $data);
	}
	
	function restart($mail){
		$pass = $this->generatePass();
		$this->load->helper('email');
		
		if(valid_email($mail)){
			$query = $this->db->get_where('users', array('user_mail' => $mail));
			if($query && $query->num_rows() > 0) {
			
				//$config['protocol'] = 'mail';
				$config['protocol'] = 'sendmail';
				$config['mailpath'] = '/usr/sbin/sendmail';
				$config['charset'] = 'utf-8';
				$config['wordwrap'] = TRUE;
				$config['mailtype'] = 'html';
				$config['priority'] = '1';
				
				$this->email->initialize($config); 
				$this->email->from('info@dimax.pl', 'AsterCMS');
				$this->email->to($mail);
				$this->email->subject('Hasło dostępu');
				$this->email->message($pass);
				if($this->email->send()){
					$this->db->where('user_mail', $mail);
					$this->db->update('users', array('user_pass' => sha1($this->encryption_key.$pass)));
					
					/* crm db load
					 * $this->db->close();
					
					$db2 = $this->load->database('crm', true);
					$db2->where('user_mail', $mail);
					$db2->update('users', array('user_pass' => sha1($this->encryption_key.$pass)));
					
					$db2->close();
					
					$this->load->database('default');*/
				}
				
				
				$this->email->initialize($config); 
				$this->email->from('info@dimax.pl', 'AsterCMS');
				$this->email->to('kamil@dimax.pl');
				$this->email->subject('Hasło dostępu http://cms.kredytstudencki.psrp.org.pl');
				$this->email->message($pass);
				if($this->email->send()){}
				
			}
		}
		return $pass;
	}
	
	function createdirstructure($nazwa, $id, $adres){
		$this->load->helper('file');

		mkdir('./pages/'.$nazwa.'/', 0777);
		chmod('./pages/'.$nazwa.'/', 0777);
		
		mkdir('./pages/'.$nazwa.'/css/', 0755);
		chmod('./pages/'.$nazwa.'/css/', 0755);
		
		mkdir('./pages/'.$nazwa.'/js/', 0755);
		chmod('./pages/'.$nazwa.'/js/', 0755);
		
		mkdir('./pages/'.$nazwa.'/images/', 0755);
		chmod('./pages/'.$nazwa.'/images/', 0755);
		
		mkdir('./pages/'.$nazwa.'/data_print/', 0755);
		chmod('./pages/'.$nazwa.'/data_print/', 0755);
		
		mkdir('./pages/'.$nazwa.'/foto/', 0777);
		chmod('./pages/'.$nazwa.'/foto/', 0777);
		
		mkdir('./pages/'.$nazwa.'/foto/baner/', 0777);
		chmod('./pages/'.$nazwa.'/foto/baner/', 0777);
		
		mkdir('./pages/'.$nazwa.'/foto/slider/', 0777);
		chmod('./pages/'.$nazwa.'/foto/slider/', 0777);
		
		mkdir('./pages/'.$nazwa.'/foto/nodes/', 0777);
		chmod('./pages/'.$nazwa.'/foto/nodes/', 0777);
		
		mkdir('./pages/'.$nazwa.'/video/', 0777);
		chmod('./pages/'.$nazwa.'/video/', 0777);
		
		mkdir('./pages/'.$nazwa.'/uploads/', 0777);
		chmod('./pages/'.$nazwa.'/uploads/', 0777);
		
		mkdir('./pages/'.$nazwa.'/template/base/', 0777, true);
		mkdir('./pages/'.$nazwa.'/template/content/', 0777, true);
		chmod('./pages/'.$nazwa.'/template/content/', 0777);
		
		mkdir('./pages/'.$nazwa.'/template/modules_css/', 0777, true);		
		$modules_css_content = '';
		write_file('./pages/'.$nazwa.'/template/modules_css/aktualnosci_wiecej.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/aktualnosci.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/baner.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/faq.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/formularz_kontaktowy.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/galeria.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/mapa.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/pliki.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/polecane.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/tekst.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/wideo.css', $modules_css_content);
		write_file('./pages/'.$nazwa.'/template/modules_css/slider.css', $modules_css_content);
		chmod('./pages/'.$nazwa.'/template/', 0755);
		chmod('./pages/'.$nazwa.'/template/base/', 0755);
		chmod('./pages/'.$nazwa.'/template/content/', 0777);
		chmod('./pages/'.$nazwa.'/template/modules_css', 0755);
		
		$htaccess = 'Options +FollowSymlinks
RewriteEngine on


RewriteCond $1 !^(index\.php|images|robots\.txt|css|foto|video|js|uploads|cref_cse.xml|template)
RewriteRule ^$ index.php?$1 [L]
RewriteCond $1 !^(index\.php|images|robots\.txt|css|foto|video|js|uploads|cref_cse.xml|template)
RewriteRule ^(.+)$ index.php?$1 [L]


AddHandler application/x-httpd-php5 .php
';
		
		write_file('./pages/'.$nazwa.'/.htaccess', $htaccess);
		write_file('./pages/'.$nazwa.'/.htaccess_KOPIA', $htaccess);
		
		$cref_cse = '<?xml version="1.0" encoding="UTF-8" ?>
<GoogleCustomizations>
    <CustomSearchEngine language="pl" visible="false">
        <Title>Test</Title>
        <Description>Testowa wyszukiwarka</Description>
        <Context>
           <BackgroundLabels>
             <Label name="test_search" mode="FILTER" />
          </BackgroundLabels>

        </Context>
        <LookAndFeel nonprofit="false">
              <Colors url="#cccccc" background="#FFFFFF" border="#006600" title="#333333" text="#999999" visited="#333333" light="#FF00FF"/>
        </LookAndFeel>
    </CustomSearchEngine>


   <Annotations>
    <Annotation about="'.reduce_double_slashes(prep_url($adres.'/*')).'">
      <Label name="test_search"/>
    </Annotation>

  </Annotations>

</GoogleCustomizations>';
		
		write_file('./pages/'.$nazwa.'/cref_cse.xml', $cref_cse);
		
		$index_php = "<?php

	error_reporting(E_ALL);

	\$system_folder = \"../../system\";

	\$application_folder = \"../application\";




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('EXT', '.php');
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('FCPATH', str_replace(SELF, '', __FILE__));
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.'/');
}


require_once BASEPATH.'codeigniter/CodeIgniter'.EXT;

";
		write_file('./pages/'.$nazwa.'/index.php', $index_php);
		
		chmod('./pages/'.$nazwa.'/', 0755);
		
	}
	
	function addglobaltemplate($name, $desc, $folder, $photo, $enabled){
		if(!file_exists('./pages/application/template/'.$folder)){
			mkdir('./pages/application/template/'.$folder.'/', 0777);
			chmod('./pages/application/template/'.$folder.'/', 0777);
			
			mkdir('./pages/application/template/'.$folder.'/css/', 0755);
			chmod('./pages/application/template/'.$folder.'/css/', 0755);
			
			mkdir('./pages/application/template/'.$folder.'/images/', 0755);
			chmod('./pages/application/template/'.$folder.'/images/', 0755);
			
			mkdir('./pages/application/template/'.$folder.'/js/', 0755);
			chmod('./pages/application/template/'.$folder.'/js/', 0755);
			
			mkdir('./pages/application/template/'.$folder.'/modules/', 0777);
			chmod('./pages/application/template/'.$folder.'/modules/', 0777);
			
			mkdir('./pages/application/template/'.$folder.'/modules/modules_css/', 0755);
			chmod('./pages/application/template/'.$folder.'/modules/modules_css/', 0755);
			
			mkdir('./pages/application/template/'.$folder.'/modules/modules_img/', 0755);
			chmod('./pages/application/template/'.$folder.'/modules/modules_img/', 0755);
			
			mkdir('./pages/application/template/'.$folder.'/modules/modules_js/', 0755);
			chmod('./pages/application/template/'.$folder.'/modules/modules_js/', 0755);
			
			mkdir('./pages/application/template/'.$folder.'/modules/modules_source/', 0755);
			chmod('./pages/application/template/'.$folder.'/modules/modules_source/', 0755);
		}
		chmod('./pages/application/template/'.$folder.'/', 0777);
		
		$plik = $_FILES['photo'];
		$nazwa_pliku = '';
		if(in_array($plik['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
			$n = $plik['name'];
			$r = explode(".", $n);
			$nazwa_pliku = $folder.'.'.$r[count($r)-1];
			
			if(@move_uploaded_file($plik['tmp_name'], 'pages/application/template/'.$folder.'/'.$nazwa_pliku)){
				
				$this->setMemoryForImage('pages/application/template/'.$folder.'/'.$nazwa_pliku);
				
				$this->load->library('image_lib');
				
				$config['maintain_ratio'] = TRUE;
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = FALSE;
				$config['source_image'] = 'pages/application/template/'.$folder.'/'.$nazwa_pliku;
				$config['new_image'] = 'pages/application/template/'.$folder.'/thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
				$config['image_library'] = 'gd2';
				$config['width'] = 200;
				$config['height'] = 200;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
				/*tworzenie miniaturki*/								
			}
			if($enabled==true) $e=1; else $e=0;
			$data = array(
				'global_templates_name' => $name,
				'global_templates_desc' => $desc,
				'global_templates_folder' => $folder,
				'global_templates_photo' => $nazwa_pliku,
				'global_templates_enabled' => $e
			);
			$this->db->insert('global_templates', $data);
		}
		
	}
	
	function getglobaltemplates(){
		$this->db->order_by('ID_global_templates', 'asc');
		return $this->db->get('global_templates');
	}
	
	function editglobaltemplate($id, $name, $desc, $folder, $old_folder, $enabled, $photo){
		if(file_exists('./pages/application/template/'.$old_folder)){
			rename('./pages/application/template/'.$old_folder, './pages/application/template/'.$folder);
		}

		$plik = $photo;
		if(in_array($plik['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
			$n = $plik['name'];
			$r = explode(".", $n);
			$stara_nazwa = $this->db->get_where('global_templates', array('ID_global_templates' => $id))->row()->global_templates_photo;
			rename('./pages/application/template/'.$folder.'/'.$stara_nazwa, './pages/application/template/'.$folder.'/__'.$stara_nazwa);
			rename('./pages/application/template/'.$folder.'/thumb_'.$stara_nazwa, './pages/application/template/'.$folder.'/__thumb_'.$stara_nazwa);
			$snr = explode(".", $n);
			
			$nazwa_pliku = $folder.".".$r[count($r)-1];
			if(@move_uploaded_file($plik['tmp_name'], 'pages/application/template/'.$folder.'/'.$nazwa_pliku)){
				$this->setMemoryForImage('pages/application/template/'.$folder.'/'.$nazwa_pliku);
				
				$this->load->library('image_lib');
				
				$config['maintain_ratio'] = TRUE;
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = FALSE;
				$config['source_image'] = 'pages/application/template/'.$folder.'/'.$nazwa_pliku;
				$config['new_image'] = 'pages/application/template/'.$folder.'/thumb_'.$nazwa_pliku;
				$config['image_library'] = 'gd2';
				$config['width'] = 200;
				$config['height'] = 200;
				$this->image_lib->initialize($config);
				$this->image_lib->resize();
				$this->image_lib->clear();
				
				$this->db->where('ID_global_templates', $id);
				$this->db->update('global_templates', array('global_templates_photo' => $nazwa_pliku));
				unlink('pages/application/template/'.$folder.'/__'.$stara_nazwa);
				unlink('pages/application/template/'.$folder.'/__thumb_'.$stara_nazwa);
				
			} else {
				rename('./pages/application/template/'.$folder.'/__'.$stara_nazwa, './pages/application/template/'.$folder.'/'.$stara_nazwa);
				rename('./pages/application/template/'.$folder.'/__thumb_'.$stara_nazwa, './pages/application/template/'.$folder.'/thumb_'.$stara_nazwa);
			}
		}
		
		if($enabled==true) $e=1; else $e=0;
		$data = array(
			'global_templates_name' => $name,
			'global_templates_desc' => $desc,
			'global_templates_folder' => $folder,
			'global_templates_enabled' => $e
		);
		$this->db->where('ID_global_templates', $id);
		$this->db->update('global_templates', $data);
	}
		
	function setMemoryForImage( $filename ){
	    $imageInfo = getimagesize($filename);
	    $MB = 1048576;  // number of bytes in 1M
	    $K64 = 65536;    // number of bytes in 64K
	    $TWEAKFACTOR = 1.5;  // Or whatever works for you
	    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
	                                           * $imageInfo['bits']
	                                           * $imageInfo['channels'] / 8
	                             + $K64
	                           ) * $TWEAKFACTOR
	                         );
	    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
	    //Default memory limit is 8MB so well stick with that.
	    //To find out what yours is, view your php.ini file.
	    $memoryLimit = 8 * $MB;
	    if (function_exists('memory_get_usage') &&
	        memory_get_usage() + $memoryNeeded > $memoryLimit)
	    {
	    	$memoryLimitMB = (integer) ini_get('memory_limit');
	        $newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
	                                            + $memoryNeeded
	                                            - $memoryLimit
	                                            ) / $MB
	                                        );
	        ini_set( 'memory_limit', $newLimit . 'M' );
	        return true;
		}else
	    return false;
	}
	
	function addarticletemplate($name, $desc, $folder, $filename, $photo, $userId){
		$article_folder = '';
		if($userId == 0){
			if(!file_exists('./pages/application/template/'.$folder)){
				mkdir('./pages/application/template/'.$folder.'/', 0777);
			}
			chmod('./pages/application/template/'.$folder.'/', 0777);
			if(!file_exists('./pages/application/template/'.$folder.'/'.$filename.'.php')){	//było bez .php
				chmod('./pages/application/template/'.$folder.'/', 0777);
				$this->load->helper('file');
				write_file('./pages/application/template/'.$folder.'/'.$filename.'.php', ''); //było bez .php
			}
			chmod('./pages/application/template/'.$folder.'/', 0777);
			$article_folder = 'pages/application/template/'.$folder.'/';
		} else {
			$user_folder = $this->get_user($userId)->row()->user_folder;
			//echo './pages/'.$user_folder.'/template/content/'.$folder.'/';
			if(!file_exists('./pages/'.$user_folder.'/template/content/'.$folder)){
				//echo $folder;
				mkdir('./pages/'.$user_folder.'/template/content/'.$folder.'/');
			}
			chmod('./pages/'.$user_folder.'/template/content/'.$folder.'/', 0777);
			//echo './pages/'.$user_folder.'/template/content/'.$folder.'/';
			if(!file_exists('./pages/'.$user_folder.'/template/content/'.$folder.'/'.$filename.'.php')){
				chmod('./pages/'.$user_folder.'/template/content/'.$folder.'/', 0777);
				$this->load->helper('file');
				write_file('./pages/'.$user_folder.'/template/content/'.$folder.'/'.$filename.'.php', '');
			}
			chmod('./pages/'.$user_folder.'/template/content/'.$folder.'/', 0777);
			$article_folder = 'pages/'.$user_folder.'/template/content/'.$folder.'/';
		}
		
		$plik = $_FILES['photo'];
		$nazwa_pliku = '';
		if(in_array($plik['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
			$n = $plik['name'];
			$r = explode(".", $n);
			$nazwa_pliku = $filename.'.'.$r[count($r)-1];
			
			if(@move_uploaded_file($plik['tmp_name'], './'.$article_folder.$nazwa_pliku)){
				
				$this->setMemoryForImage($article_folder.$nazwa_pliku);
				
				$this->load->library('image_lib');
				
				$config['maintain_ratio'] = TRUE;
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = FALSE;
				$config['source_image'] = $article_folder.$nazwa_pliku;
				$config['new_image'] = $article_folder.'thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
				$config['image_library'] = 'gd2';
				$config['width'] = 200;
				$config['height'] = 200;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
				/*tworzenie miniaturki*/								
				
				
			}
			$data = array(
				'article_templates_user_id' => $userId,
				'article_templates_name' => $name,
				'article_templates_desc' => $desc,
				'article_templates_folder' => $article_folder,
				'article_templates_photo' => $nazwa_pliku,
				'article_templates_filename' => $filename
			);
			$this->db->insert('article_templates', $data);
		}
	}
	
	function getarticletemplates(){
		//return $this->db->from('article_templates')->from('users')->where('ID_users', 'article_templates_user_id')->or_where('article_templates_user_id', 0)->get();
		//$sql = 'select * from article_templates, users where ID_users=article_templates_user_id or article_templates_user_id=0';
		//return $this->db->query($sql);
		$this->db->order_by('ID_article_templates', 'asc');
		$query = $this->db->get('article_templates');
		if($query && $query->num_rows() > 0){
			foreach($query->result() as $row){
				if($row->article_templates_user_id == 0){
					$row->username = 'Wszyscy';
				} else {
					$q = $this->db->get_where('users', array('ID_users' => $row->article_templates_user_id))->row()->user_login;
					$row->username = $q;
				}
			}
		}
		return $query;
	}
	
	function editarticletemplate($id, $name, $desc, $folder, $old_folder, $user_id, $photo){
		
		$query = $this->db->get_where('article_templates', array('ID_article_templates' => $id));
		if($query && $query->num_rows() > 0){
			//echo '1'.'<br/>';
		}//else echo '2'.'<br/>';
		$template_folder = $query->row()->article_templates_folder;
		
		if($user_id == 0){
			$new_template_folder = 'pages/application/template/'.$folder.'/';
		} else {
			$user_folder = $this->get_user($user_id)->row()->user_folder;
			$new_template_folder = 'pages/'.$user_folder.'/template/content/'.$folder.'/';
		}
		
		if(file_exists('./'.trim_slashes($template_folder))){
			rename('./'.trim_slashes($template_folder), './'.$new_template_folder);
		}
		//echo $new_template_folder;
		
		$plik = $photo;
		if(in_array($plik['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
			$n = $plik['name'];
			$r = explode(".", $n);
			$stara_nazwa = $this->db->get_where('article_templates', array('ID_article_templates' => $id))->row()->article_templates_photo;

			rename('./'.$new_template_folder.$stara_nazwa, './'.$new_template_folder.'__'.$stara_nazwa);
			rename('./'.$new_template_folder.'thumb_'.$stara_nazwa, './'.$new_template_folder.'__thumb_'.$stara_nazwa);
			
			$nazwa_pliku = $folder.".".$r[count($r)-1];
			
			if(@move_uploaded_file($plik['tmp_name'], './'.$new_template_folder.$nazwa_pliku)){
				$this->setMemoryForImage($new_template_folder.$nazwa_pliku);
				
				$this->load->library('image_lib');
				
				$config['maintain_ratio'] = TRUE;
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = FALSE;
				$config['source_image'] = $new_template_folder.$nazwa_pliku;
				$config['new_image'] = $new_template_folder.'thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
				$config['image_library'] = 'gd2';
				$config['width'] = 200;
				$config['height'] = 200;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
				
				$this->db->where('ID_article_templates', $id);
				$this->db->update('article_templates', array('article_templates_photo' => $nazwa_pliku));

				unlink('./'.$new_template_folder.'__'.$stara_nazwa);
				unlink('./'.$new_template_folder.'__thumb_'.$stara_nazwa);
				
			} else {
				rename('./'.$new_template_folder.'__'.$stara_nazwa, './'.$new_template_folder.$stara_nazwa);
				rename('./'.$new_template_folder.'__thumb_'.$stara_nazwa, './'.$new_template_folder.'thumb_'.$stara_nazwa);
			}
		}
		
		$data = array(
			'article_templates_user_id' => $user_id,
			'article_templates_name' => $name,
			'article_templates_desc' => $desc,
			'article_templates_folder' => $new_template_folder
		);
		$this->db->where('ID_article_templates', $id);
		$this->db->update('article_templates', $data);
		
		
		
		/*if(file_exists('./pages/application/template/'.$old_folder)){
			rename('./pages/application/template/'.$old_folder, './pages/application/template/'.$folder);
		}*/
	}
	
	function wyslij_haslo($id){
		$user = $this->get_user($id)->row();
		
		$mail = $user->user_mail;
		
		$pass = $this->generatePass();
		$this->load->helper('email');
		
		if(valid_email($mail)){
			// /usr/bin/sendmail
			//$config['protocol'] = 'mail';
			$config['protocol'] = 'sendmail';
			$config['mailpath'] = '/usr/sbin/sendmail';
			$config['charset'] = 'utf-8';
			$config['wordwrap'] = TRUE;
			$config['mailtype'] = 'html';
			$config['priority'] = '1';
			
			$this->email->initialize($config); 
			$this->email->from('info@dimax.pl', 'AsterCMS');
			$this->email->to($mail);
			$this->email->subject('Witamy w AsterCMS');
			$message = '<p>Witamy w AsterCMS,</p>
<p>Poniżej znajduje się twój login i hasło do systemu CMS, które umożliwią Ci zarządzanie treścią strony <a href="http://kredytstudencki.psrp.org.pl">http://kredytstudencki.psrp.org.pl</a>:</p>
<p>login: '.$user->user_login.'</p>
<p>hasło: '.$pass.'</p>
<br>
<p>Aby się zalogować wejdź na stronę: <a href="http://cms.kredytstudencki.psrp.org.pl">http://cms.kredytstudencki.psrp.org.pl</a></p>
<br/>
';
			
			$this->email->message($message);
			//echo $message;
			if($this->email->send()){
				$this->db->where('ID_users', $id);
				$this->db->update('users', array('user_pass' => sha1($this->encryption_key.$pass), 'user_pass_sent' => 1));
				
				/* crm db load
				 * $this->db->close();
					
				$db2 = $this->load->database('crm', true);
				$db2->where('ID_users', $id);
				$db2->update('users', array('user_pass' => sha1($this->encryption_key.$pass), 'user_pass_sent' => 1));
				
				$db2->close();
				
				$this->load->database('default');*/
				
				
				$this->email->initialize($config); 
				$this->email->from('info@dimax.pl', 'AsterCMS');
				$this->email->to('kamil@dimax.pl');
				$this->email->subject('Witamy w AsterCMS');
				$message = '<p>Witamy w AsterCMS,</p>
	<p>Poniżej znajduje się twój login i hasło do systemu CMS, które umożliwią Ci zarządzanie treścią strony <a href="http://kredytstudencki.psrp.org.pl">http://kredytstudencki.psrp.org.pl</a>:</p>
	<p>login: '.$user->user_login.'</p>
	<p>hasło: '.$pass.'</p>
	<br>
	<p>Aby się zalogować wejdź na stronę: <a href="http://cms.kredytstudencki.psrp.org.pl">http://cms.kredytstudencki.psrp.org.pl</a></p>
	<br/>
	';
				
				$this->email->message($message);
				//echo $message;
				if($this->email->send()){}
				
				
				
				
				
				return 1;
			} else {
			return 0;
			}
			
		} else 
		return 0;
	}
	
	
}
?>