htmlinternational $cfg->htmlspecial $cfg->nltobr - kan ersättas med templateklassens egna värden, se fixConfig Todo 08: fixConfig - skip or fix? */ class ArtoTemplate { var $debug=1; // 0 = no error report, 1 = output directly var $editmode=false; function ArtoTemplate() { $args = func_get_args(); $this->tmplfile=$args[0]; $this->tmplvars=$args[1]; // array $this->dbconn=$args[2]; $this->fixConfig(); } function fixConfig() { global $cfg; $conf_values=array("htmlspecial","htmlinternational","nltobr","encoding","makelinks"); foreach ($conf_values as $nm) { if (!isset($this->$nm)) { $this->$nm=$cfg->$nm; } } } # make mysqlquery-method that returns mysql result, doesn't work default function mysqlquery($sql) { return false; # måste fixas funktion i respektive jobbarclass (ex Inform) } function parse($newarray,$htmlstring) { $this->checkNested($htmlstring); if ($this->nestedfirst=="if") { $htmlstring=$this->parseIf($newarray,$htmlstring); $htmlstring=$this->parseIteratesql($newarray,$htmlstring); } else { $htmlstring=$this->parseIteratesql($newarray,$htmlstring); $htmlstring=$this->parseIf($newarray,$htmlstring); } $htmlstring=$this->parseFields($newarray,$htmlstring); $htmlstring=$this->parseDate($newarray,$htmlstring); $htmlstring=$this->parseImg($newarray,$htmlstring); return $htmlstring; } function checkNested($str) { $this->nestedfirst=""; if (preg_match("/@if#([^@]+)@.*?@iteratesql.*?@endif@/s",$str)) { $this->nestedfirst="if"; } } # %()something()% or %{}something{}% or just %something% function parseFields($fields,$htmlstring) { foreach ($fields as $fieldname=>$value) { // ereg('%\(([^)]*)\)'.$fieldname.'\(([^)]*)\)%',$htmlstring,$matches); // lagt till måsvinge som alternativ, om man vill ha () i sin template: file:///var/www/nk/inform/system/incl/templateclass.php while (preg_match('/%\(([^\)]*)\)'.$fieldname.'\(([^\)]*)\)%/',$htmlstring,$matches) || preg_match('/%\{([^}]*)\}'.$fieldname.'\{([^}]*)\}%/',$htmlstring,$matches) || preg_match('/%'.$fieldname.'%/',$htmlstring,$matches)) { // ooops att ha på samma: ereg('%[\({]([^\)]|[^}]*)[\)}]'.$fieldname.'[\({]([^\)]|[^}]*)[\)}]%',$htmlstring,$matches) belv för mycet.. if (!empty($value)) { if ((isset($this->htmleditorvalues) && is_array($this->htmleditorvalues) && in_array($fieldname,$this->htmleditorvalues)) && !(isset($this->templateformat) && $this->templateformat=="xml")) { $textvalue=$value; } else { $textvalue=$this->fixTextvalue($value); } $htmlstring = @str_replace($matches[0],$matches[1].$textvalue.$matches[2],$htmlstring); } else { $htmlstring = str_replace($matches[0],"",$htmlstring); } } } return $htmlstring; } function parseIf($fields,$htmlstring) { /* example @if#imgbig@
%{
}% @else@ ingen stor bild här... @endif@*/ while (preg_match("/@if#([^@]+)@(.*?)@endif@/s",$htmlstring,$matches)) { $iftrue=""; $iffalse=""; $fieldname=$matches[1]; #while ((preg_match("/@elseif#".$fieldname."@(.*?)@endif@/",$matches[1],$ifparts)) - här kan man fortsätta kolla flera... # check what parts of code we will use for parsing: if (preg_match("/^(.*)@else@(.*)$/s",$matches[2],$ifparts)) { $iftrue=$ifparts[1]; $iffalse=$ifparts[2]; } else { $iftrue=$matches[2]; } # check what part to use: if (isset($fields[$fieldname]) && !empty($fields[$fieldname])) { $htmlpart=$iftrue; } else { $htmlpart=$iffalse; } # parse the correct part $htmlpart=$this->parse($fields,$htmlpart); # replace the if-protion of the whole htmlstring with the parsed code $htmlstring = str_replace($matches[0],$htmlpart,$htmlstring); } return $htmlstring; } function parseIteratesql($fields,$htmlstring) { /* example, must start with select @iteratesql#select * from inform_trpict, inform_trshow_trpict where inform_trshow_trpict.trpict=inform_trpict.id_no and inform_trshow_trpict.trshow=%()id_no()%@ %()header()% %()imgthumb()% %()imgbig()% @enditeratesql@ @loopsql#select * from inform_trpict, inform_trshow_trpict where inform_trshow_trpict.trpict=inform_trpict.id_no and inform_trshow_trpict.trshow=%()id_no()%@ %()header()% %()imgthumb()% %()imgbig()% @endloopsql@ */ while (preg_match("/@(iterate|loop)sql#(select[^@]+)@(.*?)@end(iterate|loop)sql@/s",$htmlstring,$matches)) { $newstr=""; $sql=$matches[2]; $htmlpart=$matches[3]; // sql can hold fields to change $sql=$this->parse($fields,$sql); $res=$this->mysqlquery($sql); if ($res) { while ($row = mysql_fetch_assoc($res)) { # parse the correct part with new fields from select $this->subCurrentRow=$row; $newstr.=$this->parse($row,$htmlpart); } mysql_free_result($res); } # replace the iterate-protion of the whole htmlstring with the parsed code $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } return $htmlstring; } function parseDate($fields,$htmlstring) { /* examples @date#nd@ %Y-%m-%d @enddate@ Date format to use at: http://se.php.net/strftime with locale format @date#newsdate#sv_SE@%A %e %B %Y@enddate@ */ $newstr=""; while (preg_match("/@date#([^#@]+)#?([^@]*)@(.*?)@enddate@/s",$htmlstring,$matches)) { if ($matches[2]) setlocale(LC_TIME, $matches[2]); $thedate=$fields[$matches[1]]; $dateformat=$matches[3]; $newstr=strftime($dateformat,strtotime($thedate)); $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } return $htmlstring; } # see also img in Inform class - imgcode is more general function parseImg($fields,$htmlstring) { /* examples @imgcode#path#imgfile#additionalattributes@ */ while (preg_match("/@imgcode#([^#@]+)#?([^@]+)#([^#@]*)?@/s",$htmlstring,$matches)) { $newstr=""; if (isset($fields[$matches[1]])) { $path=$fields[$matches[1]]; if (!preg_match("#/$",$path."#")) $path.="/"; } if (isset($fields[$matches[2]])) { $imgfile=$fields[$matches[2]]; } if (file_exists($path.$imgfile)) { $size=getImageSize($path.$imgfile); $sizestr=$size[3]; $attr=($matches[3])?$this->parseFields($fields,$matches[3]):""; $newstr=''; } $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } /* examples @imgwidth#path#imgfile@ @imgheight#path#imgfile@ */ while (preg_match("/@img(width|height)#([^#@]+)#?([^@]*?)@/s",$htmlstring,$matches)) { $newstr=""; $sizetype=($matches[1]=="width")?0:1; if (isset($fields[$matches[2]])) { $path=$fields[$matches[2]]; if (!preg_match("#/$",$path."#")) $path.="/"; } if (isset($fields[$matches[3]])) { $imgfile=$fields[$matches[3]]; } if (is_file($path.$imgfile)) { $size=getImageSize($path.$imgfile); $sizestr=$size[3]; $attr=($matches[3])?$this->parseFields($fields,$matches[3]):""; $newstr=''; } $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } return $htmlstring; } # fixes text for output according to config values and editmode function fixTextvalue($textvalue) { $textvalue = stripslashes($textvalue); if (isset($this->htmlinternational) && $this->htmlinternational) { $textvalue=htmlentities($textvalue, ENT_COMPAT, $this->encoding_cms); } elseif (isset($this->htmlspecial) && $this->htmlspecial) { // never use both at the same time $textvalue=htmlspecialchars($textvalue, ENT_COMPAT, $this->encoding_cms); } if (isset($this->nltobr) && $this->nltobr) // this has to be after special or entities $textvalue=nl2br($textvalue); if (isset($this->makelinks) && $this->makelinks) { $testvalue=$textvalue; // the while loop has separate test value to avoid endless loops while (preg_match("#(https?://)([\?\&=;/\.a-zA-Z0-9_\-]+)#",$testvalue,$m)) { if ($m[2]) { $cleanlinkname=preg_replace("/[\.\/]+$/","",$m[2]); // remove trailing . and / $prot=(empty($m[1]))?"http://":$m[1]; $link=''.$cleanlinkname.''; } $textvalue=str_replace($m[0],$link,$textvalue); $testvalue=str_replace($m[0],"",$testvalue); } } if ($this->editmode) { // text is used in text boxes $textvalue=str_replace('"',""",$textvalue); } return $textvalue; } // determines what to do with errors... function errorReport($error,$info) { if ($error && $this->debug==1) { echo $error; echo "
\nAdditional info: ".$info; } } } ?>navpage=$_GET['start']; else $this->navpage=0; //$start,$noRecs,$end_value - for navigation - altered to be class variables $this->noRecs=0; // default value $this->end_value=0; // default value $this->counter=0; // for use in parseTemplate $this->currentRow=array(); $this->templatevars=array(); $this->module=@$args[0]; // Register objects $this->registerGlobals(); // fix config from cfg obj $this->fixConfig(); } function registerGlobals() { global $cfg,$files; // Register objects and variables $registry = &Registry::getInstance(); // fix the language part: $fileName='map_'.$cfg->lang.'.php'; $absolutePath=$cfg->langpath.$fileName; if (!file_exists($absolutePath)) { $absolutePath=$cfg->langpath.'map_sv.php'; } include($absolutePath); # $registry =& Registry::getInstance(); $registry->set ('lang_maps', $lang_maps); $registry->set ('cfg', $cfg); $registry->set ('files', $files); // TODO: check out where this is referenced - rather use below versions instead // echo "MODULE: ".$this->module; $registry->set ('files_'.$this->module, $files); $this->files = $files; } // all config that is overwritable is fixed here, default value is the $cfg object // $this is used instead of cfg in object // this is done once function fixConfig($force=false) { static $done=false; if (!$done or $force) { // first - import all config values to this object $registry = &Registry::getInstance(); $cfg = &$registry->get('cfg'); // TODO : check out if we need this anywhere, otherwise just in registergobals /* $files = &$registry->get('files'); echo "files_".$this->module."
"; $this->files = &$registry->get('files_'.$this->module); print_r($this->files);*/ foreach ($cfg as $nm=>$val) { if ($nm=="templatevars") { $lang_maps=&$registry->get('lang_maps'); $this->$nm=array_merge($cfg->$nm,$this->$nm,$lang_maps); } else { $this->$nm=$val; } } // all done here $done=true; // check max file upload size: if (preg_match("/^(\d+)\s*M$/",ini_get('post_max_size'),$m)) { $postmax=$m[1]; } if (preg_match("/^(\d+)\s*M$/",ini_get('upload_max_filesize'),$m)) { $uplmax=$m[1]; } $max=min($postmax,$uplmax); // take the minimum of php config and what the user sets... if (isset($cfg->maxfileweight) && $cfg->maxfileweight>0) { $this->maxfileweight=min($max*1000000,$cfg->maxfileweight); } else { $this->maxfileweight=$max*1000000; } // extra nav for filters added: $default=array( "filter", "sorttype", "sortby", "q" ); $this->navfollow=array_merge($default,$this->navfollow); } } // sets internal vars - those are used n SQL statements when called. // taken from $Inform->templates set in module config function fixSQLVars($template="inform") { $this->int=$this->templates[$template]["listsize"]; $this->shownav=$this->templates[$template]["shownav"]; $this->extraselect=$this->templates[$template]["extraselect"]; $this->whereln=$this->templates[$template]["whereln"]; $this->order=$this->templates[$template]["order"]; // added 09 $this->left=isset($this->templates[$template]["left"])?$this->templates[$template]["left"]:$this->left; $this->left_disabled=isset($this->templates[$template]["left_disabled"])?$this->templates[$template]["left_disabled"]:$this->left_disabled; $this->right=isset($this->templates[$template]["right"])?$this->templates[$template]["right"]:$this->right; $this->right_disabled=isset($this->templates[$template]["right_disabled"])?$this->templates[$template]["right_disabled"]:$this->right_disabled; $this->right2left=isset($this->templates[$template]["right2left"])?$this->templates[$template]["right2left"]:$this->right2left; $this->delimiter=isset($this->templates[$template]["delimiter"])?$this->templates[$template]["delimiter"]:$this->delimiter; $this->extranav=isset($this->templates[$template]["extranav"])?$this->templates[$template]["extranav"]:$this->extranav; $this->extranav=isset($this->templates[$template]["extranav"])?$this->templates[$template]["extranav"]:$this->extranav; $this->navfollow=isset($this->templates[$template]["navfollow"])?$this->templates[$template]["navfollow"]:$this->navfollow; $this->showpageno=isset($this->templates[$template]["showpageno"])?$this->templates[$template]["showpageno"]:$this->showpageno; //echo " $template: $this->whereln
"; if (isset($this->templates[$template]["format"]) && $this->templates[$template]["format"]=="xml") { $this->htmlspecial=true; // & -> & $this->htmlinternational=false; // å -> å $this->nltobr=false; // \n ->
$this->templateformat="xml"; } elseif (isset($this->templates[$template]["format"]) && $this->templates[$template]["format"]=="text") { $this->htmlspecial=false; // & -> & $this->htmlinternational=false; // å -> å $this->nltobr=false; // \n ->
$this->templateformat="text"; } elseif (isset($this->templates[$template]["format"]) && $this->templates[$template]["format"]=="flashxml") { // NK speciale ;-) $this->htmlspecial=true; // & -> & $this->htmlinternational=false; // å -> å $this->nltobr=true; // \n ->
$this->templateformat="flashxml"; } else {// default is always html $this->htmlspecial=true; // & -> & $this->htmlinternational=true; // å -> å $this->nltobr=true; // \n ->
$this->templateformat="html"; } } function setTemplate($template,$array) { if (!is_array($this->templates)) $this->templates=array(); $this->templates[$template]=$array; } // retreive the connection for inform function getConnVar() { $registry = &Registry::getInstance(); $conn = &$registry->get('conn'); if ((gettype($conn)!="resource") or !mysql_ping($conn)) { $conn = mysql_connect($this->mysql_server,$this->mysql_user,$this->mysql_password,true); if (!$conn) { echo $this->getTranslation('ERROR_DBCONNECT'); } if (!mysql_select_db($this->mysql_database,$conn)) { echo $this->getTranslation('ERROR_DBSELECT'); } mysql_query("SET NAMES '".str_replace("-","",$this->encoding_db)."';",$conn); echo mysql_error(); $registry->set('conn',$conn); if (!$conn) $this->debugReport("Error when making new connection to db $this->mysql_server,$this->mysql_user",__LINE__,__FILE__); } return $conn; } // retreive the language strings function getTranslationMapVar() { $registry = &Registry::getInstance(); $map = &$registry->get('lang_maps'); return $map; } // fix some nicer looking limits in inform function fixInformTemplateVars() { $this->templatevars['maxpictweight']=size_readable($this->maxpictweight); $this->templatevars['maxfileweight']=size_readable($this->maxfileweight); } // create list out of template, of database items function makeList($template) { return $this->makeListTpl($template); } // show list of items function showListTpl($template) { echo $this->makeListTpl($template); } // show list of database items using templates // use column "alternative" for alternative template, default is toggle <- note test this thourougly! // use column "markup" for addition to template %markup% // template now has nothing to do with the file - it's instead the template config name... "inform" is default ad is required function makeListTpl($template) { if (!array_key_exists($template,$this->templates)) { echo "Template $template does not exist."; exit; } // lägg till $this->templ_path. ? $listtemplate=$this->templ_path.$this->templates[$template]["templatefile"]; //$onetemplate=$this->templ_path.$this->templates[$template]["templatefile_single"]; $futuretpl=(isset($this->templates[$template]["templatefile_future"]))?$this->templ_path.$this->templates[$template]["templatefile_future"]:""; $togglestate=false; $str=""; // count the rows in this result: $res=$this->mysqlquery($this->createCountSQL($template)); if ($res) { $row = mysql_fetch_array($res); $this->noRecs=$row[0]; unset($row); } // sql select for the list $res=$this->mysqlquery($this->createListSQL($template)); if ($res) { if ($this->noRecs==1 && $onetemplate) { $this->currentRow = mysql_fetch_assoc($res); $str=$this->parseTemplate($onetemplate); } else { while ($this->currentRow = mysql_fetch_assoc($res)) { if (isset($this->currentRow["markup"]) && $this->currentRow["markup"]) { $this->templatevars['markup']=@$this->markuptrue; } else { $this->templatevars['markup']=@$this->markupfalse; } if ($togglestate) $this->templatevars['togglevar']=@$this->toggletrue; else $this->templatevars['togglevar']=@$this->togglefalse; // deprecated future template... if file exists - go with that. if (isset($this->currentRow["future"]) && $this->currentRow["future"] && $futuretpl && file_exists($futuretpl)) $str.=$this->parseTemplate($futuretpl); else $str.=$this->parseTemplate($listtemplate); $togglestate=!$togglestate; } } mysql_free_result($res); } return $str; } // show one database item function showOne($id) { echo $this->makeOneItem($id); } function makeOneItem($id) { return $this->makeOneTpl($id,"inform"); } // show one database item function showOneTpl($id,$template="inform") { echo $this->makeOneTpl($id,$template); } function makeOneTpl($id,$template) { # $this->fixConfig(); $str=""; //$this->fixSQLVars($template); $templatefile=$this->templ_path.$this->templates[$template]["templatefile_single"]; $res=$this->mysqlquery($this->createOneSQL($id,$template)); if ($res) { while ($this->currentRow = mysql_fetch_assoc($res)) { $str.=$this->parseTemplate($templatefile); } mysql_free_result($res); return $str; } else { return false; } } // show one database item function showEdit($id,$template="inform") { $this->fixInformTemplateVars(); //$this->fixSQLVars(); $templatefile=$this->templ_path.$this->templates[$template]["templatefile_single"]; $res=$this->mysqlquery($this->createOneSQL($id)); if ($res) { while ($this->currentRow = mysql_fetch_assoc($res)) { // ska man ha whila h?r eller b?ttre med bara en? echo $this->parseTemplate($templatefile,true); } mysql_free_result($res); } } // show add new page function showEditNew($template="inform") { $this->fixInformTemplateVars(); $this->fixSQLVars($template); //echo $this->templ_path.$this->templates[$template]["templatefile_single"]." stämmer det?"; $templatefile=$this->templ_path.$this->templates[$template]["templatefile_single"]; echo $this->parseTemplate($templatefile,true,true); } /* // show add new page function showEditNewWidget() { $this->fixInformTemplateVars(); $templatefile=$this->templ_path.$this->templates["inform"]["templatefile_widget"]; echo $this->parseTemplate($templatefile,true,true); }*/ // add new to db, and return message for output function addeditItem($edit,$input) { global $tables; //$files = $this->files; // with something with $this->files instead - but it's empty - why? $this->error=false; $conn=$this->getConnVar(); # $this->fixConfig(); $message=""; // files and images is dealt with if (is_array($this->files)) { $fileSize=0; list($message,$input)=$this->checkUploadFilearray($input); if ($this->error) { $message=''.$message.'
'; } } // iterate through default values to clear if the same: if (is_array($input['defaultvalues'])) { foreach ($input['defaultvalues'] as $no=>$namevalue) { list($key,$val)=explode("=",$namevalue); if ($input[$key]==$val) { $input[$key]=""; // erease from db if value is not altered } } } // include for specialised input: if (file_exists($this->informpath."config/modules/".$this->module."/incl_addnew.php")) { include($this->informpath."config/modules/".$this->module."/incl_addnew.php"); } // some kind of wordpress hack for slashes to work, WP adds slashes to POST variables even if magic quotes is off :/ $input=$this->fixWPVars($input); if (!empty($edit)) { $set_line=$tables[$this->mysql_table]->createUpdateStringFor($edit,$input); //echo ''; $this->mysqlquery($set_line); $id=$edit; // modified for brokk: if (empty($set_line)) { $this->brokk_emptyupdate=true; } else if ($this->error) { $message.=$this->getTranslation('UPDATE_FAILED'); } else { $message.=$this->getTranslation('NOW_UPDATED'); } $this->userReport("edit","","",$set_line."\n".$message); } else { $set_line=$tables[$this->mysql_table]->createInsertString($input); //echo ''; $this->mysqlquery($set_line); $id=mysql_insert_id(); if ($this->error) { $message.=$this->getTranslation('NEWENTRY_FAILED'); } else { $message.=$this->getTranslation('NOW_NEWENTRY'); } $this->userReport("add","","",$set_line."\n".$message); } $this->last_insert_id=$id; // both edit adn insert mind you! if (!empty($this->viewurl)) { $message.=' viewurl).'" target="_blank">'.$this->getTranslation('LNK_SHOW_PREVIEW').''; } $err=mysql_error(); $this->saveWidgets($id,$input); // include for specialised input in other tables - after insert or update: if (file_exists($this->informpath."config/modules/".$this->module."/incl_afterupdate.php")) { $currentid=$id; include($this->informpath."config/modules/".$this->module."/incl_afterupdate.php"); } $this->lastmessage.=$message; return $this->lastmessage; } # check fileArray, created in a fileclass (ULFile) object # upload, and set globals function checkUploadFilearray($input) { $files=$this->files; if (is_array($files)) { foreach ($files as $nr=>$tempObj) { $files[$nr]->lastaction=false; if ($_REQUEST[$files[$nr]->htmlDelete]) { if ($this->deleteFiles($nr,$input[$files[$nr]->htmlDelete])) { $input[$files[$nr]->dbcol]=""; // clear db field too } } if ($_FILES[$files[$nr]->htmlname]['name']!="" && $_FILES[$files[$nr]->htmlname]['tmp_name']) { $input[$files[$nr]->dbcol]=$files[$nr]->upload(0); // 1 for verbose, 0 for silent if (!empty($files[$nr]->lastError)) { $this->error=true; // trigger error in item too... } else { $fileSize+=$files[$nr]->fileBytes(); $files[$nr]->lastaction="add"; } } $message.=$files[$nr]->lastMsg.$files[$nr]->lastError; # if file is image: if (!empty($files[$nr]->fileName) && $files[$nr]->isImg) { $this->makeImageSizes($nr); $input[$files[$nr]->dbcol]=$files[$nr]->fileName; // filename could be changed $message.=$files[$nr]->lastMsg.$files[$nr]->lastError; } if ($files[$nr]->lastError) { $this->error=true; } } if ($fileSize>20000000000) { $this->error=true; $message.=$this->getTranslation('ERROR_BIG_FILES'); } #if (count($files)>1 && $fileSize>0) { # $message.="Filstorlek, totalt: ca ".round($fileSize/1000)." kb
"; #} } else { $this->error=true; $message.=$this->getTranslation('ERROR_FILEARRAY_MISSING'); } return array($message,$input); } // $nr is a reference to file array, directory is added to filename later // this is called when a single file is deleted from item and when a full item is deleted function deleteFiles($nr,$filename) { $files=$this->files; $success=$files[$nr]->deleteFile($filename); // image sizes if (isset($this->imagesizes[$nr])) { foreach ($this->imagesizes[$nr] as $prefix=>$settings) { $files[$nr]->deleteFile($prefix.$filename); } } $cahcefiles=glob($this->cachepath."[0-9]*_".$filename); foreach ($cahcefiles as $cahcedfile) { unlink($cahcedfile); } return $success; } function makeImageSizes($nr) { $files=$this->files; if (!empty($files[$nr]->fileName) && $files[$nr]->isImg) { $files[$nr]->changeSize(0); // 1 = verbose // create some extra sizes for images if there is config for that if (isset($this->imagesizes[$nr])) { // uploaded file, new prefix $oldsrc=$files[$nr]->directory.$files[$nr]->fileName; if (file_exists($oldsrc)) { foreach ($this->imagesizes[$nr] as $prefix=>$settings) { $newsrc=$files[$nr]->directory.$prefix.$files[$nr]->fileName; $GD=new Inform_Imagelib(); if ($GD->enabled()) { $GD->resizeMaxWH($oldsrc,$settings["w"],$settings["h"],$newsrc,true,$settings["crop"]); return $files[$nr]->fileName; // returns filename on success (convinient though not necessary since it's stored in files object) } } } } } } function deleteRelations($id,$input) { if (!$this->error) { // deleteing relations for widgets foreach ((array) $this->widgets as $widget=>$widgetarr) { if (array_key_exists("sql_rel_delete_mother",$widgetarr)) { $sql=$widgetarr["sql_rel_delete_mother"]; $sql=str_replace("%motherid%",$id,$sql); $this->mysqlquery($sql); } } } } function saveWidgets($id,$input) { // this was earlier in afterupdate file so please see to it that it doesn't hold that code too! foreach ((array) $this->widgets as $widget=>$widgetarr) { if (isset($input["widget_$widget"])) { // eg "widget_media" if it's the media module it's connected to foreach ($input["widget_$widget"] as $k=>$childid) { $childid=preg_replace("/^".$widget."_/","",$childid); if (array_key_exists("sql_rel_insert",$widgetarr)) { $sql=$widgetarr["sql_rel_insert"]; $sql=str_replace("%motherid%",$id,$sql); $sql=str_replace("%childid%",$childid,$sql); $this->mysqlquery($sql); } else if (array_key_exists("relation_mother_key",$widgetarr)) { // old one will be removed global $tables; $xtraset=""; // standard naming on table name, but we need to test if it's a general one: if (isset($tables[$widgetarr["relation_table"]]->keys['table_name'])) { $xtraset="table_name='".$this->mysql_table."',"; } $sql="insert into ".$widgetarr["relation_table"]." set $xtraset ".$widgetarr["relation_mother_key"]."='".$id."', ".$widgetarr["relation_child_key"]."='$childid';"; $this->mysqlquery($sql); } //echo $sql; } } if (isset($input["widget_delete_$widget"])) { // uses table key...! foreach ($input["widget_delete_$widget"] as $k=>$childid) { $childid=preg_replace("/^".$widget."_/","",$childid); if ($widgetarr["behaviour"]=="direct") { $this->deleteChildItem($widgetarr["child_module"],$childid); } else if (array_key_exists("sql_rel_delete_one",$widgetarr)) { $sql=$widgetarr["sql_rel_delete_one"]; $sql=str_replace("%motherid%",$id,$sql); $sql=str_replace("%childid%",$childid,$sql); $this->mysqlquery($sql); } else if (array_key_exists("relation_mother_key",$widgetarr)) { // old one will be removed global $tables; $xtraset=""; // standard naming on table name, but we need to test if it's a general one: if (isset($tables[$widgetarr["relation_table"]]->keys['table_name'])) { $xtraset="table_name='".$this->mysql_table."' and "; } $sql="delete from ".$widgetarr["relation_table"]." where $xtraset ".$widgetarr["relation_mother_key"]."='".$id."' and ".$widgetarr["relation_child_key"]."='$childid';"; $this->mysqlquery($sql); } //echo $sql; } } } } // delete item, and return message for output function deleteItem($id) { global $tables,$files; //=$this->files; $conn=$this->getConnVar(); $message=""; $currentid=$id; // old reference in include files...please keep // include for specialised input in other tables - before delete if (file_exists($this->informpath."config/modules/".$this->module."/incl_beforedelete.php")) { include($this->informpath."config/modules/".$this->module."/incl_beforedelete.php"); } if (is_array($files) && !empty($files)) { foreach ($files as $nr=>$fileObj) { if (get_class($fileObj)=='Inform_ULFile') { $sql="select ".$fileObj->dbcol." from ".$this->mysql_table." where ".$this->tableid."='$id'"; $res = $this->mysqlquery($sql); if ($res) { $row = mysql_fetch_array($res); if (!empty($row[0])) { $this->deleteFiles($nr,$row[0]); } mysql_free_result($res); } } } } $sql="delete from ".$this->mysql_table." where ".$this->tableid."='$id'"; if (mysql_query($sql,$conn)) { if (mysql_affected_rows()==1) { $message.=$this->getTranslation('DELETE_OK').' (#'.$id.')'; $this->deleteid=$id; } else { $this->error=true; $message.=''.$this->getTranslation('ERROR_DELETE_FAILED').' '.mysql_affected_rows().' (#'.$id.')'; } $this->userReport("delete","","",$message); $this->errorReport(mysql_error(),$sql); } // clean up relation tables (needs config) $this->deleteRelations($id,$input); // include for special things to execute after delete if (file_exists($this->informpath."config/modules/".$this->module."/incl_afterdelete.php")) { include($this->informpath."config/modules/".$this->module."/incl_afterdelete.php"); } $this->lastmessage.=$message; return $this->lastmessage; } // deletes child item if it's directly related to mother module function deleteChildItem($childmodule,$childid) { global $cfg; $oldcfg=$cfg; $p=$this->informpath."config/modules/$childmodule/"; include($p."config_module.php"); $Child=new Inform(); $Child->fixConfig(true); $cfg=$oldcfg; $Child->editmode=true; $Child->templ_path=$p; $Child->module=$module; $Child->files=$files; // is not made global, phew. How do we make the same for module? return $Child->deleteItem($childid); } // favicon / wordpress icon function getFavIcon() { if (!empty($this->override_fav) and file_exists($this->informpath.$this->override_fav)) { $img=$this->informurl.$this->override_fav; } else { $img=$this->informurl."system/theme/img/informfav.png"; } return $img; } // create...functions // make a sql query out of globals function createCountSQL($template="inform") { $this->fixSQLVars($template); # $this->fixConfig(); //$this->handleDates(); $version=substr(sprintf("%s", mysql_get_server_info()),0,3); if ((float) $version>=4.1) { return "select count(*) from (select * ".$this->extraselect." from ".$this->mysql_table." ".$this->whereln." ".$this->order.") as cnt"; } else { return "select count(distinct ".$this->tableid.") as cnt from ".$this->mysql_table." ".$this->whereln; } } function createListSQL($template="inform") { $this->fixSQLVars($template); // fix some other vars: $this->start_value = $this->navpage*$this->int; $this->end_value = $this->start_value+$this->int; //$this->handleDates(); return "select ".$this->mysql_table.".* ".$this->extraselect." from ".$this->mysql_table." ".$this->whereln." ".$this->order. " limit ".$this->start_value.",".$this->int; } function createOneSQL($id,$template="inform") { $this->fixSQLVars($template); //$this->handleDates(); $where=$this->appendToWhereln($this->tableid."='".mysql_real_escape_string($id)."'"); return "select ".$this->mysql_table.".* ".$this->extraselect." from ".$this->mysql_table." ".$where." ".((preg_match("/group\s+by/",$this->order))?$this->order:''); } function appendToWhereln($str) { // apeends string to user wehereln and returns new str # $this->fixConfig(); $tmp=preg_replace("/^\s*$/","",$this->whereln); $where=($tmp)?$tmp." and ":" where "; return $where.$str; } // use whereln istead of this...not in use right now. // bug: check this out and then uncomment lines above function handleDates() { # $this->fixConfig(); #$cfg->startdate="newsdate"; // main date #$cfg->enddate=""; // if ending date #$cfg->handledate="onlyfuture"; // can be "hidefuture", "onlyfuture" - hidden only affects outside of inform... if (!$this->editmode) { if ($this->startdate) { if ($this->handledate=="onlyfuture") { if ($this->enddate) { $where=$this->appendToWhereln("to_days(".$this->enddate.")>=to_days(now())"); } else { $where=$this->appendToWhereln("to_days(".$this->startdate.")>=to_days(now())"); } } else if ($this->handledate=="hidefuture") { if ($this->enddate) { $where=$this->appendToWhereln("to_days(".$this->enddate.")<=to_days(now())"); } else { $where=$this->appendToWhereln("to_days(".$this->startdate.")<=to_days(now())"); } } } return $where; // eller? inte nedast?ende i alla fall. //$this->whereln=$where; } } // the actual query to the database function mysqlquery($sql) { if (!empty($sql)) { $conn = $this->getConnVar(); mysql_query("set @no=0",$conn); mysql_query("set @txt=''",$conn); $this->errorReport(mysql_error(),$sql); $res = mysql_query($sql,$conn); $this->mysqlerror=mysql_error(); $this->errorReport($this->mysqlerror,$sql); return $res; } else { $this->errorReport("SQL empty",$sql); } } // paging in list view, can only be called AFTER makeList... function navigation($specialarg='') { # these values are set globally # $this->fixConfig(); if ((!isset($this->stopnav) or $this->stopnav!=1) and $this->noRecs>$this->int) { $followers=array('int','future','p','sub','sortby','m','module'); //'template' - krockar med wordpress # merge with user defined $this->navfollow=array_merge($this->navfollow,$followers); # check it against reqest input, create Get-string $getnavstring=$this->getStringFromArray($this->navfollow); # merge and make a convenient variable with user defined string $add=$getnavstring.$this->extranav; if (!isset($this->stopnav)) $this->stopnav=0; if ($this->stopnav!=1) { if ($this->noRecs > $this->end_value) { $right_new=str_replace("%url%",$_SERVER['PHP_SELF'].'?start='.($this->navpage+1).$add,$this->right); } else { $right_new=str_replace("%url%","",$this->right_disabled); } if ($this->showpageno) { if ($this->int>0 and ($this->noRecs/$this->int)>1) { $pages=""; $select=''; } if (!empty($this->pagenotmpl)) { $mid=$this->pagenotmpl; $mid=str_replace("%pages%",$pages,$mid); $mid=str_replace("%select%",$select,$mid); $mid=str_replace("%current%",($this->navpage+1),$mid); $mid=str_replace("%last%",$this->noRecs,$mid); $mid=str_replace("%specialarg%",$specialarg,$mid); } else { $mid=$pages; } } if ($this->navpage>0) { $left_new=str_replace("%url%",$_SERVER['PHP_SELF'].'?start='.($this->navpage-1).$add,$this->left); } else { $left_new=str_replace("%url%","",$this->left_disabled); } if ($this->showpageno) $str=($this->right2left)? $right_new.$this->delimiter.$mid.$this->delimiter.$left_new : $left_new.$this->delimiter.$mid.$this->delimiter.$right_new; else $str=($this->right2left)? $right_new.$this->delimiter.$left_new : $left_new.$this->delimiter.$right_new; return $str; } } } // belongs to navigation method // extracts the important GET or POST values and turns it into a GETstring function getStringFromArray($navfollow) { $extra=""; # check it against reqest input if (is_array($navfollow)) { foreach ($navfollow as $var) { if (!empty($_REQUEST[$var])) { $extra.='&'.$var.'='.$_REQUEST[$var]; } } } return $extra; } // // returns the navigation, from a template with %()menuurl()% and %()menuitem()% // for structured items it uses $tplfilesub as the template for header and sub items function getInformNavigation($tplfile,$tplfilesub) { $str=""; // 2 alternatives - structured menu if set, otherwise an straight one from all modules if (isset($this->structure) && is_array($this->structure)) { $this->htmleditorvalues[]="subitems"; foreach ($this->structure as $header=>$arr) { $sub=""; foreach ($arr as $no=>$url) { $this->templatevars["menuitem"]=$this->modules[$url]; $this->templatevars["menuurl"]=$url; $this->templatevars["current"]=($this->module==$url)?"current":""; $sub.=$this->parseTemplate($tplfile); } $this->templatevars["header"]=$header; $this->templatevars["subitems"]=$sub; $str.=$this->parseTemplate($tplfilesub); } } else { foreach ($this->modules as $url=>$name) { $this->templatevars["menuitem"]=$name; $this->templatevars["menuurl"]=$url; $this->templatevars["current"]=($this->module==$url)?"current":""; $str.=$this->parseTemplate($tplfile); } } return $str; } // parses a templatefile and looks for the likes of %()field()% or %{}field{}% // replaces it with database and predefined values (templatevars) function parseTemplate($tmplfile,$editmode=false,$clearempty=false) { // editmode replaced by class property if (!file_exists($tmplfile)) $this->errorReport("Template file is missing","File is missing: ".$tmplfile,__FILE__,__LINE__); global $tables; $htmlstring=join("",file($tmplfile)); if (!is_array($this->currentRow)) $this->currentRow=array(); if (!is_array($this->templatevars)) $this->templatevars=array(); $newarray=array_merge( array( "counter"=>$this->counter, "module"=>$this->module, ), # %()counter()% increases everytime parseTemplate is called - for lists. $this->currentRow, $this->templatevars ); if ($clearempty) # hmmm. vet vi med s?kerhet att denna hamnar sist? m?ste ordna det. $newarray["[a-zåäöA-ZÅÄÖ_\-\.0-9]+"]=""; //echo "
";			
			//print_r($tables[$cfg->mysql_table]);
			//echo "
