Visoka skola strukovnih studija za informacione i komunikacione tehnologije. Dokumentacija.

Величина: px
Почињати приказ од странице:

Download "Visoka skola strukovnih studija za informacione i komunikacione tehnologije. Dokumentacija."

Транскрипт

1 Visoka skola strukovnih studija za informacione i komunikacione tehnologije Dokumentacija Predmet:Praktikum PHP Student:Đorđe Antanasković 35/18 Jun 2020

2 SADRŽAJ SADRŽAJ UVOD Korišćeni programski jezici i okruženja Opis funkcionalnosti Template Organizacija Organizaciona šema...7 Mapa sajta Šema baze podataka Struktura foldera i fajlova Slike stranica i opisi funkcionalnosti index.php index.php?page=news index.php?page=singlenews index.php?page=tagnews index.php?page=authorization index.php?page=userprofile index.php?page=contact index.php?page=adminpanel index.php?page=addnews index.php?page=updatenews Kodovi PHP index.php config/.env config/config.php config/connection.php

3 3.1.5 models/admin/function.php models/admin/category/add.php models/admin/category/delete.php models/admin/news/moretags.php models/admin/news/newsadd.php models/admin/news/newsdelete.php models/admin/news/newsupdate.php models/admin/survey/deleteoractivate.php models/admin/survey/surveyadd.php models/admin/survey/surveyresult.php models/admin/users/changerole.php models/admin/users/deleteuser.php models/admin/users/searchuser.php models/authorization/function.php models/authorization/logout.php models/authorization/register.php models/authorization/signin.php models/contact/inbox.php models/mainpage/function.php models/mainpage/slidernews.php models/mainpage/surveyanswer.php models/news/filternews.php models/singlenews/function.php models/singlenews/addcomment.php models/singlenews/deletecomments.php models/tagnews/function.php models/userprofile/changeinfo.php models/userprofile/changepassword.php

4 models/menusearch.php views/fixed/footer.php views/fixed/head.php views/fixed/header.php views/addnews.php views/adminpanel.php views/authorization.php views/contact.php views/forbidden.php views/indexcontent.php views/news.php views/notfound.php views/seo.php views/singlenews.php views/tagnews.php views/updatenews.php views/userprofile.php views/verificationpage.php CSS style.scss JS main.js

5 1. UVOD 1.1 Korišćeni programski jezici i okruženja HTML/HTML5 CSS/CSS3 JavaScript Jquery PHP Bootstrap (CSS Framework) Graph Js Visual Studio Code PhotoShop 1.2 Opis funkcionalnosti Dohvatanje menija iz baze i njegovo ispisivanje na svim stranicama Mogućnost pretrage vesti na svim stranicama na osnovu naslova ili tagova vesti Dohvatanje vesti iz baze i njihovo ispisivanje,paginacija i mogućnost čitanja dodatnog sadržaja o svakoj vesti Mogućnost ostavljanja komentara na stranici izabrane vesti Mogućnost filtriranja vesti na osnovu izabranih kategorija Logovanje pristupa i grešaka Statistika o posetama stranicama na admin stranici Mogućnost upravljanja dinamičkim delom sajta preko admin panela Mogućnost prijavljivanja i registracije korisnika 1.3 Template 5

6 Za izradu ovog sajta nije korišćen nijedan gotovi template.listing koda koja kreira stranicu priložen je u nastvaku dokumenta. 6

7 2. Organizacija 2.1 Organizaciona šema Sve stranice su index.php. Mapa sajta <?xml version="1.0" encoding="utf-8" <urlset xmlns=" <url> <loc> <lastmod> </lastmod> <changefreq>daily</changefreq> <priority>1</priority> </url> <url> <loc> <lastmod> </lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc> <lastmod> </lastmod> <changefreq>yearly</changefreq> <priority>0.5</priority> </url> <url> <loc> /loc> <lastmod> </lastmod> <changefreq>yearly</changefreq> <priority>0.5</priority> </url> <url> <loc> oc> <lastmod> </lastmod> <changefreq>yearly</changefreq> <priority>0.6</priority> </url> 7

8 </urlset> 2.2 Šema baze podataka 2.3 Struktura foldera i fajlova 8

9 9

10 2.4 Slike stranica i opisi funkcionalnosti U nastavku će biti prolzeni print screen ekrana I kraktka objašnjenja za sve logičke celine sajta. 10

11 2.4.1 index.php Na naslovnoj strani se ispisjue slider sa 3 najnovije vesti.ispisuju se najnovije vesti i najpopularnije vesti (tj.vesti sa najviše komentara). Takođe se ispisuje anketa sa ponuđenih odgovorima na koja mogu odgovorit samo ulogovani korisnici index.php?page=news 11

12 Na ovom delu sajta se prikazuju vesti sa paginacijom.moguće je filtriranje vesti na osnovu kategorija.kilikom na dugme pročitaj više moguće je pročitati još podataka o vesti i ostaviti ili pogledati komentare za tu vest index.php?page=singlenews Na ovoj stranici se prikazuje detaljniji tekst o vesti zajedno sa komentarima i povezanih vestima.ukoliko administrator pristupi ovoj stranici može da briše komentare na x simbolu u gornjem desnom uglu svakog komentara.povezane vesti su vesti koje pripadaju istoj kategoriji ili imaju zajedničke tagove kao izabrana vest.prikazuju se najviše 4 povezane vesti.ukoliko nema ni jedne povezane vesti prikazuju se 4 najnovije vesti. 12

13 2.4.4 index.php?page=tagnews Na ovoj strani se prikazuju sve vesti za izabrani tag index.php?page=authorization Na ovoj stranici je moguća registracija i prijavljivanje korisnika.korisnički unos se proverava na klijentskoj i serverskoj strani i prikazuje se obaveštenje o greškama.nakon uspešne registracije korisnik dobija link koji vodi ka stranici verification gde on verifikuje svoj profil nakon čega se može ulogovati na svoj 13

14 profil.ukoliko se korisnik uspešno uloguje na dalje mu se umesto ovo stranice prikazuje strainica userprofile index.php?page=userprofile Na ovoj stranici se prikazuju osnovne informacije o korisniku uz mogućnost izmene korisničkog imena ili lozinke.ukoliko je promena korisničkog imena uspešna stranica se osvežava sa ažuriranim podatcima.ukoliko je lozinka uspešno promenjena ajax-om se ispisuje poruka.na kraju se nalazi dugme za logout index.php?page=contact 14

15 Na ovoj stranici se nalazi kontakt forma kojom je moguće poslati poruku administrator sajta,tu je i slika i kratak opis o autoru sajta. Poruke koje se pošalju sa ove strane se ispisujuu na admin panelu index.php?page=adminpanel Pristup ovoj stranici imaju samo administratori sajta.tu je moguća izmena,brisanje i dodavanje vesti,dodavanje I brisanje kateogrija vesti,promena uloga korisnika I brisanje korisnika,dodavanje,brisanje i aktivacija anketa kao i pregled odgovora na ankete. 15