"; $htmlstring=$this->parse($newarray,$htmlstring); while (preg_match("/(<\?)(.*?)(\?>)/s",$htmlstring,$matches) && $this->editmode) { // only editmode gets php parser //echo "eval this: ".htmlspecialchars($matches[0]); // en slags eval f?r de som faktiskt inte fungerar att ha i templates.... $htmlstring = str_replace($matches[0],$this->parsePHP($matches[2],$this->currentRow),$htmlstring); } $this->counter++; $htmlstring=$this->parseFileArrayImages($newarray,$htmlstring); $htmlstring=$this->parseWidgets($newarray,$htmlstring); $htmlstring=$this->parseCustomize($newarray,$htmlstring); return $htmlstring; } // use this for customization of template things function parseCustomize($newarray,$htmlstring) { return $htmlstring; } function parseFileArrayImages($newarray,$htmlstring) { $files=$this->files; if (empty($files)) global $files; // TODO - check it out. /* examples @img#fileno#additionalattributes@ */ while (preg_match("/@img#([^#@]+)#?([^@]*?)@/s",$htmlstring,$matches)) { $newstr=""; $attr=""; $fnr=$matches[1]; if (isset($files[$fnr])) { if (isset($matches[2])) { $attr=$matches[2]; if (preg_match("/%/",$attr)) { $attr=$this->parseFields($newarray,$attr); } } $fobj=$files[$fnr]; $path=$fobj->directory; $imgfile=$newarray[$fobj->dbcol]; if (file_exists($path.$imgfile)) { if ($this->isImg($imgfile)) { $sizestuff=""; $size=getImageSize($path.$imgfile); $w=$size[0]; $h=$size[1]; if ($w>$fobj->maxWidth || $h>$fobj->maxHeight) { // this should't actually happen - so we let it be fairly simple $neww=$fobj->maxWidth; $newh=round($neww*$h/$w); if ($newh>$fobj->maxHeight) { $newh=$fobj->maxHeight; $neww=round($newh*$w/$h); } $w=$neww; $h=$newh; } $sizestuff='width="'.$w.'" height="'.$h.'"'; $newstr=''; } } if (empty($newstr) && !empty($imgfile)) { // still nothing there defaults to thumbnail function /error output $newstr.=''; } } $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } // general image thumbnail handling and icons ... /* description @filethumb#fileno#width@ width is optional examples @filethumb#0#40@ - $files[0] in 40 pixels width @filethumb#1@ - $files[1] in default 140 px width */ while (preg_match("/@filethumb#([^@#]+)#?([^@]*)@/s",$htmlstring,$matches)) { $newstr=""; $fnr=$matches[1]; $fobj=$files[$fnr]; $width=(is_numeric($matches[2]))?(int) $matches[2]:140; $row=(isset($this->subCurrentRow))?$this->subCurrentRow:$this->currentRow; $filename=$row[$fobj->dbcol]; if (!empty($filename)) { $newstr.=''; } # replace the iterate-protion of the whole htmlstring with the parsed code $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } // file upload handling and icons ... /* description @fileupload#fileno@ examples @fileupload#0@ - uses $files[0] */ while (preg_match("/@fileupload#([^@]+)@/s",$htmlstring,$matches)) { $newstr=""; $fnr=$matches[1]; $newstr=$this->ulWidget($fnr); $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } return $htmlstring; } function fileThumb($fnr,$maxsize=false) { $files=$this->files; if (empty($files)) global $files; // TODO - check it out. $fobj=$files[$fnr]; /* template defaults to: (Note that width and height will always be set automatically) */ $maxsize=(is_numeric($maxsize) && $maxsize>0)?$maxsize:$this->informthumbsize; // this, we should know: $db_row=(isset($this->subCurrentRow))?$this->subCurrentRow:$this->currentRow; $IMGLIB=new Inform_Imagelib(); $src=$fobj->directory.$db_row[$fobj->dbcol]; $changesize=($this->isImg($src) && (filesize($src)<$this->maxpictweight)); if ($changesize && $IMGLIB->enabled()) { if (!is_file($src)) { // source file missing $thumbfile=$this->fileThumbIcon($db_row[$files->dbcol],'error'); } else { // make sure there's config enough of this (maybe make a note in debug if not?) if (isset($this->thumbsdir) && isset($this->thumbsurl) && is_dir($this->thumbsdir) && is_writable($this->thumbsdir)) { // new name for cached thumb file $thumbsrc=$this->thumbsdir.$maxsize."_".$db_row[$fobj->dbcol]; $thumbfile=$this->thumbsurl.$maxsize."_".$db_row[$fobj->dbcol]; if (!file_exists($thumbsrc)) { // resizeMax($src,$maxpx,$dest="",$enablecopy=true,$crop=false) if (!$IMGLIB->resizeMax($src,$maxsize,$thumbsrc,true,true)) { $thumbfile=$this->fileThumbIcon($src); } } } else { $thumbfile=$this->informurl."system/theme/image.php?src=$src&size=$maxsize"; } } } if (empty($thumbfile)) { $thumbfile=$this->fileThumbIcon($src); } return $thumbfile; } // icons for different file formats function fileThumbIcon($filename,$override=false) { $ext2icon=array( "/\.(pdf)$/i"=>"icon_pdf.gif", "/\.(jpg|png|gif|tiff?|bmp)$/i"=>"icon_pic.gif", "/\.(mov|flv|wmv)$/i"=>"icon_vid.gif", ); $generalicons=array( "error"=>"icon_alert.png", "default"=>"icon_file_40.png", ); $iconpath=$this->informurl."system/theme/img/"; if (!empty($override)) { return $iconpath.$generalicons[$override]; } else { foreach ($ext2icon as $pattern=>$file) { if (preg_match($pattern,$filename)) { $thumbfile=$iconpath.$file; break; } } if (!isset($thumbfile)) { $thumbfile=$iconpath.$generalicons['default']; } return $thumbfile; } } // new 2011, moved from fileuploadclass.php function ulWidget($fnr) { $str=""; $files=$this->files; if (empty($files)) global $files; // TODO - check it out. $fileObj=$files[$fnr]; $db_row=(isset($this->subCurrentRow))?$this->subCurrentRow:$this->currentRow; $resettemplatevars=$this->templatevars; if ($fileObj) { $filepath=$fileObj->directory.$db_row[$fileObj->dbcol]; $this->templatevars['htmlname']=$fileObj->htmlname; $this->templatevars['htmldelete']=$fileObj->htmlDelete; $this->templatevars['lang_delete']=$this->getTranslation('TXT_DELETE'); if (!empty($db_row[$fileObj->dbcol])) { if ($this->isImg) { $this->templatevars['has_image']="true"; unset($this->templatevars['has_file']); } else { $this->templatevars['has_file']="true"; unset($this->templatevars['has_image']); } } if (!empty($db_row[$fileObj->dbcol])) { $this->templatevars['not_empty']="true"; $this->templatevars['filename']=$db_row[$fileObj->dbcol]; $this->templatevars['thumbfile']=$this->fileThumb($fnr);//$this->thumb($db_row); if (is_file($filepath)) { $this->templatevars['thumbinfo']=$this->getTranslation('SIZE_').size_readable(filesize($filepath)).""; } else { $this->templatevars['thumbinfo']=$this->getTranslation('ERROR_FILE_NOFILE'); } } $str.=$this->parseTemplate($this->imagetmpl); } else { $str.=$this->getTranslation('ERROR_ULWIDGET_FILE_OBJECT_MISSING'); } $this->templatevars=$resettemplatevars; return $str; } // utility for checking if image extention on file extension function isImg($filename) { $xt=strtolower(substr(strrchr($filename, "."),1)); return ($xt=="gif" or $xt=="jpg" or $xt=="png"); } # parseWidgets not ready yet function parseWidgets($newarray,$htmlstring) { //global $Widget; /* examples @widget#widgetname#templatename@ */ while (preg_match("/@widget#([^#@]+)#([^#@]+)@/s",$htmlstring,$matches)) { $newstr=""; if (!empty($matches[1]) && !empty($matches[2])) { // TODO: ehum. fix a better isolation of this if ($this->inwordpress) { $this->templatevars["phpfile"]=INF_WPFILE_LBOX; } $widgetname=$matches[1]; $template=$matches[2]; $module=$this->widgets[$widgetname]["child_module"]; //$this->debugReport("$widgetname - $module - $template"); $newstr.='
'; $newstr.="

".$this->widgets[$widgetname]["description"]."

"; $newstr.='
'.$this->getTranslation('SAVED_SORTORDER').'
'; // this is used in javascript to add content to list // $newstr.=$this->createRelationList("media",$module,$templatefile,$this->currentRow[$this->tableid]); if ($this->currentRow[$this->tableid]) { $this->templatevars["widgetname"]=$widgetname; $newstr.=$this->createChildWidget($widgetname,$template,$this->currentRow[$this->tableid]); } $newstr.='
'; // bottom buttons //start with making the url / always in inform - even though we are in wp plugin... // modified for brokk: $href="./?";//$href=$this->informurl.'index.php?';//$cfg->templatevars["phpfile"].'?'; // and then some get vars: $getvars=array( // old ones, but still used: 'm'=>$module, 'mother'=>$this->module, // stick with these 'widgetname'=>$widgetname, 'show'=>'widget', // new 'mothermodule'=>$this->module, 'childmodule'=>$module, 'motherid'=>$this->currentRow[$this->tableid], ); $getstr=http_build_query($getvars,"","&"); // extras $getstr.="&".$this->widgets[$widgetname]["widgetpopupgetstr"]; // thickbox info $getstr.='&TB_iframe=true&height=542&width=842&modal=true'; // must be last if ($this->widgets[$widgetname]["child_module"]!=$this->module) { // not possible to add if its a self-referring module widget // left button / add media $newstr.='Lägg till...'; } // right button chose from library if ((isset($this->widgets[$widgetname]["behaviour"]) && ($this->widgets[$widgetname]["behaviour"]=="relation")) or isset($this->widgets[$widgetname]["relation_table"])) { // this means that we have a relation table and can choose from lib too // extra getvars $getstr='act=choose&'.$getstr; // thickbox must be in the end, so we tuck this new one in the beginning of array $newstr.='Välj...'; } $newstr.='
'."\n
\n"; } $htmlstring = str_replace($matches[0],$newstr,$htmlstring); } return $htmlstring; } // takes in modulename and templatename, returns content and navigation in two parts // either list or single entry (with id), in use only at site! function create($module,$template,$id=0,$usemypath=false) { // last is true if you want to set your own path, set with global $cfg; // havent fixed this yet $pathtomodule=$cfg->informpath."config/modules/$module/"; require_once($pathtomodule."config_module.php"); // $cfg->templ_path=""; //$this->registerGlobals(); $this->fixConfig(true); $this->files=$files; $this->fixSQLVars($template); //$Widget=&$this; //$widget->files=$files; //print_r($files[0]); $this->module=$module; if (!$usemypath) { $this->templ_path=$pathtomodule; } // $this->fixSQLVars($template); #$this->templatevars['fileurl']=$cfg->file_url; #$this->templatevars['filedir']=$cfg->filedir; //$tmplpath=$pathtomodule.$this->templates[$template]["templatefile"]; // check if theres's a single entry template and apply that /*if (!empty($this->templates[$template]["templatefile_single"])) $tmplpath_single=$pathtomodule.$this->templates[$template]["templatefile_single"]; else $tmplpath_single=$tmplpath; */ if ($id) { $thecontent=$this->makeOneTpl($id,$template); $thenav=""; } else { $thecontent=$this->makeListTpl($template); $thenav=$this->navigation(); } return array($thecontent,$thenav); } // takes in modulename and templatename, returns content and navigation in two parts // either list or single entry (with id), in use only at site! function createChildWidget($widgetname,$template,$motherid) { global $cfg,$Widget; $childmodule=$this->widgets[$widgetname]["child_module"]; $p=$this->informpath."config/modules/$childmodule/"; include($p."config_module.php"); $Widget=new Inform(); $Widget->fixConfig(true); $Widget->editmode=true; $Widget->templ_path=$p; $Widget->module=$module; $Widget->templatevars['mothership']=$this->module; //$Widget->templatevars['m']=$childmodule; $Widget->templatevars['widgetname']=$widgetname; $Widget->templatevars['childmodule']=$childmodule; $Widget->templatevars['motherid']=$motherid; $Widget->templatevars['template']=$template; $Widget->files=$files; // is not made global, phew. $sql=$this->createSQLRelationList($this->module,$widgetname,"sql_list",$motherid); //$sql=str_replace("%id%",$id,$this->widgets[$widgetname]["sql"]); // $this->debugReport($sql,__FILE__,__LINE__); // $thecontent=$this->makeListTpl($template); $res=$Widget->mysqlquery($sql); if ($res) { while ($Widget->currentRow = mysql_fetch_assoc($res)) { // print_r($Widget->currentRow); //old ones: //$Widget->templatevars['widgetid']=$widgetname."_".$Widget->currentRow[$this->widgets[$widgetname]["relation_table_key"]]; $Widget->templatevars['widgetsql_id']=$Widget->currentRow[$this->widgets[$widgetname]["relation_child_key"]]; // will be removed later on, keep for compatibility with old config // new ones: $Widget->templatevars['widgetid']=$widgetname."_".$Widget->currentRow[$Widget->tableid]; // it's changed to child module table key instead - it's always unique anyway - no need for relation table key at all... ;) $Widget->templatevars['childid']=$Widget->currentRow[$Widget->tableid]; // here also - in line with motherid we use childid too... no need to mix it up with widget terminology... $str.=$Widget->parseTemplate($Widget->templ_path.$Widget->templates[$template]["templatefile"]); } mysql_free_result($res); } return $str; //return $thecontent; } // takes in modulename and templatename, returns content // either list or single entry (with id) // here the scope is the chilld itself so we need to climb up the ladder a bit function createChildWidgetFromChild($widgetname,$template,$motherid=null,$childid=null,$mothership=false) { // ,$reltableid=null global $cfg,$Widget; $childmodule=$this->widgets[$widgetname]["child_module"]; if (!$childmodule) { $childmodule=$this->module; } $p=$this->informpath."config/modules/$childmodule/"; include($p."config_module.php"); $Widget=new Inform(); $Widget->fixConfig(true); $Widget->editmode=true; $Widget->templ_path=$p; $Widget->module=$module; $Widget->templatevars['mothership']=($mothership)?$mothership:$this->module; //$Widget->templatevars['m']=$childmodule; $Widget->templatevars['widgetname']=$widgetname; $Widget->templatevars['childmodule']=$childmodule; $Widget->templatevars['motherid']=$motherid; $Widget->templatevars['template']=$template; if ($this->inwordpress) { $Widget->templatevars["phpfile"]=INF_WPFILE_LBOX; } $Widget->files=$files; // is not made global, phew. if ($childid) { $sql=$Widget->createOneSQL($childid,$template); } else if ($motherid) { $sql=$this->createSQLRelationList($this->module,$widgetname,"sql_list",$motherid); } //$sql=str_replace("%id%",$id,$this->widgets[$widgetname]["sql"]); // $this->debugReport($sql,__FILE__,__LINE__); // $thecontent=$this->makeListTpl($template); $res=$Widget->mysqlquery($sql); if ($res) { while ($Widget->currentRow = mysql_fetch_assoc($res)) { if ($childid) { // old one: $Widget->templatevars['widgetsql_id']=$Widget->currentRow[$this->tableid]; } else { // old one: $Widget->templatevars['widgetsql_id']=$Widget->currentRow[$this->widgets[$widgetname]["relation_child_key"]]; } // new one, same for both $Widget->templatevars['childid']=$Widget->currentRow[$Widget->tableid]; // old one: //$Widget->templatevars['widgetid']=$widgetname."_".$Widget->currentRow[$this->widgets[$widgetname]["relation_table_key"]]; // new one: $Widget->templatevars['widgetid']=$widgetname."_".$Widget->currentRow[$Widget->tableid]; // it's changed to child module table key instead $str.=$Widget->parseTemplate($Widget->templ_path.$Widget->templates[$template]["templatefile"]); } mysql_free_result($res); } return $str; //return $thecontent; } function createSQLRelationList($module,$widgetname,$sqlstr,$id) { global $cfg; // start with the mother module and find out widget settings....: $p=$this->informpath."config/modules/$module/"; include($p."config_module.php"); $sql=str_replace("%id%",$id,$cfg->widgets[$widgetname][$sqlstr]); return $sql; } /* function findRelationTable($module,$widgetname) { global $cfg; $p=$this->informpath."config/modules/$module/"; include($p."config_module.php"); $reltbl=$cfg->widgets[$widgetname]["relation_table"]; return $reltbl; }*/ // checks the rules in $cfg->rules_modules and sees if there's some restrictions // NOTE: not fully implemented yet function canWrite($module=false) { if (!$module) $module=$this->module; if (!$module) $module=$this->currentmodule; return !isset($this->rules_modules[$module]) or stristr('write',$this->rules_modules[$module]); } function canRemove($module=false) { if (!$module) $module=$this->module; if (!$module) $module=$this->currentmodule; return !isset($this->rules_modules[$module]) or stristr('remove',$this->rules_modules[$module]); } function parsePHP($code,&$row) { // php in templates - only for admin pages // $row can be used in templates $registry = &Registry::getInstance(); $cfg = &$registry->get('cfg'); ob_start(); eval($code); $str = ob_get_contents(); ob_end_clean(); return $str; } function getTranslation($key) { static $MAP; if (!$MAP) { $MAP = $this->getTranslationMapVar(); } return isset($MAP[$key]) ? $MAP[$key] : $key; } // Special patch for wordpress - used in addeditItem // use when WP adds something like \" and \' automatically to POST vars function fixWPVars($input) { if ($this->inwordpress && !get_magic_quotes_gpc()) { foreach ($input as $k=>$v) { if (is_string($v)) $input[$k]=stripslashes($v); } } return $input; } // determines what to do with errors... function errorReport($error,$info,$file="",$line="") { if (!empty($error)) $this->error=true; if ($error && $this->debug==1) { echo $error; if ($file && $line) echo "
at line $line in $file
"; echo "
\nAdditional info: ".$info; } if (!empty($error)) { $dump=mysql_real_escape_string(var_export($_REQUEST,true)); $serverinfo=mysql_real_escape_string(var_export($_SERVER,true)); $sql="INSERT into inform_error_log set info='Error: ".mysql_real_escape_string($error)."\nInfo: ".mysql_real_escape_string($info)."\nFile: $file\nLine: $line',dump='$dump',serverinfo='$serverinfo'"; $conn = $this->getConnVar(); $res = mysql_query($sql,$conn); echo mysql_error(); } } function debugReport($debugtext,$file="",$line="",$makedump=false) { if ($debugtext && $this->debug==1) { echo $debugtext; echo "
at line $line in $file
"; } if ($makedump) { $dump=mysql_real_escape_string("_REQUEST VARS: ".var_export($_REQUEST,true)."\ninform class (this): ".var_export($this,true)); $serverinfo=mysql_real_escape_string(var_export($_SERVER,true)); $sql="INSERT into inform_debug_log set info='".mysql_real_escape_string($debugtext)."\nFile: $file\nLine: $line',dump='$dump',serverinfo='$serverinfo'"; $this->mysqlquery($sql); } } function userReport($action,$Auth="",$user="",$msg="") { //$action can be one of 'login','edit','delete','loginfail' if ($action=="loginfail") { $info=mysql_real_escape_string("_REQUEST VARS: ".var_export($_REQUEST,true)."\n_SERVER: ".var_export($_SERVER,true).$msg); } else if ($action=="login") { $info=mysql_real_escape_string("_SERVER: ".var_export($_SERVER,true).$msg); } if (empty($Auth)) global $Auth; if (empty($user)) $user=join(",",$Auth->getUsersLoggedIn()); $info.=mysql_real_escape_string($msg); $sql="INSERT into inform_login_log set user='".mysql_real_escape_string($user)."',action='$action', info='$info'"; $this->mysqlquery($sql); } } if (file_exists($cfg->informpath."config/customize/informclass.php")) { include($cfg->informpath."config/customize/informclass.php"); } else { class Inform extends Informbase {} } ?>GDinfo=""; // fill with gd_info() information, array with for example ["GD Version"] $this->versionmajor=false; // ["GD Version"] 2 and over $this->versionminor=false; // ["GD Version"] under 2 $this->gifenabled=false; // måste kolla om under version 1.6, eller finns det i gd_info(), gif support i gd över 2.0.28 $this->gifreadable=false; // måste kolla om under version 1.6, eller finns det i gd_info(), gif support i gd över 2.0.28 $this->pngenabled=false; // $this->jpgenabled=false; // $this->wbmpenabled=false; // $this->errorformat=false; // changed according to probems with format $this->newimgname=""; // if name is changed in output to file // även testa xpm (linux)? GD klarar den //$this->enabled=$this->enabled(); - fungerar inte $this->error=""; } // check if system has GD enabled, return GD value function enabled() { if (function_exists("gd_info")) { $this->GDinfo=gd_info(); if (preg_match("/[2-9]\d*\.\d+\.?.*/",$this->GDinfo["GD Version"])) { $this->versionmajor=true; } else { $this->versionminor=true; } if ($this->GDinfo["GIF Create Support"] || imagetypes() & IMG_GIF) { $this->gifenabled=true; } if ($this->GDinfo["GIF Read Support"] || imagetypes() & IMG_GIF) { $this->gifreadable=true; } if ($this->GDinfo["PNG Support"] || imagetypes() & IMG_PNG) { $this->pngenabled=true; } if (isset($this->GDinfo["JPG Support"]) || isset($this->GDinfo["JPEG Support"]) || imagetypes() & IMG_JPG) { $this->jpgenabled=true; } if ($this->GDinfo["WBMP Support"] || imagetypes() & IMG_WBMP) { $this->wbmpenabled=true; } return true; } elseif (function_exists("ImageCreate")) { $this->versionminor=true; return true; } else { return false; } } // output gdinfo directly to screen function outputInfo() { if ($this->enabled()) { echo '
';
				foreach ($this->GDinfo as $k=>$v) {
					echo "$k = $v\n";
				}
				echo '