16 2.4.9 index.php?page=addnews Na ovoj strani je moguće dodavanje vesti.sav korisnički unos se proverava na klijentskoj i serverskoj strani i ispisuje se poruke o greškama index.php?page=updatenews Na ovoj strani je moguća izmena odabrane vesti.sav korisnički unos se proverava na klijentskoj i serverskoj strani i ispisuje se poruke o greškama. 16

17 3.1 PHP index.php 3. Kodovi session_start(); ob_start(); $logged=false; $admin=false; $author=false; if(isset($_session["user"])){ $logged=true; $user=$_session["user"]; if($user["role"]=="admin"){ $admin=true; else if($user["role"]=="autor"){ $author=true; require_once "config/connection.php"; if(isset($_get["page"])){ $page=$_get["page"]; switch($page){ case "news":case "contact":case "authorization":case "singlenews": case "userprofile":case "notfound":case "adminpanel":case "verificationpage":c ase "tagnews":case "addnews":case "updatenews": case "forbidden":break; default: $page="notfound";break; $page="indexcontent"; require_once "views/fixed/head.php"; require_once "views/fixed/header.php"; require_once "views/$page.php"; require_once "views/fixed/footer.php"; config/.env HOST=localhost DBNAME=blogdb USERNAME=root 17

18 PASSWORD= config/config.php define("absolute_path",$_server["document_root"]."/praktikumsajt/"); define("env_file",absolute_path."config/.env"); define("host",env("host")); define("dbname",env("dbname")); define("username",env("username")); define("password",env("password")); define("log_file",absolute_path."data/logfile.txt"); define("error_file",absolute_path."data/errors.txt"); define("separator","\t"); function env($flag){ $envrows=file(env_file); $returnflag=""; foreach($envrows as $row){ $exploderow=explode("=",$row); if($flag==$exploderow[0]){ $returnflag=trim($exploderow[1]); break; return $returnflag; config/connection.php require_once "config.php"; writelog(); try{ $conn=new PDO("mysql:host=".HOST.";dbname=".DBNAME.";",USERNAME,PASSWO RD,array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET NAMES 'utf8' COLLATE 'utf8_unicode _ci'")); $conn->setattribute(pdo::attr_errmode,pdo::errmode_exception); catch(pdoexception $e){ echo "Veza sa bazom nije moguca"; exit; function executequery($query){ global $conn; $result=$conn->query($query)->fetchall(); return $result; 18

19 function getcategories(){ $catquery="select * FROM kategorije"; return executequery($catquery); function getmenuitems(){ $navquery="select * FROM navigacija ORDER BY prioritet"; return executequery($navquery); function getnews($id){ global $conn; $query="select v.*,k.id as catid,k.naziv as category,s.src as src,s.al t as alt,a.id as authorid,concat(kor.ime,' ',kor.prezime) AS author FROM vesti v INNER JOIN kategorije k ON v.kat_id=k.id INNER JOIN autori a ON v.autor_id= a.id INNER JOIN korisnici kor ON a.kor_id=kor.id INNER JOIN slike s ON s.vest_ id=v.id INNER JOIN tip_slike ts ON ts.id=s.tip_id WHERE v.id=:id AND ts.naziv= 'cover'"; $prepare=$conn->prepare($query); $prepare->bindparam(":id",$id); try{ $prepare->execute(); if($prepare->rowcount()==1){ $news=$prepare->fetch(); return $news; return header("location:index.php?page=notfound"); catch(pdoexception $e){ return false; function filternews($currentpage,$categoires){ global $conn; $newsonpage=8; $startindex=$newsonpage*($currentpage-1); $filterquery="select v.*,k.naziv as category,concat(kor.ime,' ',kor.pr ezime) as author,s.src as src,s.alt as alt FROM vesti v INNER JOIN kategorije k ON v.kat_id=k.id INNER JOIN autor i a ON a.id=v.autor_id INNER JOIN korisnici kor ON kor.id=a.kor_id INNER JOIN slike s ON s.vest_id=v.id INNER JOIN tip_slike tp ON tp.id=s.tip_id WHERE tp.n aziv='thumbnail' "; if(count($categoires)){ $categoiresbind=implode($categoires,","); $filterquery.="and v.kat_id IN ($categoiresbind) ORDER BY datum DE SC"; $prepare=$conn->prepare($filterquery); 19

20 try{ $prepare->execute(); $newscount=$prepare->rowcount(); $filterquery.=" LIMIT $startindex,$newsonpage"; $prepare2=$conn->prepare($filterquery); $prepare2->execute(); $news=$prepare2->fetchall(); catch(pdoexception $e){ return false; $filterquery.=" ORDER BY datum DESC"; $newscount=count(executequery($filterquery)); $filterquery.=" LIMIT $startindex,$newsonpage"; $news=executequery($filterquery); $pagesnumber=ceil($newscount/$newsonpage); return ["news"=>$news,"pagesnumber"=>$pagesnumber,"newsnumber"=>$newsc ount]; function writelog(){ $logfile=fopen(log_file,"a"); $date=date('y/m/d H:i:s'); $log="{$_server['request_uri']\t$date\t{$_server["remote_addr"]\n"; fwrite($logfile,$log); fclose($logfile); function writeerror($msg){ $errorfile=fopen(error_file,"a"); $date=date('y/m/d H:i:s'); $error="{$_server['php_self']\t$date\t$msg\n"; fwrite($errorfile,$error); fclose($errorfile); models/admin/function.php function getusers($query=""){ global $conn; if($query!=""){ $searchquery="select * FROM korisnici WHERE username LIKE :query"; $searchprepare=$conn->prepare($searchquery); $like="%$query%"; $searchprepare->bindparam(":query",$like); try{ 20

21 $searchprepare->execute(); return $searchprepare->fetchall(); catch(pdoexception $e){ writeerror($e->getmessage()); return false; return executequery("select * FROM korisnici"); function getroles(){ global $conn; return executequery("select * FROM uloge"); function getallauthors(){ global $conn; $query="select CONCAT(k.ime,' ',k.prezime) as name,a.* FROM autori a I NNER JOIN korisnici k ON a.kor_id=k.id"; return executequery($query); function makeimages($imagesrc,$imgtype,$uploaddir){ $canvascover=imagecreatetruecolor(1800,600); $canvasthumbnail=imagecreatetruecolor(420,280); if($imgtype=="png"){ $uploadedimage=imagecreatefrompng($imagesrc); $uploadedimage=imagecreatefromjpeg($imagesrc); $imagesize=getimagesize($imagesrc); $width=$imagesize[0]; $height=$imagesize[1]; $imagepatharr=explode("/",$imagesrc); $oldname=explode(".",end($imagepatharr)); $newnamecover=$oldname[0]."_cover".".".$oldname[1]; $newnamethumbnail=$oldname[0]."thumbnail".".".$oldname[1]; imagecopyresampled($canvascover,$uploadedimage,0,0,0,0,1800,600,$width,$height); imagecopyresampled($canvasthumbnail,$uploadedimage,0,0,0,0,420,280,$wi dth,$height); if($imgtype=="png"){ imagepng($canvascover,$uploaddir.$newnamecover); imagepng($canvasthumbnail,$uploaddir.$newnamethumbnail); unlink($imagesrc); imagejpeg($canvascover,$uploaddir.$newnamecover); imagejpeg($canvasthumbnail,$uploaddir.$newnamethumbnail); 21

22 unlink($imagesrc); return ["cover"=>$newnamecover,"thumbnail"=>$newnamethumbnail]; function checkuploadimage($src){ $errors=[]; $allowimgformats=["jpeg","png","jpg"]; $filetype=explode("/",$src["type"])[1]; if(!in_array($filetype,$allowimgformats)){ $errors[]="format slike nije dobar.molimo vas izaberite drugi form at."; if($src["size"]> ){ $errors[]="slika ne sme biti veća od 3MB"; if(!count($errors)){ $tmppath=$src["tmp_name"]; $originalname=explode(".",$src["name"])[0]; $uploaddir="../../../assets/images/"; $newname=time(); $newpath=$uploaddir.$newname.".".$filetype; $imageinfo=["tmppath"=>$tmppath,"originalname"=>$originalname,"upl oaddir"=>$uploaddir,"newname"=>$newname,"newpath"=>$newpath,"filetype"=>$filet ype]; return ["errors"=>[],"imginfo"=>$imageinfo]; return ["errors"=>$errors,"imginfo"=>[]]; ; function getalltags(){ return executequery("select * FROM tagovi"); function getsurveys(){ global $conn; $html=""; $allsurveys=executequery("select * FROM anketa ORDER BY aktivna DESC") ; foreach($allsurveys as $survey){ $html.="<option value='{$survey["id"]'>{$survey["pitanje"]</opti on>"; return $html; function deletesurvey($id){ global $conn; $deletequery="delete FROM anketa WHERE id=:id"; $prepare=$conn->prepare($deletequery); $prepare->bindparam(":id",$id); 22

23 try{ $prepare->execute(); if($prepare->rowcount()==1){ http_response_code(200); $newsurveys=executequery("select * FROM anketa ORDER BY aktivn a DESC"); $newactivedsurveyid=end($newsurveys)["id"]; $activatenewop=activatesurvey($newactivedsurveyid); if($activatenewop){ return $newsurveys; return false; return false; catch(pdoexception $e){ writeerror($e->getmessage()); return false; function activatesurvey($id){ global $conn; $updatequery="update anketa SET aktivna=1 WHERE id=:id"; $prepare=$conn->prepare($updatequery); $prepare->bindparam(":id",$id); try{ $deactivesurvey=$conn->query("update anketa SET aktivna=0"); $prepare->execute(); if($prepare->rowcount()==1){ return true; return false; catch(pdoexception $e){ writeerror($e->getmessage()); return false; function visitstable(){ $logfile=file(log_file); $lastday=strtotime("-1 day"); $i=count($logfile); 23

24 $pagescount=["sum"=>0,"index"=>0,"singlenews"=>0,"news"=>0,"contact"=> 0,"userProfile"=>0,"notFound"=>0,"adminPanel"=>0,"addNews"=>0,"updateNews"=>0, "forbidden"=>0,"authorization"=>0,"tagnews"=>0,"verification"=>0]; for($j=$i;$j>0;$j--){ if(strtotime(explode(separator,$logfile[$j-1])[1]) >= $lastday){ $page=explode(separator,$logfile[$j-1])[0]; $pageview=explode("=",$page); if(count($pageview)>1){ if(strpos($pageview[1],"singlenews&id")!==false){ $pagescount["singlenews"]++; $pagescount["sum"]++; else if(strpos($pageview[1],"updatenews&updateid")!==false ){ $pagescount["updatenews"]++; $pagescount["sum"]++; else if(strpos($pageview[1],"verificationpage&code")!==fal se){ $pagescount["verification"]++; $pagescount["sum"]++; else if(strpos($pageview[1],"tagnews&tag")!==false){ $pagescount["tagnews"]++; $pagescount["sum"]++; $pagescount[$pageview[1]]++; $pagescount["sum"]++; if(strpos($pageview[0],"index.php")){ $pagescount["index"]++; $pagescount["sum"]++; break; return $pagescount; function getinbox(){ global $conn; $query="select * FROM mejlovi"; return executequery($query); 24

25 3.1.6 models/admin/category/add.php header("content-type:application/json"); if(isset($_post["add"])){ require_once "../../../config/connection.php"; $catregex="/^[a-zšđčćž][a-zšđčžćčžćšđ\s]{1,49$/"; if(isset($_post["name"])){ $name=$_post["name"]; if(!preg_match($catregex,$name)){ http_response_code(400); echo json_encode("naziv kategorije nije u dobrom formatu"); $insertquery="insert INTO kategorije(naziv) VALUES(:name)"; $prepare=$conn->prepare($insertquery); $prepare->bindparam(":name",$name); try{ $prepare->execute(); http_response_code(201); $refreshcat=getcategories(); echo json_encode(["message"=>"kategorija uspešno dodata"," result"=>$refreshcat]); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode("došlo je do greške"); http_response_code(400); echo json_encode("zahtev nije dobar"); models/admin/category/delete.php header("content-type:application/json"); if(isset($_post["delete"])){ require_once "../../../config/connection.php"; if(isset($_post["catid"])){ $deleteid=$_post["catid"]; $deletequery="delete FROM kategorije WHERE id=:id"; $prepare=$conn->prepare($deletequery); 25

26 $prepare->bindparam(":id",$deleteid); try{ $prepare->execute(); http_response_code(200); $refreshcat=getcategories(); echo json_encode(["message"=>"kategorija uspešno obrisana.","r esult"=>$refreshcat]); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); //echo json_encode($e); //echo json_encode($e); echo json_encode("došlo je do greške."); http_response_code(400); echo json_encode("id kategorije nije prosledjen."); http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); models/admin/news/moretags.php header("content-type:application/json"); if(isset($_post["moretags"])){ require_once "../../../config/connection.php"; if(isset($_post["selectedtags"])){ $tags=$_post["selectedtags"]; $tagsstring=implode($tags,","); http_response_code(400); echo json_encode("morate izabrati neki tag"); $tagsquery="select * FROM tagovi WHERE id NOT IN ($tagsstring)"; try{ $moretags=executequery($tagsquery); http_response_code(200); echo json_encode($moretags); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); 26

27 ); echo json_encode("došlo je do greške.molimo vas pokušajte kasnije" http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); models/admin/news/newsadd.php header("content-type:application/json"); if(isset($_post["add"])){ require_once "../../../config/connection.php"; require_once "../function.php"; $errors=[]; $newsparams=[]; $tagsnews=false; $tagtable=false; $messageregex = "/^[A-zšđč枊ĐČŽĆ0-9\s\?\.\,\!\"\'\-\)\(\:]{2,$/"; $newsheaderregex="/^[a-zšđčžć][a-zšđčžćšđčćž\s\,\.\!\?\-\- \)\(\:]{0,59$/"; $newsdescregex = "/^[A-ZŠĐČŽĆ][A-zŠĐČŽĆšđčžć\s\?\!\.\,0-9\"\'\- \)\(\:]{1,199$/"; $imageregex = "/^image\/(jpeg jpg png)$/"; $allowimgformats=["jpeg","png","jpg"]; if(isset($_post["header"])){ $header=$_post["header"]; if(!preg_match($newsheaderregex,$header)){ $errors[]="naslov nije u dobrom formatu"; $newsparams[]=$header; $errors[]="morate uneti naslov vesti"; if(isset($_post["desc"])){ $desc=$_post["desc"]; if(!preg_match($newsdescregex,$desc)){ $errors[]="opis nije u dobrom formatu"; $newsparams[]=$desc; 27

28 $errors[]="morate uneti kratki opis vesti"; if(isset($_post["text"])){ $text=$_post["text"]; if(!preg_match($messageregex,$text)){ $errors[]="tekst vesti ne sme biti prazan"; $newsparams[]=$text; $errors[]="tekst vesti ne sme biti prazan"; if(isset($_post["category"])){ $category=$_post["category"]; $newsparams[]=$category; $errors[]="morate izabrati kategoriju"; if(isset($_post["author"])){ $author=$_post["author"]; $newsparams[]=$author; $errors[]="morate izabrati autora"; if(!isset($_post["tags"]) &&!isset($_post["newtags"])){ $errors[]="morate izabrati tag"; if(isset($_post["tags"])){ $tag=json_decode($_post["tags"]); $tagsnews=true; if(isset($_post["newtags"])){ $newtags=json_decode($_post["newtags"]); $tagtable=true; if(isset($_files["image"])){ $image=$_files["image"]; $imagecheck=checkuploadimage($image); if(count($imagecheck["errors"])){ foreach($imagecheck["errors"] as $errorimg){ $errors[]=$errorimg; 28

29 $errors[]="morate izabrati sliku"; if(!count($errors)){ $insertnewsquery="insert INTO vesti(naslov,opis,tekst,kat_id,autor _id) VALUES(?,?,?,?,?)"; $newsprepare=$conn->prepare($insertnewsquery); for($i=0;$i<count($newsparams);$i++){ $newsprepare->bindparam($i+1,$newsparams[$i]); try{ $conn->begintransaction(); $newsprepare->execute(); $newsid=$conn->lastinsertid(); $uploadimage=move_uploaded_file($imagecheck["imginfo"]["tmppat h"],$imagecheck["imginfo"]["newpath"]); if(!$uploadimage){ $errors[]="došlo je do greške prilikom upload-a slike."; http_response_code(500); echo json_encode($errors); $imagesresampled=makeimages($imagecheck["imginfo"]["newpat h"],$imagecheck["imginfo"]["filetype"],$imagecheck["imginfo"]["uploaddir"]); $coversrc=$imagesresampled["cover"]; $thumsrc=$imagesresampled["thumbnail"]; $imageinsert="insert INTO slike(src,alt,tip_id,vest_id) VA LUES(:srcCover,:altCover,1,:newsId),(:srcThumb,:altThumb,2,:newsId)"; $imageprepare=$conn->prepare($imageinsert); $imageprepare->bindparam(":srccover",$coversrc); $imageprepare->bindparam(":altcover",$coversrc); $imageprepare->bindparam(":srcthumb",$thumsrc); $imageprepare->bindparam(":altthumb",$thumsrc); $imageprepare->bindparam(":newsid",$newsid); $imageprepare->execute(); //Insert tags if($tagsnews){ $inserttags="insert INTO tag_vest(id_tag,id_vest) VALU ES(:tagId,:newsId)"; $preparetags=$conn->prepare($inserttags); foreach($tag as $t){ $preparetags->bindparam(":tagid",$t); $preparetags->bindparam(":newsid",$newsid); $preparetags->execute(); 29

30 if($tagtable){ $newtagquery="insert INTO tagovi(naziv) VALUES(:name)" ; $newtagprepare=$conn->prepare($newtagquery); foreach($newtags as $new){ $newtagprepare->bindparam(":name",$new); $newtagprepare->execute(); $newtagid=$conn->lastinsertid(); $tagnewstableinsert="insert INTO tag_vest(id_tag,i d_vest) VALUES(:tag,:news)"; $tnti=$conn->prepare($tagnewstableinsert); $tnti->bindparam(":tag",$newtagid); $tnti->bindparam(":news",$newsid); $tnti->execute(); $conn->commit(); http_response_code(200); echo json_encode("<p>vest uspešno dodata!pogledajte vest n a ovom <a href='index.php?page=singlenews&id=$newsid'>linku</a></p>"); catch(pdoexception $e){ writeerror($e->getmessage()); $conn->rollback(); http_response_code(500); $errors[]="došlo je do greške"; echo json_encode($errors); http_response_code(400); echo json_encode($errors); http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); models/admin/news/newsdelete.php header("content-type:application/json"); if(isset($_post["deletenews"])){ require_once "../../../config/connection.php"; if(isset($_post["deleteid"])){ 30

31 $deleteid=$_post["deleteid"]; http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); if(isset($_post["page"])){ $page=$_post["page"]; http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); $deletequery="delete FROM vesti WHERE id=:id"; $prepare=$conn->prepare($deletequery); $prepare->bindparam(":id",$deleteid); try{ $prepare->execute(); http_response_code(200); $newnews=filternews($page,[]); if(!count($newnews["news"])){ $newnews2=filternews($page-1,[]); echo json_encode($newnews2); echo json_encode($newnews); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode(["err"=>"došlo je do greške","baza"=>$e]); http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); models/admin/news/newsupdate.php header("content-type:application/json"); if(isset($_post["update"])){ require_once "../../../config/connection.php"; require_once "../function.php"; $messageregex = "/^[A-zšđč枊ĐČŽĆ0-9\s\?\.\,\!\"\'\-\)\(\:]{2,$/"; $newsheaderregex="/^[a-zšđčžć][a-zšđčžćšđčćž\s\,\.\!\?\-\- \)\(\:]{0,59$/"; 31

32 $newsdescregex = "/^[A-ZŠĐČŽĆ][A-zŠĐČŽĆšđčžć\s\?\!\.0-9\"\'\- \)\(\:]{1,199$/"; $errors=[]; $updatevalues=[]; $needupdate=false; $imageupdate=false; $updatequery="update vesti SET"; if(isset($_post["updateid"])){ $updateid=$_post["updateid"]; $errors[]="tražena vest ne postoji"; if(isset($_post["header"])){ $header=$_post["header"]; if(!preg_match($newsheaderregex,$header)){ $errors[]="naslov nije u dobrom formatu"; $updatequery.=" naslov=:header,"; $updatevalues[]="header"; $needupdate=true; if(isset($_post["desc"])){ $desc=$_post["desc"]; if(!preg_match($newsdescregex,$desc)){ $errors[]="opis nije u dobrom formatu"; $updatequery.=" opis=:desc,"; $updatevalues[]="desc"; $needupdate=true; if(isset($_post["text"])){ $text=$_post["text"]; if(!preg_match($messageregex,$text)){ $errors[]="tekst nije u dobrom formatu"; $updatequery.=" tekst=:text,"; $updatevalues[]="text"; $needupdate=true; if(isset($_post["category"])){ $category=$_post["category"]; 32

33 $updatequery.=" kat_id=:category,"; $updatevalues[]="category"; $needupdate=true; if(isset($_post["author"])){ $author=$_post["author"]; $updatequery.=" autor_id=:author,"; $updatevalues[]="author"; $needupdate=true; if(isset($_files["image"])){ $imageupdate=true; $image=$_files["image"]; $imagecheck=checkuploadimage($image); if(count($imagecheck["errors"])){ foreach($imagecheck["errors"] as $errorimg){ $errors[]=$errorimg; if(!count($errors)){ $conn->begintransaction(); if($needupdate){ $updatequery=substr($updatequery,0,-1); $updatequery.=" WHERE id=:id"; $preparenews=$conn->prepare($updatequery); foreach($updatevalues as $value){ $preparenews->bindparam(":$value",$$value); $preparenews->bindparam(":id",$updateid); try{ $preparenews->execute(); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode(["došlo je do greške.sve promene će biti poništene"]); if($imageupdate){ $moveimage=move_uploaded_file($imagecheck["imginfo"]["tmppath" ],$imagecheck["imginfo"]["newpath"]); if(!$moveimage){ $errors[]="došlo je do greške prilikom uploada slike.sve promene biće poništene"; $conn->rollback(); 33

34 http_response_code(500); echo json_encode($errors); $newimages=makeimages($imagecheck["imginfo"]["newpath"],$i magecheck["imginfo"]["filetype"],$imagecheck["imginfo"]["uploaddir"]); $coverimage=$newimages["cover"]; $thumbnailimage=$newimages["thumbnail"]; $updatecover="update slike SET src=:coversrc WHERE vest_id =:id AND tip_id=1"; $updatethumbmail="update slike SET src=:thumbnailsrc WHERE vest_id=:id AND tip_id=2"; $preparecover=$conn->prepare($updatecover); $preparecover->bindparam(":coversrc",$coverimage); $preparecover->bindparam(":id",$updateid); $preparethumbmail=$conn->prepare($updatethumbmail); $preparethumbmail- >bindparam(":thumbnailsrc",$thumbnailimage); $preparethumbmail->bindparam(":id",$updateid); try{ $preparecover->execute(); $preparethumbmail->execute(); catch(pdoexception $e){ writeerror($e->getmessage()); $conn->rollback(); http_response_code(500); echo json_encode(["došlo je do greške prilikom promene slike"]); if(!$needupdate &&!$imageupdate){ http_response_code(200); echo json_encode(["nema izmene"]); $conn->commit(); http_response_code(200); echo json_encode("<p>izmena vesti je uspela!pogledajte vest na ovo m <a href='index.php?page=singlenews&id=$updateid'>linku</a></p>"); http_response_code(422); echo json_encode($errors); http_response_code(404); 34

35 echo json_encode(["zahtev nije dobar"]); models/admin/survey/deleteoractivate.php header("content-type:application/json"); if(isset($_post["modify"])){ require_once "../../../config/connection.php"; require_once "../function.php"; $op; $errors=[]; if(isset($_post["surveyid"])){ $id=$_post["surveyid"]; $errors[]="id vesti nije izabran"; if(isset($_post["delete"])){ $op="delete"; if(isset($_post["activate"])){ $op="activate"; if(!count($errors) &&!empty($op)){ if($op=="activate"){ $activateop=activatesurvey($id); if($activateop){ http_response_code(200); echo json_encode(["message"=>"anketa uspešno aktivirana!", "result"=>[]]); http_response_code(500); echo json_encode(["message"=>"anketa nije uspešno aktivira na","result"=>[]]); if($op=="delete"){ $deleteop=deletesurvey($id); if(!$deleteop){ http_response_code(500); echo json_encode(["message"=>"anketa nije uspešno aktivira na","result"=>[]]); http_response_code(200); echo json_encode(["message"=>"anketa uspešno obrisana!","r esult"=>$deleteop]); 35

36 http_response_code(404); echo json_encode($errors); http_response_code(404); echo json_encode("zahtev nije u dobrom formatu"); models/admin/survey/surveyadd.php if(isset($_post["addsurvey"])){ require_once "../../../config/connection.php"; $errors=[]; $questionregex="/^[a-zšđčžćčžćšđ][a-z0-9\s\,\.\?\!]{1,39$/"; $odgregex="/^[a-zžčćšđ][a-zšđčžćšđčžć0-9\s]{1,59$/"; header("content-type:application/json"); if(isset($_post["question"])){ $question=$_post["question"]; if(!preg_match($questionregex,$question)){ $errors[]="pitanje nije u dobrom formatu"; if(isset($_post["answers"])){ $answers=$_post["answers"]; foreach($answers as $answer){ if(!preg_match($odgregex,$answer)){ $errors[]="odgovori nisu u dobrom formatu"; break; if(!count($errors)){ $anketaupit="insert INTO anketa(pitanje,aktivna) VALUES(:pitanje,0 )"; $pripremaanketa=$conn->prepare($anketaupit); $pripremaanketa->bindparam(":pitanje",$question); try{ $pripremaanketa->execute(); $anketaid=$conn->lastinsertid(); foreach($answers as $odg){ $odgupit="insert INTO odgovori(tekst,anketa_id) VALUES(:te kst,:anketaid)"; 36

37 a DESC"); $pripremaodg=$conn->prepare($odgupit); $pripremaodg->bindparam(":tekst",$odg); $pripremaodg->bindparam(":anketaid",$anketaid); $pripremaodg->execute(); http_response_code(201); $newsurveys=executequery("select * FROM anketa ORDER BY aktivn echo json_encode($newsurveys); catch(pdoexception $e){ http_response_code(500); echo json_encode([$e->getmessage()]); echo json_encode(["došlo je do greške"]); http_response_code(422); echo json_encode($errors); header("location:../../../index.php?page=notfound"); models/admin/survey/surveyresult.php if(isset($_post["rez"])){ require_once "../../../config/connection.php"; $error=false; header("content-type:application/json"); if(isset($_post["id"])){ $surveyid=$_post["id"]; $error=true; if(!$error){ $surveyquery="select COUNT(ko.odg_id) as 'broj',o.tekst FROM koris nik_odgovor ko RIGHT OUTER JOIN odgovori o ON o.id=ko.odg_id WHERE o.anketa_id =:id GROUP BY o.tekst ORDER BY o.id"; $prepare=$conn->prepare($surveyquery); $prepare->bindparam(":id",$surveyid,pdo::param_int); $answerquery="select * FROM odgovori WHERE anketa_id=:id ORDER BY id"; $prepareanswer=$conn->prepare($answerquery); $prepareanswer->bindparam(":id",$surveyid,pdo::param_int); 37

38 try{ $prepare->execute(); $result=$prepare->fetchall(); $prepareanswer->execute(); $asnwers=$prepareanswer->fetchall(); http_response_code(200); echo json_encode(["result"=>$result,"answers"=>$asnwers]); catch(pdoexception $e){ http_response_code(500); echo json_encode($e); http_response_code(422); echo json_encode("parametri nisu dobri"); header("location:../../../index.php?page=notfound.php"); models/admin/users/changerole.php header("content-type:application/json"); if(isset($_post["changerole"])){ require_once "../../../config/connection.php"; $errors=[]; $author=false; $deleteauthor=false; $samerole=false; if(isset($_post["roleid"])){ $roleid=$_post["roleid"]; $errors[]="morate izabrati ulogu"; if(isset($_post["userid"])){ $userid=$_post["userid"]; $errors[]="morate izabrati korisnika"; if(!count($errors)){ $existrole=executequery("select u.* FROM uloge u INNER JOIN korisn ici k ON k.uloga_id=u.id WHERE k.id=$userid")[0]; 38

39 0]; :id"; rid)"; erid"; njena"]); $authorid=executequery("select * FROM uloge WHERE naziv='autor'")[ if($existrole["id"]==$roleid){ $samerole=true; if($existrole["id"]==$authorid["id"]){ $deleteauthor=true; if($authorid["id"]==$roleid){ $author=true; if(!$samerole){ $updatequery="update korisnici SET uloga_id=:newrole WHERE id= $prepare=$conn->prepare($updatequery); $prepare->bindparam(":newrole",$roleid); $prepare->bindparam(":id",$userid); try{ $prepare->execute(); if($prepare->rowcount()==1){ if($author){ $insertauthor="insert INTO autori VALUES(NULL,:use $prepareauthor=$conn->prepare($insertauthor); $prepareauthor->bindparam(":userid",$userid); $prepareauthor->execute(); if($deleteauthor){ $deleteauthor="delete FROM autori WHERE kor_id=:us $prepareauthor=$conn->prepare($deleteauthor); $prepareauthor->bindparam(":userid",$userid); $prepareauthor->execute(); http_response_code(201); if($prepare->rowcount()==0){ http_response_code(500); echo json_encode(["došlo je do greške.uloga nije prome echo json_encode("uloga uspešno promenjena"); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode(["došlo je do greške"]); 39

40 http_response_code(400); echo json_encode(["korisnik već ima odabranu ulogu"]); http_response_code(400); echo json_encode($errors); http_response_code(400); echo json_encode(["zahtev nije u dobrom formatu"]); models/admin/users/deleteuser.php header("content-type:application/json"); if(isset($_post["deluser"])){ require_once "../../../config/connection.php"; require_once "../function.php"; if(isset($_post["delid"])){ $delid=$_post["delid"]; $deletequery="delete FROM korisnici WHERE id=:id"; $prepare=$conn->prepare($deletequery); $prepare->bindparam(":id",$delid); try{ $prepare->execute(); $newlistusers=getusers(); http_response_code(200); echo json_encode($newlistusers); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode("došlo je do greške"); http_response_code(400); echo json_encode("morate izabrati korisnika"); http_response_code(400); echo json_encode(["poslati zahtev nije u dobrom formatu"]); 40

41 models/admin/users/searchuser.php if(isset($_post["search"])){ require_once "../../../config/connection.php"; require_once "../function.php"; if(isset($_post["query"])){ $query=$_post["query"]; $users=getusers($query); http_response_code(200); echo json_encode($users); models/authorization/function.php function verification($code){ global $conn; $updatequery="update korisnici SET verifikacija=1 WHERE verifikacija_k od=:code"; $prepare=$conn->prepare($updatequery); $prepare->bindparam(":code",$code); try{ $prepare->execute(); if($prepare->rowcount()==1){ return true; return false; catch(pdoexception $e){ writeerror($e->getmessage()); return false; models/authorization/logout.php session_start(); unset($_session["user"]); session_destroy(); header("location:../../index.php"); models/authorization/register.php header("content-type:application/json"); if(isset($_post["register"])){ 41

42 require_once "../../config/connection.php"; $errors=[]; $unique=true; $firstnameregex ="/^[A-Z][a-z]{2,14(\s[A-Z][a-z]{2,14)*$/"; $lastnameregex = "/^[A-Z][a-z]{2,24(\s[A-Z][a-z]{2,24)*$/"; $usernameregex="/^[a-zčžćšđčžćšđ0-9\?\!\.]{3,30$/"; $ regex = if(isset($_post["firstname"])){ $firstname=$_post["firstname"]; if(!preg_match($firstnameregex,$firstname)){ $errors[]="ime nije u dobrom formatu"; if(isset($_post["lastname"])){ $lastname=$_post["lastname"]; if(!preg_match($lastnameregex,$lastname)){ $errors[]="prezime nije u dobrom formatu"; if(isset($_post["username"])){ $username=$_post["username"]; if(!preg_match($usernameregex,$username)){ $errors[]="korisničko ime nije u dobrom formatu"; if(isset($_post["mail"])){ $mail=$_post["mail"]; if(!preg_match($ regex,$mail)){ $errors[]="mail nije u dobrom formatu"; if(isset($_post["password"])){ $password=$_post["password"]; if(!preg_match($passwordregex,$password)){ $errors[]="lozinka nije u dobrom formatu"; if(isset($_post["terms"])){ $terms=$_post["terms"]; if(!filter_var($terms,filter_validate_boolean)){ $errors[]="prihvatite uslove korišćenja"; if(!count($errors)){ $uniqueusername=executequery("select * FROM korisnici WHERE userna me='$username'"); 42

43 $uniqu =executequery("select * FROM korisnici WHERE mail='$mai l'"); if(count($uniqueusername)){ $unique=false; $errors[]="korisnik sa takvim imenom već postoji"; if(count($uniqu )){ $unique=false; $errors[]="korisnik sa takvom adresom već postoji"; if($unique){ $insertquery="insert INTO korisnici(ime,prezime,mail,username, sifra,verifikacija_kod,verifikacija,uloga_id) VALUES(:firstName,:lastName,:mai l,:username,:password,:kod,0,3)"; $verificationcode=md5(time().$username); $hasedpassword=md5($password); $prepare=$conn->prepare($insertquery); $prepare->bindparam(":firstname",$firstname); $prepare->bindparam(":lastname",$lastname); $prepare->bindparam(":mail",$mail); $prepare->bindparam(":username",$username); $prepare->bindparam(":password",$hasedpassword); $prepare->bindparam(":kod",$verificationcode); try{ $prepare->execute(); http_response_code(200); echo json_encode($verificationcode); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode(["doslo je do greske"]); http_response_code(400); echo json_encode($errors); http_response_code(400); echo json_encode($errors); http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); 43

44 models/authorization/signin.php session_start(); if(isset($_post["signinbtn"])){ require_once "../../config/connection.php"; $usernameregex="/^[a-zčžćšđčžćšđ0-9\?\!\.]{3,30$/"; $errors=[]; if(isset($_post["logname"])){ $username=$_post["logname"]; if(!preg_match($usernameregex,$username)){ $errors[]="korisnikčko ime nije u dobrom formatu"; if(isset($_post["logpass"])){ $password=$_post["logpass"]; if(!preg_match($passwordregex,$password)){ $errors[]="lozinka nije u dobrom formatu"; if(!count($errors)){ $finduser="select k.*,u.naziv as role FROM korisnici k INNER JOIN uloge u ON k.uloga_id=u.id WHERE k.username=:username AND k.sifra=:password AN D k.verifikacija=1"; $prepare=$conn->prepare($finduser); $prepare->bindparam(":username",$username); $hasedpassword=md5($password); $prepare->bindparam(":password",$hasedpassword); try{ $prepare->execute(); if($prepare->rowcount()==1){ $user=$prepare->fetch(); $_SESSION["user"]=$user; header("location:../../index.php?page=userprofile"); $_SESSION["logInFail"]="Korisničko ime ili lozinka su pog rešni"; header("location:../../index.php?page=authorization"); catch(pdoexception $e){ writeerror($e->getmessage()); $_SESSION["logInFail"]=$errors; 44

45 echo "Niste dobro dosli!"; models/contact/inbox.php header("content-type:application/json"); if(isset($_post["contact"])){ require_once "../../config/connection.php"; $contactnameregex ="/^[A-ZŠĐČŽĆ][a-zšđčćž]{2,19(\s[A-ZŠĐČŽĆ][azšđčćž]{2,19)*$/"; $messageregex = "/^[A-zšđč枊ĐČŽĆ0-9\s\?\.\,\!\"\']{2,$/"; $ regex = $errors=[]; if(isset($_post["name"])){ $name=$_post["name"]; if(!preg_match($contactnameregex,$name)){ $errors[]="ime nije u dobrom formatu"; $errors[]="morate uneti ime"; if(isset($_post[" "])){ $ =$_post[" "]; if(!preg_match($ regex,$ )){ $errors[]=" adresa nije u dobrom formatu"; $errors[]="morate uneti adresu"; if(isset($_post["message"])){ $message=$_post["message"]; if(!preg_match($messageregex,$message)){ $errors[]="poruka nije u dobrom formatu"; $errors[]="morate uneti poruku"; if(count($errors)){ http_response_code(400); 45

46 echo json_encode($errors); $insertquery="insert INTO mejlovi(ime_korisnika,mail,poruka) VALUE S(:name,:mail,:message)"; $prepare=$conn->prepare($insertquery); $prepare->bindparam(":name",$name); $prepare->bindparam(":mail",$ ); $prepare->bindparam(":message",$message); try{ $prepare->execute(); http_response_code(201); echo json_encode(["vaša poruka je uspešno poslata"]); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode(["došlo je do greške"]); http_response_code(400); echo json_encode("zahtev nije u dobrom formatu"); models/mainpage/function.php function getfreshnews(){ $newsquery="select v.*,k.naziv as category,concat(kor.ime,' ',kor.prez ime) as author,s.src as src,s.alt as alt FROM vesti v INNER JOIN kategorije k ON v.kat_id=k.id INNER JOIN autor i a ON a.id=v.autor_id INNER JOIN korisnici kor ON kor.id=a.kor_id INNER JOIN slike s ON s.vest_id=v.id INNER JOIN tip_slike tp ON tp.id=s.tip_id WHERE tp.n aziv='thumbnail' ORDER BY datum DESC LIMIT 0,6"; return executequery($newsquery); function popularnews(){ $popularnewsquery="select v.*,count(k.id) AS comcount FROM vesti v LEF T OUTER JOIN komentari k ON v.id=k.vest_id GROUP BY v.id ORDER BY comcount DES C,v.datum DESC LIMIT 0,4"; return executequery($popularnewsquery); function getsurvey(){ $surveyquery="select a.pitanje,o.* FROM anketa a INNER JOIN odgovori o ON a.id=o.anketa_id WHERE a.aktivna=1"; return executequery($surveyquery); 46

47 models/mainpage/slidernews.php require_once "../../config/connection.php"; $slidernewsquery="select v.*,k.naziv as category,concat(kor.ime,' ',kor.pr ezime) as author,(select COUNT(*) FROM komentari WHERE vest_id=v.id ) as commentcount,s.src as slikasrc,s.alt as slikaalt FROM vesti v INNER JOIN kategorije k ON v.kat_id=k.id INNER JOIN autori a ON a.id=v.autor_id INNER JOIN korisnici kor ON kor.id=a.kor_id INNER JOIN slik e s ON s.vest_id=v.id INNER JOIN tip_slike ts ON ts.id=s.tip_id WHERE ts.naziv ='cover' ORDER BY datum DESC LIMIT 0,3"; header("content-type:application/json"); try{ $slidernews=executequery($slidernewsquery); http_response_code(200); echo json_encode($slidernews); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode($e); models/mainpage/surveyanswer.php header("content-type:application/json"); if(isset($_post["vote"])){ require_once "../../config/connection.php"; $errors=[]; if(isset($_post["answer"])){ $answer=$_post["answer"]; $errors[]="morate izabrati neki odgovor"; if(isset($_post["userid"])){ $userid=$_post["userid"]; $errors[]="morate biti prijavljeni da biste glasali"; if(!count($errors)){ $alreadyvoted="select * FROM korisnik_odgovor ko INNER JOIN odgovo ri o ON o.id=ko.odg_id WHERE kor_id=:user AND o.anketa_id=(select id FROM anke ta WHERE aktivna=1)"; 47

48 $prepare=$conn->prepare($alreadyvoted); $prepare->bindparam(":user",$userid); $prepare->execute(); if($prepare->rowcount()!=0){ http_response_code(400); $errors[]="već ste učestvovali u ovoj anketi"; echo json_encode($errors); $insertquery="insert INTO korisnik_odgovor(kor_id,odg_id) VALU ES(:user,:answer)"; $prepareinsert=$conn->prepare($insertquery); $prepareinsert->bindparam(":user",$userid); $prepareinsert->bindparam(":answer",$answer); try{ $prepareinsert->execute(); http_response_code(201); echo json_encode("hvala za učešće u anketi"); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); $errors[]="došlo je do greške"; $errors[]=$e; echo json_encode($errors); http_response_code(400); echo json_encode($errors); http_response_code(400); echo json_encode("morate biti prijavljeni"); models/news/filternews.php header("content-type:application/json"); if(isset($_post["filter"])){ require_once "../../config/connection.php"; //require_once "function.php"; $errors=[]; if(isset($_post["page"])){ $page=$_post["page"]; 48

49 $page=1; if(isset($_post["categoriesids"])){ $categories=$_post["categoriesids"]; $filterednews=filternews($page,$categories); $filterednews=filternews($page,[]); if($filterednews){ http_response_code(200); echo json_encode($filterednews); http_response_code(400); echo json_encode("zahtev nije dobar"); models/singlenews/function.php function gettags($id){ global $conn; $query="select t.* FROM tagovi t INNER JOIN tag_vest tv ON tv.id_tag=t.id WHERE tv.id_vest=:id"; $prepare=$conn->prepare($query); $prepare->bindparam(":id",$id); try{ $prepare->execute(); $tags=$prepare->fetchall(); return $tags; catch(pdoexception $e){ writeerror($e->getmessage()); return false; function getcomments($id){ global $conn; $query="select kom.*,kor.username FROM komentari kom INNER JOIN korisn ici kor ON kor.id=kom.kor_id WHERE vest_id=:id AND roditelj_id IS NULL"; $prepare=$conn->prepare($query); $prepare->bindparam(":id",$id); try{ $prepare->execute(); $comments=$prepare->fetchall(); 49

50 return $comments; catch(pdoexception $e){ writeerror($e->getmessage()); return false; //Funkcija namenjena da ajax-om za JS vrati sve odgvore na komentare function getallreplies($id){ global $conn; $query="select kom.*,kor.username FROM komentari kom INNER JOIN korisn ici kor ON kor.id=kom.kor_id WHERE vest_id=:id AND roditelj_id IS NOT NULL"; $prepare=$conn->prepare($query); $prepare->bindparam(":id",$id); try{ $prepare->execute(); $comments=$prepare->fetchall(); return $comments; catch(pdoexception $e){ writeerror($e->getmessage()); return false; function getreplies($id){ global $conn; $query="select kom.*,kor.username FROM komentari kom INNER JOIN korisn ici kor ON kor.id=kom.kor_id WHERE roditelj_id=:id"; $prepare=$conn->prepare($query); $prepare->bindparam(":id",$id); try{ $prepare->execute(); $comments=$prepare->fetchall(); return $comments; catch(pdoexception $e){ writeerror($e->getmessage()); return false; function countcomments($id){ $query="select COUNT(*) AS count FROM komentari WHERE vest_id=$id"; return executequery($query); function relatednews($catid,$tagsarr,$currentnewsid){ global $conn; 50

51 $inclause=implode($tagsarr,","); $relatedquery="select v.*,s.src as src,s.alt as alt FROM vesti v INNER JOIN slike s ON s.vest_id=v.id INNER JOIN tip_slike ts ON ts.id=s.tip_id INNE R JOIN tag_vest tv ON tv.id_vest=v.id WHERE ts.naziv='thumbnail' AND v.id!=$cu rrentnewsid AND (v.kat_id=$catid OR tv.id_tag IN ($inclause)) GROUP BY v.id LI MIT 0,4"; $related=executequery($relatedquery); if(count($related)==0){ return executequery("select v.*,s.src as src,s.alt as alt FROM ves ti v INNER JOIN slike s ON s.vest_id=v.id INNER JOIN tip_slike ts ON ts.id=s.t ip_id INNER JOIN tag_vest tv ON tv.id_vest=v.id WHERE ts.naziv='thumbnail' AND v.id!=$currentnewsid GROUP BY v.id LIMIT 0,4"); return $related; models/singlenews/addcomment.php header("content-type:application/json"); $errors=[]; if(isset($_post["addcomment"])){ require_once "../../config/connection.php"; require_once "function.php"; if(isset($_post["reply"]) &&!empty($_post["reply"])){ $reply=$_post["reply"]; $errors=["komentar ne sme biti prazan"]; if(isset($_post["user"])){ $userid=$_post["user"]; $errors[]="morate biti ulogovani"; if(isset($_post["newsid"])){ $newsid=$_post["newsid"]; $errors[]="vest ne psotojhi"; if(isset($_post["parentcomment"])){ $parentcomment=$_post["parentcomment"]; $parentcomment=null; 51

52 if(!count($errors)){ $query="insert INTO komentari(vest_id,tekst,kor_id,roditelj_id) VA LUES(:newsId,:reply,:userId,:parent)"; $prepare=$conn->prepare($query); $prepare->bindparam(":newsid",$newsid); $prepare->bindparam(":reply",$reply); $prepare->bindparam(":userid",$userid); $prepare->bindparam(":parent",$parentcomment); try{ $prepare->execute(); $allcomments=getcomments($newsid); $allreplies=getallreplies($newsid); $commentcounts=countcomments($newsid)[0]; http_response_code(200); echo json_encode(["comments"=>$allcomments,"replies"=>$allrepl ies,"commentscount"=>$commentcounts]); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode($e); http_response_code(400); echo json_encode($errors); http_response_code(400); $errors[]="zahtev nije u dobarom formatu"; echo json_encode($errors); models/singlenews/deletecomments.php if(isset($_post["deletecomm"])){ require_once "../../config/connection.php"; require_once "function.php"; header("content-type:application/json"); if(isset($_post["deleteid"])){ $deleteid=$_post["deleteid"]; $deletequery="delete FROM komentari WHERE id=:id"; $prepare=$conn->prepare($deletequery); $prepare->bindparam(":id",$deleteid); try{ $prepare->execute(); 52

53 http_response_code(200); echo json_encode("uspelo je sve"); catch(pdoexception $e){ writeerror($e->getmessage()); http_response_code(500); echo json_encode($e); http_response_code(400); echo json_encode("poslat zahtev nije u dobrom formatu!"); models/tagnews/function.php function getnewsbytags($tagid){ global $conn; $query="select v.*,k.naziv AS category,concat(kor.ime,' ',kor.prezime) AS author,s.src FROM tag_vest tv INNER JOIN vesti v ON tv.id_vest=v.id INNER JOIN tagovi t ON t.id=tv.id_tag INNER JOIN kategorije k ON v.kat_id=k.id INNER JOIN autori a ON v.autor_id=a.id INNER JOIN korisnici kor ON kor.id=a.kor_id INNER JOIN slike s ON s.vest_id=v.id INNER JOIN tip_slike ts ON ts.id=s.tip_id WHERE ts.naziv='thumbnail' AND tv.id_tag=:tag"; $prepare=$conn->prepare($query); $prepare->bindparam(":tag",$tagid); try{ $prepare->execute(); $newsbytag=$prepare->fetchall(); $tagname=executequery("select naziv FROM tagovi WHERE id=$tagid"); return ["news"=>$newsbytag,"tag"=>$tagname]; catch(pdoexception $e){ writeerror($e->getmessage()); return false; models/userprofile/changeinfo.php session_start(); if(isset($_post["changeinfo"])){ require_once "../../config/connection.php"; $usernameregex="/^[a-zčžćšđčžćšđ0-9\?\!\.]{3,30$/"; $errors=[]; 53