'; } else { echo "This system doesn't seem to have GD lib installed!"; } } // resize picture with specified size in pixels # Outputs image in png or jpg either to $dest (which is a writable source file) or to browser directly (sends header) function resizeMax($src,$maxpx,$dest="",$enablecopy=true,$crop=false) { return $this->resizeMaxWH($src,$maxpx,$maxpx,$dest,$enablecopy,$crop); } // resize picture with specified size in pixels - with AND height # Outputs image in png or jpg either to $dest (which is a writable source file) or to browser directly (sends header) // added crop 2011 function resizeMaxWH($src,$maxw,$maxh,$dest="",$enablecopy=true,$crop=false) { $success=false; $this->errorformat=false; if (file_exists($src)) { $size=GetImageSize($src); // cropping $oldleft=0; $oldtop=0; $doresize=false; if ($enablecopy && $size && $size[0]<=$maxw && $size[1]<=$maxh) { if (!empty($dest)) { if ($src!=$dest) copy($src,$dest); $success=true; } else { header("Content-type:".$size['mime']); header("Content-Transfer-Encoding: binary"); @readfile($src); $success=true; } } else { # make it smaller $src_img=$this->createWorkImage($src); // tests type too... if (!$this->errorformat) { $type=$size[2]; // check if we make it smaller: $old_w=$size[0]; $old_h=$size[1]; $w=$maxw; $h=round($old_h*$w/$old_w); # calc new height if ($h>$maxh) { // if still too high $h=$maxh; $w=round($old_w*$h/$old_h); # calc new width } $doresize=($old_w>$w or $old_h>$h); if ($crop) { // width and height can be smaller than new sizes! $w=min($maxw,$old_w); $h=min($maxh,$old_h); if ($old_w/$old_h>$w/$h) { // new src w and x $fullw=$old_w; $old_w=round($old_h*($w/$h)); $oldleft=round(($fullw/2)-($old_w/2)); } else { // new src h and y $fullh=$old_h; $old_h=round($old_w*($h/$w)); $oldtop=round(($fullh/2)-($old_h/2)); } } if ($doresize) { $dst_img=$this->resize($src_img,$w,$h,$old_w,$old_h,$oldleft,$oldtop); } else { $dst_img=$src_img; } $success=$this->outputWorkImage($dst_img,$dest,$type); if (!$success) $this->error.="Trouble outputing image.\n"; # destroy temp images if ($src_img) imagedestroy($src_img); if ($dst_img && $dst_img != $src_img) imagedestroy($dst_img); } } } else { $this->error.="File: $src - does not exist.\n"; } return $success; } # the actual resize work is done function resize($src_img,$w,$h,$old_w,$old_h,$oldleft=0,$oldtop=0) { if ($this->versionmajor) { # nya versioner gör bättre bilder... $dst_img=ImageCreateTrueColor($w,$h); if (!imagecopyresampled($dst_img,$src_img,0,0,$oldleft,$oldtop,$w,$h,$old_w,$old_h)) { $this->error.="Trouble with resampling image (imagecopyresampled)\n"; } } elseif ($this->versionminor) { $dst_img=ImageCreate($w,$h); if (!ImageCopyResized($dst_img,$src_img,$newleft,$newtop,$oldleft,$oldtop,$w,$h,$old_w,$old_h)) { $this->error.="Trouble with resizing image (imagecopyresized)\n"; } } return $dst_img; } # create an images with GD function createWorkImage($src) { $size=GetImageSize($src); $type=$size[2]; // 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM. if ($type==1 && ($this->gifenabled || $this->gifreadable)) { $src_img=ImageCreateFromGIF($src); } elseif ($type==2 && $this->jpgenabled) { $src_img=ImageCreateFromJPEG($src); } elseif ($type==3 && $this->pngenabled) { $src_img=ImageCreateFromPNG($src); } elseif ($type==15 && $this->wbmpenabled) { $src_img=ImageCreateFromWBMP($src); } else { $this->errorformat=true; } if(!$src_img) { $this->error.="Trouble creating work image.\n"; return false; } else { return $src_img; } } # Outputs image in png or jpg either to $dest (which is a writable source file) or to browser directly (sends header) function outputWorkImage($dst_img,$dest,$type) { # ouput gif if possible if ($type==1 && $this->gifenabled) { if ($dest) { return ImageGIF($dst_img,$dest); } else { header("Content-type: image/gif"); return ImageGIF($dst_img); } # output png: } elseif (($type==1 || $type==3) && $this->pngenabled) { if ($dest) { if ($type==1 && preg_match("/(\.gif)$/i",$dest,$match)) { $dest=str_replace($match[1],".png",$dest); $this->error.="Replacing gif with resized png now (new name = $dest).\n"; $this->newimgname=$dest; } return ImagePNG($dst_img,$dest); } else { $this->outputHeaders("image/png"); return ImagePNG($dst_img); } # output jpg: } elseif (($type==2 || $type==6) && $this->jpgenabled) { if ($dest) { if ($type==6 && preg_match("/(\.bmp)$/i",$dest,$match)) { $dest=str_replace($match[1],".jpg",$dest); $this->error.="Replacing bmp with resized jpg now (new name = $dest).\n"; $this->newimgname=$dest; } return ImageJPEG($dst_img,$dest,100); } else { $this->outputHeaders("image/jpeg"); return ImageJPEG($dst_img); } } } function outputHeaders($mimetype) { header("Content-Control: cache"); header("Content-type: $mimetype ".date('r', time()+604800)); } } $curpath=substr(__FILE__,0,strrpos(__FILE__,"/")+1); if (file_exists($curpath."../../../config/customize/imageclass.php")) { include($curpath."../../../config/customize/imageclass.php"); } else { class Inform_Imagelib extends Imagelib {} } ?>counting); $htmldel=$tmplvarname."del".strval($this->counting); $this->counting++; $this->htmlname=$html; $this->dbcol=$dbcol; if (!preg_match("#/$#",$filedir)) $filedir.="/"; $this->directory=$filedir; $this->url=$url; $this->htmlDelete=$htmldel; #xtra $this->isImg=$ispict; $this->imgSizeType="width"; // gammal! $this->maxWidth=$maxwidth; $this->imgSize=$maxwidth; // gammal! $this->maxHeight=$maxheight; $this->maxWeight=$maxweight; # dessa s�tts under upload mm: $this->lastMsg=""; $this->lastError=""; $this->fileName=""; } # calls after form submit - only i htmlname is present function fileBytes() { return $_FILES[$this->htmlname]['size']; } # calls after upload - only i fileName is present function allowedWeight() { $file=$this->directory.$this->fileName; if (file_exists($file) && is_file($file) && filesize($file)<$this->maxWeight) { return true; # allowed weight } else { return false; } } function upload($verbose=1) { $ULerrorsText[0]=""; $ULerrorsText['UPLOAD_ERR_OK']=$ULerrorsText[0]; $ULerrorsText[1]=$ULerrorsText['UPLOAD_ERR_INI_SIZE']=$this->getTranslation('ERROR_FILE_TOOBIG_PHP'); $ULerrorsText[2]=$ULerrorsText['UPLOAD_ERR_FORM_SIZE']=$this->getTranslation('ERROR_FILE_TOOBIG_HTML'); $ULerrorsText[3]=$ULerrorsText['UPLOAD_ERR_PARTIAL']=$this->getTranslation('ERROR_FILE_PARTIAL'); $ULerrorsText[4]=$ULerrorsText['UPLOAD_ERR_NO_FILE']=$this->getTranslation('ERROR_FILE_NOFILE'); # fixa lite lokala variabler för villkorssats $filefield=$this->htmlname; # för meddelanden $output=""; $this->lastMsg=""; $this->lastError=""; # file upload $filesrc=$_FILES[$filefield]['tmp_name']; if (is_uploaded_file($filesrc)) { $file_name=$_FILES[$filefield]['name']; #$file_type=$_FILES[$filefield]['type']; $file_size=$_FILES[$filefield]['size']; $this->lastError=$ULerrorsText[$_FILES[$filefield]['error']]; if (($file_size)>6000000000) { $this->lastError.=$this->getTranslation('ERROR_FILE_LARGER_THAN_')." 6Mb "; } else { $this->fileName=$this->checkUpl($filesrc,$file_name); } } if ($verbose) echo $output; $this->lastMsg.=$output; # behövs eg inte längre return $this->fileName; } function checkUpl($fromTempPath,$filename) { $toDir=$this->directory; $message=""; if (is_uploaded_file($fromTempPath)) { # fix filename to not contain strange chars, only 0-9 a-z A-Z _ . is allowed $newfilename=""; for($pos=0;$pos=47 and ord($chr)<=57) or (ord($chr)>=65 and ord($chr)<=90) or (ord($chr)>=97 and ord($chr)<=122) or $chr=="_" or $chr==".") { $newfilename.=$chr; } else { $newfilename.="_"; // felaktig ersätts med _ } } $filename=$newfilename; # check to see if filename already exists, change name if exists $filename=$this->findPlaceFor($filename); $toPath=$toDir.$filename; $this->fileName=$filename; // store last filename in object # copy file if (move_uploaded_file($fromTempPath,$toPath)) { if ($this->uploadedfilecommand) { $cmd=str_replace("%file%",$toPath,$this->uploadedfilecommand); $this->lastMsg.=exec($cmd); } } else { $this->lastError=$this->getTranslation('ERROR_COULDNT_UPLOAD_').$filename." "; $filename=""; } # return the right filename return $filename; } else { return false; } } function findPlaceFor($filename,$toDir="") { if (!$toDir) { $toDir=$this->directory; } # check to see if filename already exists $toPath=$toDir.$filename; $no=1; while(file_exists($toPath)) { $no++; $toPath=$toDir.$no.$filename; } if ($no>1) { $filename=$no.$filename; #$message.="Filen fanns redan, döps om till ".$filename."
"; } return $filename; } function changeSize($verbose=1) { $pictcomment='
'.$this->getTranslation('ERROR_IMGSIZE_FAILED'); $sizeok=$this->imgSize(); if ($this->lastError) { $this->lastError='

'.$this->getTranslation('ERROR_ON_CHANGE_IMGSIZE_').$this->lastError." $pictcomment

"; } if ($verbose) { echo ($sizeok && !$this->lastError)?$this->getTranslation('MSG_CHANGED_IMGSIZE'):$this->lastError; } return $sizeok; } # anropas av changeSize function imgSize() { $this->lastMsg=""; $this->lastError=""; $src=$this->directory.$this->fileName; $error=""; $size=GetImageSize($src); $type=$size[2]; if (!$this->allowedWeight()) { $error.=$this->getTranslation('ERROR_IMG_TOO_BIG_LARGER_THAN_').size_readable($this->maxWeight)."."; } else { $GD=new Inform_Imagelib(); if ($GD->enabled() && $GD->resizeMaxWH($src,$this->maxWidth,$this->maxHeight,$src,true)) { $success=true; if ($GD->newimgname && $GD->newimgname!=$src) { $this->lastMsg.=$this->getTranslation('MSG_CHANGED_FILETYPE')."
"; deleteFile($src); $this->fileName=str_replace($this->directory,"",$GD->newimgname); } } else { $error.=$this->getTranslation('ERROR_PROBLEM_DOWNSIZING_TO_WIDTH_').$this->maxWidth.$this->getTranslation('_AND_MAXHEIGHT_').$this->maxHeight."."; if ($GD->errorformat) { $error.=$this->getTranslation('ERROR_WRONG_IMG_FORMAT'); } } } $this->lastError=$error; if ($error && !$success) return false; else return true; } function printImgMarkup($filename,$attrextras="") { global $mainwidth,$mainheight; $filepath=$this->directory; $uri=$this->url; if ($filename && file_exists($filepath.$filename)) { $sizes=getImageSize($filepath.$filename); if ($this->imgSizeType=="width" && $this->imgSize && ($sizes[0]>$this->imgSize)) { $sz='width="'.$this->imgSize.'"'; } elseif ($this->imgSizeType=="height" && $this->imgSize && ($sizes[1]>$this->imgSize)) { $sz='height="'.$this->imgSize.'"'; } else { $sz=$sizes[3]; } echo ''; } } // This has been moved to $Inform->fileThumb() in 2011, but can still be used in old templates, so keep for a while function thumb($db_row,$maxsize=0) { global $cfg,$Inform; $IMGLIB=new Inform_Imagelib(); #$GD->outputInfo(); if ($this->isImg && $IMGLIB->enabled()) { $maxsize=($maxsize>0)?$maxsize:$cfg->informthumbsize; $src=$this->directory.$db_row[$this->dbcol]; if (!is_file($src)) { $thumbfile=$cfg->informurl."system/theme/img/icon_alert.png"; } else if (filesize($src)<$cfg->maxpictweight) { if (isset($cfg->thumbsdir) && isset($cfg->thumbsurl) && is_dir($cfg->thumbsdir) && is_writable($cfg->thumbsdir)) { $thumbsrc=$cfg->thumbsdir.$maxsize."_".$db_row[$this->dbcol]; if (!file_exists($thumbsrc)) { $IMGLIB->resizeMax($src,$maxsize,$thumbsrc,true,true); } $thumbfile=$cfg->thumbsurl.$maxsize."_".$db_row[$this->dbcol]; } else { $thumbfile=$cfg->informurl."system/theme/image.php?src=$src&size=$maxsize"; } } else { # filesize too big to make thumbnail $thumbfile=$cfg->informurl."system/theme/img/icon_pic.gif"; } } else { # filesize too big to make thumbnail or not an image at all if (preg_match("/\.(jpg|png|gif|tiff?|bmp)$/i",$db_row[$this->dbcol])) { $thumbfile=$cfg->informurl."system/theme/img/icon_pic.gif"; } else if (preg_match("/\.(pdf)$/",$db_row[$this->dbcol])) { $thumbfile=$cfg->informurl."system/theme/img/icon_pdf.gif"; } else if (preg_match("/\.(mov|flv|wmv)$/",$db_row[$this->dbcol])) { $thumbfile=$cfg->informurl."system/theme/img/icon_vid.gif"; } else { $thumbfile=$cfg->informurl."system/theme/img/icon_file_40.png"; } } return $thumbfile; } // input type=file, uses template stored in $Inform->imagetmpl // This has been moved to $Inform->ulWidget() in 2011, but can still be used in old templates, so keep for a while function ulWidget($db_row) { global $cfg,$Inform; $fileObj=$this; $resettemplatevars=$Inform->templatevars; if ($fileObj) { $filepath=$fileObj->directory.$db_row[$fileObj->dbcol]; $Inform->templatevars['htmlname']=$fileObj->htmlname; $Inform->templatevars['htmldelete']=$fileObj->htmlDelete; //$Inform->templatevars['txtdelete']=$this->getTranslation('ALERT_CURRENT_FILE_IS_REMOVED'); $Inform->templatevars['lang_delete']=$this->getTranslation('TXT_DELETE'); if (!empty($db_row[$fileObj->dbcol])) { if ($this->isImg) { $Inform->templatevars['has_image']="true"; unset($Inform->templatevars['has_file']); } else { $Inform->templatevars['has_file']="true"; unset($Inform->templatevars['has_image']); } } if (!empty($db_row[$fileObj->dbcol])) { $Inform->templatevars['not_empty']="true"; $Inform->templatevars['filename']=$db_row[$fileObj->dbcol]; $Inform->templatevars['thumbfile']=$Inform->fileThumb($fnr);//$this->thumb($db_row); if (is_file($filepath)) { $Inform->templatevars['thumbinfo']=$this->getTranslation('SIZE_').size_readable(filesize($filepath)).""; } else { $Inform->templatevars['thumbinfo']=$this->getTranslation('ERROR_FILE_NOFILE'); } } echo $Inform->parseTemplate($Inform->imagetmpl); } else { echo $this->getTranslation('ERROR_ULWIDGET_FILE_OBJECT_MISSING'); } $Inform->templatevars=$resettemplatevars; } function deleteFile($filename) { global $message, $cfg; $success=false; $deletefile=$this->directory.$filename; if (file_exists($deletefile) and is_file($deletefile)) { if (unlink($deletefile)) { $message.=$this->getTranslation('MSG_DELETED_FILE_').$deletefile; $this->lastaction="delete"; $success=true; } else { $message.=$this->getTranslation('ERROR_COULDNT_DELETE_FILE_').$deletefile; $err=true; } // this should be removed from here - use imagesizes in cfg and informclass instead! if ($cfg->thumbsdir) { $thumbfile=$cfg->thumbsdir.$filename; if (file_exists($thumbfile) and is_file($thumbfile)) { unlink($thumbfile); } } } else { $message.=$this->getTranslation('ERROR_COULDNT_DELETE_FILE')." ".$deletefile." ".$this->getTranslation('_IS_NOT_A_FILE'); } $message.="

"; return $success; } function getTranslation($key) { global $cfg; static $MAP; $fileName='map_'.$cfg->lang.'.php'; $absolutePath=$cfg->langpath.$fileName; if (!file_exists($absolutePath)) { $absolutePath=$cfg->langpath.'map_sv.php'; } if (!$MAP) { include($absolutePath); $MAP = $lang_maps; } return isset($MAP[$key]) ? $MAP[$key] : $key; } } $curpath=substr(__FILE__,0,strrpos(__FILE__,"/")+1); if (file_exists($curpath."../../../config/customize/fileuploadclass.php")) { include($curpath."../../../config/customize/fileuploadclass.php"); } else { class Inform_ULFile extends Inform_ULFilebase {} } ?>"passwd1","user2"=>"passwd2")); $MyAuth->login("elin","lösen"); $MyAuth->login("elin"); $MyAuth->logout("elin"); $MyAuth->isLoggedIn("elin"); */ if (!isset($authclassset)) { class ArtoAuth { function ArtoAuth($userpasswds,$ltemplate) { $this->user=array(); $this->loggedIn=array(); if (is_array($userpasswds)) { foreach ($userpasswds as $username=>$passwd) { $this->user[$username]=$passwd; $this->loggedIn[$username]=false; } } if ($ltemplate) { $this->logTmpl=$ltemplate; } else { $this->logTmpl="system/tmpl/loginbox.html"; } } function loginBox($user="") { global $cfg; if (!file_exists($this->logTmpl)) { echo "

Error: The login template file ".$this->logTmpl." is missing!

"; } else { include($this->logTmpl); } //exit; # Man ska inte komma vidare p� denna sida } function login($user,$passwd) { global $Inform; if ($user && $this->user[$user]==$passwd) { $this->loggedIn[$user]=true; $$user=$passwd; # blir t ex $bert="g�ran77" $_SESSION[$user]=$passwd; return true; } else { $this->message=$this->getTranslation('ERROR_LOGIN_FAILED'); $this->loginBox(); return false; } } function logout($user="") { if ($user) { $this->loggedIn[$user]=false; unset($_SESSION[$user]); } else { foreach ($this->user as $username=>$passwd) { $this->loggedIn[$username]=false; } session_destroy(); } } function isLoggedIn($user="") { if ($user && isset($_SESSION[$user]) && $_SESSION[$user]==$this->user[$user]) { return true; } else { foreach ($this->user as $username=>$passwd) { if(isset($_SESSION[$username]) && $_SESSION[$username]==$this->user[$username]) { return true; } } return false; } } function displayLoggedIn() { foreach ($this->user as $username=>$passwd) { if(isset($_SESSION[$username]) && $_SESSION[$username]==$this->user[$username]) { echo ''.$username.''; echo ' | '.$this->getTranslation('LNK_LOGOUT').''; } } } function getUsersLoggedIn() { $users=array(); foreach ($this->user as $username=>$passwd) { if(isset($_SESSION[$username]) && $_SESSION[$username]==$this->user[$username]) { $users[]=$username; } } return $users; } function getTranslation($key) { global $cfg; static $MAP; $fileName='map_'.$cfg->lang.'.php'; $absolutePath=$cfg->langpath.$fileName; if (!file_exists($absolutePath)) { $absolutePath=$this->langpath.'map_sv.php'; } if (!$MAP) { include($cfg->langpath.$fileName); $MAP = $lang_maps; } return isset($MAP[$key]) ? $MAP[$key] : $key; } } $authclassset=1; } ?>htmlname.'" size="15" class="inputfile" onclick="if (this.form.'.$fileObj->htmlDelete.') { alert(\''.$Inform->getTranslation('ALERT_CURRENT_FILE_IS_REMOVED').'\');this.form.'.$fileObj->htmlDelete.'.checked=true }" />'; // if (!empty($db_row[$fileObj->dbcol])) { // // $IMGLIB=new Inform_Imagelib(); // #$GD->outputInfo(); // // if ($fileObj->isImg && $IMGLIB->enabled()) { // $maxsize=($cfg->informthumbsize)?$cfg->informthumbsize:50; // $src=$fileObj->directory.$db_row[$fileObj->dbcol]; // echo '
'; // echo '
'; // } else { // echo '
'; // echo $Inform->getTranslation('ERASE_CURRENT_PICT').' '; // echo ''.$Inform->getTranslation('VIEW_CURRENT_PICT').''; // } // } // #echo '

V�lj bild fr�n fotoalbumet...

'; // } else { // echo "ulWidget error: File object is missing!"; // } // } // input type=text function textlnWidget($db_row,$db_col,$descr,$size=44,$attr='',$def='') { global $cfg,$tables; $value=(!$db_row[$db_col])?$def:str_replace('"',""",stripslashes($db_row[$db_col])); $typeofkey=$tables[$cfg->mysql_table]->keys[$db_col]; if (preg_match("/varchar\((\d+)\)/",$typeofkey,$matches)) { $len=$matches[1]; } else { $len=255; } echo ''.$descr.''; echo ''; if ($def) echo ''; } // function textboxWidget($db_row,$db_col,$descr,$cols=43,$rows=15,$attr='',$def='') { global $cfg,$tables; $value=(!$db_row[$db_col])?$def:stripslashes($db_row[$db_col]); # make this a javascript or something that tells if the user has entered too much text? #$typeofkey=$tables[$cfg->mysql_table]->keys[$db_col]; #if (preg_match("/varchar\((\d+)\)/",$typeofkey,$matches)) { # $len=$matches[1]; #} else { # $len=255; #} echo ''.$descr.''; echo ''; if ($def) echo ''; } // // content from db table function selectboxWidgetDB($sql,$name,$value='',$nullvalue='',$attr='') { global $cfg,$tables; echo '\n\n"; } function outputImgMarkup($filename,$filepath,$uri,$attrextras="") { global $mainwidth,$mainheight; if ($filename && file_exists($filepath.$filename)) { $sizes=getImageSize($filepath.$filename); if ($mainwidth && ($sizes[0]>$mainwidth)) { $sz='width="'.$mainwidth.'"'; } elseif ($mainheight && ($sizes[0]>$mainheight)) { $sz='width="'.$mainheight.'"'; } else { $sz=$sizes[3]; } echo ''; } } function getArrayFromDB($sql) { global $conn; $res = mysql_query($sql,$conn); echo mysql_error(); if ($res) { $arr=array(); while($row = mysql_fetch_row($res)) { if ($row[0] && $row[1]) $arr[$row[0]]=$row[1]; else $arr[]=$row[0]; } mysql_free_result($res); return $arr; } else { return false; } } /* function deleteFile($deletefile) { global $message; $err=false; if (file_exists($deletefile) and is_file($deletefile)) { if (unlink($deletefile)) { $message.="Suddade filen ".$deletefile; } else { $message.="Kunde inte sudda filen ".$deletefile; $err=true; } } else { $message.="Sudda filen - misslyckades! ".$deletefile." är ingen fil."; $err=true; } $message.="

"; return $err; // ojojoj - konstigt - måste ändras! }*/ function checkUpload($fromTempPath,$toDir,$filename,$deleteobj) { global $message; if (is_uploaded_file($fromTempPath)) { # first - delete old one.... $filedeleted=false; if (!empty($deleteobj) && file_exists($deleteobj)) { deleteFile($deleteobj); $filedeleted=true; } # fix filename to not contain strange chars, only 0-9 a-z A-Z _ . is allowed $newfilename=""; for($pos=0;$pos=47 and ord($chr)<=57) or (ord($chr)>=65 and ord($chr)<=90) or (ord($chr)>=97 and ord($chr)<=122) or $chr=="_" or $chr==".") { $newfilename.=$chr; } else { $newfilename.="_"; // felaktig ers�tts med _ } } $filename=$newfilename; # check to see if filename already exists $toPath=$toDir.$filename; $no=1; while(file_exists($toPath)) { $no++; $toPath=$toDir.$no.$filename; } if ($no>1) { $filename=$no.$filename; $message.="Filen fanns redan, döps om till ".$filename."
"; } # copy file if (copy($fromTempPath,$toPath)) { $message.="Laddade upp ".$filename."
"; } else { $message.="Kunde inte ladda upp ".$filename."
"; $filename="."; } $message.="
"; # return the right filename return $filename; } else { return false; } } function fileUpload($filefield,$destination,$deleteold,$previousfile,$urldest="",$verbose=1) { # file upload global $message; if (!empty($deleteold)) { $output.=deleteFile($destination.$previousfile); $finalfname=""; } if ($_FILES[$filefield]) { $file=$_FILES[$filefield]['tmp_name']; $file_name=$_FILES[$filefield]['name']; $file_type=$_FILES[$filefield]['type']; $file_size=$_FILES[$filefield]['size']; $ulerror.=$_FILES[$filefield]['error']; if (!empty($ulerror)) $output.=$ulerror; if (file_exists($file)) { if (($file_size)>0) $output.="

Filstorlek ca ".round(($file_size)/1000000)." Mb

"; if (($file_size)>6000000000) { $output.="

Filen som laddades upp var för stor > 6Mb

"; } $finalfname=checkUpload($file,$destination,$file_name,""); $output.="

Laddar upp $finalfname

"; $output.="

".$message."

"; if ($finalfname and file_exists($destination.$previousfile) and is_file($destination.$previousfile)) $output.=deleteFile($destination.$previousfile); } } else if (empty($deleteold)) { return $previousfile; } if ($verbose) echo $output; return $finalfname; } function totalFileBytes($filearr) { $total=0; foreach ($filearr as $fileObj) { $total+=$_FILES[$fileObj->htmlname]['size']; } return $total; } /** * Return human readable sizes * * @author Aidan Lister * @version 1.1.0 * @link http://aidanlister.com/repos/v/function.size_readable.php * @param int $size Size * @param int $unit The maximum unit * @param int $retstring The return string format * @param int $si Whether to use SI prefixes */ function size_readable($size, $unit = null, $retstring = null, $si = true) { // Units if ($si === true) { $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB'); $mod = 1000; } else { $sizes = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); $mod = 1024; } $ii = count($sizes) - 1; // Max unit $unit = array_search((string) $unit, $sizes); if ($unit === null || $unit === false) { $unit = $ii; } // Return string if ($retstring === null) { $retstring = '%01.2f %s'; } // Loop $i = 0; while ($unit != $i && $size >= 1024 && $i < $ii) { $size /= $mod; $i++; } return sprintf($retstring, $size, $sizes[$i]); } // ers�tta av informmetod? function getStringFromArray($navfollow) { $extra=""; # check it against reqest input, and globals if no request if (is_array($navfollow)) { foreach ($navfollow as $var) { global $$var; if (empty($$var) && (!empty($_REQUEST[$var]))) { $$var=$_REQUEST[$var]; } if (!empty($$var)) $extra.='&'.$var.'='.$$var; } } return $extra; } // gets certain type of files from catalogue and returns array of filenames function returnFilesFromCat($dir,$ext) { $filearr=array(); if (is_dir($dir)) { $Dir = dir($dir); while($f=$Dir->read()) { if(!preg_match("/^\./",$f)) { if (preg_match("/\.$ext$/",$f) && is_file("$dir$f")) { $filearr[]=$f; } } } } return $filearr; } function allowedFileWeight($file,$weight) { if (file_exists($file) and filesize($file)<$weight) { return true; # allowed weight } else { return false; } } /* // this should be in imageclass instead - please change to that! function changeImgSize($src,$w) { global $error; $size=GetImageSize($src); $old_w=$size[0]; $old_h=$size[1]; $type=$size[2]; if (($type==2 or $type==3) and $old_w>$w) { #if (intval(substr(phpversion(),0,3))>=4.3) # kolla version av GD-lib if ( function_exists("gd_info") or function_exists("ImageCreate")) { if (function_exists("gd_info")) $GD=gd_info(); $h=round($old_h*$w/$old_w); # ber�kna ny h�jd if (preg_match("/\.jpg$/i",$src) or $type==2) { $src_img=ImageCreateFromJPEG($src); } else if (preg_match("/\.png$/i",$src) or $type==3) { $src_img=ImageCreateFromPNG($src); } # h�r - �ndra storlek if ($GD and preg_match("/\b2\./",$GD["GD Version"])) { # nya versioner g�r b�ttre bilder... ooops fungerar ej vid "bundled (2.0.15 compatible)" :-/ $dst_img=ImageCreateTrueColor($w,$h); imagecopyresampled($dst_img,$src_img,0,0,0,0,$w,$h,$old_w,$old_h); } else { $dst_img=ImageCreate($w,$h); ImageCopyResized($dst_img,$src_img,0,0,0,0,$w,$h,$old_w,$old_h); } if (preg_match("/\.jpg$/i",$src) or $type==2) { ImageJPEG($dst_img,$src); } else if (preg_match("/\.png$/i",$src) or $type==3) { ImagePNG($dst_img,$src); } imagedestroy($dst_img); } else { $error.="GD lib is not working on this system "; } } else { if (!($type==2 or $type==3)) { # fortfarande fel filformat! deleteFile($src); $error.="Wrong file format, file deleted"; } } if ($error) return false; else return true; } */ // special for nk? if (!function_exists("runSQL")) { function runSQL($qry) { global $conn; echo '
'.$qry.'
'; mysql_query($qry,$conn); if (mysql_error()) { echo '

An error occured.

'."\n\n"; return false; } else if (mysql_insert_id()) { return mysql_insert_id(); } else { return true; } } } if (!function_exists("getRowFromDB")) { function getRowFromDB($sql) { // eh anv�nds kanske inte. global $conn; $res = mysql_query($sql,$conn); echo mysql_error(); if ($res) { $row = mysql_fetch_row($res); return $row; mysql_free_result($res); } else { return false; } } } $xtrafuncIncluded=1; } ?>