summaryrefslogtreecommitdiffstats
path: root/admin/survey/classes
diff options
context:
space:
mode:
Diffstat (limited to 'admin/survey/classes')
-rw-r--r--admin/survey/classes/class.Cache.php269
-rw-r--r--admin/survey/classes/class.Common.php2195
-rw-r--r--admin/survey/classes/class.Demografija.php166
-rw-r--r--admin/survey/classes/class.Dostop.php1783
-rw-r--r--admin/survey/classes/class.Export.php95
-rw-r--r--admin/survey/classes/class.Forum.php441
-rw-r--r--admin/survey/classes/class.GDPR.php2605
-rw-r--r--admin/survey/classes/class.GetSiteUrl.php21
-rw-r--r--admin/survey/classes/class.GlobalMisc.php31
-rw-r--r--admin/survey/classes/class.HashUrl.php296
-rw-r--r--admin/survey/classes/class.Library.php1233
-rw-r--r--admin/survey/classes/class.NewSurvey.php857
-rw-r--r--admin/survey/classes/class.Notifications.php439
-rw-r--r--admin/survey/classes/class.Prevajanje.php1047
-rw-r--r--admin/survey/classes/class.RecodeValues.php971
-rw-r--r--admin/survey/classes/class.Setting.php420
-rw-r--r--admin/survey/classes/class.SurveyAapor.php590
-rw-r--r--admin/survey/classes/class.SurveyAktivnost.php911
-rw-r--r--admin/survey/classes/class.SurveyAppendMerge.php1039
-rw-r--r--admin/survey/classes/class.SurveyBaseSetting.php84
-rw-r--r--admin/survey/classes/class.SurveyCondition.php316
-rw-r--r--admin/survey/classes/class.SurveyConditionProfiles.php977
-rw-r--r--admin/survey/classes/class.SurveyConnect.php147
-rw-r--r--admin/survey/classes/class.SurveyCopy.php1373
-rw-r--r--admin/survey/classes/class.SurveyCustomReport.php2618
-rw-r--r--admin/survey/classes/class.SurveyDataSettingProfiles.php1442
-rw-r--r--admin/survey/classes/class.SurveyDiagnostics.php1044
-rw-r--r--admin/survey/classes/class.SurveyExport.php1465
-rw-r--r--admin/survey/classes/class.SurveyExportProfiles.php291
-rw-r--r--admin/survey/classes/class.SurveyGetHeatMapRadij.php29
-rw-r--r--admin/survey/classes/class.SurveyHeatMap.php76
-rw-r--r--admin/survey/classes/class.SurveyHeatMapBackground.php137
-rw-r--r--admin/survey/classes/class.SurveyHeatMapExportIcons.php24
-rw-r--r--admin/survey/classes/class.SurveyHeatMapRadij.php31
-rw-r--r--admin/survey/classes/class.SurveyHeatMapSaveImage.php36
-rw-r--r--admin/survey/classes/class.SurveyInfo.php851
-rw-r--r--admin/survey/classes/class.SurveyInpect.php757
-rw-r--r--admin/survey/classes/class.SurveyLanguageTechnology.php809
-rw-r--r--admin/survey/classes/class.SurveyList.php3241
-rw-r--r--admin/survey/classes/class.SurveyMapData.php255
-rw-r--r--admin/survey/classes/class.SurveyMissingProfiles.php643
-rw-r--r--admin/survey/classes/class.SurveyMissingValues.php724
-rw-r--r--admin/survey/classes/class.SurveyMobile.php1142
-rw-r--r--admin/survey/classes/class.SurveyParaAnalysis.php1550
-rw-r--r--admin/survey/classes/class.SurveyParaGraph.php437
-rw-r--r--admin/survey/classes/class.SurveyPostProcess.php1070
-rw-r--r--admin/survey/classes/class.SurveyProfileManager.php433
-rw-r--r--admin/survey/classes/class.SurveyQuotas.php816
-rw-r--r--admin/survey/classes/class.SurveyRecoding.php627
-rw-r--r--admin/survey/classes/class.SurveyReminderTracking.php1380
-rw-r--r--admin/survey/classes/class.SurveyRespondents.php816
-rw-r--r--admin/survey/classes/class.SurveySession.php180
-rw-r--r--admin/survey/classes/class.SurveySetting.php132
-rw-r--r--admin/survey/classes/class.SurveySkupine.php462
-rw-r--r--admin/survey/classes/class.SurveyStaticHtml.php1247
-rw-r--r--admin/survey/classes/class.SurveyStatistic.php2482
-rw-r--r--admin/survey/classes/class.SurveyStatisticProfiles.php455
-rw-r--r--admin/survey/classes/class.SurveyStatusCasi.php340
-rw-r--r--admin/survey/classes/class.SurveyStatusProfiles.php1247
-rw-r--r--admin/survey/classes/class.SurveyTelephone.php3573
-rw-r--r--admin/survey/classes/class.SurveyTextAnalysis.php407
-rw-r--r--admin/survey/classes/class.SurveyTheme.php997
-rw-r--r--admin/survey/classes/class.SurveyThemeEditor.php533
-rw-r--r--admin/survey/classes/class.SurveyTimeProfiles.php707
-rw-r--r--admin/survey/classes/class.SurveyUrlLinks.php278
-rw-r--r--admin/survey/classes/class.SurveyUsableResp.php783
-rw-r--r--admin/survey/classes/class.SurveyUserSession.php149
-rw-r--r--admin/survey/classes/class.SurveyUserSetting.php118
-rw-r--r--admin/survey/classes/class.SurveyVariableView.php85
-rw-r--r--admin/survey/classes/class.SurveyVariablesProfiles.php649
-rw-r--r--admin/survey/classes/class.SurveyZankaProfiles.php546
-rw-r--r--admin/survey/classes/class.SurveyZoom.php915
-rw-r--r--admin/survey/classes/class.Timer.php50
-rw-r--r--admin/survey/classes/class.User.php165
-rw-r--r--admin/survey/classes/class.UserSetting.php149
-rw-r--r--admin/survey/classes/class.Vprasanje.php8062
-rw-r--r--admin/survey/classes/class.VprasanjeInline.php688
-rw-r--r--admin/survey/classes/class.params.php268
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/Purifier.php94
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.auto.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.autoload.php26
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.func.php23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.includes.php214
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.kses.php30
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.path.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.php237
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.safe-includes.php208
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrCollections.php128
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef.php123
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS.php87
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Background.php87
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php133
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Border.php43
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Color.php78
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Composite.php38
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php28
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Filter.php54
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Font.php149
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/FontFamily.php197
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php40
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Length.php47
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ListStyle.php78
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Multiple.php58
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Number.php69
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Percentage.php40
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php38
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/URI.php61
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Enum.php65
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Bool.php28
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Class.php34
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Color.php32
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/ID.php70
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Length.php41
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php53
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/MultiLength.php41
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Nmtokens.php52
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Pixels.php48
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Integer.php73
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Lang.php73
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Switch.php34
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Text.php15
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI.php77
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email.php17
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Host.php68
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv4.php39
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv6.php99
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform.php56
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Background.php23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BdoDir.php19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BgColor.php23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BoolToCSS.php36
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Border.php18
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/EnumToCSS.php58
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgRequired.php43
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgSpace.php44
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Input.php40
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Lang.php28
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Length.php27
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Name.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/NameSync.php27
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Nofollow.php41
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeEmbed.php15
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeObject.php16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeParam.php64
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ScriptRequired.php16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Textarea.php18
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTypes.php77
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrValidator.php162
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Bootstrap.php104
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/CSSDefinition.php322
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef.php48
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Chameleon.php48
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Custom.php90
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Empty.php20
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Optional.php26
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Required.php117
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/StrictBlockquote.php88
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Table.php142
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Config.php709
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema.php164
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php44
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/Xml.php106
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Exception.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange.php42
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php77
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Id.php37
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php180
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Validator.php206
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php66
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema.serbin0 -> 14140 bytes
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt8
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt8
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt8
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt5
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt31
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt15
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt46
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt8
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt18
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt18
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt28
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt17
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt15
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt7
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt34
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt29
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt74
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt25
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt20
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt18
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt33
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt16
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt20
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt7
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt8
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt24
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt8
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt15
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt25
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt7
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt17
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt17
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt15
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt13
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt83
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt17
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt30
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/info.ini3
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ContentSets.php155
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Context.php82
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Definition.php50
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache.php108
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator.php62
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php43
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Memory.php46
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in47
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Null.php39
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer.php191
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/CSS/4.3.0,4af9cb41e1f64636f725057634b6a44b,1.serbin0 -> 25462 bytes
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,3a30aa3a44d5568ce8742bef8d8eb769,1.serbin0 -> 92227 bytes
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,6e3fa754534c1e442cac3cc9c6e91513,6.serbin0 -> 101269 bytes
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/README3
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/URI/4.3.0,05c766101e813c246917b022f97b5e6e,1.serbin0 -> 345 bytes
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCacheFactory.php91
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Doctype.php60
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DoctypeRegistry.php103
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ElementDef.php183
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Encoder.php426
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup.php44
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup/entities.ser1
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityParser.php144
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorCollector.php209
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorStruct.php60
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Exception.php12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter.php46
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/ExtractStyleBlocks.php135
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/YouTube.php39
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Generator.php254
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLDefinition.php425
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule.php244
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Bdo.php31
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/CommonAttributes.php26
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Edit.php38
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Forms.php118
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Hypertext.php31
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Image.php40
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Legacy.php143
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/List.php37
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Name.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Nofollow.php19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Object.php47
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Presentation.php36
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Proprietary.php33
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Ruby.php27
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeEmbed.php34
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeObject.php52
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Scripting.php54
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/StyleAttribute.php24
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tables.php66
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Target.php23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Text.php71
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy.php207
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Name.php24
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Proprietary.php24
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Strict.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Transitional.php9
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTML.php17
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php161
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/XMLCommonAttributes.php14
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModuleManager.php403
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/IDAccumulator.php53
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector.php239
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/AutoParagraph.php345
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/DisplayLinkURI.php26
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/Linkify.php46
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/PurifierLinkify.php45
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveEmpty.php51
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveSpansWithoutAttributes.php60
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/SafeObject.php91
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language.php163
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/classes/en-x-test.php12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-test.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-testmini.php12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en.php63
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/LanguageFactory.php198
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Length.php115
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer.php326
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DOMLex.php243
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DirectLex.php490
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PEARSax3.php139
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PH5P.php3904
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PercentEncoder.php98
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer.php176
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/CSSDefinition.php38
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.css10
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.js5
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.css2
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.js2
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.php368
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/HTMLDefinition.php272
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyList.php86
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyListIterator.php32
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy.php26
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Composite.php25
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Core.php18
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/FixNesting.php328
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/MakeWellFormed.php532
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/RemoveForeignElements.php171
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/ValidateAttributes.php39
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHash.php39
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHashParser.php110
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform.php36
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Font.php98
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Simple.php35
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token.php57
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Comment.php22
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Empty.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/End.php19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Start.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Tag.php57
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Text.php33
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TokenFactory.php94
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URI.php204
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIDefinition.php93
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter.php45
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternal.php23
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternalResources.php12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableResources.php11
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/HostBlacklist.php21
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/MakeAbsolute.php114
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/Munge.php58
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIParser.php70
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme.php89
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/data.php96
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/file.php32
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/ftp.php42
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/http.php19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/https.php12
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/mailto.php27
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/news.php22
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/nntp.php19
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URISchemeRegistry.php68
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/UnitConverter.php254
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser.php154
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Flexible.php103
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Native.php26
-rw-r--r--admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParserException.php11
-rw-r--r--admin/survey/classes/log/class.SurveyLog.php98
-rw-r--r--admin/survey/classes/mobile/class.MobileSurveyAdmin.php746
-rw-r--r--admin/survey/classes/objects/obj.MailAdapter.php945
-rw-r--r--admin/survey/classes/objects/obj.PopUp.php150
-rw-r--r--admin/survey/classes/objects/obj.PopUpButton.php133
-rw-r--r--admin/survey/classes/objects/obj.PopUpCancelButton.php57
-rw-r--r--admin/survey/classes/objects/obj.SpremenljivkaSkala.php195
-rw-r--r--admin/survey/classes/phpqrcode/CHANGELOG38
-rw-r--r--admin/survey/classes/phpqrcode/INSTALL67
-rw-r--r--admin/survey/classes/phpqrcode/LICENSE165
-rw-r--r--admin/survey/classes/phpqrcode/README45
-rw-r--r--admin/survey/classes/phpqrcode/VERSION2
-rw-r--r--admin/survey/classes/phpqrcode/bindings/tcpdf/qrcode.php2875
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_1.pngbin0 -> 126 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_10.pngbin0 -> 202 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_11.pngbin0 -> 205 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_12.pngbin0 -> 216 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_13.pngbin0 -> 210 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_14.pngbin0 -> 213 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_15.pngbin0 -> 219 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_16.pngbin0 -> 211 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_17.pngbin0 -> 211 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_18.pngbin0 -> 228 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_19.pngbin0 -> 225 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_2.pngbin0 -> 144 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_20.pngbin0 -> 225 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_21.pngbin0 -> 235 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_22.pngbin0 -> 226 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_23.pngbin0 -> 220 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_24.pngbin0 -> 242 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_25.pngbin0 -> 242 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_26.pngbin0 -> 244 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_27.pngbin0 -> 237 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_28.pngbin0 -> 234 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_29.pngbin0 -> 232 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_3.pngbin0 -> 147 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_30.pngbin0 -> 255 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_31.pngbin0 -> 260 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_32.pngbin0 -> 262 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_33.pngbin0 -> 253 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_34.pngbin0 -> 256 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_35.pngbin0 -> 243 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_36.pngbin0 -> 272 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_37.pngbin0 -> 279 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_38.pngbin0 -> 279 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_39.pngbin0 -> 264 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_4.pngbin0 -> 149 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_40.pngbin0 -> 267 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_5.pngbin0 -> 150 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_6.pngbin0 -> 151 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_7.pngbin0 -> 189 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_8.pngbin0 -> 204 bytes
-rw-r--r--admin/survey/classes/phpqrcode/cache/frame_9.pngbin0 -> 199 bytes
-rw-r--r--admin/survey/classes/phpqrcode/imgs/.gitignore2
-rw-r--r--admin/survey/classes/phpqrcode/index.php94
-rw-r--r--admin/survey/classes/phpqrcode/phpqrcode.php3312
-rw-r--r--admin/survey/classes/phpqrcode/qrbitstream.php180
-rw-r--r--admin/survey/classes/phpqrcode/qrconfig.php17
-rw-r--r--admin/survey/classes/phpqrcode/qrconst.php54
-rw-r--r--admin/survey/classes/phpqrcode/qrencode.php502
-rw-r--r--admin/survey/classes/phpqrcode/qrimage.php95
-rw-r--r--admin/survey/classes/phpqrcode/qrinput.php729
-rw-r--r--admin/survey/classes/phpqrcode/qrlib.php43
-rw-r--r--admin/survey/classes/phpqrcode/qrmask.php328
-rw-r--r--admin/survey/classes/phpqrcode/qrrscode.php210
-rw-r--r--admin/survey/classes/phpqrcode/qrspec.php592
-rw-r--r--admin/survey/classes/phpqrcode/qrsplit.php311
-rw-r--r--admin/survey/classes/phpqrcode/qrtools.php172
-rw-r--r--admin/survey/classes/phpqrcode/tools/merge.bat2
-rw-r--r--admin/survey/classes/phpqrcode/tools/merge.php70
-rw-r--r--admin/survey/classes/phpqrcode/tools/merge.sh2
-rw-r--r--admin/survey/classes/phpqrcode/tools/merged_config.php17
-rw-r--r--admin/survey/classes/phpqrcode/tools/merged_header.php36
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.html363
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.html330
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.html108
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledOpisne.html106
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledOpisne.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.html43
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.html62
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.html303
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledTTest.html41
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledTTest.min.html2
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledTabele.html209
-rw-r--r--admin/survey/classes/staticHtml/AnalizaPredogledTabele.min.html2
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyAnalysis.php8156
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyAnalysisArchive.php1264
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyAnalysisHelper.php126
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyBreak.php1578
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyChart.php10829
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyCrosstabs.php2606
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyEditsAnalysis.php984
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyMeans.php1369
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyMultiCrosstabs.php2489
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyTTest.php1207
-rw-r--r--admin/survey/classes/surveyAnalysis/class.SurveyTableChart.php2853
-rw-r--r--admin/survey/classes/surveyData/class.ExclusiveLock.php80
-rw-r--r--admin/survey/classes/surveyData/class.SurveyDataCollect.php4382
-rw-r--r--admin/survey/classes/surveyData/class.SurveyDataDisplay.php3535
-rw-r--r--admin/survey/classes/surveyData/class.SurveyDataFile.php550
-rw-r--r--admin/survey/classes/surveyData/class.SurveySNDataFile.php641
-rw-r--r--admin/survey/classes/surveyEmails/class.SurveyAlert.php569
-rw-r--r--admin/survey/classes/surveyEmails/class.SurveyInvitationsNew.php10534
-rw-r--r--admin/survey/classes/surveyEmails/class.SurveySimpleMailInvitation.php464
-rw-r--r--admin/survey/classes/surveyEmails/class.SurveyUnsubscribe.php268
-rw-r--r--admin/survey/classes/surveyEmails/squalo/api_test.php97
-rw-r--r--admin/survey/classes/surveyEmails/squalo/class.SqualoApi.php298
-rw-r--r--admin/survey/classes/surveyEmails/squalo/class.SurveyInvitationsSqualo.php480
-rw-r--r--admin/survey/classes/tracking/CrossRoad.php251
-rw-r--r--admin/survey/classes/tracking/TrackingClass.php420
-rw-r--r--admin/survey/classes/tracking/UserTrackingClass.php124
540 files changed, 161677 insertions, 0 deletions
diff --git a/admin/survey/classes/class.Cache.php b/admin/survey/classes/class.Cache.php
new file mode 100644
index 0000000..6635055
--- /dev/null
+++ b/admin/survey/classes/class.Cache.php
@@ -0,0 +1,269 @@
+<?php
+
+class Cache
+{
+
+ private static $srv_spremenljivka = null;
+
+ private static $srv_branching__el_spr__el_if = null; // tabela s pointerji ce iscemo po element_spr in element_if
+ private static $srv_branching__parent = null; // tabela s pointerji ce iscemo po parentu (zraven je se order by)
+
+ private static $srv_if = null;
+
+ private static $srv_condition = null;
+
+ private static $_spremenljivkaLegenda = null;
+
+ /**
+ * vrne vrstico za podano spremenljivko iz tabele srv_spremenljivka
+ * če je podana vrednost vračamo samo specifično vrednost
+ *
+ * @param mixed $spr
+ * @param $vrednost $spr
+ * @return Cache
+ */
+ static function srv_spremenljivka($spr, $vrednost = null)
+ {
+
+ if (isset(self::$srv_spremenljivka[$spr])) {
+ if ($vrednost == null) {
+ return self::$srv_spremenljivka[$spr];
+ } else {
+ if (isset(self::$srv_spremenljivka[$spr][$vrednost])) {
+ return self::$srv_spremenljivka[$spr][$vrednost];
+ } else {
+ return null;
+ }
+ }
+ }
+
+ $sql = sisplet_query("SELECT * FROM srv_spremenljivka WHERE id = '$spr'");
+ self::$srv_spremenljivka[$spr] = mysqli_fetch_assoc($sql);
+
+ if ($vrednost == null) {
+ return self::$srv_spremenljivka[$spr];
+ } else {
+ if (isset(self::$srv_spremenljivka[$spr][$vrednost])) {
+ return self::$srv_spremenljivka[$spr][$vrednost];
+ } else {
+ return null;
+ }
+ }
+ }
+
+ /**
+ * naenkrat prebere vse spremenljivke za podano anketo (da ne delamo queryja vsakic posebej, kjer prikazujemo vse spremenljivke)
+ *
+ * @param mixed $anketa
+ */
+ static function cache_all_srv_spremenljivka($anketa, $force = false)
+ {
+ if (self::$srv_spremenljivka != null && $force == false) return;
+
+ $sql = sisplet_query("SELECT s.* FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ self::$srv_spremenljivka[$row['id']] = $row;
+ }
+
+ return self::$srv_spremenljivka;
+ }
+
+ static function get_spremenljivka($spr, $column)
+ {
+ $row = self::srv_spremenljivka($spr);
+
+ return $row[$column];
+ }
+
+ static function clear_cache()
+ {
+ self::$srv_spremenljivka = array();
+ }
+
+ static function clear_branching_cache()
+ {
+ self::$srv_branching__el_spr__el_if = null;
+ self::$srv_branching__parent = null;
+ }
+
+ static function clear_cache_all()
+ {
+ self::$srv_spremenljivka = null;
+
+ self::$srv_branching__el_spr__el_if = null;
+ self::$srv_branching__parent = null;
+
+ self::$srv_if = null;
+
+ self::$srv_condition = null;
+ }
+
+ static function cache_all_srv_branching($anketa, $force = false)
+ {
+ if (self::$srv_branching__el_spr__el_if !== null && self::$srv_branching__parent !== null && $force == false) return;
+
+ self::$srv_branching__el_spr__el_if = array(); // to je zaradi preverjanja if != null (ce je spodnji select prazen)
+ self::$srv_branching__parent = array();
+
+ $sql = sisplet_query("SELECT * FROM srv_branching WHERE ank_id='$anketa' ORDER BY vrstni_red ASC");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ while ($row = mysqli_fetch_assoc($sql)) {
+ self::$srv_branching__el_spr__el_if[$row['element_spr']][$row['element_if']] = $row;
+ self::$srv_branching__parent[$row['parent']][] = $row;
+ }
+ }
+
+ static function srv_branching($element_spr, $element_if)
+ {
+ if (isset(self::$srv_branching__el_spr__el_if[$element_spr][$element_if])) {
+ return self::$srv_branching__el_spr__el_if[$element_spr][$element_if];
+ }
+
+ $sql = sisplet_query("SELECT * FROM srv_branching WHERE element_spr='$element_spr' AND element_if='$element_if'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ self::$srv_branching__el_spr__el_if[$element_spr][$element_if] = mysqli_fetch_assoc($sql);
+
+ return self::$srv_branching__el_spr__el_if[$element_spr][$element_if];
+ }
+
+ static function srv_branching_parent($anketa, $parent)
+ {
+ if (self::$srv_branching__parent === null) {
+ self::cache_all_srv_branching($anketa);
+ }
+
+ if (isset(self::$srv_branching__parent[$parent])) {
+ return self::$srv_branching__parent[$parent];
+ }
+
+ return array(); // ce ni zadetka, vrnemo prazen array
+ }
+
+ static function srv_if($if)
+ {
+ if (isset(self::$srv_if[$if])) {
+ return self::$srv_if[$if];
+ }
+
+ $sql = sisplet_query("SELECT * FROM srv_if WHERE id = '$if'");
+ self::$srv_if[$if] = mysqli_fetch_assoc($sql);
+
+ return self::$srv_if[$if];
+ }
+
+ static function cache_all_srv_if($anketa, $force = false)
+ {
+ if (self::$srv_if != null && $force == false) return;
+
+ $sql = sisplet_query("SELECT srv_if.* FROM srv_if, srv_branching b WHERE b.element_if=srv_if.id AND b.ank_id='$anketa'");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ self::$srv_if[$row['id']] = $row;
+ }
+
+ return self::$srv_if;
+ }
+
+ static function srv_condition($if)
+ {
+ if (isset(self::$srv_condition[$if]) && is_resource(self::$srv_condition[$if])) {
+ if (mysqli_num_rows(self::$srv_condition[$if]) > 0)
+ mysqli_data_seek(self::$srv_condition[$if], 0);
+ return self::$srv_condition[$if];
+ }
+
+ self::$srv_condition[$if] = sisplet_query("SELECT * FROM srv_condition WHERE if_id = '$if' ORDER BY vrstni_red ASC");
+ return self::$srv_condition[$if];
+ }
+
+ static function spremenljivkaLegenda($spr_id)
+ {
+ if (is_array(self::$_spremenljivkaLegenda) && isset(self::$_spremenljivkaLegenda[$spr_id])) {
+ return self::$_spremenljivkaLegenda[$spr_id];
+ } else {
+ global $lang;
+
+ $result = array();
+ $spremenljivka = self::srv_spremenljivka($spr_id);
+
+ switch ($spremenljivka['tip']) {
+ case 0 : // Polje drugo
+ $result['tip'] = $lang['srv_sklop_polje_drugo'];
+ break;
+ case 1 : // radio
+ case 2 : // check
+ case 3 : // drop
+ case 7 : // number
+ case 21 : // besedilo
+ $result['tip'] = $lang['srv_sklop_osnovna_short'] . ' - ' . $lang['srv_vprasanje_tip_' . $spremenljivka['tip']];
+ break;
+ case 6 : // mgrid
+ case 16 : // mcheck
+ case 19 : // mtext
+ case 20 : // mnumber
+ $result['tip'] = $lang['srv_sklop_tabele_short'] . ' - ' . $lang['srv_vprasanje_tip_' . $spremenljivka['tip']];
+ break;
+ default : // mnumber
+ //$result = $lang['srv_sklop_posebna'];
+ $result['tip'] = $lang['srv_sklop_posebna_short'] . ' - ' . $lang['srv_vprasanje_tip_' . $spremenljivka['tip']];
+ break;
+ }
+ switch ($spremenljivka['tip']) {
+ case 1 : // radio
+ case 2 : // check
+ case 3 : // drop
+ case 6 : // mradio
+ case 16 : // mcheck
+ case 17 : // razvrščanje
+ $result['izrazanje'] = $lang['srv_analiza_vrsta_kate'];
+ break;
+ case 4 : // text
+ case 19 : // mtext
+ case 21 : // text*
+ $result['izrazanje'] = $lang['srv_analiza_vrsta_bese'];
+ break;
+ case 7 : // number
+ case 18 : // vsota
+ case 20 : // mnumber
+ case 22 : // kalkulacija
+ case 25 : // kvota
+ $result['izrazanje'] = $lang['srv_analiza_vrsta_stev'];
+ break;
+ case 8 : // datum
+ $result['izrazanje'] = $lang['srv_analiza_vrsta_stev'];
+ break;
+ case 5 : // nagovor
+ $result['izrazanje'] = $lang['srv_analiza_vrsta_nago'];
+ break;
+ }
+
+ # skalo rešimo objektno
+ $objectSkala = new SpremenljivkaSkala($spr_id);
+ $result['skalaAsValue'] = $objectSkala->getSkala();
+ $result['skala'] = $objectSkala->getSkalaAsText();
+
+ self::$_spremenljivkaLegenda[$spr_id] = $result;
+ return $result;
+ }
+ }
+
+ /************************************************
+ * Vreno srv_vrednosti za določeno spremenljivko_id
+ *
+ * @param (int) $spremenljivka_id
+ * @return (object)
+ ************************************************/
+ protected $spremenljivka_id;
+
+ public static function cache_all_srv_vrednost($spremenljivka_id)
+ {
+ $sql = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id='$spremenljivka_id'");
+ $polje = array();
+ while ($row = $sql->fetch_object()) {
+ $polje[] = $row;
+ }
+
+ return $polje;
+ }
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.Common.php b/admin/survey/classes/class.Common.php
new file mode 100644
index 0000000..6f761b6
--- /dev/null
+++ b/admin/survey/classes/class.Common.php
@@ -0,0 +1,2195 @@
+<?php
+
+/**
+ * pogoste funkcije iz SurveyAdmin
+ * da se klice raje tale mali file, namesto tisti gromozanski
+ */
+class Common {
+
+ static private $instance;
+
+ static private $anketa;
+
+ static private $db_table = '';
+
+ static private $time_start = null; // pri stetju casa izvajanja, sem shranimo zacetek izvajanja
+
+ static private $updateEditStamp = false; // ali ob koncu posodobimo time stamp ankete
+
+ // konstrutor
+ protected function __construct() {}
+ // kloniranje
+ final private function __clone() {}
+
+ /**
+ * Poskrbimo za samo eno instanco
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new Common();
+ }
+ return self::$instance;
+ }
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ static function Init( $anketa = null )
+ {
+ if ($anketa) {
+ self::$anketa = $anketa;
+ SurveyInfo::getInstance()->SurveyInit(self::$anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ self::$db_table = '_active';
+
+ }
+ }
+
+ /**
+ * @desc prestevilci variable vseh vprasanj v anketi
+ */
+ static function prestevilci ($spremenljivka = 0, $all = false, $force = false) {
+
+ // Preverimo ce imamo izklopljeno atomatsko prestevilcevanje
+ SurveySetting::getInstance()->Init(self::$anketa);
+
+ $enumerate = SurveySetting::getInstance()->getSurveyMiscSetting('enumerate'); if ($enumerate == '') $enumerate = 1;
+ if($enumerate == 0 && $all != true)
+ return;
+
+ // prestevilcimo spremenljivke (vse v anketi)
+ if ($spremenljivka == 0) {
+ self::prestevilci_if();
+
+ $i = 1;
+
+ $sql = sisplet_query("SELECT s.id, variable, variable_custom, s.tip AS tip FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='".self::$anketa."' AND s.tip!='9' ORDER BY g.vrstni_red, s.vrstni_red");
+
+ // ce je vec kot 50 spremenljivk nimamo avtomatskega prestevilcevanja
+ if ( ( mysqli_num_rows($sql) <= 50 or $all == true ) && mysqli_num_rows($sql)>0 ) {
+
+ $values = "";
+ $val_array = array();
+
+ $variable_array = array();
+
+ $j=1;
+ while ($row = mysqli_fetch_array($sql)) {
+ $variable_array[$row['id']]['id'] = $row['id'];
+ $variable_array[$row['id']]['variable'] = $row['variable'];
+ $variable_array[$row['id']]['variable_custom'] = $row['variable_custom'];
+ $variable_array[$row['id']]['vrstni_red'] = $j;
+
+ // Dodaten loop po spremenljivkah, ki so znotraj kombinirane tabele (gru_id == -2)
+ if($row['tip'] == 24){
+
+ $sqlM2 = sisplet_query("SELECT s.id, s.variable, s.variable_custom FROM srv_spremenljivka s, srv_grid_multiple m
+ WHERE m.parent='".$row['id']."' AND m.ank_id='".self::$anketa."' AND s.id=m.spr_id
+ ORDER BY m.vrstni_red");
+ while ($rowM2 = mysqli_fetch_array($sqlM2)) {
+
+ $j++;
+
+ $variable_array[$rowM2['id']]['id'] = $rowM2['id'];
+ $variable_array[$rowM2['id']]['variable'] = $rowM2['variable'];
+ $variable_array[$rowM2['id']]['variable_custom'] = $rowM2['variable_custom'];
+ $variable_array[$rowM2['id']]['vrstni_red'] = $j;
+ }
+ }
+
+ $j++;
+ }
+
+ $variable_array2 = $variable_array;
+
+ // Loop cez vsa vprasanja v anketi po vrstnem redu
+ foreach($variable_array2 as $row) {
+
+ // Ce vprasanje nima custom variable jo lahko prestevilcimo
+ if ($row['variable_custom'] == 0) {
+
+ do {
+ // Nastavimo variablo na stevilko ki pripada njenemu vrstnemu redu
+ $variable = 'Q' . $i;
+ $variable_ok = true;
+ $i++;
+
+ // Loop cez vsa ostala vprasanja, kjer preverimo ce obstaja se kaksna z istim imenom (ki je custom ali pa ima manjsi vrstni red)
+ foreach ($variable_array AS $spr => $var) {
+ if ($spr != $row['id'] && $var['variable'] == $variable && ($var['variable_custom'] == 1 || $i > $var['vrstni_red'])) {
+ $variable_ok = false;
+ }
+ }
+ } while ( ! $variable_ok );
+
+ // Nasli smo ustrezno poimenovanje in ga updatamo
+ if ($row['variable'] != $variable) {
+ $variable_array[$row['id']]['variable'] = $variable;
+ sisplet_query("UPDATE srv_spremenljivka SET variable = '$variable' WHERE id = '$row[id]'");
+ if ($values != "") $values .= ", ";
+ $values .= "('$row[id]', '$variable')";
+ }
+ }
+
+ // po vrsti shranjujemo vprasanja v array, ker moramo na koncu se prestevilciti njihove notranje variable
+ array_push($val_array, $row['id']);
+ }
+
+ // prestevilcimo se variable znotraj posameznih vprasanja - prestevilci moramo poklicati sele za zgornjim INSERTom!
+ foreach ($val_array AS $key => $val) {
+ self::prestevilci($val);
+ }
+ }
+ }
+ // prestevilcimo variable v spremenljivki
+ else {
+
+ // Nastavitev da ostevilcujemo v obratnem vrstnem redu (samo radio tip)
+ $rowSpr = Cache::srv_spremenljivka($spremenljivka);
+ $spremenljivkaParams = new enkaParameters($rowSpr['params']);
+ $reverse_var = ($spremenljivkaParams->get('reverse_var') ? $spremenljivkaParams->get('reverse_var') : 0);
+
+ //sisplet_query("BEGIN");
+ $j = 1;
+ // Ce je katerakoli variabla custom, potem ne prestevilcimo vec
+ $sql = sisplet_query("SELECT v.id AS id, s.tip AS tip, s.variable AS variable, v.other as other, v.variable AS variable_vre
+ FROM srv_vrednost v, srv_spremenljivka s
+ WHERE
+ v.spr_id = s.id AND
+ v.spr_id = '$spremenljivka' AND
+ v.variable_custom = '0' AND
+ v.vrstni_red > '0' AND
+ NOT EXISTS (SELECT v2.* from srv_vrednost v2 WHERE v2.spr_id=v.spr_id AND v2.vrstni_red>'0' AND v2.variable_custom='1')
+ ORDER BY v.vrstni_red ".($reverse_var == 1 ? ' DESC' : ' ASC')."
+ ");
+
+ $values = "";
+ $tip = 0;
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['other'] == 0 || $row['other'] == 1) { # missing value ne preštevilčimo
+ //do {
+ // Popravimo imena spremenljivk pri tabelah (zdruzimo ime variable + abeceda)
+ //if ($row['tip'] == 2 || $row['tip'] == 6 || $row['tip'] == 7 || $row['tip'] == 16 || $row['tip'] == 17 || $row['tip'] == 18 || $row['tip'] == 19 || $row['tip'] == 20 || $row['tip'] == 21 || $row['tip'] == 24) {
+ if ($row['tip'] == 2 || $row['tip'] == 6 || $row['tip'] == 7 || $row['tip'] == 16 || $row['tip'] == 17 || $row['tip'] == 18 || $row['tip'] == 19 || $row['tip'] == 20 || $row['tip'] == 21 || $row['tip'] == 24 || $row['tip'] == 26 || $row['tip'] == 27) {
+ if (mysqli_num_rows($sql) <= 26) {
+ $variable_vre = $row['variable'] . chr($j +96);
+ } else {
+ $jjj = bcdiv($j-1, 26) + 1;
+ $jj = bcmod($j-1, 26) + 1; if ($jj == 0) { $jj=26; $jjj--; };
+ $variable_vre = $row['variable'] . chr($jjj +96) . chr($jj +96);
+ }
+ } else {
+ $variable_vre = $j;
+ }
+ //$sqlCheckVariable = sisplet_query("SELECT id FROM srv_vrednost WHERE variable='$variable_vre' AND spr_id = '$spremenljivka' AND id <> '$row[id]'");
+ $j++;
+ //} while (mysqli_num_rows($sqlCheckVariable) > 0);
+
+ if ($row['variable_vre'] != $variable_vre) {
+ sisplet_query("UPDATE srv_vrednost SET variable='$variable_vre' WHERE id = '$row[id]'");
+ if ($values != "") $values .= ", ";
+ $values .= "('$row[id]', '$variable_vre')";
+ }
+ }
+ }
+
+ //sisplet_query("COMMIT");
+ }
+ }
+
+ /**
+ * @desc prestevilci ife
+ */
+ static $prestevilci_if = '';
+ static function prestevilci_if($parent = 0, & $number = 1) {
+
+ if ($parent == 0)
+ self::$prestevilci_if = '';
+
+ $sql = sisplet_query("SELECT element_if FROM srv_branching WHERE ank_id='".self::$anketa."' AND parent='$parent' AND element_if>'0' ORDER BY vrstni_red");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ if (self::$prestevilci_if != "") self::$prestevilci_if .= ", ";
+ self::$prestevilci_if .= "('$row[element_if]', '$number')";
+
+ $number++;
+ self::prestevilci_if($row['element_if'], $number);
+ }
+
+ if ($parent == 0 && self::$prestevilci_if != "") {
+ $s = sisplet_query("INSERT INTO srv_if (id, number) VALUES ".self::$prestevilci_if." ON DUPLICATE KEY UPDATE number = VALUES (number)");
+ if (!$s) echo 'e345'.mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+
+ /**
+ * pobrise podatke, ki se izpolnijo v preview modu ankete
+ *
+ * @param boolean vedno brišemo samo iz trenutne ankete zaradi brisanja iz podatkovne datoteke
+ */
+ static function deletePreviewData ($sid = null) {
+
+ if ($sid == null || (int)$sid == 0)
+ return;
+ else
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE preview='1' AND time_edit < NOW() - INTERVAL 3 HOUR AND ank_id = '".$sid."'");
+
+ # polovimo vrsto tabel za to anketo
+ $strDbTable = "SELECT db_table FROM srv_anketa WHERE id = $sid";
+ $qryDbTable = sisplet_query($strDbTable);
+ list($db_table) = mysqli_fetch_row($qryDbTable);
+
+ $list = '';
+ // se je dogajalo da je 0 ... pa se je pojavljal mysql_fetch error
+ if (mysqli_num_rows($sql) > 0) {
+ $prefix = '';
+ while ($row = mysqli_fetch_array($sql)) {
+ $list = $list.$prefix.$row['id'];
+ $prefix = ', ';
+ }
+ }
+ if ($list != '') {
+ sisplet_query("BEGIN");
+ // tabela z respondenti
+ $deleted = sisplet_query("DELETE FROM srv_user WHERE preview='1' AND id IN ($list) AND ank_id = '$sid'");
+
+ // tabele s podatki
+ sisplet_query("DELETE FROM srv_data_checkgrid".$db_table." WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_glasovanje WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_grid".$db_table." WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_imena WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_number WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_rating WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_text".$db_table." WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_textgrid".$db_table." WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_data_vrednost".$db_table." WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_userstatus WHERE usr_id IN ($list)");
+ sisplet_query("DELETE FROM srv_user_grupa".$db_table." WHERE usr_id IN ($list)");
+
+ sisplet_query("COMMIT");
+ }
+ }
+
+ /**
+ * ob zacetku izvajanja shranimo cas izvajanja
+ *
+ */
+ static function start () {
+ self::$time_start = microtime(true);
+ }
+
+ /**
+ * ob koncu izvajanja izracunamo cas izvajanja in pozenemo updateEditStampSave(), ce je treba
+ *
+ */
+ static function stop () {
+
+ // racunanje casa izvedemo v updateTracking(), ki se poklice iz updateEditStampSave()
+ if ( self::$updateEditStamp == 1 ) {
+
+ self::updateEditStampSave();
+ }
+ }
+
+ /**
+ * oznacimo, da na koncu izvajanja popravimo timestamp ankete
+ *
+ */
+ static function updateEditStamp () {
+ self::$updateEditStamp = true;
+ }
+
+ /**
+ * @desc popravimo cas in userja popravka
+ */
+ static function updateEditStampSave() {
+ global $admin_type;
+ global $global_user_id;
+
+ if (isset ($_REQUEST['spremenljivka']))
+ $spremenljivka = $_REQUEST['spremenljivka'];
+ if (isset ($_REQUEST['anketa']))
+ $anketa = $_REQUEST['anketa'];
+ if (isset ($_REQUEST['grupa']))
+ $grupa = $_REQUEST['grupa'];
+
+ if (!$anketa > 0) {
+ if ($grupa > 0) {
+ $sql = sisplet_query("SELECT ank_id FROM srv_grupa WHERE id='$grupa'");
+ $row = mysqli_fetch_array($sql);
+ $anketa = $row['ank_id'];
+ }
+ elseif ($spremenljivka > 0) {
+ $sql = sisplet_query("SELECT gru_id FROM srv_spremenljivka WHERE id='$spremenljivka'");
+ $row = mysqli_fetch_array($sql);
+ $grupa = $row['gru_id'];
+ $sql = sisplet_query("SELECT ank_id FROM srv_grupa WHERE id='$grupa'");
+ $row = mysqli_fetch_array($sql);
+ $anketa = $row['ank_id'];
+ }
+ //Uros dodal, za API
+ elseif(isset(self::$anketa) && self::$anketa > 0)
+ $anketa = self::$anketa;
+ }
+
+ if ($anketa > 0) {
+ $update = true;
+ if ($admin_type == 0) {
+ $sql = sisplet_query("SELECT * FROM srv_dostop WHERE ank_id='$anketa' AND uid='$global_user_id'");
+ if (mysqli_num_rows($sql) == 0)
+ $update = false;
+ }
+
+ if ($update) {
+ $sql = sisplet_query("UPDATE srv_anketa SET edit_uid = '$global_user_id', edit_time=NOW() WHERE id='$anketa'");
+
+ # popravimo še polje za osvežitev podatkov seznama anket uporablja class: class.SurveyList.php
+ $updateString = "INSERT INTO srv_survey_list (id, updated) "
+ ." VALUES ('$anketa', '1') ON DUPLICATE KEY UPDATE updated='1'";
+ $s = sisplet_query($updateString);
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // vsilimo refresh podatkov
+ SurveyInfo :: getInstance()->resetSurveyData();
+ }
+
+ # vsilimo refresh header datoteke in datoteke s podatki
+ $update_header = "UPDATE srv_data_files SET head_file_time='0000-00-00', data_file_time='0000-00-00' WHERE sid='$anketa'";
+ sisplet_query($update_header);
+ sisplet_query("COMMIT");
+ }
+ }
+
+
+ /**
+ * @desc Vrne ID trenutnega uporabnika (ce ni prijavljen vrne 0)
+ */
+ static function uid() {
+ global $global_user_id;
+
+ return $global_user_id;
+ }
+
+ /**
+ * @desc popravi celotno anketo
+ */
+ static function repareAnketa($anketa = 0) {
+ if ($anketa == 0)
+ $anketa = self::$anketa;
+
+ if($anketa > 0){
+ self::repareGrupa($anketa);
+
+ $sql = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='".$anketa."'");
+ while ($row = mysqli_fetch_array($sql)) {
+ self::repareSpremenljivka($row['id']);
+
+ $sql1 = sisplet_query("SELECT id FROM srv_spremenljivka WHERE gru_id='$row[id]'");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ self::repareVrednost($row1['id']);
+ }
+ }
+ }
+ }
+
+ /**
+ * @desc popravi vrstni red v tabeli srv_grupa
+ */
+ static function repareGrupa($anketa) {
+
+ if($anketa > 0){
+ sisplet_query("BEGIN");
+
+ $sql = sisplet_query("SELECT id, vrstni_red FROM srv_grupa WHERE ank_id='$anketa' ORDER BY vrstni_red");
+ $i = 1;
+
+ $values = "";
+
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['vrstni_red'] != $i) {
+ $sql1 = sisplet_query("UPDATE srv_grupa SET vrstni_red='$i' WHERE id = '$row[id]'");
+ if ($values != "") $values .= ", ";
+ $values .= "('$row[id]', '$i')";
+ }
+ $i++;
+ }
+
+ //if ($values != "") sisplet_query("INSERT INTO srv_grupa (id, vrstni_red) VALUES $values ON DUPLICATE KEY UPDATE vrstni_red=VALUES(vrstni_red)");
+ sisplet_query("COMMIT");
+ }
+ }
+
+ /**
+ * @desc popravi vrstni red v tabeli srv_spremenljivka
+ */
+ static function repareSpremenljivka($grupa) {
+
+ if($grupa > 0){
+ sisplet_query("BEGIN");
+ $sql = sisplet_query("SELECT id, vrstni_red FROM srv_spremenljivka WHERE gru_id='$grupa' ORDER BY vrstni_red");
+ $i = 1;
+
+ $values = "";
+
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['vrstni_red'] != $i) {
+ $sql1 = sisplet_query("UPDATE srv_spremenljivka SET vrstni_red='$i' WHERE id = '$row[id]'");
+ if ($values != "") $values .= ", ";
+ $values .= "('$row[id]', '$i')";
+ }
+ $i++;
+ }
+
+ //if ($values != "") sisplet_query("INSERT INTO srv_spremenljivka (id, vrstni_red) VALUES $values ON DUPLICATE KEY UPDATE vrstni_red=VALUES(vrstni_red)");
+ sisplet_query("COMMIT");
+ }
+ }
+
+ /**
+ * @desc popravi vrstni red v tabeli srv_vrednost
+ */
+ static function repareVrednost($spremenljivka) {
+
+ if($spremenljivka > 0){
+ sisplet_query("BEGIN");
+
+ $sql = sisplet_query("SELECT id, vrstni_red FROM srv_vrednost WHERE spr_id='$spremenljivka' AND vrstni_red>0 AND other <= 1 ORDER BY vrstni_red ASC");
+ $i = 1;
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['vrstni_red'] != $i) {
+ $sql1 = sisplet_query("UPDATE srv_vrednost SET vrstni_red='$i' WHERE id = '$row[id]'");
+ }
+ $i++;
+ }
+
+ //tole je za opcijo drugo (kjer gre vrstni_red v minus)
+ $sql = sisplet_query("SELECT id, vrstni_red FROM srv_vrednost WHERE spr_id='$spremenljivka' AND vrstni_red<0 AND other <= 1 ORDER BY vrstni_red DESC");
+ $i = -1;
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['vrstni_red'] != $i)
+ $sql1 = sisplet_query("UPDATE srv_vrednost SET vrstni_red='$i' WHERE id = '$row[id]'");
+ $i--;
+ }
+
+ sisplet_query("COMMIT");
+ }
+ }
+
+ /**
+ * shrani trenutno stanje ankete in obvesti administratorja, da nekaj ni ok z anketo
+ *
+ * Vcasih se je sesuval srv_branching zaradi nekih bugov, ki so popravljeni. Zdaj se to zgodi samo v primerih, ce se kopira staro pokvarjeno anketo.
+ * Ce se pokvari srv_branching je ponavadi dovolj, da se v anketi premakne kaksno vprasanje (lahko na isto mesto), da se spet izvede funkcija, ki pocisti bazo
+ *
+ * TOLE UGASNEMO KER VČASIH KAR LETIJO MAILI:)
+ */
+ static function checkStruktura () {
+ global $site_path;
+ global $site_url;
+
+ return;
+
+ if ( ! self::$anketa > 0 ) self::$anketa = (int)$_REQUEST['anketa'];
+ if ( ! self::$anketa > 0 ) return;
+
+ $check = null;
+ if ( self::$anketa < 8730 ) {
+ return;
+ $check = self::checkBranchingOld();
+ } else {
+ $check = self::checkBranching();
+ }
+
+ if ( ! $check ) {
+
+ $user = self::uid();
+
+ $get = '';
+ foreach ($_GET AS $key => $val) {
+ if ($get != '')
+ $get .= ', ';
+ $get .= $key . ': "' . $val . '"';
+ }
+
+ $post = '';
+ foreach ($_POST AS $key => $val) {
+ if ($post != '')
+ $post .= ', ';
+ $post .= $key . ': "' . $val . '"';
+ }
+
+ $branching = 'ank_id'. " \t - \t ".'parent'." \t - \t ".'vrstni_red'." \t - \t ".'element_spr'." \t - \t ".'element_if'." \t - \t ".'pagebreak'.'<br>';
+ $sql = sisplet_query("SELECT * FROM srv_branching WHERE ank_id = '".self::$anketa."' ORDER BY parent, vrstni_red");
+ while ($row = mysqli_fetch_array($sql)) {
+ $branching .= $row['ank_id']. " \t - \t ".$row['parent']." \t - \t ".$row['vrstni_red']." \t - \t ".$row['element_spr']." \t - \t ".$row['element_if']." \t - \t ".$row['pagebreak'].'<br>';
+ }
+
+ $content = " ce se pokvari srv_branching je ponavadi dovolj, da se v anketi premakne kaksno vprasanje (lahko na isto mesto), da se spet izvede funkcija, ki pocisti bazo<br><br>".
+ " anketa id:<br> " . self::$anketa . "<br><br>".
+ " <a href=\"".$site_url."admin/survey/index.php?anketa=".self::$anketa."\">".$site_url."admin/survey/index.php?anketa=".self::$anketa."</a><br><br>".
+ " site:<br> " . $site_path ."<br><br>".
+ " get:<br> " . $get ."<br><br>".
+ " post:<br> " . $post ."<br><br>".
+ " srv_branching:<br><pre>" . $branching ."</pre><br><br>".
+ " user:<br> " . $user ."<br><br>"
+ ;
+
+ try
+ {
+ $MA = new MailAdapter(self::$anketa, $type='admin');
+ //$MA->addRecipients('mitja@sisplet.org');
+ $MA->addRecipients('peter.hrvatin@siol.net');
+ $resultX = $MA->sendMail($content, 'Sesut srv_branching '.self::$anketa);
+ }
+ catch (Exception $e)
+ {
+ }
+ }
+
+ }
+
+ /**
+ * rekurzivno preverja, ce je z srv_branchingom vse ok
+ * v nulo, vrstni_red mora bit 1, 2, 3, ...
+ *
+ * @param mixed $parent
+ */
+ static function checkBranching ($parent = 0) {
+
+ if ( ! self::$anketa > 0 ) return false;
+
+ $sql = sisplet_query("SELECT parent, vrstni_red, element_if FROM srv_branching WHERE ank_id = '".self::$anketa."' AND parent='$parent' ORDER BY parent, vrstni_red");
+ $parent = null;
+ $vrstni_red = null;
+ while ($row = mysqli_fetch_array($sql)) {
+
+ if ($parent == null || $parent != $row['parent']) {
+ $parent = $row['parent'];
+ //$vrstni_red = 0;
+ $vrstni_red = 1;
+ } else {
+ $vrstni_red++;
+ }
+
+ if ( $row['vrstni_red'] == $vrstni_red ) {
+
+ //ok
+ } else {
+ // not ok
+ return false;
+ }
+
+ if ($row['element_if'] > 0) {
+ if ( ! self::checkBranching($row['element_if']) )
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * rekurzivno preverja, ce je z srv_branchingom vse ok
+ * za starejse ankete, vazno je da se vrstni_red ne ponavlja, ok je npr: 123, 124, 125, 160, 162
+ *
+ * @param mixed $parent
+ */
+ static function checkBranchingOld ($parent = 0) {
+
+ if ( ! self::$anketa > 0 ) return false;
+
+ $sql = sisplet_query("SELECT parent, vrstni_red, element_if FROM srv_branching WHERE ank_id = '".self::$anketa."' AND parent='$parent' ORDER BY parent, vrstni_red");
+ $parent = null;
+ $vrstni_red = null;
+ while ($row = mysqli_fetch_array($sql)) {
+
+ if ($parent == null || $parent != $row['parent']) {
+ $parent = $row['parent'];
+ $vrstni_red = 0;
+ //$vrstni_red = 1;
+ } else {
+ //$vrstni_red++;
+ }
+
+ //echo $row['parent'].' '.$row['vrstni_red'].' ( '.$vrstni_red.' )<br>';
+
+ if ( $row['vrstni_red'] > $vrstni_red ) {
+
+ //ok
+ } else {
+ // not ok
+ return false;
+ }
+
+ if ($row['element_if'] > 0) {
+ if ( ! self::checkBranchingOld($row['element_if']) )
+ return false;
+ }
+
+ $vrstni_red = $row['vrstni_red'];
+ }
+
+ return true;
+ }
+
+ /**
+ * rekurzivno se sprehodimo cez vse elemente v anketi in vrnemo seznam v pravem vrstnem redu
+ *
+ * @param mixed $parent
+ */
+ static $branching_array = array();
+ static function getBranchingOrder ($parent = 0) {
+
+ if (! self::$anketa > 0) return false;
+
+ $sql = sisplet_query("SELECT element_spr, element_if, parent FROM srv_branching WHERE ank_id = '".self::$anketa."' AND parent='$parent' ORDER BY parent, vrstni_red");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ self::$branching_array[] = array('spr_id'=>$row['element_spr'], 'if_id'=>$row['element_if'], 'parent'=>$row['parent']);
+
+ if ($row['element_if'] > 0)
+ self::getBranchingOrder($row['element_if']);
+ }
+
+ if($parent == 0)
+ return self::$branching_array;
+ else
+ return false;
+ }
+
+
+ /** Naslov za odgovor email sporočil.
+ * Privzeto je avtor ankete
+ * Če ne uporabimo email uporabnika
+ * v nasprotnem primeru damo info@1ka.si ali info@safe.si (odvisno od domene)
+ *
+ * @return Ambigous <string, multitype:>
+ */
+ function getReplyToEmail() {
+ global $global_user_id, $site_domain;
+
+ # naslov za odgovor je avtor ankete
+ $sql = sisplet_query("SELECT email FROM users WHERE id = (select insert_uid from srv_anketa where id='".self::$anketa."')");
+ list($MailReplyTo) = mysqli_fetch_row($sql);
+ # preverimo veljavnost e-maila
+ if ($MailReplyTo == null || !$this->validEmail($MailReplyTo))
+ {
+ $sql = sisplet_query("SELECT email FROM users WHERE id = '$global_user_id'");
+ list($MailReplyTo) = mysqli_fetch_row($sql);
+ }
+
+ if ($MailReplyTo == null || trim($MailReplyTo) == '' || !$this->validEmail($MailReplyTo) )
+ {
+ if (strpos($site_domain, "safe.si") === false)
+ {
+ $MailReplyTo = '1ka@1ka.si';
+ }
+ else
+ {
+ $MailReplyTo = '1ka@safe.si';
+ }
+ }
+
+ return $MailReplyTo;
+ }
+
+ /** Naslov pošiljatelja email sporočil.
+ * odvisno od strani če smo na safe.si uporabimo info@safe.si
+ * če ne pa preberemo nastavitev iz baze
+ * oziroma uporabimo info@1ka.si
+ * po novem se vabila in obvescanje posilja iz raziskave@1ka.si (namesto info@1ka.si)
+ *
+ * @return Ambigous <string, multitype:>
+ */
+ function getFromEmail() {
+ global $global_user_id, $site_domain;
+ $MailFrom = 'info@1ka.si';
+
+ # nastavimo pošiljatelja
+ # za SAFE.SI naredimo hardcoded da se pošilja kao iz SAFE.SI
+ if (strpos($site_domain, "safe.si") === false)
+ {
+ #nismo iz SAFE.SI
+ $r = sisplet_query("SELECT value FROM misc WHERE what='AlertFrom'");
+ list ($MailFrom) = mysqli_fetch_row($r);
+ }
+ else
+ {
+ # smo na SAFE.SI
+ $MailFrom = 'info@safe.si';
+ }
+
+ # Če je slučanjo napaka nastavimo info@1ka.si
+ if ($MailFrom == null || trim($MailFrom) == '' || !$this->validEmail($MailFrom))
+ {
+ $MailFrom = 'info@1ka.si';
+ }
+ return $MailFrom;
+ }
+
+
+
+ /**
+ Validate an email address.
+ Provide email address (raw input)
+ Returns true if the email address has the email
+ address format and the domain exists.
+ */
+ function validEmail($email = null) {
+
+ $isValid = true;
+ $atIndex = strrpos($email, "@");
+
+ if (is_bool($atIndex) && !$atIndex) {
+ $isValid = false;
+ }
+ else {
+ $domain = substr($email, $atIndex+1);
+ $local = substr($email, 0, $atIndex);
+ $localLen = strlen($local);
+ $domainLen = strlen($domain);
+ $domain_parts = explode('.',$domain);
+
+ if ($localLen < 1 || $localLen > 64) {
+ // local part length exceeded
+ $isValid = false;
+ } else if ($domainLen < 1 || $domainLen > 255) {
+ // domain part length exceeded
+ $isValid = false;
+ } else if ($local[0] == '.' || $local[$localLen-1] == '.') {
+ // local part starts or ends with '.'
+ $isValid = false;
+ } else if ($domain[0] == '.' || $domain[$domainLen-1] == '.') {
+ // domain part starts or ends with '.'
+ $isValid = false;
+ } else if (preg_match('/\\.\\./', $local)) {
+ // local part has two consecutive dots
+ $isValid = false;
+ } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
+ // character not valid in domain part
+ $isValid = false;
+ } else if (preg_match('/\\.\\./', $domain)) {
+ // domain part has two consecutive dots
+ $isValid = false;
+ } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
+ // character not valid in local part unless
+ // local part is quoted
+ if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
+ $isValid = false;
+ }
+ } else if ( strlen($domain_parts[0]) < 1) {
+ // num chars in
+ $isValid = false;
+ } else if ( strlen($domain_parts[1]) < 1) {
+ $isValid = false;
+ }
+
+ /*if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
+ // domain not found in DNS
+ $isValid = false;
+ }*/
+ }
+
+ return $isValid;
+ }
+
+ static function formatNumberSimple ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands) . $sufix;
+
+ return $result;
+ }
+
+ static function formatNumber ($value, $digit = 0, $form=null,$sufix = "") {
+ # Kako izpisujemo decimalke in tisočice
+ $default_seperators = array( 0=>array('decimal_point'=>'.', 'thousands'=>','),
+ 1=>array('decimal_point'=>',', 'thousands'=>'.'));
+
+ if (is_array($form) && isset($form['decimal_point'])&& isset($form['thousands'])) {
+ $decimal_point = $form['decimal_point'];
+ $thousands = $form['thousands'];
+ } else {
+ $decimal_point = $default_seperators['decimal_point'];
+ $thousands = $default_seperators['thousands'];
+ }
+
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ $result = number_format($result, $digit, $decimal_point, $thousands).$sufix;
+
+ return $result;
+ }
+
+
+ /**
+ * @desc V podanem stringu poisce spremenljivke in jih spajpa z vrednostmi
+ */
+ private $dataPiping_query = null; // kesiramo query, ker ga bomo ponavljali za vsako spremenljivko
+ public function dataPiping ($text, $usr_id, $loop_id=null, $lang_id=null) {
+
+ if (stripos($text, "#") !== false) {
+ if ($this->dataPiping_query == null)
+ $this->dataPiping_query = sisplet_query("SELECT s.* FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='".self::$anketa."' AND s.gru_id=g.id AND s.tip!='5' AND (s.tip < '10' OR s.tip = '17' OR s.tip = '22' OR s.tip = '25' OR s.tip='21')");
+ if (mysqli_num_rows($this->dataPiping_query))
+ mysqli_data_seek($this->dataPiping_query, 0);
+
+ // pri loopih izpisemo samo vrednost spremenljivke za trenuten loop
+ if ($loop_id != null) {
+ $sql = sisplet_query("SELECT * FROM srv_loop_data WHERE id = '$loop_id'");
+ $row = mysqli_fetch_array($sql);
+ $loop_vre_id = $row['vre_id'];
+ $sql = sisplet_query("SELECT * FROM srv_loop WHERE if_id = '$row[if_id]'");
+ $row = mysqli_fetch_array($sql);
+ $loop_spr_id = $row['spr_id'];
+ } else $loop_spr_id = 0;
+
+ while ($row1 = mysqli_fetch_array($this->dataPiping_query)) {
+
+ if ($row1['tip'] <= 3) { // radio, checkbox, select
+
+ if (stripos($text, '#'.$row1['variable'].'#') !== false) {
+ $pipe = '';
+ if ($loop_spr_id == 0) { // obicen piping
+ $sql2 = sisplet_query("SELECT v.id, v.naslov, v.other FROM srv_data_vrednost".self::$db_table." d, srv_vrednost v WHERE d.vre_id=v.id AND d.spr_id='$row1[id]' AND v.spr_id='$row1[id]' AND d.usr_id='$usr_id'");
+
+ while ($row2 = mysqli_fetch_assoc($sql2)) {
+
+ // Piping za multilang anketo
+ if($lang_id != null){
+ $translate = self::translate_vrednost($lang_id, $row2['id']);
+ $row2['naslov'] = $translate ? $translate : $row2['naslov'];
+ }
+
+ if ($pipe != '') $pipe .= ', ';
+
+ if ($row2['other'] == 0) {
+ $pipe .= $row2['naslov'];
+ }
+ elseif ($row2['other'] == 1) {
+ $sql3 = sisplet_query("SELECT text FROM srv_data_text".self::$db_table." WHERE spr_id='$row1[id]' AND vre_id='$row2[id]' AND usr_id='$usr_id'");
+ $row3 = mysqli_fetch_array($sql3);
+ $pipe .= $row3['text'];
+ }
+ }
+ }
+ // piping v loopu
+ else {
+ $sql2 = sisplet_query("SELECT v.id, v.naslov, v.other FROM srv_vrednost v WHERE id = '$loop_vre_id'");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+ // Piping za multilang anketo
+ if($lang_id != null){
+ $translate = self::translate_vrednost($lang_id, $row2['id']);
+ $row2['naslov'] = $translate ? $translate : $row2['naslov'];
+ }
+
+ if ($pipe != '') $pipe .= ', ';
+
+ if ($row2['other'] == 0) {
+ $pipe .= $row2['naslov'];
+ }
+ elseif ($row2['other'] == 1) {
+ $sql3 = sisplet_query("SELECT text FROM srv_data_text".self::$db_table." WHERE spr_id='$row1[id]' AND vre_id='$row2[id]' AND usr_id='$usr_id'");
+ $row3 = mysqli_fetch_array($sql3);
+ $pipe .= $row3['text'];
+ }
+ }
+ }
+
+ $text = str_ireplace('#'.$row1['variable'].'#', '<span class="data-piping-'.$row1['id'].'">'.$pipe.'</span>', $text);
+ }
+ }
+ elseif ($row1['tip'] == 9) { // SN - imena
+
+ if (stripos($text, '#'.$row1['variable'].'#') !== false) {
+ $pipe = '';
+
+ // piping v loopu
+ $sql2 = sisplet_query("SELECT v.id FROM srv_vrednost v WHERE id = '$loop_vre_id'");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+ if ($pipe != '') $pipe .= ', ';
+
+ $sql3 = sisplet_query("SELECT text FROM srv_data_text".self::$db_table." WHERE spr_id='$row1[id]' AND vre_id='$row2[id]' AND usr_id='$usr_id'");
+ $row3 = mysqli_fetch_array($sql3);
+ $pipe .= $row3['text'];
+ }
+
+ $text = str_ireplace('#'.$row1['variable'].'#', '<span class="data-piping-'.$row1['id'].'">'.$pipe.'</span>', $text);
+ }
+
+ }
+ elseif ($row1['tip'] == 4 or $row1['tip'] == 7 or $row1['tip'] == 8 or $row1['tip'] == 22 or $row1['tip'] == 25 or $row1['tip'] == 21) { // textbox, number, datum
+
+ // piping v loopu za number
+ if ($row1['tip'] == 7 && $loop_spr_id != 0) {
+
+ $sql3 = sisplet_query("SELECT COUNT(*)+1 AS c FROM srv_loop_data WHERE if_id='$row[if_id]' AND id<'$loop_id'");
+ $row3 = mysqli_fetch_array($sql3);
+ $text = str_ireplace('#'.$row1['variable'].'#', '<span class="data-piping-'.$row1['id'].'">'.$row3['c'].'</span>', $text);
+ }
+ else {
+ if (stripos($text, '#'.$row1['variable'].'#') !== false) {
+ $sql2 = sisplet_query("SELECT text FROM srv_data_text".self::$db_table." WHERE spr_id='$row1[id]' AND usr_id='$usr_id'");
+ if (!$sql2) echo mysqli_error($GLOBALS['connect_db']);
+
+ $row2 = mysqli_fetch_array($sql2);
+
+ $text = str_ireplace('#'.$row1['variable'].'#', '<span class="data-piping-'.$row1['id'].'">'.nl2br($row2['text']).'</span>', $text);
+ }
+ }
+
+ }
+ elseif ($row1['tip'] == 6) { // multigrid
+
+ $sqlm = sisplet_query("SELECT id, variable FROM srv_vrednost WHERE spr_id = '$row1[id]'");
+ while ($rowm = mysqli_fetch_array($sqlm)) {
+ if (stripos($text, '#'.$rowm['variable'].'#') !== false) {
+
+ $pipe = '';
+
+ $sql2 = sisplet_query("SELECT g.id, g.naslov FROM srv_data_grid".self::$db_table." d, srv_grid g WHERE d.grd_id=g.id AND d.spr_id=g.spr_id AND d.spr_id='$row1[id]' AND d.vre_id='$rowm[id]' AND d.usr_id='$usr_id'");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+
+ // Piping za multilang anketo
+ if($lang_id != null){
+ $translate = self::translate_grid($lang_id, $row1['id'], $row2['id']);
+ $row2['naslov'] = $translate ? $translate : $row2['naslov'];
+ }
+
+ if ($pipe != '') $pipe .= ', ';
+
+ $pipe .= $row2['naslov'];
+ }
+
+ $text = str_ireplace('#'.$rowm['variable'].'#', '<span class="data-piping-'.$row1['id'].'">'.$pipe.'</span>', $text);
+ }
+ }
+ }
+ elseif ($row1['tip'] == 17) { // Ranking
+
+ if (stripos($text, '#'.$row1['variable'].'#') !== false) {
+ $pipe = '';
+
+ // piping v loopu
+ $sql2 = sisplet_query("SELECT v.id, v.naslov FROM srv_vrednost v WHERE id = '$loop_vre_id'");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+ if ($pipe != '') $pipe .= ', ';
+
+ $pipe .= $row2['naslov'];
+ }
+
+ $text = str_ireplace('#'.$row1['variable'].'#', '<span class="data-piping-'.$row1['id'].'">'.$pipe.'</span>', $text);
+ }
+
+ }
+ }
+ }
+
+ return $text;
+ }
+
+ /**
+ * prevod za srv_spremenljivka
+ */
+ static function translate_spremenljivka($lang_id, $spremenljivka) {
+
+ if ($lang_id != null) {
+ $sqll = sisplet_query("SELECT * FROM srv_language_spremenljivka WHERE ank_id='".self::$anketa."' AND spr_id='".$spremenljivka."' AND lang_id='".$lang_id."'");
+ $rowl = mysqli_fetch_array($sqll);
+
+ return $rowl;
+ }
+
+ return false;
+ }
+
+ /**
+ * prevod za srv_vrednost
+ */
+ static function translate_vrednost($lang_id, $vrednost) {
+
+ if ($lang_id != null) {
+
+ $sqll = sisplet_query("SELECT naslov FROM srv_language_vrednost WHERE ank_id='".self::$anketa."' AND vre_id='".$vrednost."' AND lang_id='".$lang_id."'");
+ $rowl = mysqli_fetch_array($sqll);
+
+ if ($rowl['naslov'] != '')
+ return $rowl['naslov'];
+ }
+
+ return false;
+ }
+
+ /**
+ * prevod za srv_grid
+ */
+ static function translate_grid($lang_id, $spremenljivka, $grid) {
+
+ if ($lang_id != null) {
+
+ $sqll = sisplet_query("SELECT naslov FROM srv_language_grid WHERE ank_id='".self::$anketa."' AND spr_id=".$spremenljivka." AND grd_id='".$grid."' AND lang_id='".$lang_id."'");
+ $rowl = mysqli_fetch_array($sqll);
+
+ if ($rowl['naslov'] != '')
+ return $rowl['naslov'];
+ }
+
+ return false;
+ }
+
+
+ static function isUserAnketar($anketa,$user) {
+
+ $str = " (SELECT count(*)FROM srv_dostop AS sd WHERE sd.ank_id='$anketa' AND sd.aktiven = '1'"
+ ." AND uid = '$user' "
+ ." AND FIND_IN_SET('phone',sd.dostop )>0 AND FIND_IN_SET('edit',sd.dostop ) = 0)";
+ $qry = sisplet_query($str);
+ list($cnt) = mysqli_fetch_row($qry);
+
+ return ((int)$cnt > 0) ? true : false;;
+ }
+
+ static function getSpremenljivkaSkala($spr_id) {
+ # skala se lahko nastavlja samo za:
+ # ($row['tip'] == 1 || $row['tip'] == 2 || $row['tip'] == 3 || $row['tip'] == 6)
+
+
+ // uporabniško nastavljena
+ # skala - 1 Nominalna
+ # skala - 0 Ordinalna - računamo povprečja
+
+ # v bazi je privzeto -1
+
+ $row = Cache::srv_spremenljivka($spr_id);
+ $value = $row['skala'];
+ //pri checkboxu je default nominalna
+ if($row['skala'] == -1 && $row['tip'] == 2) {
+ $value = (int)1;
+
+ # če uporabnik še ni spremninjal
+ } elseif($row['skala'] == -1) {
+ # če je radio
+ if ($row['tip'] == 1 ) {
+ # če imamo opcij 4 ali več je ordinalna
+ $sql1 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = '$spr_id' ORDER BY vrstni_red ASC");
+ if (mysqli_num_rows($sql1) > 3) {
+ $value = (int)0; # Ordinalna - računamo povprečja
+ }
+ }
+ # če je multiradio
+ if ($row['tip'] == 6 ) {
+ # če imamo opcij 4 ali več je ordinalna
+ $sql_grid = sisplet_query("SELECT id FROM srv_grid WHERE spr_id='".$spr_id."'");
+ if (mysqli_num_rows($sql_grid) > 3) {
+ $value = (int)0; # Ordinalna - računamo povprečja
+ }
+ }
+ } else {
+ # drugače pustimo uporabniško nastavljeno (ali default (-1))
+ $value = (int)$row['skala'];
+ }
+
+ return $value;
+ }
+
+ // ime pove vse :-)
+ static function RemoveNiceUrl($ank_id) {
+ global $site_path;
+
+ $sql = sisplet_query("SELECT link FROM srv_nice_links WHERE ank_id = '$ank_id'");
+ $row = mysqli_fetch_array($sql);
+
+ $nice_url = $row['link'];
+
+ $f = fopen($site_path.'.htaccess', 'rb');
+
+ if ($f !== false) {
+ $output = array();
+
+ while (!feof($f)) {
+ $r = fgets($f);
+
+ if (strpos($r, "^".$nice_url.'\b(.*) ') !== false && strpos($r, "?anketa=".$ank_id."") !== false) {
+ // kao pobrisemo vrstico
+ } else {
+ $output[] = $r;
+ }
+ }
+
+ fclose($f);
+ }
+
+ if (count($output) > 0) {
+
+ $f = fopen($site_path.'.htaccess', 'w');
+
+ if ($f !== false) {
+ foreach ($output AS $line) {
+ fwrite($f, $line);
+ }
+ fclose($f);
+
+ $sql = sisplet_query("DELETE FROM srv_nice_links WHERE ank_id = '$ank_id'");
+
+ // Preverimo ce imamo skupine s tem urljem in jih pobrisemo
+ $sqlS = sisplet_query("SELECT * FROM srv_nice_links_skupine WHERE ank_id='$ank_id'");
+ if(mysqli_num_rows($sqlS) > 0){
+
+ $f = fopen($site_path.'.htaccess', 'rb');
+
+ if ($f !== false) {
+ $outputS = array();
+
+ while (!feof($f)) {
+ $r = fgets($f);
+
+ // Loop cez vse skupine
+ $delete = false;
+ $sqlS = sisplet_query("SELECT * FROM srv_nice_links_skupine WHERE ank_id='$ank_id'");
+
+ while($rowS = mysqli_fetch_array($sqlS)){
+
+ if (strpos($r, "^".$rowS['link'].'\b(.*) ') !== false && strpos($r, "?anketa=".$ank_id."&skupina=".$rowS['vre_id']."") !== false) {
+
+ // pobrisemo vrstico in vnos v bazi
+ $sqlD = sisplet_query("DELETE FROM srv_nice_links_skupine WHERE ank_id='$ank_id' AND nice_link_id='$row[id]' AND vre_id='$rowS[vre_id]'");
+ $delete = true;
+ }
+ }
+
+ if($delete == false){
+ $outputS[] = $r;
+ }
+ }
+ fclose($f);
+ }
+
+ if (count($outputS) > 0) {
+
+ $f = fopen($site_path.'.htaccess', 'w');
+ if ($f !== false) {
+ foreach ($outputS AS $line) {
+ fwrite($f, $line);
+ }
+ fclose($f);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * preveri ce je dolocen modul vklopljen na tej instalaciji 1ke (npr. hirearhija, evalvacija, 360...)
+ */
+ static function checkModule($module) {
+
+ $sql = sisplet_query("SELECT active FROM srv_module WHERE module_name='$module'");
+ $row = mysqli_fetch_array($sql);
+
+ return ($row['active'] == '1') ? true : false;
+ }
+
+
+ // Vrne help url glede na ustrezno podstran
+ public static function getHelpUrl($subdomain, $podstran){
+
+ // Default help url
+ $help_url = 'http://www.1ka.si/d/sl/pomoc';
+
+ // Angleški vmesnik - usmerimo na english.1ka.si help
+ if($subdomain == 'english'){
+
+ // Nastavitve in podzavihki
+ if ($_GET['anketa'] == '' && ($_GET['a'] == 'nastavitve' # in podzavihki
+ || $_GET['a'] == 'osn_pod'
+ || $_GET['a'] == 'trajanje'
+ || $_GET['a'] == 'dostop'
+ || $_GET['a'] == 'urejanje') ) {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/settings';
+ }
+
+ //Mobilne nastavitve
+ elseif($_GET['a']== 'mobile_settings'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/mobile-survey-adjustments';
+ }
+
+ //Standardne besede
+ elseif($_GET['a']== 'jezik'){
+ $help_url = 'https://www.1ka.si/d/en/help/faq/can-standard-words-be-altered';
+ }
+
+ //Dostop uredniki
+ elseif($_GET['a']== 'dostop'){
+ $help_url = 'https://www.1ka.si/d/en/help/faq/how-can-i-add-another-survey-administrator';
+ }
+
+ //Dostop respondenti
+ elseif($_GET['a']== 'piskot'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/settings-for-respondent-access-cookies-and-passwords';
+ }
+
+ // Obvescanje
+ else if ($_GET['a'] == 'alert') {
+ if($_GET['m']=='email_server'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/sending-emails-via-an-arbitrary-server-eg-gmail ';
+ }
+ else{
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/notifications';
+ }
+ }
+
+ //Aktivnost/kvote
+ elseif($_GET['a']== 'trajanje'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/survey-duration-based-on-date-or-the-number-of-responses';
+ }
+
+ //Skupine
+ elseif($_GET['a']== 'skupine'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/creating-respondent-groups';
+ }
+
+ //Komentarji
+ elseif($_GET['a']== 'urejanje'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/comments';
+ }
+
+ //Prikaz podatkov
+ elseif($_GET['a']== A_PRIKAZ){ //|| $_GET['a'] == A_PRIKAZ
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/data-display-settings';
+ }
+
+ //Parapodatki
+ elseif($_GET['a']== 'metadata'){ //|| $_GET['a'] == 'metadata'
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/edit/settings';
+ }
+
+ //Manjkajoce vrednosti
+ elseif($_GET['a']== 'missing'){ //|| $_GET['a'] == 'missing'
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/status-of-units-relevance-validity-and-missing-values';
+ }
+
+ //PDF/RFT Izvozi
+ elseif($_GET['a']== 'export_settings'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/settings-for-exporting-pdfrtf-files-with-responses';
+ }
+
+ //GDPR
+ elseif($_GET['a']== 'gdpr_settings'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/gdpr-survey-settings';
+ }
+
+ //Samoevalvacija v solah
+ elseif($_GET['a']== 'hierarhija_superadmin'){
+ //if($_GET['m']== 'uredi-sifrante'){
+ if($_GET['m']== 'uredi-sifrante' || $_GET['m']== 'status'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/advanced-modules/self-evaluation-schools';
+ }
+ }
+
+ //Klepet
+ elseif($_GET['a']== 'chat'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/advanced-modules/chat';
+ }
+
+ //Panel
+ elseif($_GET['a']== 'panel'){
+ $help_url = ' https://www.1ka.si/d/en/help/user-guide/advanced-modules/panel';
+ }
+
+ //Napredni parapodatki
+ elseif($_GET['a']== 'advanced_paradata'){
+ $help_url = 'https://www.1ka.si/d/en/about/general-description/user-levels/administrator';
+ }
+
+ //JSON izvoz ankete
+ elseif($_GET['a']== 'json_survey_export'){
+ $help_url = 'https://www.1ka.si/d/en/help';
+ }
+
+ //TABLICE, PRENOSNIKI (BETA)
+ elseif($_GET['a']== 'fieldwork'){
+ //$help_url = 'https://www.1ka.si/d/en/about/uses-of-1ka-services/1ka-offline';
+ $help_url = 'https://www.1ka.si/d/en/help';
+ }
+
+ //360 stopinj
+ elseif($_GET['a']== '360_stopinj'){
+ $help_url = 'https://www.1ka.si/d/en/help';
+ }
+
+ //borza
+ elseif($_GET['a']== 'borza'){
+ $help_url = 'https://www.1ka.si/d/en/help';
+ }
+
+ //mju
+ elseif($_GET['a']== 'mju'){
+ $help_url = 'https://www.1ka.si/d/en/help';
+ }
+
+ //excelleration matrix
+ elseif($_GET['a']== 'excell_matrix'){
+ $help_url = 'https://www.1ka.si/d/en/help';
+ }
+
+ //Povezave - jezik
+ elseif($_GET['a']== 'prevajanje'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/edit/settings/language';
+ }
+
+ // Napredni moduli
+ else if ($_GET['a'] == A_TELEPHONE) {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/advanced-modules/telephone-survey';
+ }
+ else if ($_GET['a'] == 'uporabnost') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/advanced-modules/website-evaluation-split-screen';
+ }
+ else if ($_GET['a'] == 'vnos') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/advanced-modules/administrative-data-input';
+ }
+ else if ($_GET['a'] == 'kviz') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/quiz';
+ }
+ else if ($_GET['a'] == 'slideshow') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/advanced-modules/slideshow';
+ }
+ else if ($_GET['a'] == 'social_network') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/social-networks';
+ }
+
+ // Oblika
+ else if ($_GET['a'] == 'tema') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/edit/design';
+ }
+ else if ($_GET['a'] == 'theme-editor') {
+ if($_GET['t'] == 'css'){
+ $help_url = 'https://www.1ka.si/d/en/help/faq/can-i-alter-the-design-of-an-individual-survey';
+ }else{
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/design';
+ }
+ }
+
+ // Arhivi
+ else if ($_GET['a'] == 'arhivi') {
+ if($_GET['m']== 'data'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/data-archive';
+ }elseif($_GET['m']== 'survey'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/export-survey-archive';
+ }elseif($_GET['m']== 'survey_data'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/export-survey-archive';
+ }elseif($_GET['m']== 'testdata'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/test-entries';
+ }
+ else{
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/questionnaire-archives';
+ }
+ }
+
+ //Spremembe
+ elseif($_GET['a']== 'tracking'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/archives-survey-changes';
+ }
+
+ // STATUS in podstrani
+ elseif($_GET['a']== 'reporti'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/summary';
+ }elseif($_GET['a']== 'para_graph'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/paradata';
+ }elseif($_GET['a']== 'nonresponse_graph'){
+ if($_GET['m']== 'breaks'){
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/interruptions-beta';
+ }elseif($_GET['m']== 'advanced'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/item-nonresponse';
+ }else{
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/item-nonresponse';
+ }
+ }elseif($_GET['a']== 'usable_resp'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/usable-respondents';
+ }elseif($_GET['a']== 'speeder_index'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/speed-index';
+ }elseif($_GET['a']== 'text_analysis'){
+ $help_url = '';
+ }elseif($_GET['a']== 'geoip_location'){
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/ip-location';
+ }
+
+ // Komentarji
+ else if ($_GET['a'] == 'komentarji' || $_GET['a'] == 'komentarji_anketa') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing/comments';
+ }
+
+ // Testiranje
+ else if ($_GET['a'] == 'testiranje') {
+ if ($_GET['m'] == 'diagnostika') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing/diagnostics';
+ }
+ else if ($_GET['m'] == 'testnipodatki') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing/automatic-entries';
+ }
+ else if ($_GET['m'] == 'predvidenicas') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing/diagnostics';
+ }
+ else if ($_GET['m'] == 'cas') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing/diagnostics';
+ }
+ else {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing/diagnostics';
+ }
+ }
+
+ // Vabila
+ else if ($_GET['a'] == 'vabila') {
+ if($_GET['m'] == 'url') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/publish/link-url';
+ }else{
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/publish/settings';
+ }
+ }
+
+ else if ($_GET['a'] == 'invitations') {
+ if ($_GET['m'] == 'add_recipients_view') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/publish/1ka-invitations';
+ } else if ($_GET['m'] == 'view_recipients') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/publish/1ka-invitations';
+ } else if ($_GET['m'] == 'view_message') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/publish/1ka-invitations';
+ } else if ($_GET['m'] == 'send_message') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/publish/1ka-invitations';
+ } else if ($_GET['m'] == 'view_archive') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/invitation-archives';
+ } else {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/publish/1ka-invitations';
+ }
+ }
+
+ // Podatki
+ else if ($_GET['a'] == 'data') {
+ if ($_GET['m'] == 'quick_edit') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/data/browse';
+ } else if ($_GET['m'] == 'calculation') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/computed-values';
+ } else if ($_GET['m'] == 'coding') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/manual-coding';
+ } else if ($_GET['m'] == 'coding_auto') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/automatic-coding';
+ } else if ($_GET['m'] == 'recoding') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/recoding';
+ } else if ($_GET['m'] == 'append') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/adding-data-append';
+ } else if ($_GET['m'] == 'merge') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/merging-data';
+ } else {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/data/browse';
+ }
+ }
+ // Izvoz podatkov
+ else if ($_GET['a'] == 'export') {
+ if ($_GET['m'] == 'spss' || $_GET['m'] == 'sav') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/export-to-spss';
+ }else if ($_GET['m'] == 'excel_xls') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/export-to-excel';
+ }else if ($_GET['m'] == 'excel') {
+ $help_url = 'https://www.1ka.si/d/en/help/faq/export-to-excel-why-are-answers-incomplete-when-i-export-the-data-to-excel';
+ }
+ else if ($_GET['m'] == 'txt') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/export-to-text-file';
+ } else {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/export-to-spss';
+ }
+ }
+
+ // Analiza
+ else if ($_GET['a'] == 'analysis' && (in_array($_GET['m'], array('', 'sumarnik', 'ttest', 'para')))) {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/analysis/statistics';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'charts') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/analysis/charts';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'anal_arch') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/analysis-archives';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'analysis_links') {
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/analysis/reports';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'analysis_creport') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/custom-reports';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'descriptor') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/descriptive-statistics';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'frequency') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/frequencies';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'crosstabs') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/crosstabs';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'multicrosstabs') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/multitables';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'means') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/means';
+ }else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'break') {
+ $help_url = 'https://www.1ka.si/d/en/help/manuals/break';
+ }
+
+ //My surveys
+ else if ($_GET['a'] == 'ustvari_anketo') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/creating-new-survey';
+ }
+
+ //Activities
+ else if ($_GET['a'] == 'diagnostics' && $_GET['t'] != 'uporabniki' && $_GET['m'] != 'my') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/activity';
+ }
+
+ //Users
+ else if ($_GET['a'] == 'diagnostics' && $_GET['t'] == 'uporabniki') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/users';
+ }
+
+ //Library
+ else if ($_GET['a'] == 'knjiznica') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/library';
+ }
+
+ //Sporocila
+ else if ($_GET['a'] == 'obvestila') {
+ $help_url = 'https://www.1ka.si/d/sl/o-1ka/splosen-opis/nivoji-uporabnikov/administrator';
+ }
+
+ //GDPR
+ else if ($_GET['a'] == 'gdpr') {
+ switch($_GET['m']){
+ case 'gdpr_survey_list':
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/list-of-surveys';
+ break;
+ case 'gdpr_requests':
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/gdpr-profile/processing-requests';
+ break;
+ case 'gdpr_requests_all':
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/gdpr-profile/processing-requests';
+ break;
+ case 'gdpr_dpa':
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/my-surveys/gdpr-profile/dpa';
+ break;
+ default:
+ $help_url = 'https://www.1ka.si/d/en/my-surveys/gdpr-profile/general-settings';
+ break;
+ }
+ }
+
+ //Analize urejanja
+ else if ($_GET['a'] == 'edits_analysis') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/dashboard/edits-analyses';
+ }
+
+ //Urejanje - Vprasalnik
+ else if ($_GET['a'] == 'branching') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/edit/questionnaire';
+ }
+
+ //Urejanje - Nastavitve
+ else if ($_GET['anketa'] != '' && $_GET['a'] == 'nastavitve') {
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/edit/settings';
+ }
+
+ // Moje ankete - narocila
+ else if ($_GET['a'] == 'narocila') {
+ $help_url = 'https://www.1ka.si/d/en/services';
+ }
+
+ // Ostale default podstrani
+ else {
+ switch ($podstran) {
+ case NAVI_UREJANJE:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/edit';
+ break;
+ case NAVI_OBJAVA:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/publish';
+ break;
+ case NAVI_RESULTS:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/data';
+ break;
+ case NAVI_ANALYSIS:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/analysis';
+ break;
+ case NAVI_TESTIRANJE:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/testing';
+ break;
+ case NAVI_STATUS:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/dashboard';
+ break;
+ case NAVI_ADVANCED:
+ $help_url = 'http://www.1ka.si/d/en/help/user-guide/advanced-modules';
+ break;
+ default:
+ //$help_url = 'https://www.1ka.si/d/en/help/my-surveys';
+ $help_url = 'https://www.1ka.si/d/en/help/user-guide/edit/questionnaire';
+ break;
+ }
+ }
+ }
+ // Slovenski vmesnik - usmerimo na www.1ka.si help
+ else{
+
+ // Nastavitve in podzavihki
+ if ($_GET['a'] == 'nastavitve' # in podzavihki
+ || $_GET['a'] == 'osn_pod') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/nastavitve';
+ }
+
+
+ //Mobilne nastavitve
+ elseif($_GET['a']== 'mobile_settings'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/prilagoditve-za-mobilno-anketo';
+ }
+
+ //Standardne besede
+ elseif($_GET['a']== 'jezik'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/ali-mozno-spremeniti-standardne-besede';
+ }
+
+ //Dostop uredniki
+ elseif($_GET['a']== 'dostop'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-dodam-se-eno-osebo-za-urejanje-vprasalnika';
+ }
+
+ //Dostop respondenti
+ elseif($_GET['a']== 'piskot'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/nastavitve-za-dostop-respondentov-piskotki-ip-naslovi-gesla-sistemsko-prepoznavanja';
+ }
+
+ //Aktivnost/kvote
+ elseif($_GET['a']== 'trajanje'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/trajanje-ankete-glede-na-datum-ali-stevilo-odgovorov-kvote';
+ }
+
+ //Skupine
+ elseif($_GET['a']== 'skupine'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/ustvarjanje-skupin-respondentov';
+ }
+
+ //Komentarji
+ elseif($_GET['a']== 'urejanje'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/komentarji';
+ }
+
+ //Prikaz podatkov
+ elseif($_GET['a']== A_PRIKAZ){ //|| $_GET['a'] == A_PRIKAZ
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/prikaz-podatkov-nastavitve';
+ }
+
+ //Parapodatki
+ elseif($_GET['a']== 'metadata'){ //|| $_GET['a'] == 'metadata'
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/anketni-podatki-parapodatki-identifikatorji-sistemske-spremenljivke';
+ }
+
+ //Manjkajoce vrednosti
+ elseif($_GET['a']== 'missing'){ //|| $_GET['a'] == 'missing'
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/statusi-enot-ustreznost-veljavnost-manjkajoce-vrednosti';
+ }
+
+ //PDF/RFT Izvozi
+ elseif($_GET['a']== 'export_settings'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/nastavitve-izvoza-pdfrtf-datotek-z-odgovori';
+ }
+
+ //GDPR
+ elseif($_GET['a']== 'gdpr_settings'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/gdpr-nastavitve-ankete';
+ }
+
+ //Samoevalvacija v solah
+ elseif($_GET['a']== 'hierarhija_superadmin'){
+ //if($_GET['m']== 'uredi-sifrante'){
+ if($_GET['m']== 'uredi-sifrante' || $_GET['m']== 'status'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/samoevalvacija-solah';
+ }
+ }
+
+ //Klepet
+ elseif($_GET['a']== 'chat'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/klepet';
+ }
+
+ //Panel
+ elseif($_GET['a']== 'panel'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/panel';
+ }
+
+ //Napredni parapodatki
+ elseif($_GET['a']== 'advanced_paradata'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/indeks-kakovosti-sledenje-opozorilom';
+ }
+
+ //JSON izvoz ankete
+ elseif($_GET['a']== 'json_survey_export'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc';
+ }
+
+ //
+
+ //TABLICE, PRENOSNIKI (BETA)
+ elseif($_GET['a']== 'fieldwork'){
+ //$help_url = 'https://www.1ka.si/d/sl/o-1ka/nacini-uporabe-1ka/1ka-offline';
+ $help_url = 'https://www.1ka.si/d/sl/pomoc';
+ }
+
+ //360 stopinj
+ elseif($_GET['a']== '360_stopinj'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc';
+ }
+
+ //borza
+ elseif($_GET['a']== 'borza'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc';
+ }
+
+ //mju
+ elseif($_GET['a']== 'mju'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc';
+ }
+
+ //excelleration matrix
+ elseif($_GET['a']== 'excell_matrix'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc';
+ }
+
+ //Povezave - jezik
+ elseif($_GET['a']== 'prevajanje'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/urejanje/nastavitve/jezik';
+ }
+
+ //Arhivi
+ elseif($_GET['a']== 'arhivi'){
+ if($_GET['m']== 'data'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/arhivi-podatkov';
+ }elseif($_GET['m']== 'survey'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/izvoz-arhivi-ankete';
+ }elseif($_GET['m']== 'survey_data'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/izvoz-arhivi-ankete';
+ }elseif($_GET['m']== 'testdata'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/testni-vnosi';
+ }
+ else{
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/arhivi-vprasalnika';
+ }
+ }
+
+ //Spremembe
+ elseif($_GET['a']== 'tracking'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/arhivi-spremembe-ankete';
+ }
+
+ // STATUS in podstrani
+ elseif($_GET['a']== 'reporti'){
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/povzetek/?from1ka=1';
+ }elseif($_GET['a']== 'para_graph'){
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/parapodatki/?from1ka=1';
+ }elseif($_GET['a']== 'nonresponse_graph'){
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/neodgovor-spremenljivke/?from1ka=1';
+ }elseif($_GET['a']== 'usable_resp'){
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/uporabni-respondenti/?from1ka=1';
+ }elseif($_GET['a']== 'speeder_index'){
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/indeks-hitrosti/?from1ka=1';
+ }elseif($_GET['a']== 'text_analysis'){
+ $help_url = '';
+ }elseif($_GET['a']== 'geoip_location'){
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/ip-lokacija/?from1ka=1';
+ }
+
+ // Obvescanje
+ else if ($_GET['a'] == 'alert') {
+ if($_GET['m']=='email_server'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/posiljanje-emailov-preko-smtp-email-sistema-1ka-na-strezniku-uporabnika-oziroma';
+ }
+ else{
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/obvescanje';
+ }
+ }
+
+ // Napredni moduli
+ else if ($_GET['a'] == A_TELEPHONE) {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/telefonska-anketa/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'uporabnost') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/evalvacija-strani/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'vnos') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/vnos-vprasalnikov/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'kviz') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/kviz';
+ }
+ else if ($_GET['a'] == 'slideshow') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/prezentacija/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'social_network') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/socialna-omrezja';
+ }
+
+ // Oblika
+ else if ($_GET['a'] == 'tema') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/urejanje/oblika/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'theme-editor') {
+ if($_GET['t'] == 'css'){
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/ali-lahko-spremenim-izgled-posamezne-ankete';
+ }else{
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/oblika';
+ }
+
+ }
+
+ // Komentarji
+ else if ($_GET['a'] == 'komentarji' || $_GET['a'] == 'komentarji_anketa') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/komentarji/?from1ka=1';
+ }
+
+ // Testiranje
+ else if ($_GET['a'] == 'testiranje') {
+ if ($_GET['m'] == 'diagnostika') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/diagnostika/?from1ka=1';
+ }
+ else if ($_GET['m'] == 'testnipodatki') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/avtomatski-vnosi/?from1ka=1';
+ }
+ else if ($_GET['m'] == 'predvidenicas') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/diagnostika/?from1ka=1';
+ }
+ else if ($_GET['m'] == 'cas') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/diagnostika/?from1ka=1';
+ }
+ else {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/diagnostika/?from1ka=1';
+ }
+ }
+
+ // Vabila
+ else if ($_GET['a'] == 'vabila') {
+ if($_GET['m'] == 'url') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/povezava-url/?from1ka=1';
+ }else{
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/nastavitve-objave/?from1ka=1';
+ }
+ }
+ else if ($_GET['a'] == 'invitations') {
+ if ($_GET['m'] == 'add_recipients_view') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/1ka-vabila/?from1ka=1';
+ } else if ($_GET['m'] == 'view_recipients') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/1ka-vabila/?from1ka=1';
+ } else if ($_GET['m'] == 'view_message') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/1ka-vabila/?from1ka=1';
+ } else if ($_GET['m'] == 'send_message') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/1ka-vabila/?from1ka=1';
+ } else if ($_GET['m'] == 'view_archive') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/arhivi-vabil';
+ } else {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/email-vabila';
+ }
+ }
+
+ // Podatki
+ else if ($_GET['a'] == 'data') {
+ if ($_GET['m'] == 'quick_edit') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/podatki/pregledovanje/?from1ka=1';
+ } else if ($_GET['m'] == 'calculation') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/podatki/izracuni/?from1ka=1';
+ } else if ($_GET['m'] == 'coding') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/rocno-kodiranje';
+ } else if ($_GET['m'] == 'coding_auto') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/avtomatsko-kodiranje';
+ } else if ($_GET['m'] == 'recoding') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/rekodiranje';
+ } else if ($_GET['m'] == 'append') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/dodajanje-podatkov-append';
+ } else if ($_GET['m'] == 'merge') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/zdruzevanje-podatkov';
+ } else {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/podatki/pregledovanje/?from1ka=1';
+ }
+ }
+ // Izvoz podatkov
+ else if ($_GET['a'] == 'export') {
+ if ($_GET['m'] == 'spss' || $_GET['m'] == 'sav') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/izvoz-spss';
+ }else if ($_GET['m'] == 'excel_xls') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/izvoz-excel';
+ }else if ($_GET['m'] == 'excel') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/izvoz-excel-zakaj-se-pri-izvozu-excel-odprti-odgovori-ne-izpisejo-celoti';
+ }
+ else if ($_GET['m'] == 'txt') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/izvoz-tekstovno-datoteko';
+ } else {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/izvoz-spss';
+ }
+ }
+
+ // Analiza
+ else if ($_GET['a'] == 'analysis' && (in_array($_GET['m'], array('', 'sumarnik', 'ttest', 'para')))) {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/analize/statistike/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'charts') {
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/analize/grafi/?from1ka=1';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'anal_arch') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/arhivi-analiz';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'analysis_links') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/analize/porocila';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'analysis_creport') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/porocila-meri';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'descriptor') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/opisne-statistike';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'frequency') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/frekvence';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'crosstabs') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/tabele';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'multicrosstabs') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/multitabele';
+ }
+ else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'means') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/povprecja';
+ }else if ($_GET['a'] == 'analysis' && $_GET['m'] == 'break') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/prirocniki/razbitje';
+ }
+
+ //Moje ankete
+ else if ($_GET['a'] == 'ustvari_anketo') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/kreiranje-nove-ankete';
+ }
+
+ //Aktivnost
+ else if ($_GET['a'] == 'diagnostics' && $_GET['t'] != 'uporabniki' && $_GET['m'] != 'my') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/aktivnost';
+ }
+
+ //Uporabniki
+ else if ($_GET['a'] == 'diagnostics' && $_GET['t'] == 'uporabniki') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/uporabniki';
+ }
+
+ //Knjiznica
+ else if ($_GET['a'] == 'knjiznica') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/knjiznica';
+ }
+
+ //Sporocila
+ else if ($_GET['a'] == 'obvestila') {
+ $help_url = 'https://www.1ka.si/d/sl/o-1ka/splosen-opis/nivoji-uporabnikov/administrator';
+ }
+
+ //GDPR
+ else if ($_GET['a'] == 'gdpr') {
+ switch($_GET['m']){
+ case 'gdpr_survey_list':
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/gdpr-profil/seznam-anket';
+ break;
+ case 'gdpr_requests':
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/gdpr-profil/procesiranje-zahtevkov';
+ break;
+ case 'gdpr_requests_all':
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/gdpr-profil/procesiranje-zahtevkov';
+ break;
+ case 'gdpr_dpa':
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/gdpr-profil/dpa';
+ break;
+ default:
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/moje-ankete/gdpr-profil/splosne-nastavitve';
+ break;
+ }
+ }
+
+ //Analize urejanja
+ else if ($_GET['a'] == 'edits_analysis') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/analize-urejanja';
+ }
+
+ //Urejanje - Vprasalnik
+ else if ($_GET['a'] == 'branching') {
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/urejanje/vprasalnik';
+ }
+
+ // Moje ankete - narocila
+ else if ($_GET['a'] == 'narocila') {
+ $help_url = 'https://www.1ka.si/d/en/services';
+ $help_url = 'https://www.1ka.si/d/sl/cenik';
+ }
+
+ // Ostale default podstrani
+ else {
+ switch ($podstran) {
+ case NAVI_STATUS;
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/povzetek/?from1ka=1';
+ break;
+ case NAVI_UREJANJE:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/urejanje/?from1ka=1';
+ break;
+ case NAVI_OBJAVA:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/?from1ka=1';
+ break;
+ case NAVI_RESULTS:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/podatki/?from1ka=1';
+ break;
+ case NAVI_ANALYSIS:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/analize/?from1ka=1';
+ break;
+ case NAVI_TESTIRANJE:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/testiranje/?from1ka=1';
+ break;
+ case NAVI_STATUS:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/status/?from1ka=1';
+ break;
+ case NAVI_ADVANCED:
+ $help_url = 'http://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/napredni-moduli/?from1ka=1';
+ break;
+ default:
+ //$help_url = 'https://www.1ka.si/d/sl/pomoc/moje-ankete';
+ $help_url = 'https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/urejanje/vprasalnik';
+ break;
+ }
+ }
+ }
+
+ return $help_url;
+ }
+
+ // Nov algoritem za id ankete v url-ju (ni vec stevilka ampak string - vsako liho stevilko zamenjamo z ustrezno crko npr. 1234 -> A2C4)
+ public static function encryptAnketaID($anketa_id){
+
+ // Ali imamo vklopljeno sifriranje id-ja anket v url-ju - ZENKRAT UGASNJENO
+ //if(true){
+ if(false){
+ $anketa_arr = str_split($anketa_id);
+ $anketa_string = '';
+
+ foreach($anketa_arr as $pos => $num){
+
+ // Na lihih mestih pretvorimo stevilko v crko
+ if($pos % 2 == 0)
+ $anketa_string .= chr(97 + $num);
+ else
+ $anketa_string .= $num;
+ }
+ //$anketa_string = strtolower($anketa_string);
+ }
+ else
+ $anketa_string = $anketa_id;
+
+ return $anketa_string;
+ }
+
+ // Algoritem, ki iz texta ustvari strukturo vprasanj in variabel (za uvoz anekte iz texta)
+ public static function anketaArrayFromText($raw_text){
+
+ if($raw_text != ''){
+
+ // Trenutna vrstica je vprasanje (0) ali variabla (1)
+ $prev_blank = true;
+ $questin_cnt = -1;
+ $variable_cnt = 0;
+
+ $text_array = array();
+
+ // Gremo cez vse vrstice
+ $lines = explode('\n', str_replace('\r', '', $raw_text));
+ foreach($lines as $line){
+
+ $line = trim($line);
+
+ // Ce imamo prazno vrstico
+ if($line == ''){
+ $prev_blank = true;
+
+ $variable_cnt = 0;
+ }
+ else{
+ // Ce je bila prejsnja prazna gre za novo vprasanje
+ if($prev_blank){
+ $questin_cnt++;
+ $text_array[$questin_cnt]['title'] = $line;
+ }
+ // Drugace gre za variablo v vprasanju
+ else{
+ $text_array[$questin_cnt][$variable_cnt] = $line;
+ $variable_cnt++;
+ }
+
+ $prev_blank = false;
+ }
+ }
+
+ return $text_array;
+ }
+ else
+ return false;
+ }
+
+ // Izpise obvestilo, da ni podatkov
+ static function noDataAlert() {
+ global $lang;
+
+ echo '<div class="no_data_alert">';
+ echo $lang['srv_data_no_data'];
+ echo '</div>';
+ }
+
+ // Vrne string s signaturjem za email v ustreznem jeziku (default slovenski)
+ public static function getEmailSignature($lang_id = 0){
+ global $lang;
+ global $app_settings;
+
+ if(isset($app_settings['email_signature_custom']) && $app_settings['email_signature_custom'] == 1){
+ $signature = '<br /><br /><br />'.$app_settings['email_signature_text'];
+ }
+ else{
+
+ $signature = '<br /><br /><br />';
+
+ $signature .= $lang['srv_1ka_mail_signature_bye'];
+
+ $signature .= '<br /><br />';
+
+ // Logo
+ if($lang['id'] == '1')
+ $signature .= '<img src="https://www.1ka.si/public/img/logo/1ka_slo.png" width=90 style="width:90px; height:auto; border:0;" />';
+ else
+ $signature .= '<img src="https://www.1ka.si/public/img/logo/1ka_eng.png" width=90 style="width:90px; height:auto; border:0;" />';
+
+ $signature .= '<br/>-------------------------------------------------------------------<br/>';
+
+ // Footer
+ $signature .= '<span style="font-size:13px; line-height:30px;">';
+
+ $signature .= ' <strong><span style="color:#1e88e5;">'.$lang['srv_1ka_mail_signature_help'].'</span></strong>';
+ $signature .= ' <br/><strong><span style="color:#777777;">'.$lang['srv_1ka_mail_signature_click'].':</span></strong> <a href="'.($lang['id'] == '1' ? 'https://www.1ka.si/d/sl/storitve' : 'https://www.1ka.si/d/en/services').'" target="_blank" style="color:#1e88e5;">'.$lang['srv_1ka_mail_signature_link'].'</a>';
+ $signature .= ' <br/><span style="color:#777777;">'.$lang['srv_1ka_mail_signature_social'].':</span> <a href="https://www.facebook.com/1KA-123545614388521/" target="_blank" style="color:#1e88e5;">Facebook</a> <span style="color:#777777;">'.$lang['srv_1ka_mail_signature_and'].'</span> <a href="https://twitter.com/enklikanketa" target="_blank" style="color:#1e88e5;">Twitter</a></span>';
+
+ $signature .= '</span>';
+ }
+
+ return $signature;
+ }
+}?> \ No newline at end of file
diff --git a/admin/survey/classes/class.Demografija.php b/admin/survey/classes/class.Demografija.php
new file mode 100644
index 0000000..f8c0e09
--- /dev/null
+++ b/admin/survey/classes/class.Demografija.php
@@ -0,0 +1,166 @@
+<?php
+
+/**
+* Singleton class s seznamom za demografijo. Array vsebuje IDje podtipov in imena pripadajočih variabel
+*/
+
+class Demografija {
+
+ static $instance = false;
+ private $seznamcek = array();
+
+ /**
+ * Poskrbi za singleton..
+ *
+ */
+ public static function getInstance () {
+ if (!self::$instance)
+ self::$instance = new Demografija();
+
+ return self::$instance;
+ }
+
+ /**
+ * V konstruktorju sestavimo array z variablami, ki se uporabljajo v demografiji
+ *
+ */
+ private function __construct () {
+
+ // starost
+ $this->seznamcek['starost'][] = 'XSTAR1a2';
+ $this->seznamcek['starost'][] = 'XSTAR2a4';
+ $this->seznamcek['starost'][] = 'XSTAR3ac7';
+ $this->seznamcek['starost'][] = 'XSTAR3ac7';
+ $this->seznamcek['starost'][] = 'XSTAR4ac5b';
+ $this->seznamcek['starost'][] = 'XSTAR1b2';
+ $this->seznamcek['starost'][] = 'XSTAR2b3';
+ $this->seznamcek['starost'][] = 'XSTAR3b5';
+ $this->seznamcek['starost'][] = 'XSTAR4b7';
+ $this->seznamcek['starost'][] = 'XSTAR1c2';
+ $this->seznamcek['starost'][] = 'XSTAR2c3';
+ $this->seznamcek['starost'][] = 'XSTAR1d6';
+ $this->seznamcek['starost'][] = 'XSTAR2d13';
+ $this->seznamcek['starost'][] = 'XSTAR3d19';
+ $this->seznamcek['starost'][] = 'XSTAR006';
+ $this->seznamcek['starost'][] = 'XSTARletni';
+ $this->seznamcek['starost'][] = 'XSTARleta';
+ $this->seznamcek['starost'][] = 'XLETNICA';
+ $this->seznamcek['starost'][] = 'XDATUMROJ';
+
+ // zakonski stan
+ $this->seznamcek['stan'][] = 'XZST1surs4';
+ $this->seznamcek['stan'][] = 'XZST2a5';
+ $this->seznamcek['stan'][] = 'XZST3sjm5';
+ $this->seznamcek['stan'][] = 'XZST4a5';
+ $this->seznamcek['stan'][] = 'XZST5val6';
+ $this->seznamcek['stan'][] = 'XZST6a7';
+
+ // izobrazba
+ $this->seznamcek['izobrazba'][] = 'XIZ9vris11';
+ $this->seznamcek['izobrazba'][] = 'XIZ7a9';
+ $this->seznamcek['izobrazba'][] = 'XIZ5a7';
+ $this->seznamcek['izobrazba'][] = 'XIZ4a4';
+ $this->seznamcek['izobrazba'][] = 'XIZ3a3';
+ $this->seznamcek['izobrazba'][] = 'XIZ1a2';
+ $this->seznamcek['izobrazba'][] = 'XIZ8surs9';
+ $this->seznamcek['izobrazba'][] = 'XIZ2surs3';
+ $this->seznamcek['izobrazba'][] = 'XIZ10ess12';
+ $this->seznamcek['izobrazba'][] = 'XIZ6sjm8';
+
+ // status
+ $this->seznamcek['status'][] = 'XDS1sjm2';
+ $this->seznamcek['status'][] = 'XDS2a4';
+ $this->seznamcek['status'][] = 'XDS3a7';
+ $this->seznamcek['status'][] = 'XDS4ess10';
+ $this->seznamcek['status'][] = 'XDS5a14';
+ $this->seznamcek['status'][] = 'XDS6sjm14';
+ $this->seznamcek['status'][] = 'XDS7ris16';
+ $this->seznamcek['status'][] = 'XDS8val18';
+
+ // spol
+ $this->seznamcek['spol'][] = 'XSPOL';
+
+ // podjetja
+ $this->seznamcek['podjetja'][] = 'XPODRUZ';
+ $this->seznamcek['podjetja'][] = 'XPODJPRIH';
+ $this->seznamcek['podjetja'][] = 'XPODJZAPOSL';
+ //$this->seznamcek['podjetja'][] = 'XAKADEM';
+ //$this->seznamcek['podjetja'][] = 'XZAPOSLDEJAV';
+
+ // lokacija
+ $this->seznamcek['lokacija'][] = 'XLOKACEVROPA';
+ $this->seznamcek['lokacija'][] = 'XLOKACREGs';
+ $this->seznamcek['lokacija'][] = 'XLOKACREGk';
+ $this->seznamcek['lokacija'][] = 'XLOKACUE';
+ $this->seznamcek['lokacija'][] = 'XLOKACTN6';
+ $this->seznamcek['lokacija'][] = 'XVELNASELJE';
+ $this->seznamcek['lokacija'][] = 'XLOKACTN5';
+ $this->seznamcek['lokacija'][] = 'XLOKACOB';
+ $this->seznamcek['lokacija'][] = 'XVELNASsjm';
+ $this->seznamcek['lokacija'][] = 'XTIPKSsjm';
+
+ }
+
+ /**
+ * preveri ce je podana variabla podanega tipa
+ *
+ */
+ function isDemografijaTip ($variabla, $tip) {
+ if ( in_array($variabla, $this->seznamcek[$tip]) )
+ return true;
+
+ return false;
+ }
+
+ /**
+ * Preveri ce je podana variabla v seznamu demografij
+ *
+ */
+ function isDemografija ($variabla) {
+
+ foreach ($this->seznamcek AS $key => $val)
+ if ( $this->isDemografijaTip($variabla, $key) ) return true;
+
+ return false;
+ }
+
+ /**
+ * Vrne tip demografije za podano variablo
+ *
+ */
+ function getDemografijaTip ($variabla) {
+
+ foreach ($this->seznamcek AS $key => $val)
+ if ( $this->isDemografijaTip($variabla, $key) ) return $key;
+
+ return false;
+ }
+
+ /**
+ * Vrne ID spremenljivke v knjiznici za podano variablo
+ *
+ */
+ function getSpremenljivkaID ($variable) {
+
+ $sql = sisplet_query("SELECT id FROM srv_spremenljivka WHERE variable='$variable' AND sistem='1' AND gru_id='-1' LIMIT 1");
+ $row = mysqli_fetch_array($sql);
+
+ return $row['id'];
+ }
+
+ /**
+ * Vrne seznam vseh demografij istega tipa, kot je podana variabla. Uporabi se pri spremembi vprasanja - ker prikazujemo samo istega tipa
+ *
+ */
+ function getSeznam ($variabla) {
+
+ $tip = $this->getDemografijaTip($variabla);
+ if (!$tip) return false;
+
+ return $this->seznamcek[$tip];
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.Dostop.php b/admin/survey/classes/class.Dostop.php
new file mode 100644
index 0000000..883e7ce
--- /dev/null
+++ b/admin/survey/classes/class.Dostop.php
@@ -0,0 +1,1783 @@
+<?php
+
+/**
+ *
+ * Class, ki naj bi imel stvari glede dostopa uporabnikov do anket
+ * Ampak dejansko je se ogromno stvari, ki grejo mimo classa in direktno na bazo
+ *
+ */
+
+class Dostop {
+
+ var $anketa; // trenutna anketa
+
+ function __construct($anketa = NULL)
+ {
+
+ // polovimo anketa ID
+ if (isset ($_GET['anketa'])) {
+ $this->anketa = $_GET['anketa'];
+ } elseif (isset ($_POST['anketa'])) {
+ $this->anketa = $_POST['anketa'];
+ } elseif ($anketa != 0) {
+ $this->anketa = $anketa;
+ }
+ }
+
+ /**
+ * preveri dostop do ankete
+ *
+ * @param mixed $anketa
+ */
+ function checkDostop($anketa = 0)
+ {
+ global $admin_type;
+ global $global_user_id;
+
+ if ($anketa == 0) {
+ $anketa = $this->anketa;
+ }
+ $uid = $global_user_id;
+
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ // meta admin vidi kao spet vse
+ if (self::isMetaAdmin()) {
+ return TRUE;
+ }
+
+ // za demonstracijsko je posebno preverjanje
+ if ($rowa['invisible'] == 1) {
+ return TRUE;
+ }
+
+ // posebej dostop za vsazga userja posebej
+ $sql = sisplet_query("SELECT ank_id, uid FROM srv_dostop WHERE ank_id = '$anketa' AND uid='$uid'");
+ if (mysqli_num_rows($sql) > 0) {
+ return TRUE;
+ }
+
+ // dodatno imamo se ce je manager ali admin, potem vidi ankete podrejenih userjev
+ if ($admin_type == 1 || $admin_type == 0) {
+ $sql = sisplet_query("SELECT COUNT(*) FROM srv_dostop WHERE ank_id='$anketa' AND uid IN (SELECT user FROM srv_dostop_manage WHERE manager='$uid')");
+ $row = mysqli_fetch_array($sql);
+ if ($row[0] > 0) {
+ return TRUE;
+ }
+ }
+
+ // ce imajo administratorji poseben dostop do ankete za help
+ if ($admin_type == 0 && strtotime($rowa['dostop_admin']) >= strtotime(date("Y-m-d"))) {
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ /**
+ * Kao meta admin, ki vidi vse
+ */
+ static function isMetaAdmin()
+ {
+ global $global_user_id;
+ global $admin_type;
+ global $mysql_database_name;
+
+ // Samo na www in virtualkah
+ if(($mysql_database_name == 'www1kasi' || $mysql_database_name == 'real1kasi') && $admin_type == '0'){
+ // vvasja@gmail.com - id: 100, peter.h1203@gmail.com - id: 12611, 1ka.techsupport - id: 49089 (virtualke), 72253
+ if (in_array($global_user_id, [100, 12611, 49089, 72253])) {
+ return TRUE;
+ }
+ }
+
+ // Gorenje ima svoje metaadmine
+ if ($admin_type == '0' && Common::checkModule('gorenje')){
+ global $meta_admin_emails;
+
+ $sql = sisplet_query("SELECT email FROM users WHERE id = '$global_user_id'");
+ $row = mysqli_fetch_array($sql);
+
+ if(in_array($row['email'], $meta_admin_emails)){
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+ }
+
+ /**
+ * preveri, ce ima uporabnik aktiven dostop do ankete
+ * zdaj ko nimamo vec aktivnih in pasivnih uporabnikov, gledamo ali ima edit
+ * dostop do ankete
+ *
+ * ta funkcija je v bistvu deprecated, naj se raje uporablja
+ * checkDostopSub('edit'...); ostaja za zdruzljivost za nazaj
+ *
+ * @param mixed $anketa
+ */
+ function checkDostopAktiven($anketa = 0)
+ {
+ global $admin_type;
+ global $global_user_id;
+
+ return $this->checkDostopSub('edit', $anketa);
+ }
+
+ /**
+ * preveri tocen dostop do podstoritev
+ *
+ * @param mixed $anketa
+ */
+ function checkDostopSub($type, $anketa = 0)
+ {
+ global $admin_type;
+ global $global_user_id;
+
+ if ($anketa == 0) {
+ $anketa = $this->anketa;
+ }
+ $uid = $global_user_id;
+
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ // meta admin vidi kao spet vse
+ if (self::isMetaAdmin()) {
+ return TRUE;
+ }
+
+ // za demonstracijsko je posebno preverjanje
+ if ($rowa['invisible'] == 1) {
+ return TRUE;
+ }
+
+ $sql = sisplet_query("SELECT dostop FROM srv_dostop WHERE ank_id = '$anketa' AND uid='$uid'");
+ if (mysqli_num_rows($sql) > 0) {
+ $row = mysqli_fetch_array($sql);
+
+ $dostop = explode(',', $row['dostop']);
+ if (in_array($type, $dostop)) {
+ return TRUE;
+ }
+
+ // managerji in admini majo vedno lepe linke in maile
+ if ($admin_type <= 1 && in_array($type, ['link', 'mail'])) {
+ return TRUE;
+ }
+ }
+
+ // administratorji in managerji imajo do max kar imajo njegovi podrejeni userji
+ if ($admin_type <= 1) {
+ $sql = sisplet_query("SELECT dostop FROM srv_dostop WHERE ank_id='$anketa' AND uid IN (SELECT user FROM srv_dostop_manage WHERE manager='$uid')");
+ while ($row = mysqli_fetch_array($sql)) {
+ $dostop = explode(',', $row['dostop']);
+
+ if (in_array($type, $dostop)) {
+ return TRUE;
+ }
+
+ // managerji in admini majo vedno lepe linke in maile
+ if ($admin_type <= 1 && in_array($type, ['link', 'mail'])) {
+ return TRUE;
+ }
+ }
+ }
+
+ // ce imajo administratorji poseben dostop do ankete za help
+ if ($admin_type == 0 && strtotime($rowa['dostop_admin']) >= strtotime(date("Y-m-d"))) {
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ function ajax(){
+
+ if ($_GET['a'] == 'manager_add_user') {
+ $this->ajax_manager_add_user();
+ }
+ elseif($_GET['a'] == 'add_new_user'){
+ $this->ajax_add_new_user();
+ }
+ elseif ($_GET['a'] == 'anketa_user_dostop') {
+ $this->ajax_anketa_user_dostop();
+ }
+ elseif ($_GET['a'] == 'anketa_user_dostop_save') {
+ $this->ajax_anketa_user_dostop_save();
+ }
+ elseif ($_GET['a'] == 'edit_user') {
+ $this->ajax_edit_user();
+ }
+ elseif ($_GET['a'] == 'edit_user_save') {
+ $this->ajax_edit_user_save();
+ }
+ elseif ($_GET['a'] == 'admin_add_user') {
+ $this->ajax_admin_add_user();
+ }
+ elseif ($_GET['a'] == 'admin_add_user_popup') {
+ $this->ajax_admin_add_user_popup();
+ }
+ elseif($_GET['a'] == 'find_user'){
+ $this->ajax_find_user();
+ }
+ elseif ($_GET['a'] == 'edit_remove_user') {
+ $this->ajax_edit_remove_user();
+ }
+ elseif ($_GET['a'] == 'edit_remove_user_manager') {
+ $this->ajax_edit_remove_user_manager();
+ }
+ elseif ($_GET['a'] == 'edit_remove_user_admin') {
+ $this->ajax_edit_remove_user_admin();
+ }
+ elseif ($_GET['a'] == 'all_users_list') {
+
+ if ($_GET['m'] == 'delete') {
+ $this->ajax_all_users_list_delete();
+ }
+
+ if ($_GET['m'] == 'ban') {
+ $this->ajax_all_users_list_ban();
+ }
+ else {
+ $this->ajax_all_users_list();
+ }
+ }
+ elseif($_GET['a'] == 'my_users_list'){
+ $this->ajax_all_users_list_my();
+ }
+ elseif ($_GET['a'] == 'delete_users_list') {
+ $this->ajax_delete_users_list();
+ }
+ elseif ($_GET['a'] == 'unsigned_users_list') {
+ $this->ajax_unsigned_users_list();
+ }
+ elseif ($_GET['a'] == 'unconfirmed_mail_user_list') {
+
+ if ($_GET['m'] == 'delete') {
+ $this->ajax_unconfirmed_mail_user_list_delet_user();
+ }
+ elseif ($_GET['m'] == 'accept') {
+ $this->ajax_confirm_user_email();
+ }
+ else {
+ $this->ajax_unconfirmed_mail_user_list();
+ }
+ }
+ elseif ($_GET['a'] == 'dodeljeni_uporabniki_display') {
+ $this->ajax_dodeljeni_uporabniki_display();
+ }
+ }
+
+ /**
+ * Dodamo novega uporabnika v 1KA sistem
+ */
+ public function ajax_add_new_user()
+ {
+ global $pass_salt, $site_url, $site_domain, $virtual_domain, $lang, $app_settings;
+
+ $email = $_POST['email'];
+ $name = $_POST['name'];
+ $surnname = $_POST['surname'];
+ $password = $_POST['password'];
+ $password2 = $_POST['password2'];
+ $jezik = $_POST['jezik'];
+
+ include root_dir('lang/'.$jezik.'.php');
+
+
+ if ($email != '') {
+
+ $sqlu = sisplet_query("SELECT id FROM users WHERE email='$email'");
+ if (mysqli_num_rows($sqlu) == 0) {
+
+ if ($password == '' || $password == $password2) {
+
+ $s = sisplet_query("INSERT INTO users (name, surname, email, pass, type, when_reg, came_from, lang) VALUES ('$name', '$surnname', '$email', '" . base64_encode((hash(SHA256, $password . $pass_salt))) . "', '3', DATE_FORMAT(NOW(), '%Y-%m-%d'), '1', $jezik)");
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ } else {
+ $error = 'pass';
+ }
+
+ } else {
+ // ne more si dodati že obstoječega uporabnika, ker potem bi si lahko kar kogarkoli dodal in bi videl njegove ankete
+ $id = 0;
+ $error = 'email';
+ }
+
+ if ($id > 0) {
+
+ $UserContent = $lang['add_new_user_content'];
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+ $UserContent .= $signature;
+
+ $UserContent .= $lang['register_add_user_content_edit'];
+
+ $PageName = $app_settings['app_name'];
+
+ $change = '<a href="'.$site_url.'admin/survey/index.php?a=nastavitve&m=global_user_myProfile">';
+ $out = '<a href="'.$this->page_urls['page_unregister'].'?email='.$email.'">';
+
+ // Ce gre slucajno za virtualko
+ $Subject = ($virtual_domain) ? $lang['register_user_subject_virtual'] : $lang['register_user_subject'];
+
+ $UserContent = str_replace("SFNAME", $name, $UserContent);
+ $UserContent = str_replace("SFMAIL", $email, $UserContent);
+ $UserContent = str_replace("SFWITH", $email, $UserContent);
+ $UserContent = str_replace("SFPAGENAME", $PageName, $UserContent);
+ $UserContent = str_replace("SFCHANGE", $change, $UserContent);
+ $UserContent = str_replace("SFOUT", $out, $UserContent);
+ $UserContent = str_replace("SFEND", '</a>', $UserContent);
+
+ $Subject = str_replace("SFPAGENAME", $PageName, $Subject);
+
+ // Ce gre slucajno za virtualko
+ if($virtual_domain)
+ $Subject = str_replace("SFVIRTUALNAME", $site_domain, $Subject);
+
+ if ($password2 == "") {
+ $UserContent = str_replace("SFPASS", "( ".$lang['without']." ) ", $UserContent);
+ }
+ else {
+ $UserContent = str_replace("SFPASS", $password2 ." (".$lang['register_add_user_password'].")", $UserContent);
+ }
+
+ if ($name == "") {
+ $UserContent = str_replace("SFNAME", $lang['mr_or_mrs'], $UserContent);
+ }
+ else {
+ $UserContent = str_replace("SFNAME", $name, $UserContent);
+ }
+
+ $ZaMail = '<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">'.'<html><head><title>'.$Subject.'</title><meta content="text/html; charset=utf-8" http-equiv=Content-type></head><body>';
+
+ $ZaMail .= $UserContent;
+
+
+ if(isDebug()){
+ echo $ZaMail;
+ die();
+ }
+
+ // Posljemo mail vsakemu uporabniku posebej
+ try {
+ $MA = new MailAdapter(null, 'account');
+ $MA->addRecipients($email);
+ $resultX = $MA->sendMail(stripslashes($ZaMail), $Subject);
+ }
+ catch (Exception $e) {
+ }
+
+ if ($resultX) {
+ $status = 1; // poslalo ok
+ }
+ else {
+ $status = 2; // ni poslalo
+ }
+ }
+
+ } else {
+ $error = 'email';
+ }
+
+ header("Location: index.php?a=diagnostics&t=uporabniki&m=all&add=new&error=" . ($error !== FALSE ? $error : ''));
+ }
+
+ /**
+ * Manager: dodajanje svojih novih uporabnikov
+ *
+ */
+ function ajax_manager_add_user()
+ {
+ global $pass_salt;
+ global $lang;
+ global $global_user_id, $site_path, $site_domain;
+ global $admin_type;
+
+ $error = FALSE;
+
+ $sqlu = sisplet_query("SELECT email, type FROM users WHERE id = '" . $global_user_id . "'");
+ list($MailReply) = mysqli_fetch_row($sqlu);
+
+ $aktiven = $_POST['aktiven'];
+
+ $email = $_POST['email'];
+ $name = $_POST['name'];
+ $surnname = $_POST['surname'];
+ $password = $_POST['password'];
+ $password2 = $_POST['password2'];
+
+ if ($email != '') {
+
+ $sqlu = sisplet_query("SELECT id FROM users WHERE email='$email'");
+ if (mysqli_num_rows($sqlu) == 0) {
+
+ if ($password == '' || $password == $password2) {
+
+ $s = sisplet_query("INSERT INTO users (name, surname, email, pass, type, when_reg, came_from) VALUES ('$name', '$surnname', '$email', '" . base64_encode((hash(SHA256, $password . $pass_salt))) . "', '3', DATE_FORMAT(NOW(), '%Y-%m-%d'), '1')");
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ } else {
+ $error = 'pass';
+ }
+
+ } else {
+ // ne more si dodati že obstoječega uporabnika, ker potem bi si lahko kar kogarkoli dodal in bi videl njegove ankete
+ $id = 0;
+ $error = 'email';
+ }
+
+ if ($id > 0) {
+
+ $s = sisplet_query("INSERT INTO srv_dostop_manage (manager, user) VALUES ('$global_user_id', '$id')");
+ if (!$s) {
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ $subject = sprintf($lang['srv_dodanmail_1'], $site_domain);
+
+ $content = sprintf($lang['srv_dodanmail_2'], $MailReply, $site_domain).'<br /><br />';
+ $content .= $lang['srv_dodanmail_3'];
+ $content .= '<ul>';
+ $content .= '<li>'.$lang['srv_dodanmail_3_email'].' <b>'.$email.'</b></li>';
+ $content .= '<li>'.$lang['srv_dodanmail_3_pass_1'].' <b>'.$password.'</b> ('.$lang['srv_dodanmail_3_pass_2'].')</li>';
+ $content .= '</ul>';
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+ $content .= $signature;
+
+
+ // Posljemo mail vsakemu uporabniku posebej
+ try {
+ $MA = new MailAdapter($this->anketa, $type='account');
+ $MA->addRecipients($email);
+ $MA->addRecipients($MailReply);
+ $resultX = $MA->sendMail(stripslashes($content), $subject);
+ } catch (Exception $e) {
+ }
+
+
+ if ($resultX) {
+ $status = 1; // poslalo ok
+ } else {
+ $status = 2; // ni poslalo
+ }
+ }
+
+ } else {
+ $error = 'email';
+ }
+
+ header("Location: index.php?a=diagnostics&t=uporabniki&m=my&error=" . ($error !== FALSE ? $error : ''));
+ }
+
+ /**
+ * Urejanje natančnega dostopa uporabnikov v nastavitvah ankete
+ *
+ */
+ function ajax_anketa_user_dostop()
+ {
+ global $admin_type;
+ global $lang;
+
+ $uid = $_POST['uid'];
+
+ $s = sisplet_query("SELECT name, surname, email, type FROM users WHERE id='$uid'");
+ $r = mysqli_fetch_array($s);
+
+ $sqla = sisplet_query("SELECT naslov FROM srv_anketa WHERE id = '$this->anketa'");
+ $rowa = mysqli_fetch_array($sqla);
+
+ echo '<h2>'.$lang['srv_anketa'].' '.$rowa['naslov'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="anketa_user_dostop_close(); return false;">✕</a></div>';
+
+ echo '<h3><span class="bold">';
+
+ if ($r['type'] == 2 || $r['type'] == 3) {
+ echo $lang['admin_narocnik'];
+ }
+ elseif ($r['type'] == 1) {
+ echo $lang['manager'];
+ }
+ elseif ($r['type'] == 0) {
+ echo $lang['administrator'];
+ }
+
+ $r['email'] = iconv("iso-8859-2", "utf-8", $r['email']);
+
+ echo ': ' . $r['name'] . ' ' . $r['surname'] . ' (' . $r['email'] . ')</span></h3>';
+
+ if ($r['type'] >= 2) {
+
+ $sql = sisplet_query("SELECT dostop FROM srv_dostop WHERE ank_id='$this->anketa' AND uid='$uid'");
+ $row = mysqli_fetch_array($sql);
+ $dostop = explode(',', $row['dostop']);
+ echo '<form id="dostop">';
+ echo '<input type="hidden" name="uid" value="' . $uid . '">';
+
+ echo '<input type="hidden" name="aktiven" value="1" id="aktiven_1">';
+
+ echo '<p><input type="checkbox" name="dostop[dashboard]" value="dashboard" id="dashboard" ' . (in_array('dashboard', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . '> <label for="dashboard">' . $lang['srv_dostop_dashboard'] . '</label></p>';
+ echo '<p><input type="checkbox" name="dostop[edit]" value="edit" id="edit" ' . (in_array('edit', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . ' onchange="dostop_language(this);"> <label for="edit">' . $lang['srv_dostop_edit'] . '</label></p>';
+ echo '<p><input type="checkbox" name="dostop[test]" value="test" id="test" ' . (in_array('test', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . ' onchange="dostop_language(this);"> <label for="test">' . $lang['srv_dostop_test'] . '</label></p>';
+ echo '<p><input type="checkbox" name="dostop[publish]" value="publish" id="publish" ' . (in_array('publish', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . ' onchange="dostop_language(this);"> <label for="publish">' . $lang['srv_dostop_publish'] . '</label></p>';
+ echo '<p><input type="checkbox" name="dostop[data]" value="data" id="data" ' . (in_array('data', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . '> <label for="data">' . $lang['srv_dostop_data'] . '</label></p>';
+ echo '<p><input type="checkbox" name="dostop[analyse]" value="analyse" id="analyse" ' . (in_array('analyse', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . '> <label for="analyse">' . $lang['srv_dostop_analyse'] . '</label></p>';
+
+ echo '<p><input type="checkbox" name="dostop[export]" value="export" id="export" ' . (in_array('export', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . '> <label for="export">' . $lang['srv_dostop_export'] . '</label></p>';
+
+ // Nastavitev, da ne more odklenit ankete
+ echo '<p><input type="checkbox" name="dostop[lock]" value="lock" id="lock" ' . (in_array('lock', $dostop) ? 'checked' : '') . ' ' . (in_array('phone', $dostop) ? ' disabled="disabled"' : '') . '> <label for="lock">' . $lang['srv_dostop_lock'] . '</label></p>';
+
+ // Je anketar - ne more poceti nicesar razen izvajati telefonsko anketo (ob kliku se ostale avtomatsko ugasnejo in disablajo)
+ echo '<p><input type="checkbox" name="dostop[phone]" value="phone" id="phone" ' . (in_array('phone', $dostop) ? 'checked' : '') . ' onchange="dostop_anketar(this);"> <label for="phone">' . $lang['srv_dostop_phone'] . '</label></p>';
+
+ // Če gre za Hierarhijo
+ if (SurveyInfo::checkSurveyModule('hierarhija', $this->anketa)) {
+ $tip = sisplet_query("SELECT type FROM srv_hierarhija_users WHERE user_id='" . $uid . "' AND anketa_id='" . $this->anketa . "'", "obj");
+
+ if (!empty($tip) && !empty($tip->type)) {
+ echo '<p><label>Uporabnik hierarhije s pravicami: </label>';
+ echo '<select name="hierarchy_type" id="hierarchy-type-change" onchange="hierarhijaPravice()">
+ <option value="10" ' . ($tip->type == 10 ? 'selected' : NULL) . '> Učitelj </option>
+ <option value="2" ' . ($tip->type == 2 ? 'selected' : NULL) . '> Administrator </option>
+ </select ></p>';
+ }
+ }
+
+
+ echo '<div style="position: absolute; right: 10px; top: 50px; width: 200px;">';
+
+ // Ce je katerikoli od treh checkboxou ugasnjen imamo enablano editiranje samo posameznega jezik
+ $enable_lang = (!in_array('edit', $dostop) || !in_array('test', $dostop) || !in_array('publish', $dostop)) ? TRUE : FALSE;
+
+ $sqll = sisplet_query("SELECT * FROM srv_language WHERE ank_id = '$this->anketa'");
+ if (mysqli_num_rows($sqll) > 0) {
+ echo '<p><b>' . $lang['srv_passive_multilang'] . '</b></p>';
+
+ echo '<input type="hidden" name="dostop_language_edit" id="dostop_language_edit" value="' . ($enable_lang ? '1' : '0') . '">';
+ }
+ while ($rowl = mysqli_fetch_array($sqll)) {
+
+ $sqldl = sisplet_query("SELECT * FROM srv_dostop_language WHERE ank_id = '$this->anketa' AND uid = '$uid' AND lang_id='$rowl[lang_id]'");
+ if (!$sqldl) {
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ if (mysqli_num_rows($sqldl) > 0) {
+ $checked = ' checked';
+ } else {
+ $checked = '';
+ }
+
+ echo '<label><input class="dostop_language" type="checkbox" name="dostop_language[]" value="' . $uid . '-' . $rowl['lang_id'] . '" ' . $checked . ' ' . ($enable_lang ? '' : ' disabled="disabled"') . ' > ' . $rowl['language'] . '</label> <br>';
+ }
+
+ echo '</div>';
+
+ echo '</form>';
+
+ echo '<div class="buttonwrapper floatLeft spaceRight"><a class="ovalbutton ovalbutton_orange" onclick="anketa_user_dostop_save(\'' . $this->anketa . '\'); return false;" href="#"><span>' . $lang['edit1337'] . '</span></a></div>';
+ }
+ // Manager - brez moznosti uporabe 1ka streznika
+ elseif ($r['type'] == 1) {
+
+ $sql = sisplet_query("SELECT dostop FROM srv_dostop WHERE ank_id='$this->anketa' AND uid='$uid'");
+ $row = mysqli_fetch_array($sql);
+ $dostop = explode(',', $row['dostop']);
+
+ // Admin lahko managerju spreminja samo posiljanje vabil preko 1ka streznika
+ if ($admin_type == 0) {
+
+ echo '<form id="dostop">';
+ echo '<input type="hidden" name="uid" value="' . $uid . '">';
+ echo '<input type="hidden" name="aktiven" value="1" id="aktiven_1">';
+
+ if (in_array('dashboard', $dostop)) {
+ echo '<input type="hidden" name="dostop[dashboard]" value="dashboard" id="dashboard">';
+ }
+ if (in_array('edit', $dostop)) {
+ echo '<input type="hidden" name="dostop[edit]" value="edit" id="edit">';
+ }
+ if (in_array('test', $dostop)) {
+ echo '<input type="hidden" name="dostop[test]" value="test" id="test">';
+ }
+ if (in_array('publish', $dostop)) {
+ echo '<input type="hidden" name="dostop[publish]" value="publish" id="publish">';
+ }
+ if (in_array('data', $dostop)) {
+ echo '<input type="hidden" name="dostop[data]" value="data" id="data">';
+ }
+ if (in_array('analyse', $dostop)) {
+ echo '<input type="hidden" name="dostop[analyse]" value="analyse" id="analyse">';
+ }
+ if (in_array('export', $dostop)) {
+ echo '<input type="hidden" name="dostop[export]" value="export" id="export">';
+ }
+ if (in_array('lock', $dostop)) {
+ echo '<input type="hidden" name="dostop[lock]" value="lock" id="lock">';
+ }
+ if (in_array('phone', $dostop)) {
+ echo '<input type="hidden" name="dostop[phone]" value="phone" id="phone">';
+ }
+
+ echo '</form>';
+
+ echo '<p>(' . $lang['srv_dostop_edit'] . ', ' . $lang['srv_dostop_data'] . ', ' . $lang['srv_dostop_export'] . ')</p>';
+
+ echo '<div class="buttonwrapper floatLeft spaceRight"><a class="ovalbutton ovalbutton_orange" onclick="anketa_user_dostop_save(\'' . $this->anketa . '\'); return false;" href="#"><span>' . $lang['edit1337'] . '</span></a></div>';
+ }
+ // Ostali ne morejo managerju nicesar spreminjati
+ else {
+ echo '<p>(' . $lang['srv_dostop_edit'] . ', ' . $lang['srv_dostop_data'] . ', ' . $lang['srv_dostop_export'] . ' )</p>';
+ }
+ }
+ // Admin
+ else {
+ echo '<p>(' . $lang['srv_dostop_edit'] . ', ' . $lang['srv_dostop_data'] . ', ' . $lang['srv_dostop_export'] . ')</p>';
+ }
+
+ echo '<div class="buttonwrapper floatRight"><a class="ovalbutton ovalbutton_gray" onclick="anketa_user_dostop_close(); return false;" href="#"><span>' . $lang['srv_zapri'] . '</span></a></div>';
+ }
+
+ function ajax_anketa_user_dostop_save() {
+
+ $uid = $_POST['uid'];
+ $aktiven = $_POST['aktiven'];
+
+ $dostop = implode(',', $_POST['dostop']);
+
+ $sql = sisplet_query("UPDATE srv_dostop SET aktiven='$aktiven', dostop='$dostop' WHERE uid = '$uid' AND ank_id='$this->anketa'");
+
+ if (isset($_POST['dostop_language_edit']) && $_POST['dostop_language_edit'] == '1') {
+ sisplet_query("DELETE FROM srv_dostop_language WHERE ank_id = '$this->anketa' AND uid='$uid'");
+ foreach ($_POST['dostop_language'] AS $val) {
+ $val = explode('-', $val);
+ $uid = $val[0];
+ $lang_id = $val[1];
+ sisplet_query("INSERT INTO srv_dostop_language (ank_id, uid, lang_id) VALUES ('$this->anketa', '$uid', '$lang_id')");
+ }
+ }
+
+ if (isset($_POST['hierarchy_type']) && SurveyInfo::checkSurveyModule('hierarhija', $this->anketa)) {
+ $tip = (!empty($_POST['hierarchy_type']) ? $_POST['hierarchy_type'] : NULL);
+
+ $result = sisplet_query("SELECT id FROM srv_hierarhija_users WHERE user_id='" . $uid . "' AND anketa_id='" . $this->anketa . "'", "obj");
+
+ if (!empty($result) && !empty($result->id) && !is_null($tip)) {
+ sisplet_query("UPDATE srv_hierarhija_users SET type='" . $tip . "' WHERE id='" . $result->id . "'");
+ }
+
+ }
+ }
+
+ function ajax_edit_user(){
+ global $lang;
+ global $global_user_id;
+ global $admin_type;
+ global $virtual_domain;
+
+ $uid = $_POST['uid'];
+
+ echo '<div class="edit_user_content">';
+
+ // NASTAVITVE UPORABNIKA
+ echo '<div class="user_settings">';
+
+ $sql = sisplet_query("SELECT name, surname, email, type, status, gdpr_agree FROM users WHERE id ='" . $uid . "'");
+ $row = mysqli_fetch_array($sql);
+
+ echo '<form class="manager_add_user" name="manager_edit_user" action="ajax.php?t=dostop&a=edit_user_save&uid=' . $uid . '" method="post">';
+
+ echo '<h2><strong>' . $lang['edit_user'] . '</strong></h2>';
+
+ // Segment tip uporabnika
+ echo '<div class="segment user_type">';
+
+ $row['email'] = iconv("iso-8859-2", "utf-8", $row['email']);
+
+ // Emaila ne more vec editirat, ker je prevec problemov (izgubi ankete...)
+ echo '<input type="hidden" id="email" name="email" value="' . $row['email'] . '" />';
+ echo '<p><label for="email">' . $lang['user2'] . ':</label>'.$row['name'].' '.$row['surname'].' ('.$row['email'].')</p>';
+
+ // Admin lahko spreminja tip vseh userjev
+ if ($admin_type == 0) {
+ echo '<p><label for="type">' . $lang['admin_type'] . '</label><select id="type" name="type">';
+ echo '<option value="0" ' . ($row['type'] == '0' ? 'selected' : '') . '>' . $lang['admin_admin'] . '</option>';
+ echo '<option value="1" ' . ($row['type'] == '1' ? 'selected' : '') . '>' . $lang['admin_manager'] . '</option>';
+ echo '<option value="3" ' . ($row['type'] == '3' ? 'selected' : '') . '>' . $lang['admin_narocnik'] . '</option>';
+ echo '</select></p>';
+ }
+ else {
+ echo '<input type="hidden" id="type" name="type" value="' . $row['type'] . '" />';
+ }
+
+ echo '<p><label for="status">' . $lang['status'] . '</label><select name="status" id="status"><option value="1" ' . ($row['status'] == 1 ? 'selected' : '') . '>' . $lang['srv_user_notbanned'] . '</option><option value="0" ' . ($row['status'] == 0 ? 'selected' : '') . '>' . $lang['srv_user_banned'] . '</option></select></p>';
+
+ echo '</div>';
+
+ // Segment osnovni podatki
+ echo '<div class="segment user_info">';
+
+ echo '<p><label for="name">' . $lang['name'] . ':</label><input type="text" id="name" name="name" value="' . (!empty($row['name']) ? $row['name'] : '') . '" autocomplete="off" size="50"></p>';
+ echo '<p><label for="surname">' . $lang['surname'] . ':</label><input type="text" id="surname" name="surname" value="' . (!empty($row['surname']) ? $row['surname'] : '') . '" size="50" readonly onfocus="this.removeAttribute(\'readonly\');"></p>';
+ echo '<p><label for="password">' . $lang['password'] . ':</label><input type="password" id="password" name="password" readonly onfocus="this.removeAttribute(\'readonly\');"></p>';
+ echo '<p><label for="password2">' . $lang['cms_register_user_repeat_password'] . ':</label><input type="password" id="password2" name="password2" readonly onfocus="this.removeAttribute(\'readonly\');"></p>';
+ echo '<p><label for="subscription">'.$lang['srv_subscribe'].':</label>
+ <input type="radio" id="subscriptionDa" name="gdpr_agree" value="1" '.($row['gdpr_agree'] == 1 ? 'checked="checked"' : '').'><label for="subscriptionDa" style="width: auto;">'.$lang['yes'].'</label>'.
+ ' <input type="radio" id="subscriptionNe" class="spaceLeft" name="gdpr_agree" value="0" '.($row['gdpr_agree'] == 0 ? 'checked="checked"' : '').'><label for="subscriptionNe" style="width: auto;">'.$lang['no'].'</label>'.
+ '</p>';
+
+ $user_2fa_validate = User::option($uid, 'google-2fa-validation');
+ if($admin_type == 0 && !empty($user_2fa_validate) && $user_2fa_validate != 'NOT') {
+ echo '<p><label for="google_2fa">'.$lang['google_2fa'].':</label>
+ <label for="google-2fa-da" style="width: auto;">
+ <input type="radio" id="google-2fa-da" name="google-2fa" value="1" disabled="disabled" '.((!empty($user_2fa_validate) && $user_2fa_validate != 'NOT') ? 'checked="checked"' : '').'>'.$lang['srv_mass_input_1'].'
+ </label>
+ <label for="google-2fa-ne" style="width: auto;">
+ <input type="radio" id="google-2fa-ne" name="google-2fa" value="izbrisi">'.$lang['srv_mass_input_0'].
+ '</label></p>';
+ }
+
+
+ // Admin lahko ureja katere uporabnike (mail domene) bo manager lahko dodajal pod svoj pregled
+ if ($admin_type == 0 && $row['type'] == '1') {
+ UserSetting:: getInstance()->Init($uid);
+ $emails = UserSetting:: getInstance()->getUserSetting('manage_domain');
+
+ echo '<p><label for="manage_domain" style="width:200px;">Manager domene (npr. 1ka.si):</label><input type="text" id="manage_domain" name="manage_domain" value="' . $emails . '" autocomplete="off" size="30"></p>';
+ }
+
+ // Na virtualkah manager ne sme odstraniti uporabnika iz pregleda (zaradi omejitve)
+ if($admin_type != '1' || !$virtual_domain){
+ $sqlu = sisplet_query("SELECT * FROM srv_dostop_manage WHERE manager='$global_user_id' AND user='$uid'");
+
+ if (mysqli_num_rows($sqlu) > 0) {
+ echo '<br /><p><a href="ajax.php?t=dostop&a=edit_remove_user&uid=' . $uid . '" onclick="if ( confirm(\'?\')) { } else {return false;}">' . $lang['srv_manager_rem_user2'] . '</a></p>';
+ }
+ }
+
+ echo '</div>';
+
+ // Segment paket
+ global $app_settings;
+ if($app_settings['commercial_packages'] == true){
+ echo '<div class="segment user_package">';
+
+ $userAccess = UserAccess::getInstance($uid);
+ $userAccess_data = $userAccess->getAccess();
+
+ $active_package = (isset($userAccess_data['package_id'])) ? $userAccess_data['package_id'] : '1';
+ $time_expire = (isset($userAccess_data['time_expire'])) ? date('d.m.Y', strtotime($userAccess_data['time_expire'])) : '';
+
+ // Paket
+ echo '<p>';
+ echo ' <label for="package">' . $lang['srv_access_package'] . ':</label>';
+ echo ' <select name="package" id="package">';
+ foreach($userAccess->getPackages() as $package_id => $package){
+ echo ' <option value="'.$package_id.'" '.($package_id == $active_package ? 'selected="selected"' : '').'>'.$package['name'].'</option>';
+ }
+ echo ' </select>';
+ echo '</p>';
+
+ // Trajanje paketa
+ echo '<p>';
+ echo ' <label for="package_expire">' . ucfirst($lang['srv_access_package_valid']) . ':</label>';
+ echo ' <input type="text" name="package_expire" id="package_expire" value="'.$time_expire.'" style="width:80px;">';
+ echo '</p>';
+
+ echo '
+ <script type="text/javascript">
+ $(document).ready(function () {
+ datepicker("#package_expire");
+ });
+ </script>';
+
+ echo '</div>';
+ }
+
+ echo '</form>';
+ echo '</div>';
+
+
+ // SEZNAM ANKET
+ echo '<div class="survey_list">';
+ echo ' <h3><strong>' . $lang['srv_ankete'] . '</strong></h3>';
+
+ echo ' <ul>';
+ $sql = sisplet_query("SELECT srv_anketa.id, srv_anketa.naslov FROM srv_dostop, srv_anketa WHERE srv_dostop.uid='". $uid ."' AND srv_dostop.ank_id=srv_anketa.id ORDER BY srv_anketa.edit_time DESC");
+ while ($row = mysqli_fetch_array($sql)) {
+ echo ' <li><a href="#" onclick="anketa_user_dostop(\'' . $uid . '\', \'' . $row['id'] . '\'); return false;">' . $row['naslov'] . '</a></li>';
+ }
+
+ echo ' </ul>';
+ echo '</div>';
+
+ echo '</div>';
+
+
+ // GUMBI NA DNU
+ echo '<p>';
+ echo ' <div class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_gray" href="#" onclick="edit_user_close();"><span>'.$lang['srv_zapri'].'</span></a></div>';
+ echo ' <div class="buttonwrapper floatLeft spaceLeft"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="document.manager_edit_user.submit();"><span>'.$lang['edit1337'].'</span></a></div>';
+ echo '</p>';
+ }
+
+ function ajax_edit_user_save(){
+ global $pass_salt;
+ global $admin_type;
+
+ $uid = $_GET['uid'];
+
+ $_POST['email'] = iconv("utf-8", "iso-8859-2", $_POST['email']);
+
+ if ($_POST['email'] != '') {
+
+ if ($_POST['password'] != '' && $_POST['password'] == $_POST['password2']) {
+ $password = ", pass = '" . base64_encode((hash('SHA256', $_POST['password'] . $pass_salt))) . "' ";
+ } else {
+ $password = "";
+ }
+
+ $s = sisplet_query("UPDATE users SET type='$_POST[type]', status='$_POST[status]', email='$_POST[email]', name='$_POST[name]', surname='$_POST[surname]' $password WHERE id = '$uid'");
+ if (!$s) {
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ if(isset($_POST['gdpr_agree'])){
+ sisplet_query("UPDATE users SET gdpr_agree='".$_POST['gdpr_agree']."' WHERE id = '$uid'");
+ }
+
+ if(isset($_POST['google-2fa']) && $_POST['google-2fa'] == 'izbrisi'){
+ sisplet_query("DELETE FROM user_options WHERE user_id='".$uid."' AND option_name IN ('google-2fa-secret', 'google-2fa-validation')");
+ }
+
+ if (isset($_POST['manage_domain'])) {
+
+ UserSetting::getInstance()->Init($uid);
+ UserSetting::getInstance()
+ ->setUserSetting('manage_domain', $_POST['manage_domain']);
+ UserSetting::getInstance()->saveUserSetting();
+ }
+
+ // Update or insert user package
+ if (isset($_POST['package']) && isset($_POST['package_expire']) && $_POST['package_expire'] != '') {
+
+ $package_id = $_POST['package'];
+ $package_expire = $_POST['package_expire'];
+ $package_expire_sql = date('Y-m-d H:i:s', strtotime($package_expire));
+
+ $sqlPackageTime = sisplet_query("SELECT time_activate FROM user_access WHERE usr_id='".$uid."'");
+ if(mysqli_num_rows($sqlPackageTime) > 0){
+ $rowPackageTime = mysqli_fetch_array($sqlPackageTime);
+ $time_activate = date('Y-m-d H:i:s', strtotime($rowPackageTime['time_activate']));
+
+ $sqlPackageDelete = sisplet_query("DELETE FROM user_access WHERE usr_id='".$uid."'");
+
+ $sqlPackage = sisplet_query("INSERT INTO user_access
+ (usr_id, time_activate, time_expire, package_id)
+ VALUES
+ ('".$uid."', '".$time_activate."', '".$package_expire_sql."', '".$package_id."')
+ ");
+ }
+ else{
+ $sqlPackage = sisplet_query("INSERT INTO user_access
+ (usr_id, time_activate, time_expire, package_id)
+ VALUES
+ ('".$uid."', NOW(), '".$package_expire_sql."', '".$package_id."')
+ ");
+ }
+
+
+ if (!$sqlPackage)
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ if($admin_type == 0) {
+
+ // Ce smo odprli okno v narocilih
+ if(strpos($_SERVER['HTTP_REFERER'], 'a=narocila') !== false)
+ header("Location: index.php?a=narocila");
+ else
+ header("Location: index.php?a=diagnostics&t=uporabniki&m=all");
+ }
+ else{
+ header("Location: index.php?a=diagnostics&t=uporabniki&m=my");
+ }
+ }
+
+ /**
+ * Admin: dodajanje obstojecih uporabnikov
+ *
+ */
+ function ajax_admin_add_user()
+ {
+ global $pass_salt;
+ global $lang;
+ global $global_user_id, $site_path;
+ global $admin_type;
+
+ if ($admin_type != 0 && $admin_type != 1) {
+ return;
+ }
+
+ $error = FALSE;
+
+ $sqlu = sisplet_query("SELECT email FROM users WHERE id = '" . $global_user_id . "'");
+ $rowu = mysqli_fetch_array($sqlu);
+
+ $mail_admin = $rowu['email'];
+
+ $uid = (!empty($_POST['uid']) ? $_POST['uid'] : null);
+ $uemail = (!empty($_POST['uemail']) ? $_POST['uemail'] : null);
+
+ $sqlu = sisplet_query("SELECT email, type FROM users WHERE id='$uid'");
+ if (mysqli_num_rows($sqlu) > 0) {
+ $rowu = mysqli_fetch_array($sqlu);
+ $mail_user = $rowu['email'];
+ $type_user = $rowu['type'];
+ $id = $uid;
+ }
+
+ // Za managerje pošljemo samo email
+ if(empty($id)) {
+ $sqlu = sisplet_query("SELECT id, email, type FROM users WHERE email='".$uemail."'");
+ if (mysqli_num_rows($sqlu) > 0) {
+ $rowu = mysqli_fetch_array($sqlu);
+ $mail_user = $rowu['email'];
+ $type_user = $rowu['type'];
+ $id = $rowu['id'];
+ }
+ }
+
+ if ($id > 0 && $type_user >= $admin_type) {
+
+ $s = sisplet_query("INSERT INTO srv_dostop_manage (manager, user) VALUES ('$global_user_id', '$id')");
+ if (!$s) {
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ global $site_url;
+
+ $subject = $lang['srv_dodanmail_m_1'] . '';
+ $content = sprintf($lang['srv_dodanmail_m_2'], $mail_admin, $site_url, $mail_user) . '<br /><br />' . sprintf($lang['srv_dodanmail_m_3']);
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+ $content .= $signature;
+
+ try {
+ $MA = new MailAdapter($this->anketa, $type='account');
+ $MA->addRecipients($mail_user);
+ $resultX = $MA->sendMail(stripslashes($content), $subject);
+ } catch (Exception $e) {
+ }
+
+ if ($resultX) {
+ $status = 1; // poslalo ok
+ } else {
+ $status = 2; // ni poslalo
+ }
+ }
+
+ header("Location: index.php?a=diagnostics&t=uporabniki".($error !== FALSE ? '&error='.$error : ''));
+ }
+
+ /**
+ * Admin: dodajanje obstojecih uporabnikov drugemu uporabniku v popupu
+ *
+ */
+ function ajax_admin_add_user_popup(){
+ global $lang;
+ global $admin_type;
+
+ if ($admin_type != 0)
+ return;
+
+ $manager = (isset($_POST['manager'])) ? $_POST['manager'] : '0';
+ $user = (isset($_POST['user'])) ? $_POST['user'] : '0';
+
+ if($manager == '' || $manager == '0' || $user == '' || $user == '0')
+ return;
+
+ $sql = sisplet_query("INSERT INTO srv_dostop_manage (manager, user) VALUES ('".$manager."', '".$user."')");
+ if (!$sql)
+ echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->ajax_dodeljeni_uporabniki_display();
+ }
+
+ /**
+ * Poiščemo uporabnika, ki je v bazi
+ */
+ function ajax_find_user(){
+ global $admin_type, $global_user_id;
+
+ $json['results'] = [];
+
+ if($admin_type == 0){
+
+ $sqls = sisplet_query("SELECT id, name, surname, email FROM users WHERE id NOT IN (SELECT user FROM srv_dostop_manage WHERE manager='".$global_user_id."') AND email NOT LIKE ('D3LMD-%') AND email NOT LIKE ('UNSU8MD-%') AND email LIKE '%".$_GET['term']."%' ORDER BY email", "obj");
+
+ if(!empty($sqls->email)){
+ $json['results'][] = [
+ 'id' => $sqls->id,
+ 'text' => $sqls->email.' - '.$sqls->name.' '.$sqls->surname
+ ];
+ }
+ else{
+ foreach ($sqls as $user) {
+ $json['results'][] = [
+ 'id' => $user->id,
+ 'text' => $user->email.' - '.$user->name.' '.$user->surname
+ ];
+ }
+ }
+
+ echo json_encode($json);
+ }
+ elseif ($admin_type == 1){
+ $email = trim($_POST['uemail']);
+ $user = sisplet_query("SELECT id, name, surname, email FROM users WHERE id NOT IN (SELECT user FROM srv_dostop_manage WHERE manager='".$global_user_id."') AND email NOT LIKE ('D3LMD-%') AND email NOT LIKE ('UNSU8MD-%') AND email='".$email."'");
+
+ if(mysqli_num_rows($user) > 0) {
+ echo 'success';
+ }
+ else{
+ echo 'error';
+ }
+ }
+ }
+
+ // Če je administrator
+
+ /**
+ * odstrani uporabnika iz nadzora
+ *
+ */
+ function ajax_edit_remove_user(){
+ global $global_user_id;
+ global $site_url;
+
+ $uid = (int) $_GET['uid'];
+
+ $sql = sisplet_query("DELETE FROM srv_dostop_manage WHERE user='".$uid."' AND manager='".$global_user_id."'");
+
+ header("Location: " . $site_url . "admin/survey/index.php?a=diagnostics&t=uporabniki&m=my");
+ }
+
+ /**
+ * odstrani uporabnika iz managerjevega nadzora
+ *
+ */
+ function ajax_edit_remove_user_manager(){
+ global $global_user_id;
+ global $site_url;
+
+ $uid = (int) $_GET['uid'];
+
+ $sql = sisplet_query("DELETE FROM srv_dostop_manage WHERE user='$global_user_id' AND manager='$uid'");
+
+ header("Location: " . $site_url . "admin/survey/index.php?a=diagnostics&t=uporabniki");
+ }
+
+ /**
+ * admin odstrani uporabnika iz nadzora drugemu uporabniku (managerju ali adminu)
+ *
+ */
+ function ajax_edit_remove_user_admin(){
+ global $admin_type;
+
+ if($admin_type != '0')
+ return;
+
+ $manager = (isset($_POST['manager'])) ? $_POST['manager'] : '0';
+ $user = (isset($_POST['user'])) ? $_POST['user'] : '0';
+
+ if($manager == '' || $manager == '0' || $user == '' || $user == '0')
+ return;
+
+ $sql = sisplet_query("DELETE FROM srv_dostop_manage WHERE user='$user' AND manager='$manager'");
+
+ $this->ajax_dodeljeni_uporabniki_display();
+ }
+
+ /**
+ * Seznam vseh uporabnikov znotrja 1ke
+ */
+ function ajax_all_users_list(){
+ global $admin_languages;
+ global $global_user_id;
+ global $lang;
+ global $admin_type;
+
+ $seznam = [];
+
+ $iskanjeSql = "";
+ if(!empty($_POST['search']['value'])){
+ $iskaniNiz = $_POST['search']['value'];
+ $iskanjeSql = " AND (u.name LIKE '%".$iskaniNiz."%' OR u.surname LIKE '%".$iskaniNiz."%' OR u.email LIKE '%".$iskaniNiz."%' OR d1.dostop_survey_count LIKE '%".$iskaniNiz."%' OR d2.dostop_survey_archive LIKE '%".$iskaniNiz."%')";
+ }
+
+ // Pridobimo vse uporabnike
+ $sql = "SELECT u.id as id, u.type as type, u.status, u.email as email, u.name as name, u.surname as surname, u.lang as lang, u.eduroam as aai, date_format(u.when_reg, '%d.%m.%Y') as registriran, u.gdpr_agree as gdpr_agree, dm.st_dodeljenih_uporabnikov as st_dodeljenih_uporabnikov, dm2.st_managerjev as st_managerjev, d1.dostop_survey_count as st_anket, d2.dostop_survey_archive as st_arhivskih, date_format(u.last_login, '%d.%m.%Y') as last_login, ue.email as second_email FROM users AS u ".
+ " LEFT OUTER JOIN (SELECT srv_dostop.ank_id, srv_dostop.uid, count(*) AS dostop_survey_count FROM srv_dostop, srv_anketa WHERE srv_anketa.id=srv_dostop.ank_id AND srv_anketa.backup='0' GROUP BY srv_dostop.uid ) AS d1 ON d1.uid = u.id ".
+ " LEFT OUTER JOIN (SELECT srv_dostop.ank_id, srv_dostop.uid, count(*) AS dostop_survey_archive FROM srv_dostop, srv_anketa WHERE srv_anketa.id=srv_dostop.ank_id AND srv_anketa.backup>'0' GROUP BY srv_dostop.uid ) AS d2 ON d2.uid = u.id ".
+ " LEFT OUTER JOIN (SELECT srv_dostop_manage.manager, count(*) AS st_dodeljenih_uporabnikov FROM srv_dostop_manage GROUP BY srv_dostop_manage.manager) AS dm ON dm.manager = u.id ".
+ " LEFT OUTER JOIN (SELECT srv_dostop_manage.user, count(*) AS st_managerjev FROM srv_dostop_manage GROUP BY srv_dostop_manage.user) AS dm2 ON dm2.user = u.id ".
+ " LEFT OUTER JOIN (SELECT user_emails.email, user_emails.user_id FROM user_emails WHERE active=1) AS ue ON ue.user_id = u.id".
+ " WHERE u.email NOT LIKE ('D3LMD-%') AND u.email NOT LIKE ('UNSU8MD-%') ".$iskanjeSql;
+
+ // Filtri, ki jih datatables pošilja in po katerih filtriramo
+ if($_POST['order'][0]['column'] < 12) {
+ $orderPolje = [
+ "u.name ".$_POST['order'][0]['dir'].", u.surname",
+ "u.email",
+ "u.type",
+ "u.lang",
+ "u.eduroam", //AAI
+ "d1.dostop_survey_count", //st_anket
+ "d2.dostop_survey_archive", //st_arhivskih
+ "dm.st_dodeljenih_uporabnikov", //st_dodeljenih_uporabnikov
+ "dm2.st_managerjev", //st_managerjev
+ "u.gdpr_agree",
+ "u.when_reg",
+ "u.last_login"
+ ];
+
+ if($_POST['order'][0]['column'] == 9){
+
+ $vrednost='u.gdpr_agree desc';
+ if($_POST['order'][0]['dir'] == 'asc'){
+ $vrednost= ' FIELD (u.gdpr_agree, 0, \'-1\', 1)';
+ }
+
+ $sql .= " ORDER BY ".$vrednost;
+ }
+ else {
+ $sql .= " ORDER BY ".$orderPolje[$_POST['order'][0]['column']]." ".$_POST['order'][0]['dir'];
+ }
+ }
+
+ if($_POST['length'] != '-1') {
+ $sql .= " LIMIT ".$_POST['start'].", ".$_POST['length'];
+ }
+
+ $resultQuery = sisplet_query($sql);
+ $resultU = lazyLoadSqlObj($resultQuery);
+
+ // Seznam uporabnikov vrne za administratorje vse za ostale pa samo tiste, ki smo jih dodali k uporabniku.
+ if (!empty($resultU)) {
+
+ if (!empty($resultU->name)) {
+ $vsi[] = $resultU;
+ }
+ else {
+ $vsi = $resultU;
+ }
+
+ foreach ($vsi as $uporabnik) {
+ $seznam[] = [
+ iconv(mb_detect_encoding( $uporabnik->name, mb_detect_order(), true), "UTF-8", $uporabnik->name) .' '.iconv(mb_detect_encoding( $uporabnik->surname, mb_detect_order(), true), "UTF-8", $uporabnik->surname),
+ (!empty($uporabnik->second_email) ? iconv(mb_detect_encoding( $uporabnik->second_email, mb_detect_order(), true), "UTF-8", $uporabnik->second_email) : iconv(mb_detect_encoding( $uporabnik->email, mb_detect_order(), true), "UTF-8", $uporabnik->email)),
+ $this->userTypeToText($uporabnik->type),
+ $admin_languages[$uporabnik->lang],
+ (!empty($uporabnik->aai) ? $this->vrniDaNe($uporabnik->aai) : $lang['no1']),
+ (!empty($uporabnik->st_anket) ? $uporabnik->st_anket : 0),
+ (!empty($uporabnik->st_arhivskih) ? $uporabnik->st_arhivskih : 0),
+ '<a href="#" onclick="dodeljeni_uporabniki_display(\''.$uporabnik->id.'\'); return false;" title="'.$lang['srv_manager_manager'].'">'.(!empty($uporabnik->st_dodeljenih_uporabnikov) ? $uporabnik->st_dodeljenih_uporabnikov : 0).'</a>',
+ (!empty($uporabnik->st_managerjev) ? $uporabnik->st_managerjev : 0),
+ $lang["users_gdpr".$uporabnik->gdpr_agree],
+ $uporabnik->registriran,
+ $uporabnik->last_login,
+ '<a href="#" onclick="edit_user(\''.$uporabnik->id.'\'); return false;" title="'.$lang['srv_info_modify'].'"><i class="fa fa-pencil-alt link-sv-moder"></i></a>'.
+ ' | <a href="#" onclick="vsiUporabnikiAkcija(\''.$uporabnik->id.'\', \'ban\'); return false;" title="'.$lang[($uporabnik->status == 0 ? 'srv_user_banned' : 'srv_user_notbanned')].'"><i class="fa fa-ban '.($uporabnik->status == 0 ? 'link-rdec' : 'link-sv-moder').'"></i></a>'.
+ ' | <a href="#" onclick="vsiUporabnikiAkcija(\''.$uporabnik->id.'\', \'delete\'); return false;" title="'.$lang['srv_multicrosstabs_tables_delete_short'].'"><i class="fa fa-times link-sv-moder"></i></a>'
+ ];
+ }
+ }
+
+ $sql_recordsTotal = sisplet_query("SELECT count(id) as stVseh FROM users WHERE email NOT LIKE ('D3LMD-%') AND email NOT LIKE ('UNSU8MD-%')", "obj");
+
+ // Število vseh zadetkov, ki jih imamo v bazi
+ $recordsTotal = 0;
+ if(!empty($sql_recordsTotal)) {
+ $recordsTotal = $sql_recordsTotal->stVseh;
+ }
+
+ // Število filtriranih zadetkov
+ $recordFiltered = $recordsTotal;
+ if(!empty($_POST['search']['value']))
+ $recordFiltered = sizeof($vsi);
+
+ echo json_encode([
+ "draw" => (!empty($_POST['draw']) ? $_POST['draw'] : 1),
+ "recordsTotal" => $recordsTotal,
+ "recordsFiltered" => $recordFiltered,
+ "data" => $seznam // polje z vsebino
+ ]);
+ }
+
+ /**
+ * Seznam dodeljenih uporabnikov (manager in admin)
+ */
+ function ajax_all_users_list_my(){
+ global $admin_languages;
+ global $global_user_id;
+ global $lang;
+ global $admin_type;
+
+ $seznam = [];
+
+ $iskanjeSql = "";
+ if(!empty($_POST['search']['value'])){
+ $iskaniNiz = $_POST['search']['value'];
+ $iskanjeSql = " AND (u.name LIKE '%".$iskaniNiz."%' OR u.surname LIKE '%".$iskaniNiz."%' OR u.email LIKE '%".$iskaniNiz."%' OR d1.dostop_survey_count LIKE '%".$iskaniNiz."%' OR d2.dostop_survey_archive LIKE '%".$iskaniNiz."%')";
+ }
+
+ // Pridobimo vse uporabnike
+ $sql = "SELECT u.id as id, u.type as type, u.status, u.email as email, u.name as name, u.surname as surname, u.lang as lang, u.eduroam as aai, date_format(u.when_reg, '%d.%m.%Y') as registriran, u.gdpr_agree as gdpr_agree, d1.dostop_survey_count as st_anket, d2.dostop_survey_archive as st_arhivskih, date_format(u.last_login, '%d.%m.%Y') as last_login, ue.email as second_email FROM users AS u ".
+ " LEFT OUTER JOIN ( SELECT srv_dostop.ank_id, srv_dostop.uid, count(*) AS dostop_survey_count FROM srv_dostop, srv_anketa WHERE srv_anketa.id=srv_dostop.ank_id AND srv_anketa.backup='0' GROUP BY srv_dostop.uid ) AS d1 ON d1.uid = u.id ".
+ " LEFT OUTER JOIN ( SELECT srv_dostop.ank_id, srv_dostop.uid, count(*) AS dostop_survey_archive FROM srv_dostop, srv_anketa WHERE srv_anketa.id=srv_dostop.ank_id AND srv_anketa.backup>'0' GROUP BY srv_dostop.uid ) AS d2 ON d2.uid = u.id ".
+ " LEFT OUTER JOIN (SELECT user_emails.email, user_emails.user_id FROM user_emails WHERE active=1) AS ue ON ue.user_id = u.id".
+ " WHERE u.email NOT LIKE ('D3LMD-%') AND u.email NOT LIKE ('UNSU8MD-%') ".$iskanjeSql;
+
+ // Filter samo po lastnih uporabnikih
+ $isciPoDomeni = '';
+
+ // Med lastne uporabnike prikažemo tudi, tiste ki so bili registrirani z isto domeno
+ /*UserSetting :: getInstance()->Init($global_user_id);
+ $domena = UserSetting :: getInstance()->getUserSetting('manage_domain');
+ if(!empty($domena)){
+ $isciPoDomeni = " OR u.email LIKE '%".$domena."'";
+ }*/
+
+ $sql .= " AND (u.id IN (SELECT user FROM srv_dostop_manage WHERE manager='".$global_user_id."') ".$isciPoDomeni.")";
+
+
+ // Filtri, ki jih datatables pošilja in po katerih filtriramo
+ if($_POST['order'][0]['column'] < 10) {
+ $orderPolje = [
+ "u.name ".$_POST['order'][0]['dir'].", u.surname",
+ "u.email",
+ "u.type",
+ "u.lang",
+ "u.eduroam", //AAI
+ "d1.dostop_survey_count", //st_anket
+ "d2.dostop_survey_archive", //st_arhivskih
+ "u.gdpr_agree",
+ "u.when_reg",
+ "u.last_login"
+ ];
+
+ if($_POST['order'][0]['column'] == 7){
+
+ $vrednost='u.gdpr_agree desc';
+ if($_POST['order'][0]['dir'] == 'asc'){
+ $vrednost= ' FIELD (u.gdpr_agree, 0, \'-1\', 1)';
+ }
+
+ $sql .= " ORDER BY ".$vrednost;
+ }
+ else {
+ $sql .= " ORDER BY ".$orderPolje[$_POST['order'][0]['column']]." ".$_POST['order'][0]['dir'];
+ }
+ }
+
+ if($_POST['length'] != '-1') {
+ $sql .= " LIMIT ".$_POST['start'].", ".$_POST['length'];
+ }
+
+ $resultQuery = sisplet_query($sql);
+ $resultU = lazyLoadSqlObj($resultQuery);
+
+ // Seznam uporabnikov vrne za administratorje vse za ostale pa samo tiste, ki smo jih dodali k uporabniku.
+ if (!empty($resultU) && ($this->jeAdministrator() || !$this->jeAdministrator())) {
+
+ if (!empty($resultU->name)) {
+ $vsi[] = $resultU;
+ }
+ else {
+ $vsi = $resultU;
+ }
+
+ foreach ($vsi as $uporabnik) {
+ $seznam[] = [
+ iconv(mb_detect_encoding( $uporabnik->name, mb_detect_order(), true), "UTF-8", $uporabnik->name) .' '.iconv(mb_detect_encoding( $uporabnik->surname, mb_detect_order(), true), "UTF-8", $uporabnik->surname),
+ (!empty($uporabnik->second_email) ? iconv(mb_detect_encoding( $uporabnik->second_email, mb_detect_order(), true), "UTF-8", $uporabnik->second_email) : iconv(mb_detect_encoding( $uporabnik->email, mb_detect_order(), true), "UTF-8", $uporabnik->email)),
+ $this->userTypeToText($uporabnik->type),
+ $admin_languages[$uporabnik->lang],
+ (!empty($uporabnik->aai) ? $this->vrniDaNe($uporabnik->aai) : $lang['no1']),
+ (!empty($uporabnik->st_anket) ? $uporabnik->st_anket : 0),
+ (!empty($uporabnik->st_arhivskih) ? $uporabnik->st_arhivskih : 0),
+ $lang["users_gdpr".$uporabnik->gdpr_agree],
+ $uporabnik->registriran,
+ $uporabnik->last_login,
+ '<a href="#" onclick="edit_user(\''.$uporabnik->id.'\'); return false;" title="'.$lang['srv_info_modify'].'"><i class="fa fa-pencil-alt link-sv-moder"></i></a>'.
+ ' | <a href="#" onclick="vsiUporabnikiAkcija(\''.$uporabnik->id.'\', \'ban\'); return false;" title="'.$lang[($uporabnik->status == 0 ? 'srv_user_banned' : 'srv_user_notbanned')].'"><i class="fa fa-ban '.($uporabnik->status == 0 ? 'link-rdec' : 'link-sv-moder').'"></i></a>'.
+ ' | <a href="#" onclick="vsiUporabnikiAkcija(\''.$uporabnik->id.'\', \'delete\'); return false;" title="'.$lang['srv_multicrosstabs_tables_delete_short'].'"><i class="fa fa-times link-sv-moder"></i></a>'
+ ];
+
+ }
+ }
+
+ // Število vseh zadetkov, ki jih imamo v bazi
+ $recordsTotal = 0;
+ $recordsTotal = sizeof($vsi);
+
+ // Število filtriranih zadetkov
+ $recordFiltered = $recordsTotal;
+ if(!empty($_POST['search']['value']))
+ $recordFiltered = sizeof($vsi);
+
+ echo json_encode([
+ "draw" => (!empty($_POST['draw']) ? $_POST['draw'] : 1),
+ "recordsTotal" => $recordsTotal,
+ "recordsFiltered" => $recordFiltered,
+ "data" => $seznam // polje z vsebino
+ ]);
+ }
+
+ /**
+ * Izbrišemo uporabnika, še vendo pa hranimo njegove ankete
+ */
+ function ajax_all_users_list_delete(){
+ $uid = (!empty($_POST['uid']) ? $_POST['uid'] : null);
+
+ if($this->sebeNeMoreIzbrisati($uid)){
+ return false;
+ }
+
+ $result = sisplet_query ("UPDATE users SET status=0, email=CONCAT('D3LMD-', UNIX_TIMESTAMP(), email) WHERE id='".$uid."'");
+ }
+
+ function ajax_all_users_list_ban(){
+ $uid = (!empty($_POST['uid']) ? $_POST['uid'] : null);
+
+ if($this->sebeNeMoreIzbrisati($uid)){
+ return false;
+ }
+
+ $user = sisplet_query ("SELECT id, status FROM users WHERE id='".$uid."'", 'obj');
+
+ $status = 0;
+ if($user->status == 0)
+ $status = 1;
+
+ sisplet_query ("UPDATE users SET status='".$status."' WHERE id='".$uid."'");
+ }
+
+ private function sebeNeMoreIzbrisati($id){
+ global $global_user_id;
+
+ if($global_user_id == $id)
+ return TRUE;
+
+ return false;
+ }
+
+
+ private function jeAdministrator()
+ {
+ global $admin_type;
+
+ if ($admin_type == 0) {
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ /**
+ * Pridobimo vrste uporabnika v besedilni obliki
+ *
+ * @param $db_type
+ *
+ * @return mixed
+ */
+ function userTypeToText($db_type)
+ {
+ global $lang;
+
+ $type = $lang['admin_narocnik'];
+
+ switch ($db_type) {
+ case 0:
+ $type = $lang['admin_admin'];
+ break;
+ case 1:
+ $type = $lang['admin_manager'];
+ break;
+ case 2:
+ case 3:
+ $type = $lang['admin_narocnik'];
+ break;
+ }
+
+ return $type;
+ }
+
+ /**
+ * Seznam vseh izbrisanih uporabnikov, ki jih pridobi datatables
+ */
+ function ajax_delete_users_list()
+ {
+ global $admin_languages;
+ $seznam = [];
+
+ $resultQuery = sisplet_query("SELECT name, surname, SUBSTRING(REPLACE (email, 'D3LMD-', ''),11) as email, type, DATE_FORMAT(when_reg, '%d.%m.%Y') as registriran, lang FROM users WHERE email LIKE ('D3LMD-%')");
+ $resultU = lazyLoadSqlObj($resultQuery);
+
+ if (!empty($resultU) && $this->jeAdministrator()) {
+
+ if (!empty($resultU->name)) {
+ $izbrisani[] = $resultU;
+ } else {
+ $izbrisani = $resultU;
+ }
+
+ foreach ($izbrisani as $uporabnik) {
+ $seznam[] = [
+ iconv(mb_detect_encoding( $uporabnik->name, mb_detect_order(), true), "UTF-8", $uporabnik->name) .' '.iconv(mb_detect_encoding( $uporabnik->surname, mb_detect_order(), true), "UTF-8", $uporabnik->surname),
+ iconv(mb_detect_encoding( $uporabnik->email, mb_detect_order(), true), "UTF-8", $uporabnik->email),
+ $this->userTypeToText($uporabnik->type),
+ $admin_languages[$uporabnik->lang],
+ $uporabnik->registriran,
+ ];
+ }
+ }
+
+ echo json_encode([
+ "data" => $seznam // polje z vsebino
+ ]);
+
+ }
+
+ public function ajax_unsigned_users_list()
+ {
+ global $admin_languages;
+ $seznam = [];
+
+ $odjavljeniQuery = sisplet_query("SELECT name, surname, SUBSTRING(REPLACE (email, 'UNSU8MD-', ''),11) as email, type, DATE_FORMAT(when_reg, '%d.%m.%Y') as registriran, status, lang FROM users WHERE email LIKE ('UNSU8MD-%')");
+ $odjavljeni_db = lazyLoadSqlObj($odjavljeniQuery);
+
+ if (!empty($odjavljeni_db) && $this->jeAdministrator()) {
+
+ if (!empty($odjavljeni_db->name)) {
+ $odjavljeni[] = $odjavljeni_db;
+ } else {
+ $odjavljeni = $odjavljeni_db;
+ }
+
+ foreach ($odjavljeni as $uporabnik) {
+ $seznam[] = [
+ iconv(mb_detect_encoding( $uporabnik->name, mb_detect_order(), true), "UTF-8", $uporabnik->name) .' '.iconv(mb_detect_encoding( $uporabnik->surname, mb_detect_order(), true), "UTF-8", $uporabnik->surname),
+ iconv(mb_detect_encoding( $uporabnik->email, mb_detect_order(), true), "UTF-8", $uporabnik->email),
+ $this->userTypeToText($uporabnik->type),
+ $admin_languages[$uporabnik->lang],
+ $uporabnik->registriran,
+ ];
+ }
+ }
+
+ echo json_encode([
+ "data" => $seznam // polje z vsebino
+ ]);
+ }
+
+ public function ajax_unconfirmed_mail_user_list_delet_user()
+ {
+ $uid = (!empty($_POST['uid']) ? $_POST['uid'] : NULL);
+
+ if (empty($uid)) {
+ return NULL;
+ }
+
+ sisplet_query("DELETE FROM users_to_be WHERE id='" . $uid . "'");
+
+ echo 'ok';
+ }
+
+ public function ajax_confirm_user_email(){
+ global $pass_salt;
+ global $lang;
+ global $app_settings;
+
+ $uid = (!empty($_POST['uid']) ? $_POST['uid'] : NULL);
+
+ if (empty($uid)) {
+ return NULL;
+ }
+
+ // kopirano iz user_to_be v users
+ $result = sisplet_query("SELECT type, email, name, surname, pass, status, gdpr_agree, when_reg, came_from, lang FROM users_to_be WHERE id='" . $uid . "'");
+
+ if (mysqli_num_rows($result) > 0) {
+ $r = mysqli_fetch_assoc($result);
+ $g = base64_encode((hash('SHA256', base64_decode($r['pass']) . $pass_salt)));
+
+ sisplet_query("INSERT INTO users (type, email, name, surname, pass, status, gdpr_agree, when_reg, came_from, lang, manuallyApproved)
+ VALUES ('" . $r['type'] . "', '" . $r['email'] . "', '" . $r['name'] . "', '" . $r['surname'] . "', '" . $g . "','" . $r['status'] . "', '" . $r['gdpr_agree'] . "','" . $r['when_reg'] . "', '" . $r['came_from'] . "', '" . $r['lang'] . "', 'Y')");
+ sisplet_query("DELETE FROM users_to_be WHERE id='" . $uid . "' OR email='" . $r['email'] . "'");
+
+
+ // Uporabniku posljemo email da je bil njegov racun aktiviran
+ $Content = $lang['confirmed_user_mail'];
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+ $Content .= $signature;
+
+ // Ce gre slucajno za virutalko
+ $Subject = $lang['confirmed_user_mail_subject'];
+
+ $PageName = $app_settings['app_name'];
+ $ZaMail = '<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">'.'<html><head> <title>'.$Subject.'</title><meta content="text/html; charset=utf-8" http-equiv=Content-type></head><body>';
+
+ // Besedilo v lang dilu je potrebno popravit, ker nimamo vec cel kup parametrov
+ $Content = str_replace("SFNAME", $r['name'].' '.$r['surname'], $Content);
+ $Content = str_replace("SFPAGENAME", $PageName, $Content);
+
+ $Subject = str_replace("SFPAGENAME", $PageName, $Subject);
+
+ $ZaMail .= $Content;
+ $ZaMail .= "</body></html>";
+
+ // Za testiranje brez posiljanja maila
+ if(isDebug()) {
+ echo $ZaMail;
+ die();
+ }
+
+ // Posljemo mail, da je bil racun aktiviran
+ try{
+ $MA = new MailAdapter(null, 'account');
+ $MA->addRecipients($r['email']);
+ $result = $MA->sendMail($ZaMail, $Subject);
+ }
+ catch (Exception $e){
+ echo $e;
+ }
+
+ echo 'ok';
+ }
+ else {
+ echo 'non';
+ }
+ }
+
+ public function ajax_unconfirmed_mail_user_list()
+ {
+ global $admin_languages;
+ global $lang;
+ $seznam = [];
+
+ $resultQuery = sisplet_query("SELECT id, name, surname, email, type, DATE_FORMAT(when_reg, '%d.%m.%Y') as registriran, lang FROM users_to_be");
+ $resultU = lazyLoadSqlObj($resultQuery);
+
+ if (!empty($resultU)) {
+
+ // V kolikor imamo samo eno vrstico vpisano, potem objekt spremenimo v multiarray
+ if (!empty($resultU->name)) {
+ $nepotrjeni[] = $resultU;
+ } else {
+ $nepotrjeni = $resultU;
+ }
+
+ $seznam = [];
+ foreach ($nepotrjeni as $uporabnik) {
+ $seznam[] = [
+ iconv(mb_detect_encoding( $uporabnik->name, mb_detect_order(), true), "UTF-8", $uporabnik->name) .' '.iconv(mb_detect_encoding( $uporabnik->surname, mb_detect_order(), true), "UTF-8", $uporabnik->surname),
+ iconv(mb_detect_encoding( $uporabnik->email, mb_detect_order(), true), "UTF-8", $uporabnik->email),
+ $this->userTypeToText($uporabnik->type),
+ $admin_languages[$uporabnik->lang],
+ $uporabnik->registriran,
+ '<a href="#" onclick="potrdiNepotrjenegaUporabnika(' . $uporabnik->id . ')" title="' . $lang['confirm_user_in_db'] . '"><i class="fa fa-check link-sv-moder"></i> <span class="no-print"> | </span>' .
+ '<a href="#" onclick="izbrisiNepotrjenegaUporabnika(' . $uporabnik->id . ')" title="'.$lang['delete_user_in_db'].'"><i class="fa fa-times link-sv-moder"></a>',
+ ];
+ }
+ }
+
+ echo json_encode([
+ "data" => $seznam // polje z vsebino
+ ]);
+ }
+
+ // Popup z dodeljenimi uporabniki
+ private function ajax_dodeljeni_uporabniki_display(){
+ global $lang;
+
+ $manager = (isset($_POST['manager'])) ? $_POST['manager'] : '0';
+
+ if($manager == '' || $manager == '0'){
+ return;
+ }
+
+
+ echo '<div class="popup_close"><a href="#" onClick="dodeljeni_uporabniki_close(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_manager_count'].'</h2>';
+
+
+ echo '<div class="popup_content dodeljeni_uporabniki">';
+
+ // Seznam dodeljenih uporabnikov
+ $sqlUsers = sisplet_query("SELECT u.id, u.name, u.surname, u.email, u.status
+ FROM users u, srv_dostop_manage m
+ WHERE u.id=m.user AND m.manager='".$manager."'
+ ");
+ if(mysqli_num_rows($sqlUsers) > 0){
+
+ echo '<ul>';
+
+ while($rowUsers = mysqli_fetch_array($sqlUsers)){
+ echo '<li>';
+
+ echo ' <span>';
+ echo $rowUsers['name'].' '.$rowUsers['surname'].' ('.$rowUsers['email'].')';
+ if($rowUsers['status'] == '0')
+ echo ' - <span class="red italic">NEAKTIVEN</span>';
+ echo ' </span>';
+
+ echo ' <span><a onClick="dodeljeni_uporabniki_remove(\''.$manager.'\', \''.$rowUsers['id'].'\');">'.$lang['hour_remove'].'</a></span>';
+
+ echo '</li>';
+ }
+
+ echo '</ul>';
+ }
+
+ // Dodajanje novega uporabnika
+ echo '<h4>'.$lang['srv_manager_add_admin'].'</h4>';
+ echo '<div class="add_user">';
+
+ echo '<form class="manager_add_user" name="admin_add_dostop" action="ajax.php?t=dostop&a=admin_add_user" method="post">';
+
+ echo '<h3><b>'.$lang['srv_manager_add_user_popup'].'</b></h3>';
+ echo '<p><select name="add_user_id" id="add_user_id" class="js-obstojeci-uporabniki-admin-ajax" style="width: 300px;"></select></p>';
+
+ echo '<p><div class="buttonwrapper floatLeft">';
+ echo ' <a class="ovalbutton ovalbutton_orange" href="#" onClick="dodeljeni_uporabniki_add(\''.$manager.'\', \''.$rowUsers['id'].'\');">'.$lang['add'].'</a>';
+ echo '</div></p><br><br>';
+
+ echo '</form>';
+
+ echo '<script>$(\'.js-obstojeci-uporabniki-admin-ajax\').select2({
+ minimumInputLength: 3,
+ ajax: {
+ url: \'ajax.php?t=dostop&a=find_user\',
+ dataType: \'json\'
+ }
+ });</script>';
+
+ echo '</div>';
+
+ echo '</div>';
+
+
+ echo '<div class="buttons_holder">';
+ echo '<span class="buttonwrapper floatRight" title="'.$lang['srv_zapri'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dodeljeni_uporabniki_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></span>';
+ echo '</div>';
+ }
+
+ function isAnketar()
+ {
+ global $admin_type;
+ # preverimo ali je anketar
+ return ($this->checkDostopSub('phone') && $admin_type > 1);
+
+ }
+
+ /**
+ * vrne seznam vseh uporabnikov z dostopom do ankete
+ *
+ */
+ function getDostop()
+ {
+
+ $dostop = [];
+
+ $dostop[0] = $this->getAdminsDostop();
+ $dostop[1] = $this->getManagersDostop();
+ $dostop[2] = $this->getUsersDostop();
+
+ return $dostop;
+ }
+
+ /**
+ * preveri ali imajo do ankete dostop administratorji
+ * ta funkcija ni!!! primerna za preverjat, ce prikazemo anketo
+ * administratorju, ker se mora poleg tega preverjati se, ce je uporabnik
+ * admin pa to
+ *
+ */
+ function getAdminsDostop()
+ {
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ if (strtotime($rowa['dostop_admin']) >= strtotime(date("Y-m-d"))) {
+ return $rowa['dostop_admin'];
+ }
+
+ return FALSE;
+ }
+
+ /**
+ * kdo ima managerski dostop (od managerjev in administratorjev)
+ *
+ */
+ function getManagersDostop()
+ {
+
+ $sql = sisplet_query("SELECT u.* FROM users u, srv_dostop_manage m WHERE u.id=m.manager AND m.user IN (SELECT uid FROM srv_dostop WHERE ank_id='$this->anketa') ");
+ while ($row = mysqli_fetch_array($sql)) {
+ $dostop[] = $row;
+ }
+
+ return $dostop;
+ }
+
+ /**
+ * kdo od uporabnikov ima dostop
+ *
+ */
+ function getUsersDostop()
+ {
+
+ $sql = sisplet_query("SELECT u.* FROM srv_dostop d, users u WHERE u.id=d.uid AND d.ank_id = '$this->anketa'");
+ while ($row = mysqli_fetch_array($sql)) {
+ $dostop[] = $row;
+ }
+
+ return $dostop;
+ }
+
+ /**
+ * Vrenemo besedni izraz za 1/0 iz podatkovne baze
+ *
+ * @param int $val
+ *
+ * @return mixed
+ */
+ private function vrniDaNe($val = 0)
+ {
+ global $lang;
+
+ if ($val == 1) {
+ return $lang['yes'];
+ }
+
+ return $lang['no1'];
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.Export.php b/admin/survey/classes/class.Export.php
new file mode 100644
index 0000000..49d85d6
--- /dev/null
+++ b/admin/survey/classes/class.Export.php
@@ -0,0 +1,95 @@
+<?php
+
+/***************************************
+ * Description: xport class za izvoz
+ * Autor: Robert Šmalc
+ * Created date: 02.06.2016
+ *****************************************/
+class Export
+{
+
+ private $anketa;
+ public function __construct($anketa = null)
+ {
+ if ((isset ($_REQUEST['anketa']) && $_REQUEST['anketa'] > 0) || (isset ($anketa) && $anketa > 0)) {
+ $this->anketa = (isset ($_REQUEST['anketa']) && $_REQUEST['anketa'] > 0) ? $_REQUEST['anketa'] : $anketa;
+ } else {
+ return 'Anketa ID ne obstaja';
+ }
+
+ return $this;
+ }
+
+ static private $instance;
+ public static function init()
+ {
+ if (!self::$instance)
+ self::$instance = new Export();
+
+ return self::$instance;
+ }
+
+
+ /************************************************
+ * Izvoz polja v CSV format
+ * @return CSV
+ ************************************************/
+
+ protected $prefix;
+ protected $array;
+ protected $ime;
+
+ public function csv($ime = 'CSV_izvoz', $array = null, $prefix = null)
+ {
+ global $site_path;
+
+ // Prefix mora biti male črke in braz presledkov
+ if (!is_null($prefix)) {
+ $prefix = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $prefix)));
+ }else{
+ $ime = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $ime)));
+ $prefix = $ime;
+ }
+
+ $prefix .= '_';
+
+ $temp_folder = $site_path . 'admin/survey/tmp/';
+
+ // če direktorij še ne obstaja
+ if (!file_exists($temp_folder))
+ mkdir($temp_folder, 0755);
+
+ $file = $temp_folder . $prefix . $this->anketa . '.csv';
+
+ $datoteka = fopen($file, 'w') or die('Datoteke (' . $file . ') ni mogoče odpreti.');
+
+ // Preverimo če gre za polje ali string
+ if(is_array($array)) {
+ foreach ($array as $row) {
+ fputcsv($datoteka, $row, ',');
+ }
+ }elseif(is_string($array)){
+ fputs($datoteka, $array);
+ }
+
+ fclose($datoteka);
+
+ ob_clean();
+
+ header('Content-Description: File Transfer');
+// header("Content-type: text/x-csv; charset=utf-8");
+ header('Content-Type: application/octet-stream');
+ header('Content-Length: ' . filesize($file));
+ header("Content-Disposition: attachment; filename=" . $ime . ".csv");
+
+ flush();
+
+ readfile($file);
+
+ if (file_exists($file))
+ unlink($file);
+
+ die();
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.Forum.php b/admin/survey/classes/class.Forum.php
new file mode 100644
index 0000000..a82ea10
--- /dev/null
+++ b/admin/survey/classes/class.Forum.php
@@ -0,0 +1,441 @@
+<?php
+
+class Forum {
+
+
+ var $currentForum; // Trenutni forum kjer se nahaja user
+ var $currentThread; // Trenutna tema kjer se nahaja user
+ var $currentPost; // Trenutni post kjer se nahaja user
+
+ var $currentForumNice; // NiceLink trenutnega foruma
+
+ var $displayPosts; // 0 zaporedno, 1 nitno, 2 stavcno
+ var $displayColumn; // 3, 2, 1 - stevilo stolpcev
+ var $displayIcons; // 1 prikaze, 0 ne prikaze
+
+ var $sortOrder; // ASC, DESC - za sortiranje tem
+ var $sortPostOrder; // ASC, DESC - za sorstiranje sporocil
+ var $sortLimit; // no, 1d, 1w, 2w, 1m, 3m, 6m, 1y - omejitev izpisa tem
+
+ // Spremenljivki za komentarje novic, rubrik, baze..
+ var $tableID; // ID stvari, ki se jo komentira v tabeli new
+ var $columnID; // ID zapisa v tej tabeli, na katerega komentiramo
+
+ // Stevilo tem in postov na eni strani
+ var $threadBreak;
+ var $postBreak;
+
+ var $uid;
+
+
+ function __construct ($f=0, $t=0, $p=0) {
+ $this->currentForum = $f;
+ $this->currentThread = $t;
+ $this->currentPost = $p;
+
+ $this->uid = $this->uid();
+
+ $r = sisplet_query ("SELECT NiceLink FROM forum WHERE id='" .$this->currentForum ."'");
+ $rr = mysqli_fetch_row ($r);
+ $this->currentForumNice = $rr[0];
+
+ if (isset($_COOKIE['DP'])) {
+ $this->displayPosts = $_COOKIE['DP'];
+ } else {
+ $this->displayPosts = 0; // default izpisujemo zaporedno
+ }
+ if (isset($_COOKIE['DC'])) {
+ $this->displayColumn = $_COOKIE['DC']; // po novem pa se default vrednost nastavi v adminu (in se shranjena v bazi)
+ } else {
+ $this->displayColumn = null;
+ }
+ if (isset($_COOKIE['DI'])) {
+ $this->displayIcons = $_COOKIE['DI'];
+ } else {
+ $this->displayIcons = 1; // default prikazujemo ikonce
+ }
+ if (isset($_COOKIE['SO'])) {
+ if ($_COOKIE['SO'] == 1) {
+ $this->sortOrder = 'ASC';
+ } else {
+ $this->sortOrder = 'DESC';
+ }
+ } else {
+ $this->sortOrder = 'DESC';
+ }
+ if (isset($_COOKIE['SPO'])) {
+ if ($_COOKIE['SPO'] == 1) {
+ $this->sortPostOrder = 'DESC';
+ } else {
+ $this->sortPostOrder = 'ASC';
+ }
+ } else {
+ $this->sortPostOrder = 'ASC';
+ }
+ if (isset($_COOKIE['SL'])) {
+ $this->sortLimit = $_COOKIE['SL'];
+ } else {
+ $this->sortLimit = 'no';
+ }
+
+ $this->tableName = '';
+ $this->tableId = 0;
+
+ }
+
+
+ // Nastavi trenutni forum
+ function setForum($f) {
+ $this->currentForum = $f;
+ }
+
+ // Nastavi trenutno temo
+ function setThread($t) {
+ $this->currentThread = $t;
+ }
+
+ // Nastavi trenutno sporocilo
+ function setPost($p) {
+ $this->currentPost = $p;
+ }
+
+ // Nastavi tableName
+ function setTableID ($t) {
+ $this->tableID = $t;
+ }
+
+ // Nastavi tableId
+ function setColumnID ($i) {
+ $this->columnID = $i;
+ }
+
+
+ // Vnese post v bazo (in postori vse ostale potrebne stvari ob dodajanju novega sporocila :) )
+ function addPost ($avtor, $naslov, $vsebina, $new=0, $id=0, $timeDelay=0, $mail_alert=true) {
+ global $site_url;
+ global $skin_name;
+ global $lang;
+ global $admin_type;
+ global $pass_salt;
+ global $global_user_id;
+ global $cookie_domain;
+
+ // preden naredimo karkoli, odstranimo javascript iz vsebine in naslova:
+ // Enako za meta redirect
+ $vsebina = preg_replace ('/\<script(.*?)\/script>/i', "", $vsebina);
+ $naslov = preg_replace ('/\<script(.*?)\/script>/i', "", $naslov);
+ $vsebina = preg_replace ('/\<meta(.*?)\>/i', "", $vsebina);
+ $naslov = preg_replace ('/\<meta(.*?)\>/i', "", $naslov);
+
+ // praznih sporocil ne jemljemo.
+ if (strlen ($vsebina)>0) {
+
+ $IP = $_SERVER['REMOTE_ADDR'];
+ $parent = 0;
+
+ if ($this->currentPost > 0) {
+ $parent = $this->currentPost;
+ } elseif ($this->currentThread > 0) {
+ $parent = $this->currentThread;
+ }
+
+ if ($global_user_id > 0) {
+ $uid = $global_user_id;
+ $resu = sisplet_query ("SELECT name FROM users WHERE id='" .$uid ."'");
+ $ru = mysqli_fetch_row ($resu);
+ $user = $ru[0];
+ } else {
+ $uid = 0;
+ $user = $avtor;
+ }
+
+ if ($admin_type == -1 || $global_user_id==0) {
+ if (isset($_POST['SessID']) && isset($_POST['prepis'])) {
+ // Prepis kode
+ $handle = $_POST['SessID'];
+ $resultCD = sisplet_query ("SELECT code FROM registers WHERE handle='$handle'");
+ $sqlCD = mysqli_fetch_row($resultCD);
+
+ if (strtolower ($_POST['prepis']) != strtolower ($sqlCD[0]) || mysqli_num_rows($resultCD)==0)
+ die($lang['nu_regp_pict'] .'<br><br><a href="' .$site_url .'">' .$lang['home'] .'</a>');
+
+ $vsebina = nl2br($vsebina); // neprijavljeni userji nimajo editorja in se ne nardijo <br>
+ } else
+ die($lang['nu_regp_pict'] .'<br><br><a href="' .$site_url .'">' .$lang['home'] .'</a>');
+ }
+
+ if ($new != 0 && $id != 0) {
+
+ if ($new > 10) { // baza
+ $t = $this->getTable($new);
+ $_id = 'id';
+
+ $sql1 = sisplet_query("SELECT naslov FROM $t WHERE $_id = '$id'");
+ $row1 = mysqli_fetch_row($sql1);
+ $vsebina = $lang['news_comment_txt'].' <a href="'.$site_url.'index.php?fl=2&amp;lact=1&amp;bid='.$id.'">'.$row1[0].'</a>';
+ } elseif ($new == '-1') { // navigacija
+ $vsebina = $lang['news_comment_txt'].' <a href="'.$site_url.'index.php?fl=1&amp;nt=9&amp;sid='.$id.'">'.$naslov.'</a>';
+ } else { // novice
+ $t = $this->getTable($new);
+ $_id = 'sid';
+
+ $sql1 = sisplet_query("SELECT naslov, vsebina FROM $t WHERE $_id = '$id'");
+ $row1 = mysqli_fetch_row($sql1);
+
+ $f = 'index.php?fl=1&amp;nt='.$new;
+ $vsebina = $lang['news_comment_txt'].' <a href="'.$site_url.''.$f.'&amp;sid='.$id.'">'.$row1[0].'</a>:<br /><br />'.skrajsaj(trim(strip_tags($row1[1])), 200);
+ }
+ }
+
+ // obvescanje na mail - nov (neprijavljen) user se hoce narocit
+ // Sem premaknil gor, da spremenimo ime avtorja preden dodamo post! --may
+ if (isset($_POST['alertmail'])) {
+
+ if ($_POST['alertmail'] != '') {
+ $mail = $_POST['alertmail'];
+ $sqla = sisplet_query("SELECT id FROM users WHERE email = '$mail'");
+
+ if (mysqli_num_rows($sqla) > 0) {
+ $rowa = mysqli_fetch_row($sqla);
+ $narocnikID = $rowa[0];
+ } else {
+
+ // Preveri ali je vzdevek ze zaseden- ce je, mu dodaj neko stevilko da bo unique
+ $a2 = $avtor;
+
+ $result = sisplet_query ("SELECT * FROM users WHERE name='$a2' AND surname=''");
+ while (mysqli_num_rows ($result) > 0) {
+ $a2 = $avtor .rand(0, 32767);
+ $result = sisplet_query ("SELECT * FROM users WHERE name='$a2' AND surname=''");
+ }
+
+ $avtor = $a2;
+ $g = base64_encode((hash('SHA256', '' .$pass_salt)));
+
+ $sqln = sisplet_query("INSERT INTO users (email, name, when_reg, came_from, pass) VALUES ('" .$_POST['alertmail'] ."', '$avtor', NOW(), '2', '$g')");
+ $narocnikID = mysqli_insert_id($GLOBALS['connect_db']);
+
+ // Ker je noviregistriran mu dajmo se UID.
+ $uid = $narocnikID;
+ $user = "";
+ }
+
+ setcookie("uid", base64_encode ($mail), time()+3600*24*365, "/", $cookie_domain);
+ setcookie("secret", base64_encode((hash('SHA256', '' .$pass_salt))), time()+3600*24*365, "/", $cookie_domain);
+
+ $sqlaa = sisplet_query("INSERT INTO obvescanje_tema (uid, tid) VALUES ('" .$narocnikID ."', '" .$this->currentThread ."')");
+ $sqlaa = sisplet_query("UPDATE post SET uid='" .$narocnikID ."', user='' WHERE id='" .$this->currentPost ."'");
+ }
+ }
+
+ $admin = $_POST['admin'];
+ if (isset ($_POST['admin_override']) && $_POST['admin_override'] == "1") $admin = 0;
+
+ if (!isset ($_POST['admin'])) $admin = 3;
+ if (isset ($_POST['sporocilo']) && !($new != 0 && $id != 0)) $admin = $_POST['sporocilo'];
+
+ // preveri ce moras nastaviti dispauth
+ $la = sisplet_query ("SELECT lockedauth FROM forum WHERE id='" .$this->currentForum ."' AND lockedauth=1");
+ if (!($new != 0 && $id != 0) && (mysqli_num_rows ($la)>0 || (isset ($_POST['dispauth']) && $_POST['dispauth']=="1"))) {$dispauth=1; $dispthread=1;}
+
+ else {$dispauth=0; $dispthread=0;}
+
+ $vsebina = str_replace ("'", "`", $vsebina);
+ $sql = sisplet_query("INSERT INTO post (fid, tid, parent, naslov, vsebina, uid, user, time, admin, IP, dispauth, dispthread) VALUES ('".$this->currentForum."', '".$this->currentThread."', '$parent', '$naslov', '$vsebina', '$uid', '$user', NOW() - INTERVAL $timeDelay SECOND, '$admin', '$IP', '$dispauth', '$dispthread')");
+ if (!$sql) $error = mysqli_error($GLOBALS['connect_db']);
+ $ittdd = mysqli_insert_id($GLOBALS['connect_db']); // tale ID je pomemben na koncu, ker se ga returna na koncu funkcije !
+
+ // Ce je to nova tema, potem naredi link.
+ if ($parent == 0) {
+ $fnl = sisplet_query ("SELECT NiceLink FROM forum WHERE id='" .$this->currentForum ."'");
+ $fnlr = mysqli_fetch_row ($fnl);
+ $flink = preg_replace ("/(.*?[^\/])\/\/(.*?[^\/])\/(.*?[^\/])\/(.*?[^\/])\/(.*)/i", "$5", $rnlr[0]);
+
+ sisplet_query ("UPDATE post SET NiceLink = '" .$site_url .'thread/' .$this->currentForum .'/' .$ittdd .'/' .$flink .'/' .$naslov .'/' ."' WHERE id='" .$ittdd ."'");
+ }
+
+
+ // dodaj v index...
+ $this->setPost($ittdd);
+
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($this->currentThread == 0) {
+ $u = sisplet_query("UPDATE post SET tid='$ittdd' WHERE id='$ittdd'");
+ $this->setThread($ittdd);
+ }
+
+ $sql = sisplet_query("UPDATE post SET time2=NOW() WHERE id='".$this->currentThread."'");
+
+
+ // obvescanje na mail
+ if (isset($_POST['alert'])) {
+ $sqlaa = sisplet_query("SELECT * FROM obvescanje_tema WHERE uid='" .$global_user_id ."' AND tid='" .$this->currentThread ."'");
+ if (mysqli_num_rows($sqlaa) == 0) {
+ $sqla = sisplet_query("INSERT INTO obvescanje_tema (uid, tid) VALUES ('" .$global_user_id ."', '" .$this->currentThread ."')");
+ }
+ } else {
+ $sqlaa = sisplet_query("DELETE FROM obvescanje_tema WHERE uid='" .$global_user_id ."' AND tid='" .$this->currentThread ."'");
+ }
+
+ // hendlanje skupin - GROUP
+ if (isset($_POST['group']) && $_POST['group']!='') {
+
+ $group = $_POST['group'];
+ $mails = explode("\n", $group);
+
+ foreach ($mails as $key => $mail) {
+ $mail = trim($mail);
+ $sqla = sisplet_query("SELECT id FROM users WHERE email = '$mail'");
+
+ if (mysqli_num_rows($sqla) > 0) {
+ $rowa = mysqli_fetch_row($sqla);
+ $narocnikID = $rowa[0];
+ } else {
+ $g = base64_encode((hash('SHA256', '' .$pass_salt)));
+ $sqln = sisplet_query("INSERT INTO users (email, name, when_reg, camefrom, pass) VALUES ('$mail', '$mail', NOW(), '2', '$g')");
+ $narocnikID = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ $sqlaa = sisplet_query("INSERT INTO obvescanje_tema (uid, tid) VALUES ('$narocnikID', '" .$this->currentThread ."')");
+ $sqlaa = sisplet_query("INSERT INTO forum_group (uid, tid) VALUES ('$narocnikID', '" .$this->currentThread ."')");
+ }
+ $sqlaa = sisplet_query("INSERT INTO forum_group (uid, tid) VALUES ('" .$global_user_id ."', '" .$this->currentThread ."')");
+ }
+
+ if (isset($_GET['table'])) {
+ $this->setTableID($_GET['table']);
+ if (isset($_GET['column'])) {
+ $this->setColumnID($_GET['column']);
+ }
+
+ $t = $this->getTable($this->tableID);
+ $sqlc = sisplet_query("UPDATE $t SET thread='".$this->currentThread."' WHERE ".($this->tableID<=10?'s':'')."id='".$this->columnID."' AND thread='0'");
+ }
+ if (!isset($_GET['table']) && isset($_GET['column'])) {
+ $sqlc = sisplet_query("UPDATE menu SET thread='" .$this->currentThread ."' WHERE id='" .$_GET['column'] ."'");
+ }
+ $user_id = $global_user_id;
+
+ if ($mail_alert)
+ include('alert.php');
+ }
+
+ return $ittdd;
+ }
+
+
+ // Vrne tabelo glede na id v tabeli new (baze imajo id v tabeli new svoj_ID+10)
+ function getTable($new) {
+ switch ($new) {
+ case 9: $t = 'novice'; break;
+ case 3: $t = 'aktualno'; break;
+ case 4: $t = 'faq'; break;
+ case 10: $t = 'mailnovice'; break;
+ case 2: $t = 'vodic'; break;
+ case 5: $t = 'rubrika1'; break;
+ case 6: $t = 'rubrika2'; break;
+ case 7: $t = 'rubrika3'; break;
+ case 8: $t = 'rubrika4'; break;
+ }
+ if ($new > 10) {
+ $t = 'data_baze';
+ }
+ return $t;
+ }
+
+ // Vrne ID trenutnega uporabnika (ce ni prijavljen vrne 0)
+ function uid () {
+ global $mysql_database_name;
+ global $global_user_id;
+ global $admin_type;
+ global $lang;
+
+ if (isset ($_GET['em'])) { // email iz alerta
+ $result = sisplet_query ("SELECT id FROM users WHERE email='" .$_GET['em'] ."'");
+ $r = mysqli_fetch_row ($result);
+ return $r[0];
+ }
+ else {
+ return $global_user_id;
+ }
+ }
+
+ // Vrne userja
+ function user ($uid, $link=0, $user='') {
+ global $lang;
+ global $site_url;
+ global $skin_name;
+
+ if ($uid > 0) {
+ $sql = sisplet_query("SELECT email, name, show_email FROM users WHERE id='$uid'");
+ $row = mysqli_fetch_row($sql);
+ $return = '';
+
+ if ($link == 1) $return .= '<a href="'.$site_url.'forums/?lact=2&amp;uid='.$uid.'">';
+ if ($row[1] != '') {
+ $return .= $row[1];
+ } elseif ($row[2] == 2) {
+ $return .= $row[0];
+ } else {
+ $return .= $lang['user2'];
+ }
+ if ($link == 1) $return .= '</a>';
+ return $return;
+ } elseif ($user != '') {
+ return $user;
+ } else {
+ return $lang['guest'];
+ }
+ }
+
+
+ function inicialke ($ime) {
+
+ $out = '';
+
+ $ime = strtoupper($ime);
+ $b = explode(' ', $ime);
+ foreach ($b AS $beseda) {
+ $out .= $beseda[0];
+ }
+
+ return $out;
+ }
+
+ // Polepsa izpis datuma in ure
+ function datetime($time) {
+ global $admin_type;
+
+ $sql = sisplet_query("SELECT value FROM misc WHERE what='ForumHourDisplay'");
+ $row = mysqli_fetch_row($sql);
+
+ // Funkcija se klice zelooooo pogosto, zato sem vrgel ven substr in sestavljam rocno, je hitreje.
+ if ($row[0] == 0 || $admin_type==0)
+ return $time[8] .$time[9] ."." .$time[5] .$time[6] ."." .$time[0] .$time[1] .$time[2] .$time[3] ." " .$time[11] .$time[12] .":" .$time[14] .$time[15];
+ else
+ return $time[8] .$time[9] ."." .$time[5] .$time[6] ."." .$time[0] .$time[1] .$time[2] .$time[3];
+ }
+
+ // Polepsa izpis datuma in ure
+ function datetime1($time) {
+ global $admin_type;
+
+ $sql = sisplet_query("SELECT value FROM misc WHERE what='ForumHourDisplay'");
+ $row = mysqli_fetch_row($sql);
+ if ($row[0] == 0 || $admin_type==0)
+ return $time[8] .$time[9] ."." .$time[5] .$time[6] ." " .$time[11] .$time[12] .":" .$time[14] .$time[15];
+ else
+ return $time[8] .$time[9] ."." .$time[5] .$time[6];
+ }
+
+ // Polepsa izpis datuma (brez leta
+ function date1($time) {
+ return $time[8] .$time[9] ."." .$time[5] .$time[6];
+ }
+
+}
+
+
+
+?>
diff --git a/admin/survey/classes/class.GDPR.php b/admin/survey/classes/class.GDPR.php
new file mode 100644
index 0000000..c5a6c2c
--- /dev/null
+++ b/admin/survey/classes/class.GDPR.php
@@ -0,0 +1,2605 @@
+<?php
+
+/*
+ * Class, ki skrbi za vse v zvezi z GDPR uredbo
+ *
+ */
+
+
+
+class GDPR{
+
+
+ // GDPR avtoritete po drzavah
+ public static $authorities = array(
+ array('country'=>'Austria', 'drzava'=>'Avstrija', 'name'=>'Andrea Jelinek', 'title'=>'Director, Austrian Data Protection Authority', 'email'=>'dsb@dsb.gv.at', 'phone'=>'+43 1 531 15 202525', 'fax'=>'+43 1 531 15 202690'),
+ array('country'=>'Austria', 'drzava'=>'Avstrija', 'name'=>'Dietmar Wagner', 'title'=>'Compliance-Officer of the FMA', 'email'=>'compliance@fma.gv.at', 'phone'=>'+43 1 249 59-6112', 'fax'=>''),
+ array('country'=>'Belgium', 'drzava'=>'Belgija', 'name'=>'', 'title'=>'', 'email'=>'commission@privacycommission.be', 'phone'=>'+32 2 274 48 00', 'fax'=>'+32 2 274 48 10'),
+ array('country'=>'Bulgaria', 'drzava'=>'Bolgarija', 'name'=>'Ventsislav Karadjov', 'title'=>'Chairman of the Commission for Personal Data Protection', 'email'=>'kzld@cpdp.bg', 'phone'=>'+359 2 915 3523', 'fax'=>'+359 2 915 3525'),
+ array('country'=>'Croatia', 'drzava'=>'Hrvaška', 'name'=>'Anto RAJKOVAČA', 'title'=>'Director of the Croatian Data Protection Agency', 'email'=>'azop@azop.hr', 'phone'=>'+385 1 4609 000', 'fax'=>'+385 1 4609 099'),
+ array('country'=>'Cyprus', 'drzava'=>'Ciper', 'name'=>'Irene LOIZIDOU NIKOLAIDOU', 'title'=>'', 'email'=>'commissioner@dataprotection.gov.cy', 'phone'=>'+357 22 818 456', 'fax'=>'+357 22 304 565'),
+ array('country'=>'Czech Republic', 'drzava'=>'Češka republika', 'name'=>'Ivana JANŮ', 'title'=>'President of the Office for Personal Data Protection', 'email'=>'posta@uoou.cz', 'phone'=>'+420 234 665 111', 'fax'=>'+420 234 665 444'),
+ array('country'=>'Denmark', 'drzava'=>'Danska', 'name'=>'Cristina Angela GULISANO', 'title'=>'Director, Danish Data Protection Agency', 'email'=>'dt@datatilsynet.dk', 'phone'=>'+45 33 1932 00', 'fax'=>'+45 33 19 32 18'),
+ array('country'=>'Estonia', 'drzava'=>'Estonija', 'name'=>'Viljar PEEP', 'title'=>'Director General, Estonian Data Protection Inspectorate', 'email'=>'info@aki.ee', 'phone'=>'+372 6274 135', 'fax'=>'+372 6274 137'),
+ array('country'=>'Finland', 'drzava'=>'Finska', 'name'=>'Reijo AARNIO', 'title'=>'Ombudsman of the Finnish Data Protection Authority', 'email'=>'tietosuoja@om.fi', 'phone'=>'+358 10 3666 700', 'fax'=>'+358 10 3666 735'),
+ array('country'=>'France', 'drzava'=>'Francija', 'name'=>'Isabelle FALQUE-PIERROTIN', 'title'=>'President of CNIL', 'email'=>'', 'phone'=>'01 47 22 43 34', 'fax'=>'01 47 38 72 43'),
+ array('country'=>'Germany', 'drzava'=>'Nemčija', 'name'=>'Andrea VOSSHOFF', 'title'=>'Federal Commissioner for Freedom of Information', 'email'=>'poststelle@bfdi.bund.de', 'phone'=>'+49 228 997799 0', 'fax'=>'+49 228 997799 550'),
+ array('country'=>'Greece', 'drzava'=>'Grčija', 'name'=>'Petros CHRISTOFOROS', 'title'=>'President of the Hellenic Data Protection Authority', 'email'=>'contact@dpa.gr', 'phone'=>'+30 210 6475 600', 'fax'=>'+30 210 6475 628'),
+ array('country'=>'Hungary', 'drzava'=>'Madžarska', 'name'=>'Attila PÉTERFALVI', 'title'=>'President of the National Authority for Data Protection and Freedom of Information', 'email'=>'peterfalvi.attila@naih.hu', 'phone'=>'+36 1 3911 400', 'fax'=>''),
+ array('country'=>'Ireland', 'drzava'=>'Irska', 'name'=>'Helen DIXON', 'title'=>'Data Protection Commissioner', 'email'=>'info@dataprotection.ie', 'phone'=>'+353 57 868 4800', 'fax'=>'+353 57 868 4757'),
+ array('country'=>'Italy', 'drzava'=>'Italija', 'name'=>'Antonello SORO', 'title'=>'President of Garante per la protezione dei dati personali', 'email'=>'garante@garanteprivacy.it', 'phone'=>'+39 06 69677 1', 'fax'=>'+39 06 69677 785'),
+ array('country'=>'Latvia', 'drzava'=>'Latvija', 'name'=>'Signe PLUMINA', 'title'=>'Director of Data State Inspectorate', 'email'=>'info@dvi.gov.lv', 'phone'=>'+371 6722 3131', 'fax'=>'+371 6722 3556'),
+ array('country'=>'Lithuania', 'drzava'=>'Litva', 'name'=>'Algirdas KUNČINAS', 'title'=>'Director of the State Data Protection Inspectorate', 'email'=>'ada@ada.lt', 'phone'=>'+370 5 279 14 45', 'fax'=>'+370 5 261 94 94'),
+ array('country'=>'Luxembourg', 'drzava'=>'Luksemburg', 'name'=>'Tine A. LARSEN', 'title'=>'President of the Commission Nationale pour la Protection des Données', 'email'=>'info@cnpd.lu', 'phone'=>'+352 2610 60 1', 'fax'=>'+352 2610 60 29'),
+ array('country'=>'Malta', 'drzava'=>'Malta', 'name'=>'Saviour CACHIA', 'title'=>'Information and Data Protection Commissioner', 'email'=>'commissioner.dataprotection@gov.mt', 'phone'=>'+356 2328 7100', 'fax'=>'+356 2328 7198'),
+ array('country'=>'Netherlands', 'drzava'=>'Nizozemska', 'name'=>'Aleid WOLFSEN', 'title'=>'Chairman of Autoriteit Persoonsgegevens', 'email'=>'info@autoriteitpersoonsgegevens.nl', 'phone'=>'+31 70 888 8500', 'fax'=>'+31 70 888 8501'),
+ array('country'=>'Poland', 'drzava'=>'Poljska', 'name'=>'Edyta BIELAK-JOMAA', 'title'=>'Inspector General for the Protection of Personal Data', 'email'=>'kancelaria@giodo.gov.pl', 'phone'=>'+48 22 53 10 440', 'fax'=>'+48 22 53 10 441'),
+ array('country'=>'Portugal', 'drzava'=>'Portugalska', 'name'=>'Filipa CALVÃO', 'title'=>'President, Comissão Nacional de Protecção de Dados', 'email'=>'geral@cnpd.pt', 'phone'=>'+351 21 392 84 00', 'fax'=>'+351 21 397 68 32'),
+ array('country'=>'Romania', 'drzava'=>'Romunija', 'name'=>'Ancuţa Gianina OPRE', 'title'=>'President of the National Supervisory Authority for Personal Data Processing', 'email'=>'anspdcp@dataprotection.ro', 'phone'=>'+40 21 252 5599', 'fax'=>'+40 21 252 5757'),
+ array('country'=>'Slovakia', 'drzava'=>'Slovaška', 'name'=>'Soňa PŐTHEOVÁ', 'title'=>'President of the Office for Personal Data Protection of the Slovak Republic', 'email'=>'statny.dozor@pdp.gov.sk', 'phone'=>'+ 421 2 32 31 32 14', 'fax'=>'+ 421 2 32 31 32 34'),
+ array('country'=>'Slovenia', 'drzava'=>'Slovenija', 'name'=>'Mojca PRELESNIK', 'title'=>'Information Commissioner of the Republic of Slovenia', 'email'=>'gp.ip@ip-rs.si', 'phone'=>'+386 1 230 9730', 'fax'=>'+386 1 230 9778'),
+ array('country'=>'Spain', 'drzava'=>'Španija', 'name'=>'María del Mar España Martí', 'title'=>'Director of the Spanish Data Protection Agency', 'email'=>'internacional@agpd.es', 'phone'=>'+34 91399 6200', 'fax'=>'+34 91455 5699'),
+ array('country'=>'Sweden', 'drzava'=>'Švedska', 'name'=>'Kristina SVAHN STARRSJÖ', 'title'=>'Director General of the Data Inspection Board', 'email'=>'datainspektionen@datainspektionen.se', 'phone'=>'+46 8 657 6100', 'fax'=>'+46 8 652 8652'),
+ array('country'=>'United Kingdom', 'drzava'=>'Velika Britanija', 'name'=>'Elizabeth DENHAM', 'title'=>'Information Commissioner', 'email'=>'international.team@ico.org.uk', 'phone'=>'+44 1625 545 745', 'fax'=>''),
+ );
+
+
+ function __construct(){
+ global $site_url;
+
+ }
+
+
+ // Prikazemo vsebino zavihka gdpr - seznam anket
+ public function displayGDPRSurveyList(){
+ global $site_url;
+ global $lang;
+
+ $survey_list = array();
+ $survey_list = $this->getUserSurveys();
+
+
+ echo '<div style="font-style:italic; margin-top:-10px;">';
+
+ echo '<p>'.$lang['srv_gdpr_survey_list_text'].'</p>';
+
+ echo $lang['srv_gdpr_survey_list_text2'].'<ul style="margin-top:2px;">';
+ echo ' <li>'.$lang['srv_gdpr_survey_list_li_1'].'</li>';
+ echo ' <li>'.$lang['srv_gdpr_survey_list_li_2'].'</li>';
+ echo ' <li>'.$lang['srv_gdpr_survey_list_li_3'].'</li>';
+ echo ' <li>'.$lang['srv_gdpr_survey_list_li_4'].'</li>';
+ echo '</ul>';
+
+ echo '<p>'.$lang['srv_gdpr_survey_list_text3'].'</p>';
+
+ echo '</div>';
+
+
+ echo '<table class="gdpr_surveys">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_gdpr_survey_list_survey'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_survey_list_activity'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_survey_list_pot_gdpr'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_survey_list_gdpr'].'</th>';
+ echo '</tr>';
+
+ foreach($survey_list as $anketa){
+
+ // Nastavimo barvo vrstice
+ if($anketa['gdpr'] == 1)
+ $color = ' class="green_row"';
+ elseif($anketa['potential_gdpr'] == 1)
+ $color = ' class="red_row"';
+ else
+ $color = '';
+
+ echo '<tr '.$color.'>';
+
+ echo '<td><a href="'.$site_url.'admin/survey/index.php?anketa='.$anketa['id'].'&a=gdpr_settings">'.$anketa['naslov'].'</a></td>';
+ echo '<td>'.$anketa['active'].'</td>';
+ echo '<td>'.$anketa['potential_gdpr'].'</td>';
+
+ //echo '<td>'.$anketa['gdpr'].'</td>';
+ echo '<td><input type="checkbox" value="1" class="pointer" onClick="setGDPRSurvey(\''.$anketa['id'].'\', this.checked); return false;" '.($anketa['gdpr'] == '1' ? ' checked="checked"' : '').'</td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+
+ // Prikazemo vsebino zavihka gdpr - nastavitve uporabnika
+ public function displayGDPRUser($error=array()){
+ global $site_url;
+ global $lang;
+
+ $user_settings = self::getUserSettings();
+
+ echo '<form name="settingsgdpr" id="form_gdpr_user_settings" method="post">';
+
+ echo ' <input name="submited" value="1" type="hidden">';
+
+ echo ' <fieldset><legend>'.$lang['srv_gdpr_user_settings_title'].'</legend>';
+
+ echo '<p class="italic">'.$lang['srv_gdpr_user_settings_desc1'].'<br />';
+ echo $lang['srv_gdpr_user_settings_desc2'].'<br /><br />';
+ echo $lang['srv_gdpr_user_settings_desc3'].'</p>';
+
+
+ // PODATKI AVTORJA
+ // Opozorilo za obvezna polja
+ if($user_settings['firstname'] == '' || $user_settings['lastname'] == '' || $user_settings['email'] == '')
+ echo '<p><span class="red bold">'.$lang['srv_gdpr_user_settings_err'].'</span></p>';
+ else
+ echo '<br />';
+
+ echo ' <div class="setting '.($user_settings['firstname'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_firstname'].':</label></span> ';
+ echo ' <input class="text" name="firstname" value="'.$user_settings['firstname'].'" type="text"></div>';
+
+ echo ' <div class="setting '.($user_settings['lastname'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_lastname'].':</label></span> ';
+ echo ' <input class="text" name="lastname" value="'.$user_settings['lastname'].'" type="text"></div>';
+
+ $email = ($user_settings['email'] == '') ? User::getInstance()->primaryEmail() : $user_settings['email'];
+ echo ' <div class="setting '.($user_settings['email'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_email'].':</label></span> ';
+ echo ' <input class="text '.(isset($error['email']) ? ' red' : '').'" name="email" value="'.$email.'" type="text"> '.(isset($error['email']) ? '<span class="red italic">'.$lang['srv_remind_email_hard'].'</span>' : '').'</div>';
+
+ echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_phone'].':</label></span> ';
+ echo ' <input class="text" name="phone" value="'.$user_settings['phone'].'" type="text"></div>';
+
+ echo ' <br />';
+
+ // Naslov in drzava
+ echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_address'].':</label></span> ';
+ echo ' <input class="text" name="address" value="'.$user_settings['address'].'" type="text"></div>';
+
+ echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_country'].':</label></span> ';
+
+ echo ' <select name="country" onChange="editGDPRAuthority(this.value); return false;">';
+ //echo ' <option value="" '.($user_settings['country'] == '' ? ' selected="selected"' : '').'>'.$lang['srv_gdpr_user_settings_country_select'].'</option>';
+ $country_filter = array();
+ foreach(self::$authorities as $authority){
+
+ if (in_array($authority['country'], $country_filter)) {
+ continue;
+ }
+
+ if($lang['id'] == '1')
+ echo ' <option value="'.$authority['drzava'].'" '.(($user_settings['country'] == $authority['drzava'] || $user_settings['country'] == $authority['country']) ? ' selected="selected"' : '').'>'.$authority['drzava'].'</option>';
+ else
+ echo ' <option value="'.$authority['country'].'" '.(($user_settings['country'] == $authority['drzava'] || $user_settings['country'] == $authority['country']) ? ' selected="selected"' : '').'>'.$authority['country'].'</option>';
+
+ $country_filter[] = $authority['country'];
+ }
+ echo ' </select>';
+ echo ' </div>';
+
+
+ echo ' <br />';
+
+
+ // ORGANIZACIJA ALI ZASEBNIK
+ echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_type'].':</label></span> ';
+ echo ' <label for="type_0"><input class="radio" name="type" id="type_0" value="0" type="radio" '.($user_settings['type'] != '1' ? ' checked="checked"' : '').' onClick="toggleGDPRDPO();"> '.$lang['srv_gdpr_user_settings_type_0'].'</label>';
+ echo ' <label for="type_1"><input class="radio" name="type" id="type_1" value="1" type="radio" '.($user_settings['type'] == '1' ? ' checked="checked"' : '').' onClick="toggleGDPRDPO();"> '.$lang['srv_gdpr_user_settings_type_1'].'</label>';
+ echo ' </div>';
+
+
+ // PODATKI PODJETJA
+ echo ' <div id="gdpr_organization" '.($user_settings['type'] != '1' ? ' style="display:none;"' : '').'>';
+
+ // Opozorilo za obvezna polja
+ if($user_settings['organization'] == '' || $user_settings['organization_maticna'] == '')
+ echo '<p><span class="red bold">'.$lang['srv_gdpr_user_settings_err2'].'</span></p>';
+
+ echo ' <div class="setting '.($user_settings['organization'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_organization'].':</label></span> ';
+ echo ' <input class="text" name="organization" value="'.$user_settings['organization'].'" type="text"></div>';
+
+ echo ' <div class="setting '.($user_settings['organization_maticna'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_organization_maticna'].':</label></span> ';
+ echo ' <input class="text" name="organization_maticna" value="'.$user_settings['organization_maticna'].'" type="text"></div>';
+
+ /*echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_organization_davcna'].':</label></span> ';
+ echo ' <input class="text" name="organization_davcna" value="'.$user_settings['organization_davcna'].'" type="text"></div>';*/
+
+ echo ' </div>';
+
+
+ // IMA DPO
+ echo ' <div id="gdpr_has_dpo" '.($user_settings['type'] != '0' ? ' style="display:none;"' : '').'>';
+
+ echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_has_dpo'].':</label></span> ';
+ echo ' <label for="has_dpo_0"><input class="radio" name="has_dpo" id="has_dpo_0" value="0" type="radio" '.($user_settings['has_dpo'] != '1' ? ' checked="checked"' : '').' onClick="toggleGDPRHasDPO();"> '.$lang['no'].'</label>';
+ echo ' <label for="has_dpo_1"><input class="radio" name="has_dpo" id="has_dpo_1" value="1" type="radio" '.($user_settings['has_dpo'] == '1' ? ' checked="checked"' : '').' onClick="toggleGDPRHasDPO();"> '.$lang['yes'].'</label>';
+ echo ' </div>';
+
+ echo '<br /><br />';
+
+ echo ' </div>';
+
+
+ // DPO
+ echo ' <div id="gdpr_dpo" '.($user_settings['type'] != '1' && $user_settings['has_dpo'] != '1' ? ' style="display:none;"' : '').'>';
+
+ echo ' <p class="bold">'.$lang['srv_gdpr_user_settings_dpo'].':</p>';
+
+ // Opozorilo za obvezna polja
+ if($user_settings['dpo_firstname'] == '' || $user_settings['dpo_lastname'] == '' || $user_settings['dpo_email'] == '')
+ echo '<p><span class="red bold">'.$lang['srv_gdpr_user_settings_err'].'</span></p>';
+ else
+ echo '<br />';
+
+ echo ' <div class="setting '.($user_settings['dpo_firstname'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_dpo_firstname'].':</label></span> ';
+ echo ' <input class="text" name="dpo_firstname" value="'.$user_settings['dpo_firstname'].'" type="text"></div>';
+
+ echo ' <div class="setting '.($user_settings['dpo_lastname'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_dpo_lastname'].':</label></span> ';
+ echo ' <input class="text" name="dpo_lastname" value="'.$user_settings['dpo_lastname'].'" type="text"></div>';
+
+ echo ' <div class="setting '.($user_settings['dpo_email'] == '' ? ' red' : '').'"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_dpo_email'].':</label></span> ';
+ echo ' <input class="text '.(isset($error['dpo_email']) ? ' red' : '').'" name="dpo_email" value="'.$user_settings['dpo_email'].'" type="text"> '.(isset($error['dpo_email']) ? '<span class="red italic">'.$lang['srv_remind_email_hard'].'</span>' : '').'</div>';
+
+ echo ' <div class="setting"><span class="nastavitveSpan2"><label>'.$lang['srv_gdpr_user_settings_dpo_phone'].':</label></span> ';
+ echo ' <input class="text" name="dpo_phone" value="'.$user_settings['dpo_phone'].'" type="text"></div>';
+
+ echo ' </div>';
+
+
+ // Podatki trenutne avtoritete
+ echo '<div id="gdpr_authority_info">';
+ self::displayGDPRAuthority($user_settings['country']);
+ echo '</div>';
+
+ echo ' </fieldset>';
+
+
+ // Gumb shrani
+ echo '<div class="buttonwrapper floatLeft spaceLeft"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="editGDPRProfile(); return false;"><span>'.$lang['edit1337'].'</span></a></div>';
+
+ // div za prikaz uspešnosti shranjevanja
+ if ($_GET['s'] == '1') {
+ echo '<span class="clr"></span>';
+ echo '<div id="success_save"></div>';
+ echo '<script type="text/javascript">$(document).ready(function() {show_success_save();});</script>';
+ }
+
+ echo '</form>';
+ echo '<span class="clr"></span>';
+ }
+
+ // Prikazemo GDPR avtoriteto za izbrano drzavo
+ public function displayGDPRAuthority($country){
+ global $lang;
+
+ if($country != ''){
+
+ $current_authorities = array();
+
+ // Dobimo vse avtoritete za drzavo
+ foreach(self::$authorities as $authority){
+ // Ce je ta avtoriteta izbrana
+ if($country == $authority['drzava'] || $country == $authority['country'])
+ $current_authorities[] = $authority;
+ }
+
+ echo '<p class="bold">'.$lang['srv_gdpr_user_settings_authority'].':</p>';
+
+ // Prikazemo podatke za vse avtoritete (lahko jih je vec na drzavo)
+ foreach ($current_authorities as $authority) {
+ echo '<div class="gdpr_authority_info_data">';
+
+ if($authority['name'] != '')
+ echo '<span class="bold">'.$authority['name'].'</span><br />';
+ if($authority['title'] != '')
+ echo '<span>'.$authority['title'].'</span><br />';
+ if($authority['email'] != '')
+ echo '<span class="spaceLeft">'.$lang['srv_gdpr_user_settings_email'].': '.$authority['email'].'</span><br />';
+ if($authority['phone'] != '')
+ echo '<span class="spaceLeft">'.$lang['srv_gdpr_user_settings_phone'].': '.$authority['phone'].'</span><br />';
+ if($authority['fax'] != '')
+ echo '<span class="spaceLeft">Fax: '.$authority['fax'].'</span><br />';
+
+ echo '</div>';
+ }
+ }
+ }
+
+ // Prikazemo vsebino zavihka gdpr - zahteve za izbris
+ public function displayGDPRRequests(){
+ global $site_url;
+ global $lang;
+
+ echo '<div style="font-style:italic; margin-top:-10px;">';
+ echo '<p>'.$lang['srv_gdpr_requests_desc'].'</p>';
+ echo '</div>';
+
+ // Seznam cakajocih zahtevkov
+ $request_list = array();
+ $request_list = $this->getUserRequests($ank_id=0, $status=0);
+
+ // Seznam opravljenih zahtevkov
+ $request_list_done = array();
+ $request_list_done = $this->getUserRequests($ank_id=0, $status=1);
+
+ if(count($request_list) > 0){
+ echo '<table class="gdpr_surveys requests">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_gdpr_requests_survey'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_recnum'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_ip'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_url'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_email'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_date'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_text'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_type'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_date_sent'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_done'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_comment'].'</th>';
+ echo '</tr>';
+
+ foreach($request_list as $request_id => $request){
+
+ echo '<tr '.($request['status'] == 0 ? ' class="red_row"' : '').'>';
+
+ echo '<td><a href="'.$site_url.'admin/survey/index.php?anketa='.$request['ank_id'].'&a=data">'.$request['naslov'].'</a></td>';
+
+ //echo '<td>'.$request['recnum'].'</td>';
+ //echo '<td>'.$request['ip'].'</td>';
+ echo '<td>'.$request['url'].'</td>';
+ echo '<td>'.$request['email'].'</td>';
+ //echo '<td>'.$request['date'].'</td>';
+ echo '<td>'.$request['text'].'</td>';
+
+ echo '<td>'.$lang['srv_gdpr_requests_type_'.$request['type']].'</td>';
+
+ echo '<td>'.date('j.n.Y', strtotime($request['datum'])).'</td>';
+
+ // Checkbox ce je zahteva opravljena
+ //echo '<td>'.($request['status'] == '1' ? $lang['srv_gdpr_requests_status_1'] : $lang['srv_gdpr_requests_status_0']).'</td>';
+ echo '<td><input type="checkbox" value="1" class="pointer" onClick="setGDPRRequestStatus(\''.$request_id.'\', this.checked); return false;" '.($request['status'] == '1' ? ' checked="checked"' : '').'></td>';
+
+ // Komentar avtorja
+ echo '<td><textarea style="height:30px; width:200px;" onBlur="setGDPRRequestComment(\''.$request_id.'\', this.value);">'.$request['comment'].'</textarea></td>';
+
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ else{
+ echo '<p>'.$lang['srv_gdpr_requests_none'].'</p>';
+ }
+
+
+ // Tabela opravljenih zahtevkov
+ if(count($request_list_done) > 0){
+
+ echo '<br /><span class="requests_table_title">'.$lang['srv_gdpr_requests_done'].'</span>';
+
+ echo '<table class="gdpr_surveys requests" style="margin-top:0;">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_gdpr_requests_survey'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_recnum'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_ip'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_url'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_email'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_date'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_text'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_type'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_date_sent'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_done'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_comment'].'</th>';
+ echo '</tr>';
+
+ foreach($request_list_done as $request_id => $request){
+
+ echo '<tr '.($request['status'] == 0 ? ' class="red_row"' : '').'>';
+
+ echo '<td><a href="'.$site_url.'admin/survey/index.php?anketa='.$request['ank_id'].'&a=data">'.$request['naslov'].'</a></td>';
+
+ //echo '<td>'.$request['recnum'].'</td>';
+ //echo '<td>'.$request['ip'].'</td>';
+ echo '<td>'.$request['url'].'</td>';
+ echo '<td>'.$request['email'].'</td>';
+ //echo '<td>'.$request['date'].'</td>';
+ echo '<td>'.$request['text'].'</td>';
+
+ echo '<td>'.$lang['srv_gdpr_requests_type_'.$request['type']].'</td>';
+
+ echo '<td>'.date('j.n.Y', strtotime($request['datum'])).'</td>';
+
+ // Checkbox ce je zahteva opravljena
+ //echo '<td>'.($request['status'] == '1' ? $lang['srv_gdpr_requests_status_1'] : $lang['srv_gdpr_requests_status_0']).'</td>';
+ echo '<td><input type="checkbox" value="1" class="pointer" onClick="setGDPRRequestStatus(\''.$request_id.'\', this.checked); return false;" '.($request['status'] == '1' ? ' checked="checked"' : '').'></td>';
+
+ // Komentar avtorja
+ echo '<td><textarea style="height:30px; width:200px;" onBlur="setGDPRRequestComment(\''.$request_id.'\', this.value);">'.$request['comment'].'</textarea></td>';
+
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ }
+
+ // Prikazemo vsebino zavihka gdpr - VSE zahteve za izbris (samo admini)
+ public function displayGDPRRequestsAll(){
+ global $site_url;
+ global $lang;
+
+ $sql = sisplet_query("SELECT r.*,
+ a.naslov,
+ u.email AS u_email, u.name AS u_name, u.surname AS u_surname,
+ gu.type AS gu_type, gu.organization AS gu_organization, gu.dpo_firstname AS gu_dpo_firstname, gu.dpo_lastname AS gu_dpo_lastname, gu.dpo_email AS gu_dpo_email, gu.dpo_phone AS gu_dpo_phone, gu.email AS gu_email, gu.firstname AS gu_firstname, gu.lastname AS gu_lastname, gu.phone AS gu_phone, gu.address AS gu_address, gu.country AS gu_country
+ FROM srv_gdpr_requests AS r
+ LEFT JOIN srv_anketa AS a ON (r.ank_id=a.id)
+ LEFT JOIN users AS u ON (r.usr_id=u.id)
+ LEFT JOIN srv_gdpr_user AS gu ON (r.usr_id=gu.usr_id)
+ WHERE r.status='0'
+ ORDER BY date(r.datum) ASC");
+ if(mysqli_num_rows($sql) > 0){
+
+ echo '<table class="gdpr_surveys requests">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_gdpr_requests_author'].'</th>';
+
+ echo '<th>'.$lang['srv_gdpr_requests_responsible'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_organization'].'</th>';
+
+ echo '<th>'.$lang['srv_gdpr_requests_survey'].'</th>';
+
+ //echo '<th>'.$lang['srv_gdpr_requests_recnum'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_ip'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_url'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_email'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_date'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_text'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_type'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_date_sent'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_status'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_comment'].'</th>';
+ echo '</tr>';
+
+
+ while($row = mysqli_fetch_array($sql)){
+
+ echo '<tr '.($row['status'] == 0 ? ' class="red_row"' : '').'>';
+
+ // Avtor
+ echo '<td>'.$row['u_name'].' '.$row['u_surname'].'<br />('.$row['u_email'].')</td>';
+
+ // Odgovorna oseba
+ echo '<td style="text-align:left; white-space:nowrap;">';
+ if($row['gu_firstname'] != '' || $row['gu_lastname'] != '' || $row['gu_email'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_firstname'].':</span> '.$row['gu_firstname'].' '.$row['gu_lastname'].($row['gu_email'] != '' ? ' ('.$row['gu_email'].')' : '').'<br />';
+ if($row['gu_phone'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_phone'].':</span> '.$row['gu_phone'].'<br />';
+ if($row['gu_address'] != '' || $row['gu_country'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_address'].':</span> '.$row['gu_address'].($row['gu_country'] != '' ? ', '.$row['gu_country'] : '');
+ echo '</td>';
+
+ // Organizacija
+ echo '<td style="text-align:left; white-space:nowrap;">';
+ if($row['gu_type'] == '1'){
+ if($row['gu_organization'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_organization'].':</span> '.$row['gu_organization'].'<br />';
+ if($row['gu_dpo_firstname'] != '' || $row['gu_dpo_lastname'] != '' || $row['gu_dpo_email'] != '')
+ echo '<span class="bold">DPO:</span> '.$row['gu_dpo_firstname'].' '.$row['gu_dpo_lastname'].($row['gu_dpo_email'] != '' ? ' ('.$row['gu_dpo_email'].')' : '').'<br />';
+ if($row['gu_dpo_phone'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_phone'].':</span> '.$row['gu_dpo_phone'].'<br />';
+ }
+ else{
+ echo '/';
+ }
+ echo '</td>';
+
+ // Anketa
+ echo '<td><a href="'.$site_url.'admin/survey/index.php?anketa='.$row['ank_id'].'&a=data">'.$row['naslov'].'</a></td>';
+
+ //echo '<td>'.$row['recnum'].'</td>';
+ //echo '<td>'.$row['ip'].'</td>';
+ echo '<td>'.$row['url'].'</td>';
+ echo '<td>'.$row['email'].'</td>';
+ //echo '<td>'.$row['date'].'</td>';
+ echo '<td>'.$row['text'].'</td>';
+ echo '<td>'.$lang['srv_gdpr_requests_type_'.$row['type']].'</td>';
+ echo '<td>'.date('j.n.Y', strtotime($row['datum'])).'</td>';
+ echo '<td>'.($row['status'] == '1' ? $lang['srv_gdpr_requests_status_1'] : $lang['srv_gdpr_requests_status_0']).'</td>';
+ echo '<td style="text-align:left;">'.$row['comment'].'</td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ else{
+ echo '<p>'.$lang['srv_gdpr_requests_none'].'</p>';
+ }
+
+
+ // Opravljeni zahtevki
+ $sql = sisplet_query("SELECT r.*,
+ a.naslov,
+ u.email AS u_email, u.name AS u_name, u.surname AS u_surname,
+ gu.type AS gu_type, gu.organization AS gu_organization, gu.dpo_firstname AS gu_dpo_firstname, gu.dpo_lastname AS gu_dpo_lastname, gu.dpo_email AS gu_dpo_email, gu.dpo_phone AS gu_dpo_phone, gu.email AS gu_email, gu.firstname AS gu_firstname, gu.lastname AS gu_lastname, gu.phone AS gu_phone, gu.address AS gu_address, gu.country AS gu_country
+ FROM srv_gdpr_requests AS r
+ LEFT JOIN srv_anketa AS a ON (r.ank_id=a.id)
+ LEFT JOIN users AS u ON (r.usr_id=u.id)
+ LEFT JOIN srv_gdpr_user AS gu ON (r.usr_id=gu.usr_id)
+ WHERE r.status='1'
+ ORDER BY date(r.datum) DESC");
+ if(mysqli_num_rows($sql) > 0){
+
+ echo '<br />';
+ echo '<a href="#" onClick="$(\'#table_requests_done\').toggle(); $(\'#requests_table_title_plus\').toggle(); $(\'#requests_table_title_minus\').toggle();">';
+ echo ' <span class="requests_table_title"><span id="requests_table_title_plus">+</span><span id="requests_table_title_minus" style="display:none;">-</span> '.$lang['srv_gdpr_requests_done'].'</span>';
+ echo '</a>';
+
+ echo '<table class="gdpr_surveys requests" id="table_requests_done" style="margin-top:0; display:none;">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_gdpr_requests_author'].'</th>';
+
+ echo '<th>'.$lang['srv_gdpr_requests_responsible'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_organization'].'</th>';
+
+ echo '<th>'.$lang['srv_gdpr_requests_survey'].'</th>';
+
+ //echo '<th>'.$lang['srv_gdpr_requests_recnum'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_ip'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_url'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_email'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_date'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_text'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_type'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_date_sent'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_status'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_comment'].'</th>';
+ echo '</tr>';
+
+
+ while($row = mysqli_fetch_array($sql)){
+
+ echo '<tr '.($row['status'] == 0 ? ' class="red_row"' : '').'>';
+
+ // Avtor
+ echo '<td>'.$row['u_name'].' '.$row['u_surname'].'<br />('.$row['u_email'].')</td>';
+
+ // Odgovorna oseba
+ echo '<td style="text-align:left; white-space:nowrap;">';
+ if($row['gu_firstname'] != '' || $row['gu_lastname'] != '' || $row['gu_email'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_firstname'].':</span> '.$row['gu_firstname'].' '.$row['gu_lastname'].($row['gu_email'] != '' ? ' ('.$row['gu_email'].')' : '').'<br />';
+ if($row['gu_phone'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_phone'].':</span> '.$row['gu_phone'].'<br />';
+ if($row['gu_address'] != '' || $row['gu_country'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_address'].':</span> '.$row['gu_address'].($row['gu_country'] != '' ? ', '.$row['gu_country'] : '');
+ echo '</td>';
+
+ // Organizacija
+ echo '<td style="text-align:left; white-space:nowrap;">';
+ if($row['gu_type'] == '1'){
+ if($row['gu_organization'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_organization'].':</span> '.$row['gu_organization'].'<br />';
+ if($row['gu_dpo_firstname'] != '' || $row['gu_dpo_lastname'] != '' || $row['gu_dpo_email'] != '')
+ echo '<span class="bold">DPO:</span> '.$row['gu_dpo_firstname'].' '.$row['gu_dpo_lastname'].($row['gu_dpo_email'] != '' ? ' ('.$row['gu_dpo_email'].')' : '').'<br />';
+ if($row['gu_dpo_phone'] != '')
+ echo '<span class="bold">'.$lang['srv_gdpr_user_settings_phone'].':</span> '.$row['gu_dpo_phone'].'<br />';
+ }
+ else{
+ echo '/';
+ }
+ echo '</td>';
+
+ // Anketa
+ echo '<td><a href="'.$site_url.'admin/survey/index.php?anketa='.$row['ank_id'].'&a=data">'.$row['naslov'].'</a></td>';
+
+ //echo '<td>'.$row['recnum'].'</td>';
+ //echo '<td>'.$row['ip'].'</td>';
+ echo '<td>'.$row['url'].'</td>';
+ echo '<td>'.$row['email'].'</td>';
+ //echo '<td>'.$row['date'].'</td>';
+ echo '<td>'.$row['text'].'</td>';
+ echo '<td>'.$lang['srv_gdpr_requests_type_'.$row['type']].'</td>';
+ echo '<td>'.date('j.n.Y', strtotime($row['datum'])).'</td>';
+ echo '<td>'.($row['status'] == '1' ? $lang['srv_gdpr_requests_status_1'] : $lang['srv_gdpr_requests_status_0']).'</td>';
+ echo '<td style="text-align:left;">'.$row['comment'].'</td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ }
+
+
+ // Prikazemo vsebino zavihka gdpr - nastavitve posamezne ankete
+ public function displayGDPRSurvey($ank_id){
+ global $site_url;
+ global $lang;
+ global $admin_languages;
+ global $global_user_id;
+
+ $gdpr_settings = self::getSurveySettings($ank_id);
+
+ // Prikaz naprednih nastavitev
+ if($gdpr_settings != 0 && ($gdpr_settings['name'] == 1 || $gdpr_settings['email'] == 1 || $gdpr_settings['location'] == 1 || $gdpr_settings['phone'] == 1 || $gdpr_settings['web'] == 1 || $gdpr_settings['other'] == 1))
+ $gdpr_show_advanced = true;
+ else
+ $gdpr_show_advanced = false;
+
+
+ // Preverimo, če imamo anketo v večih jezikih
+ $survey_settings = SurveyInfo::getInstance()->getSurveyRow();
+
+ $language_slo = ($survey_settings['lang_resp'] == 1) ? true : false;
+ $language_eng = ($survey_settings['lang_resp'] > 1) ? true : false;
+
+ $sqlLang = sisplet_query("SELECT lang_id FROM srv_language WHERE ank_id='".$ank_id."' ORDER BY lang_id ASC");
+ while ($rowLang = mysqli_fetch_array($sqlLang)) {
+
+ if($rowLang['lang_id'] == '1'){
+ $language_slo = true;
+ }
+ else{
+ $language_eng = true;
+ break;
+ }
+ }
+
+
+ // GDPR nastavitve ankete
+ echo '<fieldset class="wide">';
+ echo '<legend>'.$lang['srv_gdpr_survey_settings'].'</legend>';
+
+ // Besedilo na vrhu
+ echo '<p class="italic">'.$lang['srv_gdpr_survey_settings_desc1'].'</p>';
+
+ echo '<p class="italic">'.$lang['srv_gdpr_survey_settings_desc2'].' <a href="'.$site_url.'admin/survey/index.php?a=gdpr" target="_blank"><span class="bold">'.$lang['srv_here'].' >></span></a></p>';
+
+ echo '<p class="italic">'.$lang['srv_gdpr_survey_settings_desc3'].'</p>';
+
+ // Ali gre za gdpr anketo
+ echo '<span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_data'].':</span>';
+ echo '<label for="is_gdpr_1"><input type="radio" name="is_gdpr" id="is_gdpr_1" '.($gdpr_settings != 0 ? ' checked':'').' value="1" onClick="showGDPRSettings();">'.$lang['yes'].'</label> ';
+ echo '<label for="is_gdpr_0"><input type="radio" name="is_gdpr" id="is_gdpr_0" '.($gdpr_settings == 0 ? ' checked':'').' value="0" onClick="showGDPRSettings();">'.$lang['no'].'</label> ';
+
+
+ echo '<br /><br />';
+
+
+ // Oznacena kot GDPR - prikazemo identifikatorje
+ echo '<div id="gdpr_data_identifiers" '.($gdpr_settings == 0 ? ' style="display:none;"' : '').'>';
+
+ echo '<span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_data_q'].'</span><br /><br />';
+
+ // Osebni podatek ime
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_name'].':</span>';
+ echo ' <label for="name_1"><input type="radio" name="name" id="name_1" '.($gdpr_settings['name'] != 0 ? ' checked':'').' value="1" onClick="showGDPRSettings();">'.$lang['yes'].'</label> ';
+ echo ' <label for="name_0"><input type="radio" name="name" id="name_0" '.($gdpr_settings['name'] == 0 ? ' checked':'').' value="0" onClick="showGDPRSettings();">'.$lang['no'].'</label> ';
+
+ echo ' <br />';
+
+ // Osebni podatek email
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_email'].':</span>';
+ echo ' <label for="email_1"><input type="radio" name="email" id="email_1" '.($gdpr_settings['email'] != 0 ? ' checked':'').' value="1" onClick="showGDPRSettings();">'.$lang['yes'].'</label> ';
+ echo ' <label for="email_0"><input type="radio" name="email" id="email_0" '.($gdpr_settings['email'] == 0 ? ' checked':'').' value="0" onClick="showGDPRSettings();">'.$lang['no'].'</label> ';
+
+ echo ' <br />';
+
+ // Osebni podatek lokacija
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_location'].':</span>';
+ echo ' <label for="location_1"><input type="radio" name="location" id="location_1" '.($gdpr_settings['location'] != 0 ? ' checked':'').' value="1" onClick="showGDPRSettings();">'.$lang['yes'].'</label> ';
+ echo ' <label for="location_0"><input type="radio" name="location" id="location_0" '.($gdpr_settings['location'] == 0 ? ' checked':'').' value="0" onClick="showGDPRSettings();">'.$lang['no'].'</label> ';
+
+ echo ' <br />';
+
+ // Osebni podatek telefon
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_phone'].':</span>';
+ echo ' <label for="phone_1"><input type="radio" name="phone" id="phone_1" '.($gdpr_settings['phone'] != 0 ? ' checked':'').' value="1" onClick="showGDPRSettings();">'.$lang['yes'].'</label> ';
+ echo ' <label for="phone_0"><input type="radio" name="phone" id="phone_0" '.($gdpr_settings['phone'] == 0 ? ' checked':'').' value="0" onClick="showGDPRSettings();">'.$lang['no'].'</label> ';
+
+ echo ' <br />';
+
+ // Osebni podatek spletni identifikator
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_web'].':</span>';
+ echo ' <label for="web_1"><input type="radio" name="web" id="web_1" '.($gdpr_settings['web'] != 0 ? ' checked':'').' value="1" onClick="showGDPRSettings();">'.$lang['yes'].'</label> ';
+ echo ' <label for="web_0"><input type="radio" name="web" id="web_0" '.($gdpr_settings['web'] == 0 ? ' checked':'').' value="0" onClick="showGDPRSettings();">'.$lang['no'].'</label> ';
+
+ echo ' <br />';
+
+ // Osebni podatek drugo
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_other'].':</span>';
+ echo ' <label for="other_1"><input type="radio" name="other" id="other_1" '.($gdpr_settings['other'] != 0 ? ' checked':'').' value="1" onChange="showGDPRSettings(); toggleGDPROtherText(this);">'.$lang['yes'].'</label> ';
+ echo ' <label for="other_0"><input type="radio" name="other" id="other_0" '.($gdpr_settings['other'] == 0 ? ' checked':'').' value="0" onChange="showGDPRSettings(); toggleGDPROtherText(this);">'.$lang['no'].'</label> ';
+
+ echo '<div id="other_text" '.($gdpr_settings['other'] == 0 ? ' style="display:none;"' : '').'>';
+ if($language_slo){
+ echo ' <span class="nastavitveSpan1">&nbsp;</span>';
+ echo ' <textarea class="other" name="other_text_slo" id="other_text_slo" style="width:500px; height:80px; margin-top:10px;">'.$gdpr_settings['other_text_slo'].'</textarea> <span class="italic">'.$admin_languages['1'].'</span>';
+ echo '<br />';
+ }
+ if($language_eng){
+ echo ' <span class="nastavitveSpan1">&nbsp;</span>';
+ echo ' <textarea class="other" name="other_text_eng" id="other_text_eng" style="width:500px; height:80px; margin-top:10px;">'.$gdpr_settings['other_text_eng'].'</textarea> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+ echo '</div>';
+
+ echo '</div>';
+
+
+ echo ' <br /><br />';
+
+
+ // Oznacena kot GDPR - prikazemo dodatne nastavitve gdpr
+ echo '<div id="gdpr_data_settings" '.(!$gdpr_show_advanced ? ' style="display:none;"' : '').'>';
+
+ // Ali se uporabi 1ka template v uvodu
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_1ka_template'].':</span>';
+ echo ' <label for="1ka_template_1"><input type="radio" name="1ka_template" id="1ka_template_1" '.(!isset($gdpr_settings['1ka_template']) || $gdpr_settings['1ka_template'] != 0 ? ' checked':'').' value="1" onClick="showGDPRTemplate(this.value);">'.$lang['yes'].'</label> ';
+ echo ' <label for="1ka_template_0"><input type="radio" name="1ka_template" id="1ka_template_0" '.(isset($gdpr_settings['1ka_template']) && $gdpr_settings['1ka_template'] == 0 ? ' checked':'').' value="0" onClick="showGDPRTemplate(this.value);">'.$lang['no'].'</label> ';
+
+ echo ' <div class="spaceLeft floatRight red" style="display:inline; width:520px;">';
+ // Obvestilo z linkom na preview preduvoda
+ echo '<span id="gdpr_data_template" class="italic" '.(isset($gdpr_settings['1ka_template']) && $gdpr_settings['1ka_template'] == 0 ? ' style="display:none;"' : '').'>';
+ echo $lang['srv_gdpr_survey_gdpr_1ka_template_note'];
+ echo '<br /><span class="bold"><a href="#" onClick="previewGDPRIntro(); return false;">'.$lang['srv_gdpr_survey_gdpr_1ka_template_preview'].'</a></span>';
+ echo '</span>';
+ // Warning ce ne uporablja template preduvoda
+ echo ' <span id="gdpr_data_template_warning" class="italic red" '.(!isset($gdpr_settings['1ka_template']) || $gdpr_settings['1ka_template'] == 1 ? ' style="display:none;"' : '').'>'.$lang['srv_gdpr_survey_gdpr_1ka_template_warning'].'</span>';
+ echo ' </div>';
+
+ echo ' <br /><br /><br /><br />';
+
+ // Podrobnosti o zbiranju podatkov (popup v uvodu)
+ /*if($gdpr_settings['about'] == ''){
+ $about_array = self::getGDPRInfoArray($ank_id);
+ $about_text = self::getGDPRTextFromArray($about_array, $type='textarea');
+ }
+ else{
+ $about_text = $gdpr_settings['about'];
+ }
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_about'].':<br /><br /><span class="italic">'.$lang['srv_gdpr_survey_gdpr_about_note'].'</span></span>';
+ echo ' <textarea name="about" id="about" style="width:500px; height:200px;" disabled="disabled">'.$about_text.'</textarea> ';*/
+
+ echo ' <span class="nastavitveSpan1" >'.$lang['srv_gdpr_survey_gdpr_about'].':<br /><br /><span class="italic">'.$lang['srv_gdpr_survey_gdpr_about_note'].'</span></span>';
+ if($language_slo){
+ $about_array = self::getGDPRInfoArray($ank_id, $language_id='1');
+ $about_text = self::getGDPRTextFromArray($about_array, $type='textarea');
+
+ echo ' <textarea name="about" id="about" style="width:500px; height:200px;" disabled="disabled">'.$about_text.'</textarea> <span class="italic">'.$admin_languages['1'].'</span>';
+ echo ' <br><br><span class="nastavitveSpan1">&nbsp;</span>';
+ }
+ if($language_eng){
+ $about_array = self::getGDPRInfoArray($ank_id, $language_id='2');
+ $about_text = self::getGDPRTextFromArray($about_array, $type='textarea');
+
+ echo ' <textarea name="about" id="about" style="width:500px; height:200px;" disabled="disabled">'.$about_text.'</textarea> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo '<br /><br />';
+
+ // Povezava na splosne gdpr nastavitve - ce ni izpolnil osebnih podatkov, je rdec warning
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=gdpr" target="_blank"><span class="bold">'.$lang['srv_gdpr_general_settings'].'</span></a>';
+ if(!self::checkUserSettings())
+ echo '<br /><span class="red italic">'.$lang['srv_gdpr_general_settings_warning'].'</span>';
+
+ echo '<br /><br />';
+
+ echo '</div>';
+
+ echo '</fieldset>';
+
+
+ echo '<br class="clr" />';
+
+
+ // Dodatne informacije
+ echo '<fieldset id="gdpr_additional_info" class="wide" '.(!$gdpr_show_advanced ? ' style="display:none;"' : '').'>';
+ echo '<legend>'.$lang['srv_gdpr_survey_settings'].'</legend>';
+
+ echo ' <br />';
+
+
+ // Cas hranjenja podatkov
+ echo ' <span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_expire'].':</span>';
+ echo ' <label for="expire_0"><input type="radio" name="expire" id="expire_0" '.($gdpr_settings['expire'] == 0 ? ' checked':'').' value="0" onClick="toggleGDPRInfoText(this);">'.$lang['srv_gdpr_survey_gdpr_expire_0'].'</label> ';
+
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span>';
+ echo ' <label for="expire_1"><input type="radio" name="expire" id="expire_1" '.($gdpr_settings['expire'] != 0 ? ' checked':'').' value="1" onClick="toggleGDPRInfoText(this);">'.$lang['srv_gdpr_survey_gdpr_expire_1'].'</label> ';
+ if($language_slo){
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span><input type="text" class="line_text expire" placeholder="'.$lang['srv_gdpr_survey_gdpr_expire_1_placeholder'].'" name="expire_text_slo" id="expire_text_slo" value="'.$gdpr_settings['expire_text_slo'].'" '.($gdpr_settings['expire'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['1'].'</span>';
+ }
+ if($language_eng){
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span><input type="text" class="line_text expire" placeholder="'.$lang['srv_gdpr_survey_gdpr_expire_1_placeholder'].'" name="expire_text_eng" id="expire_text_eng" value="'.$gdpr_settings['expire_text_eng'].'" '.($gdpr_settings['expire'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo ' <br /><br />';
+
+
+ // Drugi uporabniki podatkov
+ echo ' <span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_other_users'].':</span>';
+ echo ' <label for="other_users_0"><input type="radio" name="other_users" id="other_users_0" '.($gdpr_settings['other_users'] == 0 ? ' checked':'').' value="0" onClick="toggleGDPRInfoText(this);">'.$lang['srv_gdpr_survey_gdpr_other_users_0'].'</label> ';
+
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span>';
+ echo ' <label for="other_users_1"><input type="radio" name="other_users" id="other_users_1" '.($gdpr_settings['other_users'] != 0 ? ' checked':'').' value="1" onClick="toggleGDPRInfoText(this);">'.$lang['srv_gdpr_survey_gdpr_other_users_1'].'</label> ';
+ if($language_slo){
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span><input type="text" class="line_text other_users" placeholder="'.$lang['srv_gdpr_survey_gdpr_other_users_1_placeholder'].'" name="other_users_text_slo" id="other_users_text_slo" value="'.$gdpr_settings['other_users_text_slo'].'" '.($gdpr_settings['other_users'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['1'].'</span>';
+ }
+ if($language_eng){
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span><input type="text" class="line_text other_users" placeholder="'.$lang['srv_gdpr_survey_gdpr_other_users_1_placeholder'].'" name="other_users_text_eng" id="other_users_text_eng" value="'.$gdpr_settings['other_users_text_eng'].'" '.($gdpr_settings['other_users'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo ' <br /><br />';
+
+
+ // Izvoz v tuje drzave
+ echo ' <span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_export'].':</span>';
+ echo ' <label for="export_0"><input type="radio" name="export" id="export_0" '.($gdpr_settings['export'] == 0 ? ' checked':'').' value="0" onClick="toggleGDPRInfoText(this);">'.$lang['srv_gdpr_survey_gdpr_export_0'].'</label> ';
+
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span>';
+ echo ' <label for="export_1"><input type="radio" name="export" id="export_1" '.($gdpr_settings['export'] != 0 ? ' checked':'').' value="1" onClick="toggleGDPRInfoText(this);">'.$lang['srv_gdpr_survey_gdpr_export_country'].'</label> ';
+ if($language_slo){
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span><input type="text" class="line_text export" placeholder="'.$lang['srv_gdpr_survey_gdpr_export_country_placeholder'].'" name="export_country_slo" id="export_country_slo" value="'.$gdpr_settings['export_country_slo'].'" '.($gdpr_settings['export'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['1'].'</span>';
+ }
+ if($language_eng){
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span><input type="text" class="line_text export" placeholder="'.$lang['srv_gdpr_survey_gdpr_export_country_placeholder'].'" name="export_country_eng" id="export_country_eng" value="'.$gdpr_settings['export_country_eng'].'" '.($gdpr_settings['export'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo ' <br /><br /><span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_export_user'].':</span>';
+ if($language_slo){
+ echo ' <input type="text" class="line_text export" placeholder="'.$lang['srv_gdpr_survey_gdpr_export_user_placeholder'].'" name="export_user_slo" id="export_user_slo" value="'.$gdpr_settings['export_user_slo'].'" '.($gdpr_settings['export'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['1'].'</span>';
+ echo ' <br />';
+ }
+ if($language_eng){
+ echo ' <input type="text" class="line_text export" placeholder="'.$lang['srv_gdpr_survey_gdpr_export_user_placeholder'].'" name="export_user_eng" id="export_user_eng" value="'.$gdpr_settings['export_user_eng'].'" '.($gdpr_settings['export'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo '<br /><br /><span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_export_legal'].':</span>';
+ if($language_slo){
+ echo ' <input type="text" class="line_text long export" placeholder="'.$lang['srv_gdpr_survey_gdpr_export_legal_placeholder'].'" name="export_legal_slo" id="export_legal_slo" value="'.$gdpr_settings['export_legal_slo'].'" '.($gdpr_settings['export'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['1'].'</span>';
+ echo ' <br /><span class="nastavitveSpan1">&nbsp;</span>';
+ }
+ if($language_eng){
+ echo ' <input type="text" class="line_text long export" placeholder="'.$lang['srv_gdpr_survey_gdpr_export_legal_placeholder'].'" name="export_legal_eng" id="export_legal_eng" value="'.$gdpr_settings['export_legal_eng'].'" '.($gdpr_settings['export'] == 0 ? ' disabled="disabled"' : '').'> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo ' <br /><br />';
+
+
+ // Pooblascena oseba za varstvo podatkov
+ if($gdpr_settings['authorized'] == ''){
+
+ $user_settings = self::getUserSettings();
+
+ // Zasebnik brez DPO
+ if($user_settings['type'] == '0' && $user_settings['has_dpo'] == '0'){
+
+ // DPO mail je enak navadnemu mailu, ki ga je vnesel v splosnih nastavitvah
+ if($user_settings['email'] != ''){
+ $gdpr_authorized = $user_settings['email'];
+ }
+ // Ce ga ni vnesel, je DPO mail enak mailu avtorja ankete
+ else{
+ $gdpr_authorized = User::getInstance()->primaryEmail();
+ }
+ }
+ // Zasebnik z DPO ali organizacija
+ else{
+
+ // DPO mail je enak DPO mailu, ki ga je vnesel v splosnih nastavitvah
+ if($user_settings['dpo_email'] != ''){
+ $gdpr_authorized = $user_settings['dpo_email'];
+ }
+ // Ce ga ni vnesel, je DPO mail enak splosnemu mailu oz. mailu avtorja ankete
+ else{
+ if($user_settings['email'] != '')
+ $gdpr_authorized = $user_settings['email'];
+ else
+ $gdpr_authorized = User::getInstance()->primaryEmail();
+ }
+ }
+ }
+ else{
+ $gdpr_authorized = $gdpr_settings['authorized'];
+ }
+ echo ' <span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_authorized'].':</span>';
+ echo ' <input type="text" name="authorized" id="authorized" value="'.$gdpr_authorized.'">';
+
+ echo ' <br /><br />';
+
+
+ // Kontaktni email
+ if($gdpr_settings['contact_email'] == ''){
+
+ $user_settings = self::getUserSettings();
+
+ // Kontaktni mail je enak mailu, ki ga je vnesel v splosnih nastavitvah
+ if($user_settings['email'] != ''){
+ $gdpr_contact_email = $user_settings['email'];
+ }
+ // Ce ga ni vnesel, je kontaktni mail enak mailu avtorja ankete
+ else{
+ $gdpr_contact_email = User::getInstance()->primaryEmail();
+ }
+ }
+ else{
+ $gdpr_contact_email = $gdpr_settings['contact_email'];
+ }
+ echo ' <span class="nastavitveSpan1">'.$lang['srv_gdpr_survey_gdpr_contact_email'].':</span>';
+ echo ' <input type="text" name="contact_email" id="contact_email" value="'.$gdpr_contact_email.'">';
+
+ echo ' <br /><br />';
+
+
+ // Opomba
+ echo ' <span class="nastavitveSpan1">'.$lang['note'].':</span>';
+ if($language_slo){
+ echo ' <textarea name="note_slo" id="note_slo" style="width:500px; height:80px;">'.$gdpr_settings['note_slo'].'</textarea> <span class="italic">'.$admin_languages['1'].'</span>';
+ echo ' <span class="nastavitveSpan1">&nbsp;</span>';
+ }
+ if($language_eng){
+ echo ' <textarea name="note_eng" id="note_eng" style="width:500px; height:80px;">'.$gdpr_settings['note_eng'].'</textarea> <span class="italic">'.$admin_languages['2'].'</span>';
+ }
+
+ echo ' <br /><br />';
+
+ echo '</fieldset>';
+
+
+ // Gumb shrani spremembe
+ echo '<br class="clr" />';
+
+ //echo '<span class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="document.settingsanketa_' . $ank_id . '.submit(); return false;"><span>';
+ echo '<span class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onClick="editGDPRSurvey(\''.$ank_id.'\'); return false;"><span>';
+ echo $lang['edit1337'] . '</span></a></div></span>';
+ echo '<div class="clr"></div>';
+
+ echo '<br /><br />';
+
+
+ // Export - informacije dane posamezniku
+ echo '<fieldset id="gdpr_export_individual" class="wide" '.(!$gdpr_show_advanced ? ' style="display:none;"' : '').'>';
+ echo '<legend>'.$lang['srv_gdpr_survey_gdpr_export_individual'].'</legend>';
+
+ echo ' <br />';
+
+ echo '<a href="#" onClick="previewGDPRExport(\'1\'); return false;"><span class="faicon preview"></span>'.$lang['srv_poglejanketo2'].'</a>';
+ echo ' <br />';
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ if(!$userAccess->checkUserAccess($what='gdpr_export')){
+ $userAccess->displayNoAccess($what='gdpr_export');
+ }
+ else{
+
+ echo '<br />';
+
+ if($language_slo){
+ echo '<span class="bold">'.$admin_languages['1'].':</span><br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=pdf_gdpr_individual&anketa='.$ank_id.'&language=1').'" target="_blank"><span class="faicon pdf"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=rtf_gdpr_individual&anketa='.$ank_id.'&language=1').'" target="_blank"><span class="faicon rtf"></span>&nbsp;DOC - (Microsoft Word)</a>';
+
+ echo '<br /><br />';
+ }
+
+ if($language_eng){
+ echo '<span class="bold">'.$admin_languages['2'].':</span><br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=pdf_gdpr_individual&anketa='.$ank_id.'&language=2').'" target="_blank"><span class="faicon pdf"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=rtf_gdpr_individual&anketa='.$ank_id.'&language=2').'" target="_blank"><span class="faicon rtf"></span>&nbsp;DOC - (Microsoft Word)</a>';
+
+ echo '<br /><br />';
+ }
+ }
+
+ echo '</fieldset>';
+
+
+ echo ' <br />';
+
+
+ // Export - evidenca dejavnosti obdelav
+ echo '<fieldset id="gdpr_export_activity" class="wide" '.(!$gdpr_show_advanced ? ' style="display:none;"' : '').'>';
+ echo '<legend>'.$lang['srv_gdpr_survey_gdpr_export_activity'].'</legend>';
+
+ echo ' <br />';
+
+ echo '<a href="#" onClick="previewGDPRExport(\'2\'); return false;"><span class="faicon preview"></span>'.$lang['srv_poglejanketo2'].'</a>';
+ echo ' <br />';
+
+ if(!$userAccess->checkUserAccess($what='gdpr_export')){
+ $userAccess->displayNoAccess($what='gdpr_export');
+ }
+ else{
+
+ echo '<br />';
+
+ if($language_slo){
+ echo '<span class="bold">'.$admin_languages['1'].':</span><br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=pdf_gdpr_activity&anketa='.$ank_id.'&language=1').'" target="_blank"><span class="faicon pdf"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo ' <br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=rtf_gdpr_activity&anketa='.$ank_id.'&language=1').'" target="_blank"><span class="faicon rtf"></span>&nbsp;DOC - (Microsoft Word)</a>';
+
+ echo '<br /><br />';
+ }
+
+ if($language_eng){
+ echo '<span class="bold">'.$admin_languages['2'].':</span><br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=pdf_gdpr_activity&anketa='.$ank_id.'&language=2').'" target="_blank"><span class="faicon pdf"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo ' <br />';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=rtf_gdpr_activity&anketa='.$ank_id.'&language=2').'" target="_blank"><span class="faicon rtf"></span>&nbsp;DOC - (Microsoft Word)</a>';
+
+ echo '<br /><br />';
+ }
+ }
+
+ echo '</fieldset>';
+ }
+
+ // Prikazemo vsebino zavihka gdpr - nastavitve posamezne ankete
+ public function displayGDPRSurveyRequests($ank_id){
+ global $site_url;
+ global $lang;
+
+ echo '<div style="font-style:italic; margin-top:-10px;">';
+ echo '<p>'.$lang['srv_gdpr_requests_desc'].'</p>';
+ echo '</div>';
+
+ $request_list = array();
+ $request_list = self::getUserRequests($ank_id, $status=0);
+
+ $request_list_done = array();
+ $request_list_done = self::getUserRequests($ank_id, $status=1);
+
+ if(count($request_list) > 0){
+ echo '<table class="gdpr_surveys requests">';
+
+ echo '<tr>';
+ //echo '<th>'.$lang['srv_gdpr_requests_recnum'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_ip'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_url'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_email'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_date'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_text'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_type'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_date_sent'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_done'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_comment'].'</th>';
+ echo '</tr>';
+
+ foreach($request_list as $request_id => $request){
+
+ echo '<tr '.($request['status'] == 0 ? ' class="red_row"' : '').'>';
+
+ //echo '<td>'.$request['recnum'].'</td>';
+ //echo '<td>'.$request['ip'].'</td>';
+ echo '<td>'.$request['url'].'</td>';
+ echo '<td>'.$request['email'].'</td>';
+ //echo '<td>'.$request['date'].'</td>';
+ echo '<td>'.$request['text'].'</td>';
+
+ echo '<td>'.$lang['srv_gdpr_requests_type_'.$request['type']].'</td>';
+
+ echo '<td>'.date('j.n.Y', strtotime($request['datum'])).'</td>';
+
+ //echo '<td>'.($request['status'] == '1' ? $lang['srv_gdpr_requests_status_1'] : $lang['srv_gdpr_requests_status_0']).'</td>';
+ echo '<td><input type="checkbox" value="1" class="pointer" onClick="setGDPRRequestStatusSurvey(\''.$request_id.'\', this.checked); return false;" '.($request['status'] == '1' ? ' checked="checked"' : '').'</td>';
+
+ echo '<td><textarea style="height:30px; width:200px;" onBlur="setGDPRRequestCommentSurvey(\''.$request_id.'\', this.value);">'.$request['comment'].'</textarea></td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ else{
+ echo '<p>'.$lang['srv_gdpr_requests_none'].'</p>';
+ }
+
+
+ // Tabela opravljenih zahtevkov
+ if(count($request_list_done) > 0){
+
+ echo '<br /><span class="requests_table_title">'.$lang['srv_gdpr_requests_done'].'</span>';
+
+ echo '<table class="gdpr_surveys requests" style="margin-top:0;">';
+
+ echo '<tr>';
+ //echo '<th>'.$lang['srv_gdpr_requests_recnum'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_ip'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_url'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_email'].'</th>';
+ //echo '<th>'.$lang['srv_gdpr_requests_date'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_text'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_type'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_date_sent'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_done'].'</th>';
+ echo '<th>'.$lang['srv_gdpr_requests_comment'].'</th>';
+ echo '</tr>';
+
+ foreach($request_list_done as $request_id => $request){
+
+ echo '<tr '.($request['status'] == 0 ? ' class="red_row"' : '').'>';
+
+ //echo '<td>'.$request['recnum'].'</td>';
+ //echo '<td>'.$request['ip'].'</td>';
+ echo '<td>'.$request['url'].'</td>';
+ echo '<td>'.$request['email'].'</td>';
+ //echo '<td>'.$request['date'].'</td>';
+ echo '<td>'.$request['text'].'</td>';
+
+ echo '<td>'.$lang['srv_gdpr_requests_type_'.$request['type']].'</td>';
+
+ echo '<td>'.date('j.n.Y', strtotime($request['datum'])).'</td>';
+
+ //echo '<td>'.($request['status'] == '1' ? $lang['srv_gdpr_requests_status_1'] : $lang['srv_gdpr_requests_status_0']).'</td>';
+ echo '<td><input type="checkbox" value="1" class="pointer" onClick="setGDPRRequestStatusSurvey(\''.$request_id.'\', this.checked); return false;" '.($request['status'] == '1' ? ' checked="checked"' : '').'</td>';
+
+ echo '<td><textarea style="height:30px; width:200px;" onBlur="setGDPRRequestCommentSurvey(\''.$request_id.'\', this.value);">'.$request['comment'].'</textarea></td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ }
+
+ // Prikaze DPA zavihek
+ public static function displayGDPRDPA(){
+ global $lang;
+ global $site_url;
+
+ echo '<p>'.$lang['srv_gdpr_dpa_text'].'</p>';
+ echo '<ul>';
+ echo ' <li><a href="'.$site_url.'uploadi/dokumenti/DPA_SLO.pdf">'.$lang['srv_gdpr_dpa_slo'].'</a></li>';
+ echo ' <li><a href="'.$site_url.'uploadi/dokumenti/DPA_ANG.pdf">'.$lang['srv_gdpr_dpa_eng'].'</a></li>';
+ echo '</ul>';
+
+ echo '<p>'.$lang['srv_gdpr_dpa_info'].'</p>';
+ }
+
+
+
+ // Pridobimo vse ankete userja in za vsako preverimo ce je GDPR
+ private function getUserSurveys(){
+
+ $survey_list = array();
+
+ // Pridobimo seznam vseh anket uporabnika
+ $SL = new SurveyList();
+ $surveys = $SL->getSurveysSimple();
+
+ $temp_gdpr = array();
+ $temp_gdpr_p = array();
+ $temp_naslov = array();
+ $temp_active = array();
+
+ $key = 0;
+ foreach($surveys as $anketa){
+
+ $potential_gdpr = $this->potentialGDPRSurvey($anketa['id']);
+ $gdpr = $this->isGDPRSurvey($anketa['id']);
+
+ $temp_gdpr[$key] = $gdpr;
+ $temp_gdpr_p[$key] = $potential_gdpr;
+ $temp_naslov[$key] = $anketa['naslov'];
+ $temp_active[$key] = $anketa['active'];
+
+ $survey_list[$key] = array(
+ 'id' => $anketa['id'],
+ 'naslov' => $anketa['naslov'],
+ 'active' => $anketa['active'],
+ 'potential_gdpr' => $potential_gdpr,
+ 'gdpr' => $gdpr
+ );
+
+ $key++;
+ }
+
+ array_multisort($temp_gdpr, SORT_DESC, $temp_gdpr_p, SORT_DESC, $temp_active, SORT_DESC, $temp_naslov, SORT_DESC, $survey_list);
+
+ return $survey_list;
+ }
+
+ // Pridobimo vse zahteve za izbris za userja (za vse ankete ali samo za doloceno anketo)
+ private function getUserRequests($ank_id=0, $status=0){
+ global $global_user_id;
+
+ $requests = array();
+
+ $anketa_query = '';
+ if($ank_id != 0)
+ $anketa_query = " AND r.ank_id='".$ank_id."'";
+
+ $status_query = " AND r.status='".$status."'";
+
+ $order_by = ($status == 0) ? 'ASC' : 'DESC';
+
+ $sql = sisplet_query("SELECT r.*, a.naslov
+ FROM srv_gdpr_requests r, srv_anketa a
+ WHERE r.usr_id='".$global_user_id."' AND r.ank_id=a.id ".$anketa_query." ".$status_query."
+ ORDER BY date(datum) ".$order_by."");
+ while($row = mysqli_fetch_array($sql)){
+ $requests[$row['id']] = $row;
+ }
+
+ return $requests;
+ }
+
+ // Pridobimo vse zahteve za izbris za userja (za vse ankete ali samo za doloceno anketo)
+ public static function countUserUnfinishedRequests(){
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT COUNT(id) FROM srv_gdpr_requests WHERE usr_id='".$global_user_id."' AND status!='1'");
+ $row = mysqli_fetch_array($sql);
+
+ return $row['COUNT(id)'];
+ }
+
+
+ // Pridobimo vse gdpr nastavitve userja
+ private static function getUserSettings(){
+ global $global_user_id;
+ global $lang;
+
+ $sql = sisplet_query("SELECT * FROM srv_gdpr_user WHERE usr_id='".$global_user_id."'");
+ $row = mysqli_fetch_array($sql);
+
+ if($row['country'] == ''){
+ $row['country'] = ($lang['id'] == '1') ? 'Slovenija' : 'Slovenia';
+ }
+
+ return $row;
+ }
+
+ // Preverimo ce je uporabnik izpolnil gdpr profil
+ private function checkUserSettings(){
+ global $global_user_id;
+ global $lang;
+
+ $sql = sisplet_query("SELECT * FROM srv_gdpr_user WHERE usr_id='".$global_user_id."'");
+ $row = mysqli_fetch_array($sql);
+
+ if($row['firstname'] == '' || $row['lastname'] == '' || $row['email'] == '')
+ return false;
+
+ // Ce ima dpo so obvezni ime, priimek in posta
+ if(($row['type'] == '1' || $row['has_dpo'] == '1') && ($row['dpo_firstname'] == '' || $row['dpo_lastname'] == '' || $row['dpo_email'] == ''))
+ return false;
+
+ // Za podjetje sta obvezni ime in maticna
+ if($row['type'] == '1' && ($row['organization'] == '' || $row['organization_maticna'] == ''))
+ return false;
+
+ return true;
+ }
+
+ // Pridobimo vse gdpr nastavitve za anketo
+ public static function getSurveySettings($ank_id){
+
+ $sql = sisplet_query("SELECT * FROM srv_gdpr_anketa WHERE ank_id='".$ank_id."'");
+
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_array($sql);
+ return $row;
+ }
+ else
+ return 0;
+ }
+
+ // Vrne text za gdpr preduvod glede na to kaj je oznaceno da se zbira
+ public static function getSurveyIntro($ank_id){
+ global $lang;
+ global $site_url;
+
+ // Poseben GDPR text za gorenje
+ if (Common::checkModule('gorenje')){
+
+ $naslov = '<p>'.$lang['gorenje_gdpr_1_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.sprintf($lang['gorenje_gdpr_1_1'], $site_url, $site_url).'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_1_2'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_2_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_2'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_3_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_3'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_4_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_4'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_5_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_5'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_6_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_6'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_7_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_7'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_8_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_8'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_9_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_9'].'</p>';
+
+ $naslov .= '<br />';
+
+ $naslov .= '<p>'.$lang['gorenje_gdpr_10_naslov'].'</p>';
+ $naslov .= '<p style="font-weight:normal; margin:10px 10px 10px 0;">'.$lang['gorenje_gdpr_10'].'</p>';
+ }
+ else{
+ $user_settings = GDPR::getSurveySettings($ank_id);
+
+ $translation = ($lang['id'] == '1') ? '_slo' : '_eng';
+
+ $naslov = '<h3 style="margin-top: 0;">'.$lang['srv_gdpr_intro_title'].'</h3>';
+
+ $naslov .= '<p>'.$lang['srv_gdpr_intro'].':</p>';
+ $naslov .= '<ul>';
+ if($user_settings['name'])
+ $naslov .= '<li>'.$lang['srv_gdpr_intro_name'].'</li>';
+ if($user_settings['email'])
+ $naslov .= '<li>'.$lang['srv_gdpr_intro_email'].'</li>';
+ if($user_settings['location'])
+ $naslov .= '<li>'.$lang['srv_gdpr_intro_location'].'</li>';
+ if($user_settings['phone'])
+ $naslov .= '<li>'.$lang['srv_gdpr_intro_phone'].'</li>';
+ if($user_settings['web'])
+ $naslov .= '<li>'.$lang['srv_gdpr_intro_web'].'</li>';
+ if($user_settings['other'])
+ $naslov .= '<li>'.$lang['srv_gdpr_intro_other'].' - '.$user_settings['other_text'.$translation].'</li>';
+ $naslov .= '</ul>';
+
+ $naslov .= '<p>'.$lang['srv_gdpr_intro2'];
+ $naslov .= ' '.$lang['srv_gdpr_intro3'].'</p>';
+ }
+
+ $naslov .= '<br />';
+ $naslov .= '<p>'.$lang['srv_gdpr_intro4'].'</p>';
+
+ return $naslov;
+ }
+
+ // Preverimo ce je anketa potrjena s strani urednika, da je gdpr
+ public static function isGDPRSurvey($ank_id){
+
+ $sql = sisplet_query("SELECT * FROM srv_gdpr_anketa WHERE ank_id='".$ank_id."'");
+
+ if(mysqli_num_rows($sql) > 0){
+ return 1;
+ }
+ else
+ return 0;
+ }
+
+ // Preverimo ce je anketa gdpr in ima vklopljen gdpr 1ka template uvod
+ public static function isGDPRSurveyTemplate($ank_id){
+
+ $sql = sisplet_query("SELECT * FROM srv_gdpr_anketa WHERE ank_id='".$ank_id."' AND 1ka_template='1'");
+
+ if(mysqli_num_rows($sql) > 0){
+ return 1;
+ }
+ else
+ return 0;
+ }
+
+
+ /*
+ * Preverimo ce ima anketa kaksne nastavitve, ki lahko padejo pod gdpr
+ * - preverjamo imena spremenljivk "ime", "priimek", "firstname", "lastname", "email" (za tipe text) in tip vprasanja lokacija
+ * - preverjamo ce ima vklopljena vabila
+ * - preverjamo ce je tel. anketa
+ */
+ public function potentialGDPRSurvey($ank_id){
+
+ $gdpr = 0;
+
+ // Preverimo ce obstaja kaksno vprasanje za ime, priimek, email, lokacijo
+ $gdpr_questions = $this->getGDPRSurveyQuestions($ank_id);
+ if(count($gdpr_questions) > 0)
+ $gdpr = 1;
+
+ // Preverimo ce ima vklopljena vabila
+ if($this->checkSurveyInvitations($ank_id))
+ $gdpr = 1;
+
+ // Preverimo ce je telefonska anketa
+ if($this->checkSurveyTelephone($ank_id))
+ $gdpr = 1;
+
+ return $gdpr;
+ }
+
+ // Preverimo ce obstaja v anketi kaksno vprasanje za ime, priimek, email, lokacijo - vrnemo array vprasanj, ki so problematicna
+ private function getGDPRSurveyQuestions($ank_id){
+
+ $gdpr_questions = array();
+
+ // Loop cez vsa vprasanja
+ $sql = sisplet_query("SELECT s.id, s.variable, s.variable_custom, s.sistem, s.tip
+ FROM srv_spremenljivka s, srv_grupa g
+ WHERE s.gru_id=g.id AND g.ank_id='".$ank_id."'
+ AND ((s.variable IN ('ime', 'priimek', 'email', 'firstname', 'lastname') AND s.tip='21' /*AND s.sistem='1'*/) OR s.tip='26')");
+ while($row = mysqli_fetch_array($sql)){
+ $gdpr_questions[] = $row;
+ }
+
+ return $gdpr_questions;
+ }
+
+ // Preverimo ce ima anketa vklopljena email vabila
+ private function checkSurveyInvitations($ank_id){
+
+ $gdpr_email = SurveyInfo::getInstance()->checkSurveyModule('email');
+
+ return $gdpr_email;
+ }
+
+ // Preverimo ce je telefonska anketa
+ private function checkSurveyTelephone($ank_id){
+
+ $gdpr_phone = SurveyInfo::getInstance()->checkSurveyModule('phone');
+
+ return $gdpr_phone;
+ }
+
+
+ // Poskrbi za vse potrebno ko respondent zahteva izbris oz. vpogled v podatke
+ public function sendGDPRRequest($request_data){
+ global $lang;
+ global $gdpr_admin_email;
+ global $app_settings;
+
+ $errors = array();
+
+
+ // Natavimo angleski jezik
+ if((!empty($_POST['drupal_lang']) && $_POST['drupal_lang'] == 2) || (!empty($_POST['lang_id']) && $_POST['lang_id'] == 2)){
+ $file = '../lang/2.php';
+ include($file);
+ }
+
+
+ // Preverimo email
+ if(!isset($request_data['email']) || $request_data['email'] == '')
+ $errors['email'] = '1';
+ elseif(!validEmail($request_data['email']))
+ $errors['email'] = $lang['srv_remind_email_hard'];
+ else
+ $email = $request_data['email'];
+
+ // Preverimo naslov ankete - naslov ni obvezen
+ $survey_name = (isset($request_data['srv-name'])) ? $request_data['srv-name'] : '';
+
+ // Preverimo url ankete
+ if(!isset($request_data['srv-url']) || $request_data['srv-url'] == '')
+ $errors['srv-url'] = '1';
+ else{
+ $survey_url = $request_data['srv-url'];
+
+ // Preverimo url ankete in pridobimo podatke za anketo (avtor, id...)
+ $survey_data = self::getSurveyFromURL($survey_url);
+
+ if(!$survey_data || empty($survey_data)) {
+ if((!empty($_POST['drupal_lang']) && $_POST['drupal_lang'] == 2) || (!empty($_POST['lang_id']) && $_POST['lang_id'] == 2)) {
+ $errors['srv-url'] = 'Invalid survey URL. Enter the correct URL for the 1KA survey. If you have any problems, please contact 1KA helpdesk (<a href="mailto:help@1ka.si?subject=GDPR">help@1ka.si</a>).';
+ }
+ else{
+ $errors['srv-url'] = 'Nepravilen URL ankete. Vpišite pravilen URL 1KA ankete. V primeru težav kontaktirajte Center za pomoč uporabnikom 1KA (<a href="mailto:help@1ka.si?subject=GDPR">help@1ka.si</a>).';
+ }
+ }
+ }
+
+ // Preverimo ce imamo action
+ if(!isset($request_data['gdpr-action']))
+ $errors['gdpr-action'] = '1';
+ else{
+ $action = $request_data['gdpr-action'];
+
+ // Nastavimo jezik vmesnika
+ if(!empty($_POST['drupal_lang']))
+ $jezik = $_POST['drupal_lang'];
+ elseif(!empty($_POST['lang_id']))
+ $jezik = $_POST['lang_id'];
+ else
+ $jezik = $survey_data['usr_lang'];
+
+
+ if($jezik == '2'){
+ if($action == '1')
+ $action_text = '<b>Delete</b> personal and survey data for a specific survey.';
+ elseif($action == '2')
+ $action_text = '<b>Gain insight</b> into personal and survey data for a specific survey.';
+ elseif($action == '3')
+ $action_text = '<b>Change</b> personal data in a specific survey.';
+ elseif($action == '4')
+ $action_text = '<b>Transmission</b> of personal data from a specific survey.';
+ elseif($action == '5')
+ $action_text = '<b>Restriction</b> of processing of personal data in a specific survey.';
+ elseif($action == '6')
+ $action_text = '<b>Withdrawal of consent</b> of processing of personal data in a specific survey.';
+ else
+ $errors['gdpr-action'] = '1';
+ }
+ else{
+ if($action == '1')
+ $action_text = '<b>izbris</b> osebnih in anketnih podatkov iz omenjene ankete.';
+ elseif($action == '2')
+ $action_text = '<b>vpogled</b> v osebne in anketne podatke iz omenjene ankete.';
+ elseif($action == '3')
+ $action_text = '<b>spremembo</b> osebnih in anketnih podatkov iz omenjene ankete.';
+ elseif($action == '4')
+ $action_text = '<b>Prenos</b> osebnih podatkov iz omenjene ankete.';
+ elseif($action == '5')
+ $action_text = '<b>Omejitev obdelave</b> osebnih podatkov v omenjeni anketi.';
+ elseif($action == '6')
+ $action_text = '<b>Preklic privolitve v obdelavo</b> osebnih podatkov v omenjeni anketi.';
+ else
+ $errors['gdpr-action'] = '1';
+ }
+ }
+
+ // Preverimo opis
+ //$note = (isset($request_data['gdpr-note'])) ? $request_data['gdpr-note'] : '';
+ if(!isset($request_data['gdpr-note']) || $request_data['gdpr-note'] == '')
+ $errors['gdpr-note'] = '1';
+ else
+ $note = $request_data['gdpr-note'];
+
+
+ // Ce imamo vse potrebne podatke posredujemo zahtevo
+ if(empty($errors)){
+
+ // Zabelezimo zahtevo v bazo
+ $sql = sisplet_query("INSERT INTO srv_gdpr_requests
+ (usr_id, ank_id, email, url, datum, text, type)
+ VALUES
+ ('".$survey_data['usr_id']."', '".$survey_data['ank_id']."', '".$email."', '".$survey_url."', NOW(), '".$note."', '".$action."')");
+
+ // Nastavimo podatke maila (text)
+ // ANG
+ if($jezik == '2'){
+ $subject = 'Request for deletion/insight or change of personal survey data';
+
+ $content = 'Dear 1KA user,<br />';
+ $content .= '<p>As an author of the survey <b>'.$survey_data['title'].' ('.$survey_data['url'].')</b>, in which you collected personal data (GDPR), we would like to inform you that the respondent with e-mail '.$email.' submitted a request for:<br />';
+ $content .= '&nbsp;&nbsp;&nbsp;- '.$action_text.'</p>';
+
+ $content .= '<p>';
+ $content .= 'Respondent’s email:<br /><b>'.$email.'</b><br /><br />';
+ $content .= 'Survey URL:<br /><b>'.$survey_url.'</b><br /><br />';
+ $content .= 'The submitted request relates to the following personal data:<br /><b>'.$note.'</b>';
+ $content .= '</p>';
+
+ $content .= '<p>Please process the request within <b>one month</b> and inform the respondent to the above email address of the (<a href="https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679" target="_blank">Article 19 of the GDPR Regulation</a>).</p>';
+
+ $content .= '<p>If you do not execute the request after one month, we will notify you again. If the request is not executed, we reserve the right to delete this survey.</p>';
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+ $content .= $signature;
+ }
+ // SLO
+ else{
+ $subject = 'Obvestilo o zahtevi za izbris/vpogled ali spremembo osebnih oziroma anketnih podatkov';
+
+ $content = 'Pozdravljeni,<br />';
+ $content .= '<p>Kot avtorja ankete <b>'.$survey_data['title'].' ('.$survey_data['url'].')</b>, v kateri ste zbirali osebne podatke (GDPR), vas želimo obvestiti, da je respondent z elektronskim naslovom '.$email.' oddal prošnjo za:<br />';
+ $content .= '&nbsp;&nbsp;&nbsp;- '.$action_text.'</p>';
+
+ $content .= '<p>';
+ $content .= 'Email respondenta:<br /><b>'.$email.'</b><br /><br />';
+ $content .= 'URL ankete:<br /><b>'.$survey_url.'</b><br /><br />';
+ $content .= 'Oddana prošnja se nanaša na naslednje osebne podatke:<br /><b>'.$note.'</b>';
+ $content .= '</p>';
+
+ $content .= '<p>Prosimo, da <b>v roku enega meseca</b> izvršite zahtevo in o tem obvestite respondenta na zgoraj navedeni elektronski naslov respondenta (<a href="http://eur-lex.europa.eu/legal-content/SL/TXT/?uri=uriserv:OJ.L_.2016.119.01.0001.01.SLV&toc=OJ:L:2016:119:FULL" target="_blank">Člen 19 uredbe GDPR</a>).</p>';
+
+ $content .= '<p>V primeru, da tega po enem mesecu ne boste izvršili, vas bomo ponovno obvestili. Če se zahteva ne izvrši, si pridružujemo pravico, da anketo izbrišemo.</p>';
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+ $content .= $signature;
+ }
+
+ // Posljemo mail avtorju ankete in na help@1ka.si za obvestilo adminu
+ try{
+ $MA = new MailAdapter();
+ $MA->addRecipients($survey_data['author_email']);
+
+ if(Common::checkModule('gorenje')){
+ //$MA->addRecipients('dusan.rutnik@gorenje.com');
+ $MA->addRecipients('gdpr@gorenje.com');
+ }
+ elseif(isset($gdpr_admin_email) && $gdpr_admin_email != ''){
+ $MA->addRecipients($gdpr_admin_email);
+ }
+ else{
+ $MA->addRecipients('help@1ka.si');
+ $MA->addRecipients('enklikanketa@gmail.com');
+ }
+
+ $resultX = $MA->sendMail($content, $subject);
+ }
+ catch (Exception $e){
+ }
+
+ // Vrnemo vse ok
+ if($jezik == '2'){
+ $success_text = 'Your request for the deletion, change or insight into your personal information for a particular survey is submitted to
+ the author of the survey. The author of the survey must, within a month since you submitted the request, execute your
+ request and inform you about it. If the author fails to do so within 30 days, we will delete the survey, including your information.';
+ }else {
+ $success_text = 'Prošnja za izbris, spremembo ali vpogled do vaših osebnih podatkov iz določene ankete je posredovana avtorju ankete.
+ Avtor ankete mora v roku meseca dni od oddane zahteve urediti vašo zahtevo in vas o tem obvestiti.
+ Če v roku 30 dni avtor tega ne izvede, bomo anketo izbrisali, vključno z vašimi podatki.';
+ }
+
+ $response = json_encode(array('success' => $success_text), true);
+ }
+ else{
+ // Vrnemo errorje
+ //$response = json_encode(array('error' => $errors), true);
+ $response = json_encode(array('error' => $errors, 'posted' => $request_data), true);
+ }
+
+ echo $response;
+ }
+
+ // Poiscemo anketo na podlagi vnesenega url-ja
+ private function getSurveyFromURL($url){
+ global $site_url;
+
+ $data = array();
+
+ $url_data = parse_url($url);
+ $path = $url_data['path'];
+ $host = $url_data['host'];
+
+ // Preverimo ce gre za pravo domeno
+ if($host == parse_url($site_url, PHP_URL_HOST)){
+
+ $arr = explode("/", $path);
+
+ // Pridobimo id ankete iz url-ja
+ if($arr[1] == 'a'){
+ $data['ank_id'] = $arr[2];
+ }
+ else{
+ // Preverimo ce imamo mogoce lep url
+ $nice_url = $arr[1];
+
+ $sqlN = sisplet_query("SELECT ank_id, link FROM srv_nice_links WHERE link='".$nice_url."'");
+ if(mysqli_num_rows($sqlN) > 0){
+ $rowN = mysqli_fetch_array($sqlN);
+ $data['ank_id'] = $rowN['ank_id'];
+ }
+ else
+ return false;
+ }
+
+ // Nastavimo url ankete
+ $data['url'] = $site_url.'a/'.$data['ank_id'];
+
+ // Pridobimo avtorja in naslov ankete
+ $sql = sisplet_query("SELECT a.naslov, u.id, u.lang, u.email
+ FROM srv_anketa a, users u
+ WHERE a.id='".$data['ank_id']."' AND u.id=a.insert_uid");
+ if(mysqli_num_rows($sql) == 1){
+ $row = mysqli_fetch_array($sql);
+
+ $data['title'] = $row['naslov'];
+ $data['usr_id'] = $row['id'];
+ $data['usr_lang'] = $row['lang'];
+ $data['author_email'] = $row['email'];
+ }
+ else
+ return false;
+ }
+ else
+ return false;
+
+ if(isset($data['ank_id']) && isset($data['usr_id']) && isset($data['title']) && isset($data['url']) && isset($data['author_email']))
+ return $data;
+ else
+ return false;
+ }
+
+ // Prikaze obrazec za zahteve za izbris (v simple frontend)
+ public static function displayGDPRRequestForm($status=array()){
+ global $lang;
+ global $site_url;
+
+ // Uspesno poslan zahtevek
+ if(isset($status['success'])){
+ echo $status['success'];
+ }
+ else{
+ // Ce imamo errorje
+ $error = (isset($status['error'])) ? $status['error'] : array();
+
+ // Kar smo predhodno poslali
+ $posted = (isset($status['posted'])) ? $status['posted'] : array();
+
+ // Nastavimo se jezik ob napakah
+ if(isset($posted['lang_id'])){
+ $file = '../../lang/'.$posted['lang_id'].'.php';
+ include($file);
+ }
+
+ echo ' <h1>'.$lang['srv_gdpr_drupal_title'].'</h1>';
+
+ echo ' <p>'.$lang['srv_gdpr_drupal_intro1'].'</p>';
+ echo ' <p>'.$lang['srv_gdpr_drupal_intro2'].'</p>';
+
+ echo ' <form name="gdpr" id="gdpr" action="'.$site_url.'utils/gdpr_request.php" method="post">';
+
+ // Jezik vmesnika
+ echo ' <input id="lang_id" name="lang_id" value="'.$lang['id'].'" type="hidden">';
+
+ // Email
+ echo ' <div class="form_row '.(isset($error['email']) ? ' red' : '').'"><div class="label"><label for="email">'.$lang['srv_gdpr_drupal_field_email'].':</label></div>';
+ echo ' <input class="regfield" id="email" name="email" value="'.(isset($posted['email']) && !isset($error['email']) ? $posted['email'] : '').'" placeholder="'.$lang['email'].'" type="text">';
+ if(isset($error['email']) && $error['email'] != '1')
+ echo '<span class="spaceLeft">'.$error['email'].'</span>';
+ echo ' </div>';
+
+ // Ime ankete
+ echo ' <div class="form_row '.(isset($error['srv-name']) ? ' red' : '').'"><div class="label"><label for="srv-name">'.$lang['srv_gdpr_drupal_field_srv-name'].':</label></div>';
+ echo ' <input class="regfield" id="srv-name" name="srv-name" value="'.(isset($posted['srv-name']) && !isset($error['srv-name']) ? $posted['srv-name'] : '').'" placeholder="'.$lang['srv_gdpr_drupal_field_srv-name'].'" type="text">';
+ if(isset($error['srv-name']) && $error['srv-name'] != '1')
+ echo '<span class="spaceLeft">'.$error['srv-name'].'</span>';
+ echo ' </div>';
+
+ // URL ankete
+ echo ' <div class="form_row '.(isset($error['srv-url']) ? ' red' : '').'"><div class="label"><label for="srv-url">'.$lang['srv_gdpr_drupal_field_srv-url'].':</label></div>';
+ echo ' <input class="regfield" id="srv-url" name="srv-url" value="'.(isset($posted['srv-url']) && !isset($error['srv-url']) ? $posted['srv-url'] : '').'" placeholder="'.$lang['srv_gdpr_drupal_field_srv-url'].'" type="text">';
+ if(isset($error['srv-url']) && $error['srv-url'] != '1')
+ echo '<span class="spaceLeft">'.$error['srv-url'].'</span>';
+ echo ' </div>';
+
+ echo ' <br />';
+
+ // Tip zahteve
+ echo ' <p>'.$lang['srv_gdpr_drupal_q1_title'].'</p>';
+
+ echo ' <div class="form_row '.(isset($error['gdpr-action']) ? ' red' : '').'"><label for="gdpr-action_1">';
+ echo ' <input type="radio" id="gdpr-action_1" name="gdpr-action" value="1" '.(isset($posted['gdpr-action']) && $posted['gdpr-action'] == '1' ? ' checked="checked"' : '').'> '.$lang['srv_gdpr_drupal_q1_answer1'];
+ echo ' </label></div>';
+ echo ' <div class="form_row '.(isset($error['gdpr-action']) ? ' red' : '').'"><label for="gdpr-action_2">';
+ echo ' <input type="radio" id="gdpr-action_2" name="gdpr-action" value="2" '.(isset($posted['gdpr-action']) && $posted['gdpr-action'] == '2' ? ' checked="checked"' : '').'> '.$lang['srv_gdpr_drupal_q1_answer2'];
+ echo ' </label></div>';
+ echo ' <div class="form_row '.(isset($error['gdpr-action']) ? ' red' : '').'"><label for="gdpr-action_3">';
+ echo ' <input type="radio" id="gdpr-action_3" name="gdpr-action" value="3" '.(isset($posted['gdpr-action']) && $posted['gdpr-action'] == '3' ? ' checked="checked"' : '').'> '.$lang['srv_gdpr_drupal_q1_answer3'];
+ echo ' </label></div>';
+ echo ' <div class="form_row '.(isset($error['gdpr-action']) ? ' red' : '').'"><label for="gdpr-action_4">';
+ echo ' <input type="radio" id="gdpr-action_4" name="gdpr-action" value="4" '.(isset($posted['gdpr-action']) && $posted['gdpr-action'] == '4' ? ' checked="checked"' : '').'> '.$lang['srv_gdpr_drupal_q1_answer4'];
+ echo ' </label></div>';
+ echo ' <div class="form_row '.(isset($error['gdpr-action']) ? ' red' : '').'"><label for="gdpr-action_5">';
+ echo ' <input type="radio" id="gdpr-action_5" name="gdpr-action" value="5" '.(isset($posted['gdpr-action']) && $posted['gdpr-action'] == '5' ? ' checked="checked"' : '').'> '.$lang['srv_gdpr_drupal_q1_answer5'];
+ echo ' </label></div>';
+ echo ' <div class="form_row '.(isset($error['gdpr-action']) ? ' red' : '').'"><label for="gdpr-action_6">';
+ echo ' <input type="radio" id="gdpr-action_6" name="gdpr-action" value="6" '.(isset($posted['gdpr-action']) && $posted['gdpr-action'] == '6' ? ' checked="checked"' : '').'> '.$lang['srv_gdpr_drupal_q1_answer6'];
+ echo ' </label></div>';
+
+ echo ' <br />';
+
+ // Opomba
+ echo ' <p '.(isset($error['gdpr-note']) ? ' class="red"' : '').'>'.$lang['srv_gdpr_drupal_q2_note'].'</p>';
+ echo ' <textarea id="gdpr-note" name="gdpr-note" value="" '.(isset($error['gdpr-note']) ? ' class="red"' : '').'>'.(isset($posted['gdpr-note']) ? $posted['gdpr-note'] : '').'</textarea>';
+
+ echo ' <br /><br />';
+
+
+ // Poslji prosnjo
+ echo ' <p>'.$lang['srv_gdpr_drupal_end'].'</p>';
+ //echo ' <input name="submit" value="'.$lang['srv_potrdi'].'" class="regfield" type="submit"><br />';
+ echo ' <input name="submit" value="'.$lang['srv_potrdi'].'" class="regfield" type="button" onClick="sendGDPRRequest();"><br />';
+
+ echo ' </form>';
+ }
+ }
+
+
+ // Vrnemo celoten gdpr text za respondenta (pravice...) v obliki array-a
+ public static function getGDPRInfoArray($ank_id, $language_id=''){
+ global $global_user_id;
+ global $lang;
+
+ $gdpr_settings = self::getUserSettings();
+ $gdpr_survey_settings = self::getSurveySettings($ank_id);
+
+ // Force language
+ $language_id_bck = '';
+ if($language_id != '' && $lang['id'] != $language_id){
+
+ // Shranimo star jezik da lahko preklopimo nazaj
+ $language_id_bck = $lang['id'];
+
+ $file = '../../lang/'.$language_id.'.php';
+ include($file);
+
+ $translation = ($language_id == '1') ? '_slo' : '_eng';
+ }
+ else{
+ $translation = ($lang['id'] == '1') ? '_slo' : '_eng';
+ }
+
+ $result = array();
+
+ // OSEBNI PODATKI
+ $result[0]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text1_1'];
+ $result[0]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text1_2'];
+
+ // Avtor raziskave
+ $research_author = self::getResearchAuthor($ank_id, $gdpr_settings, $gdpr_survey_settings);
+ if($research_author != '')
+ $result[0]['text'][1] = $lang['srv_gdpr_survey_gdpr_about_text1_3'].' <strong>'.$research_author.'</strong>';
+
+ $result[0]['text'][2] = $lang['srv_gdpr_survey_gdpr_about_text1_4'].':';
+ $temp_text = '';
+ if($gdpr_survey_settings['name'])
+ $temp_text .= $lang['srv_gdpr_intro_name'].', ';
+ if($gdpr_survey_settings['email'])
+ $temp_text .= $lang['srv_gdpr_intro_email'].', ';
+ if($gdpr_survey_settings['location'])
+ $temp_text .= $lang['srv_gdpr_intro_location'].', ';
+ if($gdpr_survey_settings['phone'])
+ $temp_text .= $lang['srv_gdpr_intro_phone'].', ';
+ if($gdpr_survey_settings['web'])
+ $temp_text .= $lang['srv_gdpr_intro_web'].', ';
+ if($gdpr_survey_settings['other'])
+ $temp_text .= $lang['srv_gdpr_intro_other'].' - '.$gdpr_survey_settings['other_text'.$translation].', ';
+
+ $result[0]['text'][2] .= ' <strong>'.substr(ucfirst(strtolower($temp_text)), 0,-2).'</strong>';
+
+
+ // UPORABA IN HRAMBA PODATKOV
+ $result[1]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text2_1'];
+ $result[1]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text2_2'];
+ $result[1]['text'][1] = $lang['srv_gdpr_survey_gdpr_about_text2_3'];
+ $result[1]['text'][2] = $lang['srv_gdpr_survey_gdpr_about_text2_4'];
+
+ if($gdpr_survey_settings['expire'] == '1' && $gdpr_survey_settings['expire_text'.$translation] != '')
+ $result[1]['text'][2] .= ' <strong>'.$gdpr_survey_settings['expire_text'.$translation].'</strong>.';
+ else
+ $result[1]['text'][2] .= ' <strong>'.$lang['srv_gdpr_survey_gdpr_about_text2_5'].'</strong>';
+
+
+ // UPORABNIKI OSEBNI PODATKOV
+ $result[2]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text3_1'];
+ $result[2]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text3_2'];
+
+ if($gdpr_survey_settings['other_users'] == '1' && $gdpr_survey_settings['other_users_text'.$translation] != '')
+ $result[2]['text'][1] = $lang['srv_gdpr_survey_gdpr_about_text3_32'].' <strong>'.$gdpr_survey_settings['other_users_text'.$translation].'</strong>. ';
+ else
+ $result[2]['text'][1] = '<strong>'.$lang['srv_gdpr_survey_gdpr_about_text3_31'].'.</strong>';
+
+ $result[2]['text'][2] = $lang['srv_gdpr_survey_gdpr_about_text3_4'];
+
+
+ // IZNOS PODATKOV V TRETJE DRŽAVE
+ $result[3]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text4_1'];
+
+ if($gdpr_survey_settings['export'] == '1'){
+ $result[3]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text4_22'].' '.$lang['srv_gdpr_survey_gdpr_about_text4_22_2'].' <strong>'.$gdpr_survey_settings['export_country'.$translation].'</strong> '.$lang['srv_gdpr_survey_gdpr_about_text4_22_3'];
+ $result[3]['text'][1] = $lang['srv_gdpr_survey_gdpr_about_text4_22_4'].' <strong>'.$gdpr_survey_settings['export_user'.$translation].'</strong>';
+ $result[3]['text'][1] = ' '.$lang['srv_gdpr_survey_gdpr_about_text4_22_5'].' <strong>'.$gdpr_survey_settings['export_legal'.$translation].'</strong>.';
+ }
+ else{
+ $result[3]['text'][0] = '<strong>'.$lang['srv_gdpr_survey_gdpr_about_text4_21'].'</strong>';
+ }
+
+
+ // PODATKI O POOBLAŠČENI OSEBI ZA VARSTVO OSEBNIH PODATKOV
+ $result[4]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text5_1'];
+
+ // DPO
+ if($gdpr_survey_settings['authorized'] == ''){
+
+ // Zasebnik brez DPO
+ if($gdpr_settings['type'] == '0' && $gdpr_settings['has_dpo'] == '0'){
+
+ // DPO mail je enak navadnemu mailu, ki ga je vnesel v splosnih nastavitvah
+ if($gdpr_settings['email'] != ''){
+ $gdpr_authorized = $gdpr_settings['email'];
+ }
+ // Ce ga ni vnesel, je DPO mail enak mailu avtorja ankete
+ else{
+ $gdpr_authorized = User::getInstance()->primaryEmail();
+ }
+ }
+ // Zasebnik z DPO ali organizacija
+ else{
+
+ // DPO mail je enak DPO mailu, ki ga je vnesel v splosnih nastavitvah
+ if($gdpr_settings['dpo_email'] != ''){
+ $gdpr_authorized = $gdpr_settings['dpo_email'];
+ }
+ // Ce ga ni vnesel, je DPO mail enak splosnemu mailu oz. mailu avtorja ankete
+ else{
+ if($gdpr_settings['email'] != ''){
+ $gdpr_authorized = $gdpr_settings['email'];
+ }
+ else{
+ $gdpr_authorized = User::getInstance()->primaryEmail();
+ }
+ }
+ }
+ }
+ else{
+ $gdpr_authorized = $gdpr_survey_settings['authorized'];
+ }
+
+ // Kontaktni email
+ if($gdpr_survey_settings['contact_email'] == ''){
+
+ $user_settings = self::getUserSettings();
+
+ // Kontaktni mail je enak mailu, ki ga je vnesel v splosnih nastavitvah
+ if($user_settings['email'] != ''){
+ $gdpr_contact_email = $user_settings['email'];
+ }
+ // Ce ga ni vnesel, je kontaktni mail enak mailu avtorja ankete
+ else{
+ $gdpr_contact_email = User::getInstance()->primaryEmail();
+ }
+ }
+ else{
+ $gdpr_contact_email = $gdpr_survey_settings['contact_email'];
+ }
+
+ $result[4]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text5_2'].' <strong>'.$gdpr_authorized.'</strong>';
+
+ // Ce mail ni isti izpisemo se avtorja
+ if($gdpr_authorized != $gdpr_contact_email)
+ $result[4]['text'][1] = $lang['srv_gdpr_survey_gdpr_about_text5_2_2'].' <strong>'.$gdpr_contact_email.'</strong>';
+
+ // ZAVAROVANJE PODATKOV
+ $result[5]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text6_1'];
+ $result[5]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text6_2'];
+
+
+ // IZBRIS, SPREMEMBA ALI VPOGLED DO OSEBNIH ANKETNIH PODATKOV
+ $result[6]['heading'] = $lang['srv_gdpr_survey_gdpr_about_text7_1'];
+ $result[6]['text'][0] = $lang['srv_gdpr_survey_gdpr_about_text7_2'];
+ $result[6]['text'][1] = $lang['srv_gdpr_survey_gdpr_about_text7_3'];
+
+ if($gdpr_survey_settings['contact_email'] != ''){
+ $result[6]['text'][1] .= ' <strong>'.$gdpr_survey_settings['contact_email'].'</strong>. ';
+ }
+ elseif($gdpr_settings['email'] != ''){
+ $result[6]['text'][1] .= ' <strong>'.$gdpr_settings['email'].'</strong>. ';
+ }
+ else{
+ $sql = sisplet_query("SELECT email FROM users WHERE id = '$global_user_id'");
+ $row = mysqli_fetch_array($sql);
+ $result[6]['text'][1] .= ' '.$row['email'].'. ';
+ }
+
+ $result[6]['text'][1] .= $lang['srv_gdpr_survey_gdpr_about_text7_3_2'];
+
+ $result[6]['text'][2] = $lang['srv_gdpr_survey_gdpr_about_text7_4'];
+
+
+ // OPOMBA
+ if($gdpr_survey_settings['note'.$translation] != ''){
+ $result[7]['heading'] = $lang['note'];
+ $result[7]['text'][0] = '<strong>'.$gdpr_survey_settings['note'.$translation].'</strong>';
+ }
+
+
+ // Preklopimo nazaj jezik
+ if($language_id_bck != '' && $language_id_bck != $lang['id']){
+ $file = '../../lang/'.$language_id_bck.'.php';
+ include($file);
+ }
+
+
+ return $result;
+ }
+
+ // Vrnemo celoten gdpr text za evidencov obliki array-a
+ public static function getGDPREvidencaArray($ank_id){
+ global $global_user_id;
+ global $lang;
+
+ $gdpr_settings = self::getUserSettings();
+ $gdpr_survey_settings = self::getSurveySettings($ank_id);
+
+ $translation = ($lang['id'] == '1') ? '_slo' : '_eng';
+
+ $result = array();
+
+ $result[0]['heading'] = 'I. '.$lang['srv_gdpr_survey_gdpr_evidenca_text1'];
+ $result[0]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text1_1'];
+
+
+ $result[1]['heading'] = 'II. '.$lang['srv_gdpr_survey_gdpr_evidenca_text2'];
+
+ if($gdpr_settings['type'] == '1'){
+ $result[1]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text2_1'].': ';
+ $result[1]['text'][0] .= '<strong>'.$gdpr_settings['organization'].'</strong>';
+
+ $result[1]['text'][1] = $lang['srv_gdpr_survey_gdpr_evidenca_text2_2'].': ';
+ $result[1]['text'][1] .= '<strong>'.$gdpr_settings['address'].'</strong>';
+
+ $result[1]['text'][2] = $lang['srv_gdpr_survey_gdpr_evidenca_text2_3'].': ';
+ $result[1]['text'][2] .= '<strong>'.$gdpr_settings['organization_maticna'].'</strong>';
+ }
+ else{
+ $result[1]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text2_1'].': ';
+ $result[1]['text'][0] .= '<strong>'.$gdpr_settings['firstname'].' '.$gdpr_settings['lastname'].'</strong>';
+
+ $result[1]['text'][1] = $lang['srv_gdpr_survey_gdpr_evidenca_text2_2'].': ';
+ $result[1]['text'][1] .= '<strong>'.$gdpr_settings['address'].'</strong>';
+ }
+
+
+ $result[2]['heading'] = 'III.'.$lang['srv_gdpr_survey_gdpr_evidenca_text3'];
+ $result[2]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text3_1'];
+
+
+ $result[3]['heading'] = 'IV. '.$lang['srv_gdpr_survey_gdpr_evidenca_text4'];
+ $result[3]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text4_1'];
+
+
+ $result[4]['heading'] = 'V. '.$lang['srv_gdpr_survey_gdpr_evidenca_text5'];
+ $temp_text = '';
+ if($gdpr_survey_settings['name'])
+ $temp_text .= $lang['srv_gdpr_intro_name'].', ';
+ if($gdpr_survey_settings['email'])
+ $temp_text .= $lang['srv_gdpr_intro_email'].', ';
+ if($gdpr_survey_settings['location'])
+ $temp_text .= $lang['srv_gdpr_intro_location'].', ';
+ if($gdpr_survey_settings['phone'])
+ $temp_text .= $lang['srv_gdpr_intro_phone'].', ';
+ if($gdpr_survey_settings['web'])
+ $temp_text .= $lang['srv_gdpr_intro_web'].', ';
+ if($gdpr_survey_settings['other'])
+ $temp_text .= $lang['srv_gdpr_intro_other'].' - '.$gdpr_survey_settings['other_text'.$translation].', ';
+
+ $result[4]['text'][0] = '<strong>'.substr(ucfirst(strtolower($temp_text)), 0,-2).'</strong>';
+
+
+ $result[5]['heading'] = 'VI. '.$lang['srv_gdpr_survey_gdpr_evidenca_text6'];
+ $result[5]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text6_1'];
+ $result[5]['text'][1] = $lang['srv_gdpr_survey_gdpr_evidenca_text6_2'];
+
+
+ $result[6]['heading'] = 'VII. '.$lang['srv_gdpr_survey_gdpr_evidenca_text7'];
+
+ $result[6]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text7_1'].' ';
+ if($gdpr_survey_settings['expire'] != '1')
+ $result[6]['text'][0] .= '<strong>'.$lang['srv_gdpr_survey_gdpr_evidenca_text7_2'].'</strong>';
+ else
+ $result[6]['text'][0] .= '<strong>'.$gdpr_survey_settings['expire_text'.$translation].'</strong>.';
+
+
+ $result[7]['heading'] = 'VIII. '.$lang['srv_gdpr_survey_gdpr_evidenca_text8'];
+ $result[7]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text8_1'];
+ $result[7]['text'][1] = $lang['srv_gdpr_survey_gdpr_evidenca_text8_2'];
+
+ if($gdpr_survey_settings['other_users'] == '1')
+ $result[7]['text'][2] = '<strong>'.ucfirst($gdpr_survey_settings['other_users_text'.$translation]).'</strong>';
+
+
+ $result[8]['heading'] = 'IX. '.$lang['srv_gdpr_survey_gdpr_evidenca_text9'];
+
+ if($gdpr_survey_settings['export'] == '1'){
+ $result[8]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text9_22'].' ';
+ $result[8]['text'][0] .= '<strong>'.$gdpr_survey_settings['export_country'.$translation].'</strong>';
+ $result[8]['text'][0] .= $lang['srv_gdpr_survey_gdpr_evidenca_text9_23'].' ';
+ $result[8]['text'][0] .= '<strong>'.$gdpr_survey_settings['export_user'.$translation].'</strong>';
+ $result[8]['text'][0] .= $lang['srv_gdpr_survey_gdpr_evidenca_text9_24'].' ';
+ $result[8]['text'][0] .= '<strong>'.$gdpr_survey_settings['export_legal'.$translation].'</strong>.';
+ }
+ else{
+ $result[8]['text'][0] = '<strong>'.$lang['srv_gdpr_survey_gdpr_evidenca_text9_21'].'</strong>';
+ }
+
+
+ $result[9]['heading'] = 'X. '.$lang['srv_gdpr_survey_gdpr_evidenca_text10'];
+ $result[9]['text'][0] = $lang['srv_gdpr_survey_gdpr_evidenca_text10_1'];
+
+
+ // OPOMBA
+ if($gdpr_survey_settings['note'.$translation] != ''){
+ $result[10]['heading'] = 'XI. '.$lang['note'];
+ $result[10]['text'][0] = '<strong>'.$gdpr_survey_settings['note'.$translation].'</strong>.';
+ }
+
+
+ return $result;
+ }
+
+ // Pretvorimo array v text za info oz. evidenco (html popup, textarea)
+ public static function getGDPRTextFromArray($text_array, $type='html'){
+
+ // Dolocimo line break glede na tip (html, pdf ali textarea)
+ if($type == 'textarea')
+ $br = '&#13;&#10;';
+ else
+ $br = '<br />';
+
+ // Loop po posameznih sklopih
+ foreach($text_array as $sklop){
+
+ // Naslov sklopa
+ $text .= '<strong>'.$sklop['heading'].'</strong>'.$br;
+
+ // Loop po posameznih vrsticah
+ foreach($sklop['text'] as $vrstica){
+
+ $text .= $br.$vrstica.$br;
+ }
+
+ $text .= $br.$br;
+ }
+
+ if($type == 'textarea'){
+ $text = str_replace('<strong>', '', $text);
+ $text = str_replace('</strong>', '', $text);
+ }
+
+ return $text;
+ }
+
+
+ // Pridobimo avtorja raziskave
+ public static function getResearchAuthor($ank_id, $gdpr_settings, $gdpr_survey_settings){
+ global $global_user_id;
+
+ $author = '';
+
+ // Email avtorja - najprej se pogleda ce je nastavljen GDPR na anketi, potem se povlece splosnega iz GDPR na koncu pa avtor maila
+ if($gdpr_survey_settings['contact_email'] != ''){
+ $author = ' '.$gdpr_survey_settings['contact_email'];
+ }
+ elseif($gdpr_settings['email'] != ''){
+ $author = ' '.$gdpr_settings['email'];
+ }
+ else{
+ $sql = sisplet_query("SELECT email FROM users WHERE id = '$global_user_id'");
+ $row = mysqli_fetch_array($sql);
+
+ $author = ' '.$row['email'];
+ }
+
+ // Podjetje ce je nastavljeno v GDPR nastavitvah
+ if($gdpr_settings['type'] == '1' && $gdpr_settings['organization'] != ''){
+ $author .= ' ('.$gdpr_settings['organization'].').';
+ }
+ else{
+ $author .= '.';
+ }
+
+ return $author;
+ }
+
+
+ // Funkcije ajaxa
+ public function ajax() {
+ global $lang;
+ global $global_user_id;
+ global $site_url;
+
+ if (isset ($_POST['ank_id']))
+ $ank_id = $_POST['ank_id'];
+
+ if (isset ($_POST['what']))
+ $what = $_POST['what'];
+ if (isset ($_POST['value']))
+ $value = $_POST['value'];
+
+
+ // Urejanje gdpr nastavitve za userja
+ if($_GET['a'] == 'gdpr_edit_user'){
+
+ $error = array();
+
+ $firstname = isset($_POST['firstname']) ? $_POST['firstname'] : '';
+ $lastname = isset($_POST['lastname']) ? $_POST['lastname'] : '';
+ $email = isset($_POST['email']) ? $_POST['email'] : '';
+ $phone = isset($_POST['phone']) ? $_POST['phone'] : '';
+
+ $type = isset($_POST['type']) ? $_POST['type'] : '0';
+
+ $has_dpo = isset($_POST['has_dpo']) ? $_POST['has_dpo'] : '0';
+
+ $organization = isset($_POST['organization']) ? $_POST['organization'] : '';
+ $organization_maticna = isset($_POST['organization_maticna']) ? $_POST['organization_maticna'] : '';
+ //$organization_davcna = isset($_POST['organization_davcna']) ? $_POST['organization_davcna'] : '';
+ $dpo_firstname = isset($_POST['dpo_firstname']) ? $_POST['dpo_firstname'] : '';
+ $dpo_lastname = isset($_POST['dpo_lastname']) ? $_POST['dpo_lastname'] : '';
+ $dpo_email = isset($_POST['dpo_email']) ? $_POST['dpo_email'] : '';
+ $dpo_phone = isset($_POST['dpo_phone']) ? $_POST['dpo_phone'] : '';
+
+ $address = isset($_POST['address']) ? $_POST['address'] : '';
+ $country = isset($_POST['country']) ? $_POST['country'] : '';
+
+ // Dodatno preverimo ce gre za veljavna maila
+ if($email != '' && !validEmail($email)){
+ $email = '';
+ $error['email'] = 1;
+ }
+ if($dpo_email != '' && !validEmail($dpo_email)){
+ $dpo_email = '';
+ $error['dpo_email'] = 1;
+ }
+
+ $sql = sisplet_query("INSERT INTO srv_gdpr_user
+ (usr_id,
+ type,
+ has_dpo,
+ organization,
+ organization_maticna,
+ dpo_firstname,
+ dpo_lastname,
+ dpo_email,
+ dpo_phone,
+ firstname,
+ lastname,
+ email,
+ phone,
+ address,
+ country)
+ VALUES
+ ('".$global_user_id."',
+ '".$type."',
+ '".$has_dpo."',
+ '".$organization."',
+ '".$organization_maticna."',
+ '".$dpo_firstname."',
+ '".$dpo_lastname."',
+ '".$dpo_email."',
+ '".$dpo_phone."',
+ '".$firstname."',
+ '".$lastname."',
+ '".$email."',
+ '".$phone."',
+ '".$address."',
+ '".$country."')
+ ON DUPLICATE KEY UPDATE
+ type='".$type."',
+ has_dpo='".$has_dpo."',
+ organization='".$organization."',
+ organization_maticna='".$organization_maticna."',
+ dpo_firstname='".$dpo_firstname."',
+ dpo_lastname='".$dpo_lastname."',
+ dpo_email='".$dpo_email."',
+ dpo_phone='".$dpo_phone."',
+ firstname='".$firstname."',
+ lastname='".$lastname."',
+ email='".$email."',
+ phone='".$phone."',
+ address='".$address."',
+ country='".$country."'");
+ if (!$sql)
+ echo mysqli_error($GLOBALS['connect_db']);
+
+ self::displayGDPRUser($error);
+ }
+
+ // Prikaz ustrezne gdpr avtoritetec
+ if($_GET['a'] == 'gdpr_edit_authority'){
+
+ $country = isset($_POST['country']) ? $_POST['country'] : '';
+
+ self::displayGDPRAuthority($country);
+ }
+
+
+ // Nastavljanje ankete da je gdpr
+ elseif($_GET['a'] == 'gdpr_add_anketa'){
+
+ if($ank_id != '' && $ank_id != '0'){
+ if($value == '1')
+ $sql = sisplet_query("INSERT INTO srv_gdpr_anketa (ank_id) VALUES ('".$ank_id."')");
+ else
+ $sql = sisplet_query("DELETE FROM srv_gdpr_anketa WHERE ank_id='".$ank_id."'");
+ }
+
+ self::displayGDPRSurveyList();
+ }
+
+ // Urejanje gdpr nastavitve za userja
+ if($_GET['a'] == 'gdpr_edit_anketa'){
+
+ if($ank_id != '' && $ank_id != '0'){
+
+ $is_gdpr = isset($_POST['is_gdpr']) ? $_POST['is_gdpr'] : '0';
+
+ // Vklopimo gdpr
+ if($is_gdpr == '1'){
+
+ $name = isset($_POST['name']) ? $_POST['name'] : '';
+ $email = isset($_POST['email']) ? $_POST['email'] : '';
+ $location = isset($_POST['location']) ? $_POST['location'] : '';
+ $phone = isset($_POST['phone']) ? $_POST['phone'] : '';
+ $web = isset($_POST['web']) ? $_POST['web'] : '';
+ $other = isset($_POST['other']) ? $_POST['other'] : '';
+ $other_text_slo = isset($_POST['other_text_slo']) ? $_POST['other_text_slo'] : '';
+ $other_text_eng = isset($_POST['other_text_eng']) ? $_POST['other_text_eng'] : '';
+
+ $template_1ka = isset($_POST['1ka_template']) ? $_POST['1ka_template'] : '';
+
+ $about = (isset($_POST['about'])) ? $_POST['about'] : '';
+
+ $expire = isset($_POST['expire']) ? $_POST['expire'] : '';
+ $expire_text_slo = isset($_POST['expire_text_slo']) ? $_POST['expire_text_slo'] : '';
+ $expire_text_eng = isset($_POST['expire_text_eng']) ? $_POST['expire_text_eng'] : '';
+ $other_users = isset($_POST['other_users']) ? $_POST['other_users'] : '';
+ $other_users_text_slo = isset($_POST['other_users_text_slo']) ? $_POST['other_users_text_slo'] : '';
+ $other_users_text_eng = isset($_POST['other_users_text_eng']) ? $_POST['other_users_text_eng'] : '';
+ $export = isset($_POST['export']) ? $_POST['export'] : '';
+ $export_country_slo = isset($_POST['export_country_slo']) ? $_POST['export_country_slo'] : '';
+ $export_country_eng = isset($_POST['export_country_eng']) ? $_POST['export_country_eng'] : '';
+ $export_user_slo = isset($_POST['export_user_slo']) ? $_POST['export_user_slo'] : '';
+ $export_user_eng = isset($_POST['export_user_eng']) ? $_POST['export_user_eng'] : '';
+ $export_legal_slo = isset($_POST['export_legal_slo']) ? $_POST['export_legal_slo'] : '';
+ $export_legal_eng = isset($_POST['export_legal_eng']) ? $_POST['export_legal_eng'] : '';
+ $authorized = isset($_POST['authorized']) ? $_POST['authorized'] : '';
+ $contact_email = isset($_POST['contact_email']) ? $_POST['contact_email'] : '';
+ $note_slo = isset($_POST['note_slo']) ? $_POST['note_slo'] : '';
+ $note_eng = isset($_POST['note_eng']) ? $_POST['note_eng'] : '';
+
+ $sql = sisplet_query("INSERT INTO srv_gdpr_anketa (
+ ank_id,
+ 1ka_template,
+ name,
+ email,
+ location,
+ phone,
+ web,
+ other,
+ other_text_slo,
+ other_text_eng,
+ about,
+ expire,
+ expire_text_slo,
+ expire_text_eng,
+ other_users,
+ other_users_text_slo,
+ other_users_text_eng,
+ export,
+ export_user_slo,
+ export_user_eng,
+ export_country_slo,
+ export_country_eng,
+ export_legal_slo,
+ export_legal_eng,
+ authorized,
+ contact_email,
+ note_slo,
+ note_eng
+ )
+ VALUES (
+ '".$ank_id."',
+ '".$template_1ka."',
+ '".$name."',
+ '".$email."',
+ '".$location."',
+ '".$phone."',
+ '".$web."',
+ '".$other."',
+ '".$other_text_slo."',
+ '".$other_text_eng."',
+ '".$about."',
+ '".$expire."',
+ '".$expire_text_slo."',
+ '".$expire_text_eng."',
+ '".$other_users."',
+ '".$other_users_text_slo."',
+ '".$other_users_text_eng."',
+ '".$export."',
+ '".$export_user_slo."',
+ '".$export_user_eng."',
+ '".$export_country_slo."',
+ '".$export_country_eng."',
+ '".$export_legal_slo."',
+ '".$export_legal_eng."',
+ '".$authorized."',
+ '".$contact_email."',
+ '".$note_slo."',
+ '".$note_eng."'
+ )
+ ON DUPLICATE KEY UPDATE
+ 1ka_template='".$template_1ka."',
+ name='".$name."',
+ email='".$email."',
+ location='".$location."',
+ phone='".$phone."',
+ web='".$web."',
+ other='".$other."',
+ other_text_slo='".$other_text_slo."',
+ other_text_eng='".$other_text_eng."',
+ about='".$about."',
+ expire='".$expire."',
+ expire_text_slo='".$expire_text_slo."',
+ expire_text_eng='".$expire_text_eng."',
+ other_users='".$other_users."',
+ other_users_text_slo='".$other_users_text_slo."',
+ other_users_text_eng='".$other_users_text_eng."',
+ export='".$export."',
+ export_user_slo='".$export_user_slo."',
+ export_user_eng='".$export_user_eng."',
+ export_country_slo='".$export_country_slo."',
+ export_country_eng='".$export_country_eng."',
+ export_legal_slo='".$export_legal_slo."',
+ export_legal_eng='".$export_legal_eng."',
+ authorized='".$authorized."',
+ contact_email='".$contact_email."',
+ note_slo='".$note_slo."',
+ note_eng='".$note_eng."'"
+ );
+ if (!$sql)
+ echo mysqli_error($GLOBALS['connect_db']);
+
+ // Dodatno prikazemo uvod in zakljucek ce se uporablja 1ka template
+ if($template_1ka == '1'){
+ $sqlA = sisplet_query("UPDATE srv_anketa SET show_intro='1', show_concl='1' WHERE id='".$ank_id."'");
+ }
+ }
+ // Izklopimo gdpr - pobrisemo nastavitve
+ else{
+ $sql = sisplet_query("DELETE FROM srv_gdpr_anketa WHERE ank_id='".$ank_id."'");
+ if (!$sql)
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+ // Prikaz preview-ja gdpr uvoda
+ if($_GET['a'] == 'gdpr_preview_intro'){
+
+ if($ank_id != '' && $ank_id != '0'){
+
+ echo '<div id="preview_spremenljivka">';
+
+ echo '<div class="popup_close"><a href="#" onClick="preview_spremenljivka_cancle(); return false;">✕</a></div>';
+
+ echo ' <div class="spremenljivka">';
+
+ // Naslov vprasanja
+ echo '<div class="naslov">';
+ $naslov = self::getSurveyIntro($ank_id);
+ echo $naslov;
+ echo '</div>';
+
+ // Variabli "da" in "ne"
+ echo '<div class="variable_holder clr">';
+ echo ' <div class="variabla"><label for="intro_0"><input type="radio" id="intro_0" name="intro"> '.$lang['srv_gdpr_intro_no'].'</label></div>';
+ echo ' <div class="variabla"><label for="intro_1"><input type="radio" id="intro_1" name="intro"> '.$lang['srv_gdpr_intro_yes'].'</label></div>';
+ echo '</div>';
+
+ echo ' </div>';
+
+ // Gumba zapri
+ //echo '<div class="buttonwrapper floatRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="preview_spremenljivka_cancle(); return false;"><span>Zapri</span></a></div>';
+
+ echo '</div>';
+ }
+ }
+
+ // Prikaz preview-ja gdpr izvoza
+ if($_GET['a'] == 'gdpr_preview_export'){
+
+ if($ank_id != '' && $ank_id != '0'){
+
+ // Tip izvoza
+ if (isset ($_POST['type']))
+ $type = $_POST['type'];
+
+
+ echo '<div id="preview_gdpr_export" class="divPopUp">';
+
+ echo '<div class="popup_close"><a href="#" onClick="preview_spremenljivka_cancle(); return false;">✕</a></div>';
+
+ echo '<div class="content">';
+
+ // Informacije dane posamezniku
+ if($type == '1'){
+
+ $text_array = self::getGDPRInfoArray($ank_id);
+ $text = self::getGDPRTextFromArray($text_array, $type='html');
+
+ // Naslov
+ echo '<h2 style="color">';
+ echo $lang['export_gdpr_individual'];
+ echo '</h2>';
+ }
+ // Evidenca dejavnosti obdelav
+ else{
+
+ $text_array = self::getGDPREvidencaArray($ank_id);
+ $text = self::getGDPRTextFromArray($text_array, $type='html');
+
+ // Naslov
+ echo '<h2>';
+ echo $lang['export_gdpr_activity'];
+ echo '</h2>';
+ }
+
+ echo $text;
+
+ echo '</div>';
+
+ echo '</div>';
+ }
+ }
+
+
+ // Zahteva je obdelana
+ elseif($_GET['a'] == 'gdpr_request_done'){
+
+ if (isset ($_POST['request_id'])){
+
+ $request_id = $_POST['request_id'];
+ $sql = sisplet_query("UPDATE srv_gdpr_requests SET status='".$value."' WHERE id='".$request_id."'");
+ }
+
+ self::displayGDPRRequests();
+ }
+ // Zahteva je obdelana - v posamezni anketi
+ elseif($_GET['a'] == 'gdpr_request_done_survey'){
+
+ if (isset ($_POST['request_id']) && isset ($_POST['ank_id'])){
+
+ $ank_id = $_POST['ank_id'];
+ $request_id = $_POST['request_id'];
+ $sql = sisplet_query("UPDATE srv_gdpr_requests SET status='".$value."' WHERE id='".$request_id."'");
+ }
+
+ self::displayGDPRSurveyRequests($ank_id);
+ }
+
+ // Komentar na zahtevo
+ elseif($_GET['a'] == 'gdpr_request_comment'){
+
+ if (isset ($_POST['request_id'])){
+
+ $request_id = $_POST['request_id'];
+ $sql = sisplet_query("UPDATE srv_gdpr_requests SET comment='".$value."' WHERE id='".$request_id."'");
+ }
+
+ self::displayGDPRRequests();
+ }
+ // Komentaran zahtevo - v posamezni anketi
+ elseif($_GET['a'] == 'gdpr_request_comment_survey'){
+
+ if (isset ($_POST['request_id']) && isset ($_POST['ank_id'])){
+
+ $ank_id = $_POST['ank_id'];
+ $request_id = $_POST['request_id'];
+ $sql = sisplet_query("UPDATE srv_gdpr_requests SET comment='".$value."' WHERE id='".$request_id."'");
+ }
+
+ self::displayGDPRSurveyRequests($ank_id);
+ }
+ }
+}
diff --git a/admin/survey/classes/class.GetSiteUrl.php b/admin/survey/classes/class.GetSiteUrl.php
new file mode 100644
index 0000000..a4c964a
--- /dev/null
+++ b/admin/survey/classes/class.GetSiteUrl.php
@@ -0,0 +1,21 @@
+<?php
+/**
+ * Julij 2018
+ *
+ * Pridobi site url
+ *
+ * @author Patrik Pucer
+ */
+include_once('../survey/definition.php');
+
+class GetSiteUrl
+{
+ function __construct() {
+ }
+
+ function ajax() {
+ global $site_url;
+ echo $site_url;
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.GlobalMisc.php b/admin/survey/classes/class.GlobalMisc.php
new file mode 100644
index 0000000..8075284
--- /dev/null
+++ b/admin/survey/classes/class.GlobalMisc.php
@@ -0,0 +1,31 @@
+<?php
+
+/**
+* class z globalnimi nastavitvami/opcijami za vse surveye
+*/
+
+class GlobalMisc {
+
+ static $getMisc = array(); // cache, ce veckrat dostopamo do istih podatkov
+
+ static function getMisc($what) {
+
+ if (isset(self::$getMisc[$what]))
+ return self::$getMisc[$what];
+
+ $sql = sisplet_query("SELECT * FROM srv_misc WHERE what = '$what'");
+ $row = mysqli_fetch_array($sql);
+ return self::$getMisc[$what] = $row['value'];
+
+ }
+
+ static function setMisc($what, $value) {
+
+ $sql = sisplet_query("REPLACE INTO srv_misc (what, value) VALUES ('$what', '$value')");
+ self::$getMisc[$what] = $value;
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.HashUrl.php b/admin/survey/classes/class.HashUrl.php
new file mode 100644
index 0000000..1c4e536
--- /dev/null
+++ b/admin/survey/classes/class.HashUrl.php
@@ -0,0 +1,296 @@
+<?php
+
+class HashUrl
+{
+
+ private $_anketa;
+ private $_hash_length = 8;
+ private $_hash_page = 'data';
+
+ const PAGE_DATA = 'data';
+ const PAGE_ANALYSIS = 'analysis';
+
+ public function __construct($anketa = null)
+ {
+ global $lang;
+ try {
+ if (!empty($anketa) && (int)$anketa > 0)
+ {
+ $this->_anketa = $anketa;
+ }
+ else
+ {
+ throw new Exception($lang['srv_urlLinks_exception_sid']);
+ }
+ } catch (Exception $e) {
+ die( $e->getMessage().' Exiting script!');
+ }
+
+ return $this;
+ }
+
+ public function hashExists($_hash)
+ {
+
+ if (!empty($_hash))
+ {
+ $str = "SELECT hash FROM srv_hash_url WHERE anketa='$this->_anketa' AND hash='$_hash'";
+ $qry = sisplet_query($str);
+ return mysqli_num_rows($qry);
+ }
+ return false;
+ }
+
+ public function getProperties($_hash)
+ {
+
+ if (!empty($_hash))
+ {
+ $str = "SELECT properties FROM srv_hash_url WHERE anketa='$this->_anketa' AND hash='$_hash'";
+
+ $qry = sisplet_query($str);
+ list($properties) = mysqli_fetch_row($qry);
+ $_properties = unserialize($properties);
+ if (is_array($_properties))
+ {
+ return $_properties;
+ }
+ }
+
+ return array();
+ }
+
+ public function saveProperty($hash, $properties = array())
+ {
+ global $global_user_id;
+ if (!empty($hash))
+ {
+ $_properties = serialize($properties);
+ $str = "SELECT h.hash, h.properties, h.comment, h.page, h.add_date, u.email FROM srv_hash_url as h LEFT JOIN users AS u ON h.add_uid = u.id WHERE anketa='$this->_anketa'";
+
+ $str = "INSERT INTO srv_hash_url (hash,anketa,properties,page,add_date,add_uid) VALUES"
+ ." ('{$hash}','{$this->_anketa}','{$_properties}','{$this->_hash_page}', NOW(), {$global_user_id})"
+ ." ON DUPLICATE KEY UPDATE properties = '".$_properties."'";
+ $updated = sisplet_query($str);
+ sisplet_query('COMMIT');
+ }
+ else
+ {
+ die($lang['srv_urlLinks_error_save']);
+ }
+ return $this;
+ }
+
+ public function getNewHash()
+ {
+ $hashs_in_db = array();
+ $str = "SELECT hash FROM srv_hash_url WHERE anketa='$this->_anketa'";
+ $qry = sisplet_query($str);
+ while (list($hash_in_db) = mysqli_fetch_row($qry))
+ {
+ $hashs_in_db[] = $hash_in_db;
+ }
+
+ do
+ {
+ $newHash = $this->generateHash();
+ }
+ while (in_array($newHash,$hashs_in_db));
+ if (!empty($newHash) && $newHash != '')
+ {
+ return $newHash;
+ }
+ else
+ {
+ die('Can\'t generate new hash!');
+ }
+ }
+
+ private function generateHash()
+ {
+ return substr(strtoupper(hash('md5', uniqid() )),0,$this->_hash_length);
+ }
+
+ public function getSurveyHashes()
+ {
+ $result = array();
+ $str = "SELECT h.hash, h.properties, h.comment, h.refresh, h.access_password, h.page, DATE_FORMAT(h.add_date,'".STP_CALENDAR_DATE_FORMAT."') as add_date, DATE_FORMAT(h.add_date,'%H:%i') as add_date, u.email FROM srv_hash_url as h LEFT JOIN users AS u ON h.add_uid = u.id WHERE anketa='$this->_anketa' ORDER BY h.add_date DESC";
+ $qry = sisplet_query($str);
+ while ( list($hash,$properties,$comment,$refresh,$access_password, $page, $add_date, $add_time, $email) = mysqli_fetch_row($qry))
+ {
+ $result[] = array('hash'=>$hash,'properties'=>unserialize($properties), 'comment'=>$comment, 'refresh'=>$refresh, 'access_password'=>$access_password,
+ 'page'=>$page, 'add_date'=>$add_date, 'add_time'=>$add_time, 'email'=>$email);
+ }
+
+ return $result;
+
+ }
+
+ public function updateComment($hash,$comment)
+ {
+ $str = "UPDATE srv_hash_url SET comment='$comment' WHERE anketa='$this->_anketa' AND hash='$hash'";
+ sisplet_query($str);
+ }
+
+ public function updateRefresh($hash,$refresh)
+ {
+ $str = "UPDATE srv_hash_url SET refresh='$refresh' WHERE anketa='$this->_anketa' AND hash='$hash'";
+ sisplet_query($str);
+ }
+
+ public function updateAccessPassword($hash,$pass)
+ {
+ $str = "UPDATE srv_hash_url SET access_password='$pass' WHERE anketa='$this->_anketa' AND hash='$hash'";
+ sisplet_query($str);
+ }
+
+ public function deleteLink($hash)
+ {
+ $str = "DELETE FROM srv_hash_url WHERE anketa='$this->_anketa' AND hash='$hash'";
+ sisplet_query($str);
+ }
+
+ public function setPage($string)
+ {
+ if ($string == HashUrl::PAGE_ANALYSIS)
+ {
+ $this->_hash_page = HashUrl::PAGE_ANALYSIS;
+ }
+ else
+ {
+ $this->_hash_page = HashUrl::PAGE_DATA;
+ }
+ }
+
+ /**
+ * Check if hashlink access password matches
+ * @param type $hash - haslink id
+ * @param type $pass - access password
+ * @return boolean
+ */
+ public function CheckHashAccessPass($hash, $pass) {
+ $sql = sisplet_query("SELECT access_password AS pass FROM srv_hash_url WHERE hash = '$hash'");
+ if($sql){
+ $row = mysqli_fetch_array($sql);
+ if($row['pass'] == $pass)
+ return true;
+ else
+ return false;
+ }
+ return false;
+ }
+
+ /**
+ * Check if hashlink access password exists
+ * @return boolean
+ */
+ public function IsHashAccessPass($hash) {
+ $sql = sisplet_query("SELECT access_password AS pass FROM srv_hash_url WHERE hash = '$hash'");
+ if($sql){
+ $row = mysqli_fetch_array($sql);
+ if($row['pass'] == '' || $row['pass'] == 'NULL')
+ return false;
+ else
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if hashlink refresh is on
+ * @param type $hash - haslink id
+ * @return boolean
+ */
+ public function IsHashRefresh($hash) {
+ $sql = sisplet_query("SELECT refresh FROM srv_hash_url WHERE hash = '$hash'");
+ if($sql){
+ $row = mysqli_fetch_array($sql);
+ if($row['refresh'] == '1')
+ return true;
+ else
+ return false;
+ }
+ return false;
+ }
+
+ /**
+ * Display from for password to access public link
+ * @global type $lang
+ * @param type $hash - hash id
+ */
+ public function HashlinkAccessPasswordForm($hash){
+ global $lang, $site_url, $lang_admin;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ //echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ if ($_GET['mode'] != 'old') {
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=jsnew"></script>'."\n";
+ } else {
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=js"></script>'."\n";
+ }
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '</head>'."\n";
+ echo '<body id="arch_body" >'."\n";
+ echo '<div id="arch_body_div">';
+
+ echo '<br><div style="float:left"><fieldset>';
+ echo '<legend>' . $lang['srv_analiza_archive_access'] . '</legend>';
+
+ echo '<form name="archive_access_pass_form" id="archive_access_pass_form" method="post" action="'.$site_url.'podatki/'.$this->_anketa.'/'.$hash.'/">';
+ //echo '<input type="hidden" name="archive_id" value="' . $aid . '">';
+
+ //user insertet wrong password
+ if(isset($_SESSION['hashlink_access'][$hash]) && $_SESSION['hashlink_access'][$hash] == '0')
+ echo '<i class="red" id="archive_access_wrong_pass_warning">' . $lang['srv_analiza_archive_access_wrong_pass'] . '</i><br>';
+
+ echo '<br>'.$lang['srv_analiza_archive_access_password_label'].': ';
+ echo '<input type="password" name="hashlink_access_pass" id="hashlink_access_pass" maxlength="25" value="" /><br><br>';
+
+ echo '<span class="spaceRight floatLeft"><div class="buttonwrapper">'
+ . '<a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="$(\'#archive_access_pass_form\').submit();">';
+ echo $lang['srv_analiza_archive_access_button'];
+ echo '</a></div></span><br><br>';
+ echo '</form></fieldset></div>';
+
+ #izpišemo še zaključek html
+ echo '</div>'."\n";
+ echo '</div>'."\n";
+ echo '</body>'."\n";
+ echo '</html>';
+ }
+
+ /**
+ * Just for acces with password
+ */
+ function checkHashlinkAccessSessionValues($hash){
+ if(isset($_POST['hashlink_access_pass'])){
+ if($this->CheckHashAccessPass($hash, $_POST['hashlink_access_pass']))
+ $_SESSION['hashlink_access'][$hash] = '1';
+ else
+ $_SESSION['hashlink_access'][$hash] = '0';
+ }
+ }
+}
diff --git a/admin/survey/classes/class.Library.php b/admin/survey/classes/class.Library.php
new file mode 100644
index 0000000..a509fcc
--- /dev/null
+++ b/admin/survey/classes/class.Library.php
@@ -0,0 +1,1233 @@
+<?php
+class Library {
+
+ var $SurveyAdmin;
+ var $Branching;
+
+ var $tab = 2; // tab pove kater tab je odprt (od 4ih)
+ var $tip = 1; // tip pove v bazi srv_library_folder za kater tip gre (0-vpra�anja, 1-ankete)
+ var $prva = 0; // prva pove, ce je to library na prvi strani (1) ali v urejanju ankete (0)
+
+ // v odvisnosti od mode prilagajamu UI. (Mode je odvisen od tipa ankete - survey_type)
+ var $mode = -1; // mode: -1 -> library pri datotekah, 0 -> glasovanje, 1 -> forma, 2 -> ankata na več straneh, 3 -> ifi
+ var $skin = 0;
+
+ private $isSearch = 0; // ali izvajamo search po anektah
+ private $searchString = ''; // geslo po katerem iscemo po anketah
+ private $searchStringProcessed = array(); // geslo po katerem iscemo po anketah, obdelano (skrajsano da isce tudi po drugih sklanjatvah)
+ private $searchSettings = array(); // nastavitve searcha
+
+
+ /**
+ * @desc konstruktor
+ */
+ function __construct ($_options = array()) {
+ global $surveySkin;
+
+ if (isset($surveySkin))
+ $this->skin = $surveySkin;
+
+ $this->SurveyAdmin = new SurveyAdmin(1, -1);
+ $this->Branching = new Branching($this->SurveyAdmin->anketa);
+
+ if (isset($_options['tab'])) {
+ $this->tab = $_options['tab'];
+ if ($this->tab <= 1)
+ $this->tip = 0;
+ else
+ $this->tip = 1;
+ }
+ else if (isset($_POST['tab'])) {
+ $this->tab = ($_POST['tab'] == 0 || $_POST['tab'] == 'undefined') ? 0 : $_POST['tab'];
+ if ($this->tab <= 1)
+ $this->tip = 0;
+ else
+ $this->tip = 1;
+ }
+ else {
+ $this->tab = 0;
+ $this->tip = 0;
+ }
+
+ if (isset($_options['prva'])) {
+ $this->prva = $_options['prva'];
+ }
+ else {
+ $this->prva = 0;
+ }
+
+ if (isset($_GET['tab'])) $this->tab = (int)$_GET['tab'];
+
+ // nastavimo mode v odvisnosti od survey_type ( če nismo v anketi je -1)
+ if (isset($this->SurveyAdmin->anketa) && $this->SurveyAdmin->anketa > 0) {
+ $_st = $this->SurveyAdmin->getSurvey_type($this->SurveyAdmin->anketa);
+
+ if ($_st > -1)
+ $this->mode = $_st;
+ }
+
+ $this->repareTabs();
+
+ // Preverimo ce gre za search po anketah
+ if(isset($_GET['search']) && $_GET['search'] != ''){
+ $this->isSearch = 1;
+ $this->searchString = str_replace("\\", "", trim($_GET['search']));
+
+ // Iscemo po naslovu ali vsebini
+ $this->searchSettings['stype'] = (isset($_GET['stype'])) ? $_GET['stype'] : '0';
+ }
+ }
+
+
+ /**
+ * @desc prikaze knjiznico znotraj ankete na desni
+ */
+ function display () {
+ global $admin_type;
+ global $global_user_id;
+ global $lang;
+
+ echo '<div id="library_title">';
+ echo '<span class="faicon library"></span> '.$lang['srv_library'];
+ echo '<a href="#" title="'.$lang['srv_zapri'].'" onclick="change_mode(\'toolboxback\', \'1\'); return false;"><span class="faicon close" style="float:right;"></span></a>';
+ echo '</div>';
+
+ $this->display_tabs();
+
+ echo '<div id="library">';
+
+ echo '<div id="libraryInner">';
+ $this->display_folders();
+ echo '</div><!-- id="libraryInner" -->';
+
+ echo '</div><!-- id="library" -->';
+ }
+
+ /**
+ * @desc prikaze tabe za izbiro
+ */
+ function display_tabs () {
+ global $lang;
+
+ echo '<p class="display_tabs">';
+ echo '<span' . ($this->tab==0 || $this->tab==1 ? ' class="highlightTabBlackLeft"' : ' class="nohighlight"') . ' >';
+ echo '<a href="/" onclick="display_knjiznica(\'0\'); return false;" title="'.$lang['srv_vprasanja'].'"><span>' . $lang['srv_vprasanja'] . '</span></a></span>';
+ echo '<span' . ($this->tab==2 || $this->tab==3 ? ' class="highlightTabBlackRight"' : ' class="nohighlight"') . ' >';
+ echo '<a href="/" onclick="display_knjiznica(\'2\'); return false;" title="'.$lang['srv_ankete'].'"><span>' . $lang['srv_ankete'] . '</span></a></span>';
+ echo '</p>';
+ }
+
+ function display_folders () {
+ global $global_user_id;
+ global $lang;
+
+ // Knjiznica znotraj posamezne ankete
+ if ($this->prva == 0) {
+ $this->display_contentfolders(0, 0);
+ $this->display_contentfolders(0, $global_user_id);
+
+ if ($this->tip == 1) {
+ echo '<p class="bold"><a href="index.php?a=knjiznica">'.$lang['srv_library_edit'].'</a><br>';
+
+ $sql = sisplet_query("SELECT * FROM srv_library_anketa WHERE uid='".$global_user_id."' AND ank_id='".$this->SurveyAdmin->anketa."'");
+ if (mysqli_num_rows($sql) == 0) {
+ echo '<div class="buttonwrapper" style="float:left;">
+ <a class="ovalbutton ovalbutton_orange btn_savesettings" onclick="add_to_my_library(); return false;" href="#"><span>'.$lang['srv_library_edit_add'].'</span></a>
+ </div></p>';
+ }
+
+ } else {
+ echo '<p>'.$lang['srv_library_q_txt'].'</p>';
+ }
+
+ //echo '<a style="padding:5px; background-color: white; bottom: 1px; position: absolute; right: 18px;" onclick="change_mode(\'toolboxback\', \'1\'); return false;" href="#">'.$lang['srv_zapri'].'</a>';
+ }
+ // Knjiznica na prvi strani zraven mojih anket
+ else {
+ // Na prvi strani imamo search
+ if($this->isSearch == 1){
+ echo '<div id="searchLibrarySettings">';
+ $this->displaySearchSettings();
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+
+ $this->display_contentfolders_searchList();
+ }
+ else{
+ echo '<div id="searchLibrarySurveys">';
+ $this->displaySearch();
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+
+ $this->display_contentfolders();
+ }
+ }
+ }
+
+ /**
+ * @desc prikaze folderje v knjiznici
+ */
+ function display_contentfolders ($parent = 0, $uid = -1) {
+ global $lang;
+ global $admin_type;
+ global $global_user_id;
+ global $site_url;
+
+ $language = "";
+
+ if ($uid == -1) {
+ if ($this->tab == 0 || $this->tab == 2) {
+ $uid = 0;
+ } else {
+ $uid = $global_user_id;
+ }
+ }
+
+ if ($parent == 0 && $uid == 0) {
+ $language = " AND lang='$lang[id]' ";
+ }
+
+ $cookie = $_COOKIE['library_folders'];
+ // da se v url lahko doda odprte folderje: &libfolder=131-147 (more vkljucevat tudi parente)
+ if (isset($_GET['libfolder'])) $cookie .= '-'.$_GET['libfolder'].'-';
+
+ if ($parent == 0) {
+ // v skrite html elemente shranimo tab, in prva
+ echo '<input type="hidden" name="lib_tab" id="lib_tab" value="'.($this->tab == 0 || $this->tab == "" ? "0" : "$this->tab").'">';
+ echo '<input type="hidden" name="lib_tip" id="lib_tip" value="'.($this->tip == 0 || $this->tip== "" ? "0" : "$this->tip").'">';
+ echo '<input type="hidden" name="lib_prva" id="lib_prva" value="'.($this->prva == 0 || $this->prva== "" ? "0" : "$this->prva").'">';
+
+ echo '<ul title="'.($uid==0?$lang['srv_library_left']:$lang['srv_library_left_right']).'" style="padding-left:0;" class="'.($admin_type==0 || $uid == $global_user_id?'can_edit':'').'">'."\n";
+ }
+
+ $sql = sisplet_query("SELECT id, naslov FROM srv_library_folder WHERE uid='$uid' AND parent = '$parent' AND tip='$this->tip' $language ORDER BY naslov");
+ if (!$sql)
+ echo mysqli_error($GLOBALS['connect_db']);
+
+ if (mysqli_num_rows($sql) == 0 && $uid > 0 && $parent == 0) {
+
+ // za prvic ko pride user, da mu dodamo folder
+ if ($this->tip == 0)
+ $naslov = $lang['srv_moja_vprasanja'];
+ else
+ $naslov = $lang['srv_moje_ankete'];
+
+ sisplet_query("INSERT INTO srv_library_folder (uid, tip, naslov, parent, lang) VALUES ('$uid', '$this->tip', '$naslov', '0', '$lang[id]')");
+
+ $sql = sisplet_query("SELECT id, naslov FROM srv_library_folder WHERE uid='$uid' AND parent = '$parent' AND tip='$this->tip' ORDER BY naslov");
+ if (!$sql)
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ while ($row = mysqli_fetch_array($sql)) {
+ if (strpos($cookie, '-'.$row['id'].'-')=== false && $parent!=0)
+ $hidden = true;
+ else
+ $hidden = false;
+
+
+ echo ' <li id="li'.$row['id'].'" eid="'.$row['id'].'" class="folder" name="folder">';
+
+ if ($parent != 0)
+ echo ' <a href="/" onclick="javascript:library_folders_plusminus(\''.$row['id'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" id="f_pm_'.$row['id'].'"><span class="faicon icon-blue '.($hidden?'plus':'minus').'"></span></a>';
+ else
+ echo ' <span class="sprites spacer12"></span>';
+
+ echo ' <span class="'.($parent!=0 || $uid>0 || $admin_type==0 ? ' folderdrop' : '').'" id="sp'.$row['id'].'" eid="'.$row['id'].'"><span class="faicon folder icon-blue'.($parent!=0?' movable':'').'"></span>'.
+ ' <span title="'.$lang['srv_rename_profile'].'" '.($admin_type==0||$uid>0?' onclick="folder_rename(\''.$row['id'].'\'); return false;"':'').'>'.$row['naslov'].'</span>';
+ if ($admin_type==0 || $uid>0)
+ echo ' <a href="/" onclick="javascript:library_new_folder(\''.$row['id'].'\',\''.$uid.'\'); return false;"><span class="faicon add icon-blue-hover-orange small new_folder" id="new_folder_'.$row['id'].'" title="'.$lang['srv_newfolder'].'"></span></a>';
+
+ if ($parent != 0 && ($admin_type==0||$uid>0) )
+ echo ' <a href="/" onclick="javascript:library_delete_folder(\''.$row['id'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;"><span class="faicon remove icon-orange small delete_folder" id="delete_folder_'.$row['id'].'" title="'.$lang['srv_deletefolder'].'"></span></a>';
+
+ echo ' </span>'."\n";
+
+ echo '<ul id="folder_'.$row['id'].'"'.($hidden?' style="display:none"':'').'>'."\n";
+
+ $this->display_contentfolders($row['id'], $uid);
+
+ $this->display_ifs($row['id']);
+
+ // Izpis spremenljivk v folderju - v root folderju ne izpisujemo vprasanj (ker jih itak ne sme bit)
+ if(!($this->tip == 0 && $parent == 0 && $uid == 0)){
+
+ if ($this->tip == 0)
+ $sql1 = sisplet_query("SELECT * FROM srv_spremenljivka WHERE folder = '$row[id]' AND gru_id='-1' ORDER BY naslov ASC");
+ else
+ $sql1 = sisplet_query("SELECT * FROM srv_anketa a, srv_library_anketa l WHERE a.id=l.ank_id AND l.folder='$row[id]' AND l.uid='$uid' ORDER BY naslov ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+
+ if (mysqli_num_rows($sql1) > 0) {
+
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ echo '<li class="anketa tip'.$this->tip.'">';
+ echo ' <div copy="'.$row1['id'].'" eid="'.$row1['id'].'" class="folder_container '.($this->tip==0?'new_spr':'').'" name="library">';
+
+ echo ' <div class="folder_right">';
+
+ if ($this->tip == 0) {
+ //echo '<a href="/" onclick="javascript:copy_spremenljivka(\''.$row1['id'].'\'); return false;"><img src="img_'.$this->skin.'/copy.png" title="'.$lang['srv_copy_spr'].'" /></a>';
+ if ($admin_type==0 or $uid==$global_user_id)
+ echo ' <a href="/" onclick="library_brisi_spremenljivko(\''.$row1['id'].'\', \''.$lang['srv_brisispremenljivkoconfirm'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;"><span class="faicon delete_circle icon-orange" title="'.$lang['srv_brisispremenljivko'].'"></span></a>';
+ }
+ else {
+ SurveyInfo::getInstance()->SurveyInit($row1['id']);
+
+ if ($this->prva == "1") {
+
+ // Dodaj anketo v javno knjiznico
+ if ($admin_type == 0 && $this->tab == 3) {
+
+ $sqlPublic = sisplet_query("SELECT * FROM srv_library_anketa WHERE ank_id='".$row1['id']."' AND uid='0'");
+ if (!$sqlPublic) echo mysqli_error($GLOBALS['connect_db']);
+
+ // Anketa ze obstaja v javni knjiznici - jo pobrisemo
+ if (mysqli_num_rows($sqlPublic) > 0) {
+ echo ' <a href="/" onclick="surveyList_knjiznica_new(\''.$row1['id'].'\'); return false;" title="'.$lang['srv_ank_lib_off'].'">';
+ echo ' <span class="sprites faicon remove icon-orange small"></span> <span class="library_item_setting_text">'.$lang['srv_ank_lib_off'].'</span>';
+ echo ' </a>';
+ }
+ // Anketo dodamo v javno knjiznico
+ else{
+ echo ' <a href="/" onclick="surveyList_knjiznica_new(\''.$row1['id'].'\'); return false;" title="'.$lang['srv_ank_lib_on'].'">';
+ echo ' <span class="sprites faicon library"></span> <span class="library_item_setting_text">'.$lang['srv_ank_lib_on'].'</span>';
+ echo ' </a>';
+ }
+ }
+
+ // nova anketa kot template iz knjiznice
+ echo '<a href="/" onclick="anketa_copy(\''.$row1['id'].'\'); return false;" title="'.$lang['srv_library_use_survey'].'"><span class="faicon copy"></span> <span class="library_item_setting_text">'.$lang['srv_anketacopy'].'</span></a> ';
+ echo '<a href="'.$site_url.'main/survey/'.(!SurveyInfo::getInstance()->checkSurveyModule('uporabnost') ? 'index' : 'uporabnost').'.php?anketa='.$row1['id'].'&preview=on" target="_blank" title="'.$lang['srv_poglejanketo'].'"><span class="faicon preview"></span> <span class="library_item_setting_text">'.$lang['srv_poglejanketo2'].'</span></a> ';
+
+ // brisi iz knjiznice
+ if ($admin_type == 0) {
+ echo ' <a href="index.php?anketa='.$row1['id'].'" title="'.$lang['srv_editirajanketo'].'"><span class="faicon edit"></span> <span class="library_item_setting_text">'.$lang['edit3'].'</span></a>';
+ }
+
+ if ($admin_type==0 && $this->tab==2) {// sistemska
+ echo ' <a href="/" onclick="library_del_anketa(\''.$row1['id'].'\', \''.$lang['srv_anketadeletelibrary_4'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" title="'.$lang['srv_ank_lib_off'].'"><span class="sprites faicon remove icon-orange small"></span> <span class="library_item_setting_text">'.$lang['hour_remove'].'</span></a>';
+ }
+
+ if($this->tab==3){// moja knjiznica
+ echo ' <a href="/" onclick="library_del_myanketa(\''.$row1['id'].'\', \''.$lang['srv_anketadeletelibrary_3'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" title="'.$lang['srv_ank_mylib_off'].'"><span class="faicon remove icon-orange small"></span> <span class="library_item_setting_text">'.$lang['hour_remove'].'</span></a>';
+ }
+ }
+ else {
+ echo '<a href="'.$site_url.'main/survey/'.(!SurveyInfo::getInstance()->checkSurveyModule('uporabnost') ? 'index' : 'uporabnost').'.php?anketa='.$row1['id'].'&preview=on" target="_blank" title="'.$lang['srv_poglejanketo'].'"><span class="faicon preview"></span></a>';
+ // moznost da povozi anketo z anketo iz knjiznice
+ //TEGA NE DOVOLIMO KER NI OK DA SE KAR PREPISE OBSTOJECO ANKETO - anketo iz knjiznice se lahko po novem dodaja samo iz mojih anket oz. pri ustvarjanju
+ echo ' <a href="/" onclick="alert_copy_anketa(\''.$row1['id'].'\'); return false;"><span class="sprites copy_small" title="'.$lang['srv_copy_srv'].'"></span></a>';
+ }
+ }
+ echo '</div>';
+
+ echo ' <div class="folder_left'.($this->tip==1?' indent"':'" onclick="library_spremenljivka_new(\''.$row1['id'].'\'); return false;"').'>';
+ if ($this->tip == 1 && $this->prva == "0") {
+ echo '<a href="/" onclick="javascript:library_anketa_plusminus(\''.$row1['id'].'\', this); return false;"><span class="faicon icon-blue plus" style="opacity: 0.3"></span></a> ';
+ } else {
+ if ($this->tip != 0)
+ echo ' <span class="sprites spacer12"></span>';
+ }
+
+
+ if ($this->tip == 0) {
+ if ($row1['tip']==1 || $row1['tip']==2 || $row1['tip']==3 || $row1['tip']==21 || $row1['tip']==7)
+ $ikonca = 'osnovna_vprasanja';
+ elseif ($row1['tip']==6 || $row1['tip']==16 || $row1['tip']==19 || $row1['tip']==20)
+ $ikonca = 'table';
+ else
+ $ikonca = 'other_vprasanja';
+ } else {
+ $ikonca = 'anketa';
+ }
+
+ echo '<span class="faicon '.$ikonca.' mapca icon-blue" style="display:inline-block"></span> ';
+ echo skrajsaj(strip_tags($row1['naslov']), 40).'</a>'."\n";
+
+ echo ' </div>';
+
+
+ if ($this->prva == "0") {
+
+ echo '<div id="anketa_vprasanja_'.$row1['id'].'" class="anketa_vprasanja">';
+ if ($this->tip == 1) {
+ $sql2 = sisplet_query("SELECT s.id, s.naslov, s.tip FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$row1[id]'");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+
+ if ($row2['tip']==1 || $row2['tip']==2 || $row2['tip']==3 || $row2['tip']==21 || $row2['tip']==7)
+ $ikonca = 'osnovna_vprasanja';
+ elseif ($row2['tip']==6 || $row2['tip']==16 || $row2['tip']==19 || $row2['tip']==20)
+ $ikonca = 'table';
+ else
+ $ikonca = 'other_vprasanja';
+
+ echo '<span class="new_spr" copy="'.$row2['id'].'" onclick="library_spremenljivka_new(\''.$row2['id'].'\'); return false;"><span class="faicon '.$ikonca.' icon-blue" title="'.$lang['srv_copy_spr'].'" style="display:inline-block"></span>';
+ echo ' '.skrajsaj(strip_tags($row2['naslov']), 40).'</span>';
+
+ }
+ }
+
+ echo '</div>';
+ }
+
+ echo '</div></li>';
+ }
+
+ }
+ }
+
+ echo ' </ul>'."\n";
+
+ echo ' </li>'."\n";
+ }
+
+ if ($parent == 0) {
+ echo '</ul>'."\n";
+ }
+
+ if ( $parent == 0 ) {
+ ?>
+ <script type="text/javascript">
+ $(function() {
+ library();
+ });
+ </script>
+ <?php
+ }
+ }
+
+ /**
+ * @desc prikaze ife / bloke v knjiznici
+ */
+ function display_ifs ($folder) {
+ global $lang, $admin_type;
+
+ $sql = sisplet_query("SELECT * FROM srv_if WHERE folder = '$folder' ORDER BY label ASC, id ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<li class="anketa tip0">';
+ echo ' <div eid="'.$row['id'].'" copy="'.$row['id'].'" class="folder_container new_if" name="library_if">';
+
+ echo ' <div class="folder_right">';
+ if ($admin_type==0 or $this->tab==1)
+ echo ' <a href="/" onclick="library_if_remove(\''.$row['id'].'\', \''.$lang['srv_brisispremenljivkoconfirm'].'\'); return false;"><span class="faicon delete_circle icon-orange" title="'.($row['tip']==0?$lang['srv_if_rem']:$lang['srv_block_rem']).'"></span></a>';
+ echo ' </div>';
+
+ echo ' <div class="folder_left'.($this->tip==1?' indent':'').'" onclick="library_if_new(\''.$row['id'].'\'); return false;">';
+
+ echo '<span class="faicon '.($row['tip']==0?'if':'b').' mapca icon-blue"></span> ';
+
+ echo skrajsaj(strip_tags(($row['label']!=''?$row['label']:($row['tip']==0?$lang['srv_pogoj']:$lang['srv_blok']))), 40).'</a>'."\n";
+
+ echo ' </div>';
+
+ echo '</div></li>';
+ }
+
+ }
+
+
+ /**
+ * @desc prikaze seznam iskanih anket v knjiznici
+ */
+ function display_contentfolders_searchList () {
+ global $lang;
+ global $admin_type;
+ global $global_user_id;
+ global $site_url;
+
+ $language = "";
+
+ if ($this->tab == 2)
+ $uid = 0;
+ else
+ $uid = $global_user_id;
+
+ if ($uid == 0)
+ $language = " AND lang='$lang[id]' ";
+
+ // v skrite html elemente shranimo tab, in prva
+ echo '<input type="hidden" name="lib_tab" id="lib_tab" value="'.$this->tab.'">';
+ echo '<input type="hidden" name="lib_tip" id="lib_tip" value="1">';
+ echo '<input type="hidden" name="lib_prva" id="lib_prva" value="1">';
+
+ echo '<ul title="'.($uid == 0 ? $lang['srv_library_left'] : $lang['srv_library_left_right']).'" style="padding-left:0; margin-left:-12px; margin-top:10px;" class="'.($admin_type == 0 || $uid == $global_user_id ? 'can_edit' : '').'">'."\n";
+
+
+ // Sestavimo query za search po knjiznici
+ $search_query = $this->getSearchString();
+
+ $sql1 = sisplet_query("SELECT sa.*
+ FROM srv_anketa sa, srv_library_anketa l, srv_grupa sg, srv_spremenljivka ss, srv_vrednost sv
+ WHERE sa.id=l.ank_id AND sg.ank_id=sa.id AND ss.gru_id=sg.id AND sv.spr_id=ss.id
+ AND l.uid='$uid' ".$search_query."
+ GROUP BY sa.id
+ ORDER BY sa.naslov ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+
+ // Loop po najdenih anketah
+ if (mysqli_num_rows($sql1) > 0) {
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ echo '<li class="anketa tip1">';
+ echo ' <div copy="'.$row1['id'].'" eid="'.$row1['id'].'" class="folder_container" name="library">';
+
+ echo ' <div class="folder_right">';
+
+ SurveyInfo::getInstance()->SurveyInit($row1['id']);
+
+ // nova anketa kot template iz knjiznice
+ echo '<a href="/" onclick="anketa_copy(\''.$row1['id'].'\'); return false;" title="'.$lang['srv_library_use_survey'].'"><span class="faicon copy"></span> '.$lang['srv_anketacopy'].'</a> ';
+
+ // Preview
+ echo '<a href="'.$site_url.'main/survey/'.(!SurveyInfo::getInstance()->checkSurveyModule('uporabnost') ? 'index' : 'uporabnost').'.php?anketa='.$row1['id'].'&preview=on" target="_blank" title="'.$lang['srv_poglejanketo'].'"><span class="faicon preview"></span> '.$lang['srv_poglejanketo2'].'</a> ';
+
+ // Urejanje - admin
+ if ($admin_type == 0)
+ echo ' <a href="index.php?anketa='.$row1['id'].'" title="'.$lang['srv_editirajanketo'].'"><span class="faicon edit"></span> '.$lang['edit3'].'</a>';
+
+ // Brisanje - admin iz javne knjiznice
+ if ($admin_type == 0 && $this->tab == 2)
+ echo ' <a href="/" onclick="library_del_anketa(\''.$row1['id'].'\', \''.$lang['srv_anketadeletelibrary_4'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" title="'.$lang['srv_ank_lib_off'].'"><span class="faicon remove icon-orange small"></span> '.$lang['hour_remove'].'</a>';
+
+ // Brisanje - uporabnik iz moje knjiznice
+ if($this->tab == 3)
+ echo ' <a href="/" onclick="library_del_myanketa(\''.$row1['id'].'\', \''.$lang['srv_anketadeletelibrary_3'].'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" title="'.$lang['srv_ank_mylib_off'].'"><span class="faicon remove icon-orange small"></span> '.$lang['hour_remove'].'</a>';
+
+ echo '</div>';
+
+
+ echo ' <div class="folder_left'.($this->tip==1?' indent"':'" onclick="library_spremenljivka_new(\''.$row1['id'].'\'); return false;"').'>';
+ echo ' <span class="sprites spacer12"></span>';
+
+ $ikonca = 'anketa';
+
+ echo '<span class="faicon '.$ikonca.' mapca icon-blue" style="display:inline-block"></span> ';
+
+ // Ce gre za search moramo ustrezno pobarvati najden del besede
+ $text_searched = $row1['naslov'];
+ if($this->isSearch == 1 && $this->searchSettings['stype'] == '0'){
+ foreach($this->searchStringProcessed as $search_word){
+
+ // Pobarvamo najden niz v naslovu ankete
+ preg_match_all("/$search_word+/i", $text_searched, $matches);
+ if (is_array($matches[0]) && count($matches[0]) >= 1) {
+ foreach ($matches[0] as $match) {
+ $text_searched = str_replace($match, '<span class="red">'.$match.'</span>', $text_searched);
+ }
+ }
+ }
+ }
+
+ echo skrajsaj($text_searched, 40).'</a>'."\n";
+
+ echo ' </div>';
+ echo '</div></li>';
+ }
+ }
+
+ echo ' </ul>'."\n";
+ echo ' </li>'."\n";
+
+
+ if ($parent == 0) {
+ echo '</ul>'."\n";
+ }
+
+ if ( $parent == 0 ) {
+ ?>
+ <script type="text/javascript">
+ $(function() {
+ library();
+ });
+ </script>
+ <?php
+ }
+ }
+
+ // Prikazemo nastavitve za napredno iskanje ce iscemo po anketah znotraj knjiznice
+ private function displaySearchSettings(){
+ global $lang;
+ global $site_url;
+
+ echo '<span class="title">'.$lang['s_search_settings_lib'].'</span>';
+
+ echo '<form method="GET" id="1kasf2" action="'.$site_url.'admin/survey/index.php?a=knjiznica">';
+
+ // Hidden polja za knjiznico
+ echo '<input type="hidden" name="a" value="knjiznica">';
+ if($this->tab == '3')
+ echo '<input type="hidden" name="t" value="moje_ankete">';
+
+ // Iskano geslo
+ echo '<p>';
+ echo ' <span class="bold">'.$lang['s_search2'].':</span> <input type="text" name="search" id="searchMySurveyText" value="'.htmlentities($this->searchString).'" placeholder="' . $lang['s_search'] . '" />';
+ echo '</p>';
+
+ // Iskanje po naslovu ali avtorju ali besedilu
+ echo '<p>';
+ echo ' <span>'.$lang['s_thru'].': </span>';
+ echo ' <label for="stype_0"><input type="radio" name="stype" id="stype_0" value="0" '.($this->searchSettings['stype'] == '0' ? ' checked="checked"' : '').' />'.$lang['s_title'].'</label>';
+ echo ' <label for="stype_1"><input type="radio" name="stype" id="stype_1" value="1" '.($this->searchSettings['stype'] == '1' ? ' checked="checked"' : '').' />'.$lang['s_text'].'</label>';
+ echo '</p>';
+
+ // Gumba isci in zapri
+ echo '<span style="margin-top: 10px;" class="floatRight spaceRight">';
+ echo ' <div class="buttonwrapper floatLeft spaceRight">';
+ echo ' <a class="ovalbutton ovalbutton_gray" href="'.$site_url.'admin/survey/index.php?a=knjiznica'.($this->tab == '3' ? '&t=moje_ankete' : '').'"><span>'.$lang['srv_zapri'].'</span></a>';
+ echo ' </div>';
+ echo ' <div class="buttonwrapper floatRight">';
+ echo ' <a class="ovalbutton ovalbutton_orange" href="#" onclick="$(\'#1kasf2\').submit(); return false;"><span>'.$lang['s_search'].'</span></a>';
+ echo ' </div>';
+ echo '</span>';
+
+ // Link na isci po mojih anketah
+ echo '<span class="link"><a href="'.$site_url.'admin/survey/index.php?search='.$this->searchString.'">'.$lang['s_search_mySurvey'].'</a></span>';
+
+ echo '<input style="display: none;" value="Išči" type="submit">';
+
+ echo '</form>';
+ }
+
+ // Prikazemo search okno za iskanje po anketah znotraj knjiznice
+ private function displaySearch(){
+ global $lang;
+ global $site_url;
+
+ echo '<form method="GET" id="1kasmysurvey" action="'.$site_url.'admin/survey/index.php">';
+
+ // Hidden polja za knjiznico
+ echo '<input type="hidden" name="a" value="knjiznica">';
+ if($this->tab == '3')
+ echo '<input type="hidden" name="t" value="moje_ankete">';
+
+ //echo '<span class="sprites search"></span> ';
+ echo '<input id="searchMySurvey" class="floatLeft" type="text" value="" placeholder="' . $lang['s_search_Library'] . '" name="search" />';
+
+ //echo '<input type="submit" value="' . $lang['s_search'] . '" />';
+ echo ' <div class="buttonwrapper floatLeft">';
+ echo ' <a class="ovalbutton ovalbutton_orange" href="#" onclick="$(\'#1kasmysurvey\').submit(); return false;"><span>'.$lang['s_search2'].'</span></a>';
+ echo ' </div>';
+
+ echo '</form>';
+ }
+
+ // vrne sql string za search po anketah glede na nastavitve searcha
+ private function getSearchString(){
+
+ $search_text = mysqli_real_escape_string($GLOBALS['connect_db'], $this->searchString);
+
+ // Vse gre v lowerstring
+ $search_text = strtolower($search_text);
+
+ // Sklanjamo po search besedi
+ $search_text = explode (" ", $search_text);
+
+ for ($a=0; $a<sizeof($search_text); $a++) {
+ if (strlen ($search_text[$a]) > 5)
+ $search_text[$a] = substr ($search_text[$a], 0, -2);
+ elseif (strlen ($search_text[$a]) > 2)
+ $search_text[$a] = substr ($search_text[$a], 0, -1);
+ else
+ $search_text[$a] = $search_text[$a];
+
+ $this->searchStringProcessed[$a] = $search_text[$a];
+ $search_text[$a] = '%'.$search_text[$a].'%';
+ }
+
+ $search_text = implode (" ", $search_text);
+
+ // Search po kljucnih besedah znotraj vprasanj (naslovi vprasanj in vrednosti)
+ if($this->searchSettings['stype'] == '1')
+ $result = " AND (LOWER(sa.introduction) LIKE LOWER('".$search_text."')
+ OR LOWER(sa.conclusion) LIKE LOWER('".$search_text."')
+ OR LOWER(ss.naslov) LIKE LOWER('".$search_text."')
+ OR LOWER(sv.naslov) LIKE LOWER('".$search_text."'))";
+ // Search po naslovu
+ else
+ $result = " AND (LOWER(sa.naslov) LIKE LOWER('".$search_text."') OR LOWER(sa.akronim) LIKE LOWER('".$search_text."'))";
+
+ return $result;
+ }
+
+
+ /**
+ * @desc pohendla ajax klice
+ */
+ function ajax () {
+
+ if (isset($_POST['tab']))
+ $this->tab = (int)$_POST['tab'];
+ else if (isset($_GET['tab']))
+ $this->tab = (int)$_GET['tab'];
+ if ($this->tab == 'undefined')
+ $this->tab = 0;
+ if (isset($_POST['prva']))
+ $this->prva = $_POST['prva'];
+ else if (isset($_GET['prva']))
+ $this->prva = $_GET['prva'];
+ if ($this->prva == 'undefined')
+ $this->prva = 0;
+
+ if ($this->tab <= 1)
+ $this->tip = 0;
+ else
+ $this->tip = 1;
+
+ if ($_GET['a'] == 'display_knjiznica') {
+ $this->ajax_display_knjiznica();
+
+ } elseif ($_GET['a'] == 'library_add') {
+ $this->ajax_library_add();
+
+ } elseif ($_GET['a'] == 'spr_dropped') {
+ $this->ajax_spr_dropped();
+
+ } elseif ($_GET['a'] == 'if_dropped') {
+ $this->ajax_if_dropped();
+
+ } elseif ($_GET['a'] == 'folder_dropped') {
+ $this->ajax_folder_dropped();
+
+ } elseif ($_GET['a'] == 'folder_rename') {
+ $this->ajax_folder_rename();
+
+ } elseif ($_GET['a'] == 'folder_newname') {
+ $this->ajax_folder_newname();
+
+ } elseif ($_GET['a'] == 'new_folder') {
+ $this->ajax_new_folder();
+
+ } elseif ($_GET['a'] == 'delete_folder') {
+ $this->ajax_delete_folder();
+
+ } elseif ($_GET['a'] == 'folder_collapsed') {
+ $this->ajax_folder_collapsed();
+
+ } elseif ($_GET['a'] == 'library_del_anketa') {
+ $this->ajax_library_del_anketa();
+
+ } elseif ($_GET['a'] == 'library_del_myanketa') {
+ $this->ajax_library_del_myanketa();
+
+ } elseif ($_GET['a'] == 'library_add_myanketa') {
+ $this->ajax_library_add_myanketa();
+
+ } elseif ($_GET['a'] == 'anketa_copy') {
+ $this->ajax_anketa_copy();
+ } elseif ($_GET['a'] == 'anketa_copy_new') {
+ $this->ajax_anketa_copy_new();
+
+ } elseif ($_GET['a'] == 'if_remove') {
+ $this->ajax_if_remove();
+
+ } elseif ($_GET['a'] == 'brisi_spremenljivko') {
+ $this->ajax_brisi_spremenljivko();
+
+ } elseif ($_GET['a'] == 'alert_copy_anketa') {
+ $this->ajax_alert_copy_anketa();
+
+ } elseif ($_GET['a'] == 'anketa_archive_and_copy') {
+ $this->ajax_anketa_archive_and_copy();
+
+ }
+ }
+
+ function ajax_display_knjiznica () {
+ $this->display();
+ }
+
+ function ajax_library_add () {
+ global $lang;
+
+ $data = array();
+
+ if ($this->tip == 0) {
+ $spremenljivka = substr($_POST['spremenljivka'], 10); // odrezemo branching_
+ $folder = $_POST['folder'];
+
+ // v knjiznico dodamo spremenljivko
+ if ($spremenljivka > 0) {
+ $id = $this->Branching->nova_spremenljivka(-1, 0, 0, $spremenljivka);
+ sisplet_query("UPDATE srv_spremenljivka SET folder = '$folder' WHERE id = '$id'");
+
+ $data['response'] = $lang['srv_library_q_added'];
+
+ // v knjiznico dodamo if/blok
+ } else {
+ $if = substr($_POST['spremenljivka'], 12); // odrezemo branching_if
+
+ if ($if > 0) {
+ $id = $this->Branching->if_copy(0, $if, true);
+ sisplet_query("UPDATE srv_if SET folder = '$folder' WHERE id = '$id'");
+
+ $data['response'] = $lang['srv_library_b_added'];
+ }
+ }
+ }
+
+ ob_start();
+ $this->display_folders();
+ $data['folders'] = ob_get_clean();
+
+ echo json_encode($data);
+
+ }
+
+
+ function ajax_spr_dropped() {
+ global $global_user_id;
+
+ $spremenljivka = $_POST['spremenljivka'];
+ $folder = $_POST['folder'];
+
+ if ($this->tab == 0 or $this->tab == 2)
+ $uid = 0;
+ elseif ($this->tab == 1 or $this->tab == 3)
+ $uid = $global_user_id;
+
+ if ($this->tip == 0) {
+ sisplet_query("UPDATE srv_spremenljivka SET folder = '$folder' WHERE id = '$spremenljivka'");
+ } else {
+ sisplet_query("UPDATE srv_library_anketa SET folder = '$folder' WHERE ank_id = '$spremenljivka' AND uid='$uid'");
+ }
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_if_dropped() {
+ global $global_user_id;
+
+ $if = $_POST['if'];
+ $folder = $_POST['folder'];
+
+ sisplet_query("UPDATE srv_if SET folder = '$folder' WHERE id = '$if'");
+
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_folder_dropped() {
+
+ $drop = $_POST['drop'];
+ $folder = $_POST['folder'];
+
+ if ($drop != $folder)
+ sisplet_query("UPDATE srv_library_folder SET parent = '$folder' WHERE id = '$drop' AND tip='$this->tip'");
+
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_folder_rename () {
+
+ $folder = $_POST['folder'];
+
+ $sql = sisplet_query("SELECT naslov FROM srv_library_folder WHERE id = '$folder'");
+ $row = mysqli_fetch_array($sql);
+
+ echo '<form method="post" onsubmit="javascript:library_folder_newname(\''.$folder.'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" style="display:inline">';
+ echo '<span class="faicon folder icon-blue"></span> '.
+ '<input type="text" name="naslov" id="naslov_'.$folder.'" value="'.$row['naslov'].'" onblur="javascript:library_folder_newname(\''.$folder.'\',\''.$this->tab.'\',\''.$this->prva.'\'); return false;" />';
+ echo '</form>';
+
+ }
+
+ function ajax_folder_newname () {
+ $folder = $_POST['folder'];
+ $naslov = $_POST['naslov'];
+
+ sisplet_query("UPDATE srv_library_folder SET naslov='$naslov' WHERE id ='$folder'");
+
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_new_folder () {
+ global $lang;
+ global $global_user_id;
+ $folder = $_POST['folder'];
+
+ if ($this->tab == 0 or $this->tab == 2)
+ $uid = 0;
+ elseif ($this->tab == 1 or $this->tab == 3)
+ $uid = $global_user_id;
+
+ $uid = $_POST['uid'];
+
+ $s = sisplet_query("INSERT INTO srv_library_folder (uid, tip, naslov, parent) VALUES ('$uid', '$this->tip', '$lang[srv_newfolder]', '$folder')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ $insert_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $_COOKIE['library_folders'] .= '-'.$insert_id.'-'; // $_COOKIE popravimo, da bo sprememba vidna tudi v display_folders()
+ setcookie('library_folders', $_COOKIE['library_folders'], time()+2500000);
+
+ // $this->display();
+ $this->display_folders();
+
+ }
+
+ function ajax_delete_folder () {
+ global $lang;
+
+ $folder = $_POST['folder'];
+
+ $sql = sisplet_query("SELECT parent FROM srv_library_folder WHERE id = '$folder'");
+ $row = mysqli_fetch_array($sql);
+
+ if ($this->tip == 0) {
+ sisplet_query("UPDATE srv_spremenljivka SET folder = '$row[parent]' WHERE folder = '$folder'");
+ sisplet_query("UPDATE srv_if SET folder = '$row[parent]' WHERE folder = '$folder'");
+ } else {
+ sisplet_query("UPDATE srv_library_anketa SET folder = '$row[parent]' WHERE folder = '$folder'");
+ }
+
+ sisplet_query("UPDATE srv_library_folder SET parent = '$row[parent]' WHERE parent = '$folder'");
+
+ sisplet_query("DELETE FROM srv_library_folder WHERE id = '$folder'");
+
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_folder_collapsed () {
+ $folder = $_POST['folder'];
+ $collapsed = $_POST['collapsed'];
+
+ $cookie = $_COOKIE['library_folders'];
+
+ if ($collapsed == 0) {
+ $cookie .= '-'.$folder.'-';
+ } else {
+ $cookie = str_replace('-'.$folder.'-', '', $cookie);
+ }
+
+ setcookie('library_folders', $cookie, time()+2500000);
+
+ echo '<span class="faicon icon-blue '.($collapsed==1?'plus':'minus').'"></span>';
+ }
+
+ function ajax_library_del_anketa () {
+ $anketa = $_POST['anketa'];
+
+ sisplet_query("DELETE FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='0'");
+
+ $this->display_folders();
+ }
+
+ function ajax_library_del_myanketa () {
+ global $global_user_id;
+
+ $anketa = $_POST['anketa'];
+
+ sisplet_query("DELETE FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='$global_user_id'");
+
+ $this->display_folders();
+ }
+
+ function ajax_library_add_myanketa () {
+ global $global_user_id;
+
+ $anketa = $_POST['anketa'];
+
+ $sql1 = sisplet_query("SELECT id FROM srv_library_folder WHERE uid='$global_user_id' AND tip='1' AND parent='0'");
+ $row1 = mysqli_fetch_array($sql1);
+
+ sisplet_query("INSERT INTO srv_library_anketa (ank_id, uid, folder) VALUES ('$anketa', '$global_user_id', '$row1[id]')");
+ }
+
+ /**
+ * skopira anketo cez neko ze obstojeco anketo
+ *
+ */
+ function ajax_anketa_copy () {
+ global $global_user_id;
+ global $lang;
+ global $site_url;
+ $anketa = $_POST['anketa']; // nasa anketa (jo povozimo)
+ $ank_id = $_POST['ank_id']; // anketa, ki jo uporabimo za predlogo
+
+ $hierarhija = (empty($_POST['hierarhija']) ? false : true);
+
+ if($hierarhija && $ank_id == 'privzeta'){
+ global $hierarhija_default_id;
+
+ $ank_id = $hierarhija_default_id;
+ }
+
+ if ($anketa > 0) {
+
+ // preberemo osnovne podatke obstojece ankete (naslov.....)
+ $sql = sisplet_query("SELECT naslov, dostop FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_array($sql);
+
+ $sql2 = sisplet_query("SELECT naslov FROM srv_anketa WHERE id = '$ank_id'");
+ $row2 = mysqli_fetch_array($sql2);
+
+ $sqls = sisplet_query("SELECT ank_id, uid FROM srv_dostop WHERE ank_id='$anketa'");
+
+ $this->SurveyAdmin->anketa_delete($anketa);
+
+ } else {
+
+ $sql = sisplet_query("SELECT naslov, dostop FROM srv_anketa WHERE id = '$ank_id'");
+ $row = mysqli_fetch_array($sql);
+
+ $sqls = sisplet_query("SELECT ank_id, uid FROM srv_dostop WHERE ank_id='$ank_id'");
+ }
+
+ $naslov = " naslov='".(isset($_POST['naslov']) ? $_POST['naslov'] : $row['naslov'])."',";
+ $intro_opomba = " intro_opomba='".(addslashes($lang['srv_library_copy_of_note'].'<a href="'.$site_url.'admin/survey/index.php?anketa='.$ank_id.'">'.$row2['naslov'].'</a>'))."',";
+
+
+ //$new_id = $this->SurveyAdmin->anketa_copy($ank_id);
+ $sas = new SurveyAdminSettings();
+ $new_id = $sas->anketa_copy($ank_id);
+
+ // popravimo naslov, opombo, dostop, in novega avtorja
+ sisplet_query("UPDATE srv_anketa SET $naslov $intro_opomba dostop='$row[dostop]', insert_uid='$global_user_id', edit_uid='$global_user_id' WHERE id='$new_id'");
+ // vsilimo refresh podatkov
+ SurveyInfo :: getInstance()->resetSurveyData();
+
+ // dostop uporabimo od stare ankete in ne od skopirane (trnutno ne kopira pravic od prej, če ustvarjamo novo anketo)
+ // TODO: po kakšni logiki ohranimo dostop od stare ankete?? Če jo jaz ustvarim je prav, v kolikor kopirma iz knjižnice pa tole ni ok!
+ if(!empty($anketa)) {
+ sisplet_query("DELETE FROM srv_dostop WHERE ank_id = '$new_id'");
+ while ($rows = mysqli_fetch_array($sqls)) {
+ sisplet_query("INSERT INTO srv_dostop (ank_id, uid) VALUES ('$new_id', '$rows[uid]')");
+ }
+ }
+
+ // Vrnemo samo ID ankete
+ if($hierarhija) {
+ sisplet_query("INSERT INTO srv_anketa_module (ank_id, modul) VALUES ('".$new_id."', 'hierarhija')");
+ sisplet_query("INSERT INTO srv_hierarhija_users (user_id, anketa_id, type) VALUES ('".$global_user_id."', '".$new_id."', 1)");
+
+ // Določimo vlogo
+ (new \Hierarhija\Hierarhija($new_id))->izrisisSistemskoVprsanjeVloga();
+
+ echo $new_id;
+ }else{
+ echo 'index.php?anketa='.$new_id.'&a=branching';
+ }
+ }
+
+ /**
+ * ustvari novo kopijo ankete
+ * @param ank_id samo za API - prekrije tudi vse echo
+ */
+ function ajax_anketa_copy_new ($ank_id = null) {
+ global $global_user_id, $lang, $site_url;
+
+ $API_call = false;
+
+ if($ank_id == null) {
+ $ank_id = $_POST['ank_id']; // anketa, ki jo uporabimo za predlogo
+
+ // Če imamo hierarhijo in je privzeta anketa potem preverimo v settings_optional.php
+ if(!empty($_POST['hierarhija']) && $ank_id == 'privzeta'){
+ global $hierarhija_default_id;
+ $ank_id=$hierarhija_default_id;
+ }
+ }else {
+ $API_call = true;
+ }
+
+ $sql = sisplet_query("SELECT naslov, dostop FROM srv_anketa WHERE id = '$ank_id'");
+ $row = mysqli_fetch_array($sql);
+
+ // Nastavimo naslov
+ if(isset($_POST['naslov']) && $_POST['naslov'] != '' && $_POST['naslov'] != $lang['srv_naslov'] && $_POST['naslov'] != $lang['srv_novaanketa_polnoime'] && trim($_POST['naslov']) != "")
+ $naslov = " naslov='".$_POST['naslov']."',";
+ else
+ $naslov = " naslov='".addslashes($lang['srv_library_copy_of'].$row['naslov'])."',";
+
+ // Nastavimo akronim, ce ga imamo
+ $akronim = "";
+ if(isset($_POST['akronim']) && $_POST['akronim'] != '' && $_POST['akronim'] != $lang['srv_naslov'] && $_POST['akronim'] != $lang['srv_novaanketa_ime_respondenti'] && trim($_POST['akronim']) != "")
+ $akronim = " akronim='".$_POST['akronim']."',";
+
+ $intro_opomba = " intro_opomba='".(addslashes($lang['srv_library_copy_of_note'].'<a href="'.$site_url.'admin/survey/index.php?anketa='.$ank_id.'">'.$row['naslov'].'</a>'))."',";
+
+ //$new_id = $this->SurveyAdmin->anketa_copy($ank_id);
+ $sas = new SurveyAdminSettings();
+ $new_id = $sas->anketa_copy($ank_id);
+
+ // popravimo naslov, opombo, dostop, in novega avtorja in ugasnemo email vabila
+ sisplet_query("UPDATE srv_anketa
+ SET $naslov $akronim $intro_opomba dostop='$row[dostop]', insert_uid='$global_user_id', edit_uid='$global_user_id', user_base='0'
+ WHERE id='$new_id'");
+
+ // vsilimo refresh podatkov
+ SurveyInfo :: getInstance()->resetSurveyData();
+
+ // dostop od stare ankete odstranimo
+ sisplet_query("DELETE FROM srv_dostop WHERE ank_id = '$new_id'");
+
+ //dostop dodamo uporabniku, ki si kopira anketo
+ sisplet_query("INSERT INTO srv_dostop (ank_id, uid) VALUES ('$new_id', '$global_user_id')");
+
+ // Ce imamo pri ustvarjanju doloceno tudi mapo, anketo vstavimo v njo
+ if(isset($_POST['folder']) && $_POST['folder'] > 0){
+
+ // Razpremo folder v akterega uvrscamo anketo
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET open='1' WHERE id='".$_POST['folder']."' AND usr_id='".$global_user_id."'");
+
+ // Vstavimo anketo
+ $sql = sisplet_query("INSERT INTO srv_mysurvey_anketa (ank_id, usr_id, folder) VALUES ('".$new_id."', '".$global_user_id."', '".$_POST['folder']."')");
+ }
+
+ // popravimo branching, ce kopiramo staro anketo, ki ima lahko pokvarjenega
+ $b = new Branching($new_id);
+ $b->repare_branching();
+
+ // v kolikor je vkloplje modul evalvacija v šolah - hierarhija potem modul vključimo tudi v izbrani anketi
+ if(SurveyInfo::checkSurveyModule('hierarhija', $ank_id) || !empty($_POST['novaHierarhjia'])){
+ sisplet_query("INSERT INTO srv_anketa_module (ank_id, modul) VALUES ('".$new_id."', 'hierarhija')");
+ sisplet_query("INSERT INTO srv_hierarhija_users (user_id, anketa_id, type) VALUES ('".$global_user_id."', '".$new_id."', 1)");
+
+
+ // Določimo vlogo
+ (new \Hierarhija\Hierarhija($new_id))->izrisisSistemskoVprsanjeVloga();
+
+ // Omenjeno funkcijo kopije strukture in preusmeritev uporabimo, kadar kopiramo obstoječe anketo skupaj s strukturo
+ if($_POST['hierarhija'] == 1 && empty($_POST['novaHierarhjia'])){
+ // $new_id je ID nove ankete, ki je bila skopirana
+ // $ank_id pa je ID naše trenutne ankete
+ \Hierarhija\HierarhijaKopiranjeClass::getInstance($new_id)->kopirajCelotroStrukturoKNoviAnketi($ank_id);
+
+ }
+
+ if(empty($_POST['novaHierarhjia'])){
+ echo 'index.php?anketa=' . $new_id .'&a='.A_HIERARHIJA_SUPERADMIN.'&m='.M_ADMIN_UREDI_SIFRANTE;
+ }else{
+ echo $new_id;
+ }
+
+ }else {
+ if(!$API_call)
+ echo 'index.php?anketa=' . $new_id;
+ }
+
+ //vrrni id nove ankete za API
+ return $new_id;
+ }
+
+ function ajax_if_remove () {
+
+ $if = $_POST['if'];
+ $this->anketa = $_POST['anketa'];
+
+ $BranchingAjax = new BranchingAjax($this->anketa);
+ // ne bomo izpisal kar izpisuje ta funkcija
+ ob_start();
+ $BranchingAjax->ajax_if_remove($if);
+ ob_end_clean();
+
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_brisi_spremenljivko () {
+ $spremenljivka = $_POST['spremenljivka'];
+
+ $this->SurveyAdmin->brisi_spremenljivko($spremenljivka);
+
+ //$this->display();
+ $this->display_folders();
+ }
+
+ function ajax_alert_copy_anketa () {
+ global $lang;
+
+ // preverimo stevilo trenutno dodanih vprasanj ce jih ni, ni potrebno arhivirat
+ $sql = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='".$_POST['anketa']."'");
+ if (mysqli_num_rows($sql) > 0)
+ {
+ ?>
+ <div id="copy_library_alert"><?=$lang['srv_alert_copy_anketa'];?>
+ <br/>
+ <div class="floatRight spaceRight" title="<?=$lang['srv_alert_copy_anketa_archive'];?>"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="anketa_archive_and_copy('<?=$_POST['anketa'];?>','<?=$_POST['ank_id'];?>'); return false;"><span><?=$lang['srv_alert_copy_anketa_archive'];?></span></a></div></div>
+ <div class="floatRight spaceRight" title="<?=$lang['srv_alert_copy_anketa_copy'];?>"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="anketa_copy_no_archive('<?=$_POST['anketa'];?>','<?=$_POST['ank_id'];?>'); return false;"><span><?=$lang['srv_alert_copy_anketa_copy'];?></span></a></div></div>
+ <div class="floatRight spaceRight" title="<?=$lang['srv_close_profile'];?>"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="alert_copy_anketa_cancle(); return false;"><span><?=$lang['srv_close_profile'];?></span></a></div></div>
+ <div class="clr"></div>
+ </div>
+ <?php
+ } else {
+ ?>
+ <div id="copy_library_alert"><?=$lang['srv_alert_copy_anketa1'];?>
+ <br/>
+ <div class="floatRight spaceRight" title="<?=$lang['srv_alert_copy_anketa_copy1'];?>"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="anketa_copy_no_archive('<?=$_POST['anketa'];?>','<?=$_POST['ank_id'];?>'); return false;"><span><?=$lang['srv_alert_copy_anketa_copy1'];?></span></a></div></div>
+ <div class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="alert_copy_anketa_cancle(); return false;"><span><?=$lang['srv_close_profile'];?></span></a></div></div>
+ <div class="clr"></div>
+ </div>
+ <?php
+
+ }
+ }
+
+ function ajax_anketa_archive_and_copy () {
+ global $global_user_id;
+ global $lang;
+ global $site_url;
+
+ $anketa = $_POST['anketa']; // obstoječa anketa
+ $ank_id = $_POST['ank_id']; // id ankete iz katere kopiramo
+
+ // preberemo osnovne podatke obstojece ankete (naslov.....)
+ $sql = sisplet_query("SELECT naslov, dostop FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_array($sql);
+
+ $sql2 = sisplet_query("SELECT naslov FROM srv_anketa WHERE id = '$ank_id'");
+ $row2 = mysqli_fetch_array($sql2);
+
+ $sqls = sisplet_query("SELECT uid FROM srv_dostop WHERE ank_id='$anketa'");
+
+ // kreiramo novo anketo tako da jo skopiramo iz knjižnice
+ //$new_id = $this->SurveyAdmin->anketa_copy($ank_id);
+ $sas = new SurveyAdminSettings();
+ $new_id = $sas->anketa_copy($ank_id);
+
+ $intro_opomba = addslashes( $lang['srv_library_copy_of_note'].'<a href="'.$site_url.'admin/survey/index.php?anketa='.$ank_id.'">'.$row2['naslov'].'</a>' );
+
+ // popravimo polja
+ sisplet_query("UPDATE srv_anketa SET naslov='$row[naslov]', intro_opomba='$intro_opomba', dostop='$row[dostop]', insert_uid='$global_user_id', insert_time=NOW(), edit_uid='$global_user_id', edit_time=NOW() WHERE id='$new_id'");
+
+ // dostop uporabimo od stare ankete in ne od skopirane
+ sisplet_query("DELETE FROM srv_dostop WHERE ank_id = '$new_id'");
+ while ($rows = mysqli_fetch_array($sqls)) {
+ sisplet_query("INSERT INTO srv_dostop (ank_id, uid) VALUES ('$new_id', '$rows[uid]')");
+ }
+
+ // staro anketo razglasimo kot backup(arhiv) nove
+ sisplet_query("UPDATE srv_anketa SET backup='$new_id', active=0, edit_uid='$global_user_id', edit_time=NOW(), naslov = CONCAT( naslov, ' ', DAY(NOW()), '.', MONTH(NOW()), '.', YEAR(NOW()) ) WHERE id='$anketa'");
+ // vsilimo refresh podatkov
+ SurveyInfo :: getInstance()->resetSurveyData();
+
+ // redirektamo na novo anketo
+ echo 'index.php?anketa='.$new_id;
+ }
+
+ function repareTabs() {
+ if ($this->tab >= 2)
+ $this->tip = 1;
+ else
+ $this->tip = 0;
+
+ // popravimo tabe če smo v glasovanju ali formi
+ if ($this->mode < 2) {
+ // uredimo tabe
+ if ($this->tab==0 || $this->tab==1) {
+ $this->tip = 1;
+ $this->tab=2;
+ }
+ }
+ }
+
+}
+
+?>
diff --git a/admin/survey/classes/class.NewSurvey.php b/admin/survey/classes/class.NewSurvey.php
new file mode 100644
index 0000000..e3fefb8
--- /dev/null
+++ b/admin/survey/classes/class.NewSurvey.php
@@ -0,0 +1,857 @@
+<?php
+
+/*
+ * Prikaz vmesnika za ustvarjanje nove ankete
+ *
+ * (ce uporabnik klikne "nova anketa" ali ce se nima nobene ankete)
+ *
+ */
+
+use Hierarhija\HierarhijaHelper;
+
+class NewSurvey{
+
+ private $subpage; // Podstran na kateri se nahajamo (nova anketa, iz predloge, uvoz)
+
+ private $template_category; // Podstran kategorij predlog na kateri se nahajamo (vse predloge, organizacija dogodka...)
+ private $templates; // Array vseh templatov
+
+ function __construct(){
+ global $site_url;
+
+ $this->subpage = (isset($_GET['b'])) ? $_GET['b'] : 'new';
+ $this->template_category = (isset($_GET['c'])) ? $_GET['c'] : '0';
+ }
+
+
+ // Izris strani za ustvarjanje ankete
+ public function displayNewSurveyPage(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+
+ // Leva stran - meni
+ echo '<div id="left_menu">';
+ $this->displayLeftMenu();
+ echo '</div>';
+
+ // Desna stran - vsebina
+ echo '<div id="right_content">';
+ $this->displayRightContent();
+ echo '</div>';
+ }
+
+ // Izris levega menija
+ private function displayLeftMenu(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $virtual_domain;
+ global $debug;
+ global $admin_type;
+
+ echo '<div class="title">'.$lang['srv_newSurvey_title'].':</div>';
+
+ // Nova anketa
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=new" title="'.$lang['srv_newSurvey_survey_new2'].'"><span class="item '.($this->subpage == 'new' ? ' active' : '').'" onClick="">'.$lang['srv_newSurvey_survey_new'].'</span></a>';
+
+ // Anketa iz predloga (knjiznice) - samo na www.1ka.si, testu in arnesu
+ if((strpos($site_url, 'www.1ka.si') !== false && !$virtual_domain)
+ || strpos($site_url, 'test.1ka.si')
+ || strpos($site_url, '1ka.arnes.si')
+ || $debug == '1'){
+
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=template" title="'.$lang['srv_newSurvey_survey_template2'].'"><span class="item '.($this->subpage == 'template' ? ' active' : '').'">'.$lang['srv_newSurvey_survey_template'].'</span></a>';
+
+ if($this->subpage == 'template'){
+ echo '<ul>';
+ for($i=0; $i<=10; $i++){
+ echo '<li><a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=template&c='.$i.'" title="'.$lang['srv_newSurvey_survey_template_cat'.$i].'"><span class="subitem '.($this->subpage == 'template' && $this->template_category == $i ? ' active' : '').'">'.$lang['srv_newSurvey_survey_template_cat'.$i].'</span></a></li>';
+ }
+ echo '</ul>';
+ }
+ }
+
+ // Kopiraj mojo anketo
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=copy" title="'.$lang['srv_newSurvey_survey_copy'].'"><span class="item '.($this->subpage == 'copy' ? ' active' : '').'">'.$lang['srv_newSurvey_survey_copy'].'</span></a>';
+
+ // Uvoz ankete
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=archive" title="'.$lang['srv_newSurvey_survey_archive2'].'"><span class="item '.($this->subpage == 'archive' ? ' active' : '').'">'.$lang['srv_newSurvey_survey_archive'].'</span></a>';
+
+ // Anketa iz besedila
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=from_text" title="'.$lang['srv_newSurvey_survey_from_text'].'"><span class="item '.($this->subpage == 'from_text' ? ' active' : '').'">'.$lang['srv_newSurvey_survey_from_text'].'</span></a>';
+
+ if(HierarhijaHelper::aliImaDostopDoIzdelovanjaHierarhije()) {
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=hierarhija" title="'.$lang['srv_hierarchy'].'"><span class="item hierarhija-button '.($this->subpage == 'hierarhija' ? ' active' : '').'">'.$lang['srv_hierarchy'].'</span></a>';
+ }
+ }
+
+ // Izris desne vsebine
+ private function displayRightContent(){
+ global $global_user_id;
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+ if(!$userAccess->checkUserAccess()){
+ $userAccess->displayNoAccess();
+ return;
+ }
+
+ // Anketa iz predloge
+ if($this->subpage == 'template')
+ $this->displayRightContentTemplates();
+ // Kopiranje iz moje ankete
+ elseif($this->subpage == 'copy')
+ $this->displayRightContentCopy();
+ // Anketa iz arhiva (uvoz)
+ elseif($this->subpage == 'archive')
+ $this->displayRightContentArchive();
+ // Hierarhija
+ elseif($this->subpage == 'hierarhija')
+ $this->displayRightContentHierarhija();
+ // Iz besedila
+ elseif($this->subpage == 'from_text')
+ $this->displayRightContentFromText();
+ // Nova anketa
+ else
+ $this->displayRightContentNew();
+ }
+
+
+ // Vsebina za ustvarjanje nove ankete
+ private function displayRightContentNew(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $global_user_id;
+
+
+ // 1. sklop - ime ankete
+ echo '<div class="fieldset">';
+
+ // Naslov
+ echo '<div class="title">' . $lang['srv_noSurvey_settings'] . '</div>';
+
+ echo '<div class="survey_title_text_holder">';
+
+ // Interno ime
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_list_no_data_create'] . ':</span>';
+ echo '<input type="text" id="novaanketa_naslov_1" name="novaanketa_naslov_1" placeholder="' . $lang['srv_novaanketa_polnoime'] . '" value="' . $lang['srv_novaanketa_polnoime'] . '" size="40" maxlength="' . ANKETA_NASLOV_MAXLENGTH . '" onfocus="if(this.value==\'' . $lang['srv_novaanketa_polnoime'] . '\') {this.value=\'\';}" />';
+ echo '<span id="novaanketa_naslov_1_chars">0 / ' . ANKETA_NASLOV_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Objavljeno ime
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_novaanketa_kratkoime'] . ':</span>';
+ echo '<input type="text" id="novaanketa_akronim_1" name="novaanketa_akronim_1" value="' . $lang['srv_novaanketa_ime_respondenti'] . '" placeholder="' . $lang['srv_novaanketa_ime_respondenti'] . '" size="40" maxlength="' . ANKETA_AKRONIM_MAXLENGTH . '" onfocus="$(this).attr(\'changed\',\'1\'); if(this.value==\'' . $lang['srv_novaanketa_ime_respondenti'] . '\') {this.value=\'\';}" changed="0" />';
+ echo '<span id="novaanketa_akronim_1_chars">0 / ' . ANKETA_AKRONIM_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Ce ima uporabnik mape, lahko izbere v katero mapo se anketa uvrsti
+ UserSetting::getInstance()->Init($global_user_id);
+ $show_folders = UserSetting::getInstance()->getUserSetting('survey_list_folders');
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE usr_id='$global_user_id' ORDER BY naslov ASC");
+ if($show_folders == 1 && mysqli_num_rows($sql) > 0){
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_newSurvey_survey_new_folder'] . ':</span>';
+
+ echo '<select name="novaanketa_folder" id="novaanketa_folder">';
+ echo '<option value="0">'.$lang['srv_newSurvey_survey_new_folder_def'].'</option>';
+ while($row = mysqli_fetch_array($sql)){
+ echo '<option value="'.$row['id'].'">'.$row['naslov'].'</option>';
+ }
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ echo '</div>';
+ echo '</div>';
+
+
+ // 2. sklop - tip ankete (navadna, forma, glasovanje)
+ echo '<div class="fieldset">';
+
+ echo '<div class="title">' . $lang['srv_noSurvey_type'] . '</div>';
+
+ echo '<div class="survey_type_holder">';
+
+ // Navadna anketa
+ echo '<label for="newAnketaBlank_2"><div class="setting survey_type active">';
+ echo '<input type="radio" name="newAnketaBlank" id="newAnketaBlank_2" value="2" checked="checked" onClick="$(\'.survey_type\').removeClass(\'active\'); $(this).parent().parent().find(\'.survey_type\').addClass(\'active\');" />';
+ echo '<span class="radioSetting_type">';
+ echo ' <div class="survey_type_title">' . $lang['srv_vrsta_survey_type_2'] . Help::display('srv_create_survey'). '</div>';
+ echo ' <div class="survey_type_text">' . $lang['srv_noSurvey_type_2'] . '</div>';
+ echo '</span>';
+ echo '</div></label>';
+
+ // Forma
+ echo '<label for="newAnketaBlank_1"><div class="setting survey_type">';
+ echo '<input type="radio" name="newAnketaBlank" id="newAnketaBlank_1" value="1" onClick="$(\'.survey_type\').removeClass(\'active\'); $(this).parent().parent().find(\'.survey_type\').addClass(\'active\');" />';
+ echo '<span class="radioSetting_type">';
+ echo ' <div class="survey_type_title">' . $lang['srv_vrsta_survey_type_1'] . Help::display('srv_create_form'). '</div>';
+ echo ' <div class="survey_type_text">' . $lang['srv_noSurvey_type_1'] . '</div>';
+ echo '</span>';
+ echo '</div></label>';
+
+ // Glasovanje
+ echo '<label for="newAnketaBlank_0"><div class="setting survey_type">';
+ echo '<input type="radio" name="newAnketaBlank" id="newAnketaBlank_0" value="0" onClick="$(\'.survey_type\').removeClass(\'active\'); $(this).parent().parent().find(\'.survey_type\').addClass(\'active\');" />';
+ echo '<span class="radioSetting_type">';
+ echo ' <div class="survey_type_title">' . $lang['srv_vrsta_survey_type_0'] . Help::display('srv_create_poll'). '</div>';
+ echo ' <div class="survey_type_text">' . $lang['srv_noSurvey_type_0'] . '</div>';
+ echo '</span>';
+ echo '</div></label>';
+
+ echo '</div>';
+ echo '</div>';
+
+
+ // 3. sklop - skin ankete
+ echo '<div class="fieldset noSurvey_skin">';
+
+ echo '<span class="title">' . $lang['srv_noSurvey_skin'] . ' ' . Help::display('srv_choose_skin') . '</span>';
+
+ // Gorenje ima svoj default skin
+ if(Common::checkModule('gorenje'))
+ echo '<input type="hidden" name="skin" id="noSurvey_skin_id" value="GorenjeGroup" /><br /><br />';
+ else
+ echo '<input type="hidden" name="skin" id="noSurvey_skin_id" value="1kaBlue" /><br /><br />';
+
+ // Puscica levo
+ echo '<a href="#" onClick="scroll_noSurvey_skin(\'left\'); return false;"><span id="skin_arrow_left" class="faicon arrow_verylarge2_l"></span></a>';
+
+ echo '<div id="skins_holder"><div id="noSurvey_skins">';
+
+ // Gorenje ima samo 1 skin
+ if(Common::checkModule('gorenje')){
+ echo '<div class="skin selected" id="skin_GorenjeGroup">';
+
+ echo 'GorenjeGroup (' . $lang['default'] . ')';
+
+ echo '<div class="preview">';
+ echo '<img src="' . $site_url . 'public/img/skins_previews/Gorenje.png">';
+ echo '</div>';
+
+ echo '</div>';
+ }
+ else{
+ // Loop cez vse skine (zaenkrat samo sistemske)
+ $st = new SurveyTheme();
+ $skins = $st->getGroups();
+ foreach ($skins['0']['skins'] as $key => $skin) {
+
+ $simple_name = preg_replace("/\.css$/", '', $skin);
+
+ // Default skin po novem izkljucimo
+ if ($simple_name != 'Default') {
+ echo '<div class="skin ' . ($simple_name == '1kaBlue' ? ' selected' : '') . '" id="skin_' . $simple_name . '" onClick="change_noSurvey_skin(\'' . $simple_name . '\');">';
+
+ echo '<div class="preview">';
+ echo '<img src="' . $site_url . 'public/img/skins_previews/' . urlencode($simple_name) . '.png">';
+ echo '</div>';
+
+ echo $simple_name . ($simple_name == '1kaBlue' ? ' (' . $lang['default'] . ')' : '');
+
+ // Vprasajcki
+ if ($simple_name == 'Embed' || $simple_name == 'Embed2' || $simple_name == 'Fdv' || $simple_name == 'Uni' || $simple_name == 'Slideshow')
+ echo ' ' . Help:: display('srv_skins_' . $simple_name);
+
+ echo '</div>';
+ }
+ }
+ }
+
+ echo '</div></div>';
+
+ // Puscica desno
+ echo '<a href="#" onClick="scroll_noSurvey_skin(\'right\'); return false;"><span id="skin_arrow_right" class="faicon arrow_verylarge2_r"></span></a>';
+
+ echo '</div>';
+
+
+ // Gumba naprej in preklici
+ echo '<div class="noSurvey_buttons">';
+
+ echo '<a href="' . $site_url . 'admin/survey/index.php" title="' . $lang['srv_cancel'] . '"><span id="noSurvey_cancel">' . $lang['srv_cancel'] . '</span></a>';
+ echo '<a href="#" onclick="newAnketaBlank();" title="' . $lang['srv_create_survey'] . '"><span id="noSurvey_create">' . $lang['next1'] . '</span></a>';
+
+ echo '</div>';
+ }
+
+
+ // Vsebina za ustvarjanje ankete iz predloge
+ private function displayRightContentTemplates(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $global_user_id;
+
+ $this->setTemplates();
+
+
+ // 1. sklop - ime ankete
+ echo '<div class="fieldset">';
+
+ // Naslov
+ echo '<div class="title">' . $lang['srv_noSurvey_settings'] . '</div>';
+
+ echo '<div class="survey_title_text_holder">';
+
+ // Interno ime
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_list_no_data_create'] . ':</span>';
+ echo '<input type="text" id="novaanketa_naslov_1" name="novaanketa_naslov_1" placeholder="' . $lang['srv_novaanketa_polnoime'] . '" value="' . $lang['srv_novaanketa_polnoime'] . '" size="40" maxlength="' . ANKETA_NASLOV_MAXLENGTH . '" onfocus="if(this.value==\'' . $lang['srv_novaanketa_polnoime'] . '\') {this.value=\'\';}" />';
+ echo '<span id="novaanketa_naslov_1_chars">0 / ' . ANKETA_NASLOV_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Objavljeno ime
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_novaanketa_kratkoime'] . ':</span>';
+ echo '<input type="text" id="novaanketa_akronim_1" name="novaanketa_akronim_1" value="' . $lang['srv_novaanketa_ime_respondenti'] . '" placeholder="' . $lang['srv_novaanketa_ime_respondenti'] . '" size="40" maxlength="' . ANKETA_AKRONIM_MAXLENGTH . '" onfocus="$(this).attr(\'changed\',\'1\'); if(this.value==\'' . $lang['srv_novaanketa_ime_respondenti'] . '\') {this.value=\'\';}" changed="0" />';
+ echo '<span id="novaanketa_akronim_1_chars">0 / ' . ANKETA_AKRONIM_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Ce ima uporabnik mape, lahko izbere v katero mapo se anketa uvrsti
+ UserSetting::getInstance()->Init($global_user_id);
+ $show_folders = UserSetting::getInstance()->getUserSetting('survey_list_folders');
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE usr_id='$global_user_id' ORDER BY naslov ASC");
+ if($show_folders == 1 && mysqli_num_rows($sql) > 0){
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_newSurvey_survey_new_folder'] . ':</span>';
+
+ echo '<select name="novaanketa_folder" id="novaanketa_folder">';
+ echo '<option value="0">'.$lang['srv_newSurvey_survey_new_folder_def'].'</option>';
+ while($row = mysqli_fetch_array($sql)){
+ echo '<option value="'.$row['id'].'">'.$row['naslov'].'</option>';
+ }
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ echo '</div>';
+ echo '</div>';
+
+
+ // 2. sklop - izbira predloge
+ echo '<div class="fieldset noSurvey_template">';
+
+ echo '<div class="title">' . $lang['srv_newSurvey_survey_template_cat'.$this->template_category] . '</div>';
+
+ echo '<input type="hidden" name="noSurvey_template_id" id="noSurvey_template_id" value="">';
+
+ // Prikaz predlog
+ foreach($this->templates as $template_id => $template_name){
+ $this->displayRightContentTemplate($template_id);
+ }
+
+ echo '</div>';
+
+
+ // Gumba naprej in preklici
+ echo '<div class="noSurvey_buttons">';
+
+ echo '<a href="' . $site_url . 'admin/survey/index.php" title="' . $lang['srv_cancel'] . '"><span id="noSurvey_cancel">' . $lang['srv_cancel'] . '</span></a>';
+ echo '<a href="#" onclick="newAnketaTemplate();" title="' . $lang['srv_create_survey'] . '"><span id="noSurvey_create">' . $lang['next1'] . '</span></a>';
+
+ echo '</div>';
+ }
+
+ // Pripravimo podatke o vseh predlogah na trenutni strani
+ private function setTemplates(){
+ global $lang;
+
+ // Pridobimo seznam templatov anket za izbrano kategorijo in jezik
+ $lang_str = ($lang['id'] == '1') ? '_slo' : '_eng';
+ $cat_str = ($this->template_category == '0') ? '' : ' AND kategorija=\''.$this->template_category.'\'';
+
+ $sql = sisplet_query("SELECT kategorija, ank_id".$lang_str." AS ank_id, naslov".$lang_str." AS naslov, desc".$lang_str." AS opis
+ FROM srv_anketa_template
+ WHERE ank_id".$lang_str.">0 ".$cat_str."");
+ while($row = mysqli_fetch_array($sql)){
+
+ SurveyInfo::getInstance()->SurveyInit($row['ank_id']);
+ $survey_type = SurveyInfo::getInstance()->getSurveyColumn('survey_type');
+
+ if($survey_type === '0')
+ $survey_type_str = $lang['srv_vrsta_survey_type_0'];
+ elseif($survey_type === '1')
+ $survey_type_str = $lang['srv_vrsta_survey_type_1'];
+ else
+ $survey_type_str = $lang['srv_vrsta_survey_type_2'];
+
+ $this->templates[$row['ank_id']] = array(
+ 'naslov' => $row['naslov'],
+ 'tip' => $survey_type_str,
+ 'opis' => $row['opis']
+ );
+ }
+ }
+
+ // Prikazemo posamezen element predloge
+ private function displayRightContentTemplate($template_id){
+ global $lang;
+ global $site_url;
+
+ $template_data = $this->templates[$template_id];
+
+ echo '<div class="template" id="template_'.$template_id.'" onClick="newAnketaTemplate_change(\''.$template_id.'\');">';
+
+ // Naslov
+ echo '<input type="hidden" name="template_title_'.$template_id.'" id="template_title_'.$template_id.'" value="'.$template_data['naslov'].'">';
+
+
+ // Vsebina
+ echo '<div class="template_content">';
+ echo '<div class="template_content_white">';
+ echo $lang['srv_newSurvey_survey_template_type'].': <span class="bold">'.$template_data['tip'].'</span>';
+ echo '<br /><br /><br />';
+ if($template_data['opis'] != '')
+ echo (strlen($template_data['opis']) > 155) ? substr($template_data['opis'], 0, 152).'...' : $template_data['opis'];
+ else
+ echo $template_data['naslov'];
+
+ echo '</div>';
+
+ echo '<span class="template_title">'.$template_data['naslov'].'</span>';
+
+ echo '</div>';
+
+ // Predogled
+ echo '<a href="'.$site_url.'a/'.$template_id.'?preview=on&no_preview=1&size=full" target="_blank" class="template_preview"><span class="faicon preview"></span> '.$lang['srv_newSurvey_survey_template_preview'].'</a>';
+
+ echo '</div>';
+ }
+
+
+ // Vsebina za ustvarjanje ankete iz predloge
+ private function displayRightContentCopy(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $global_user_id;
+
+ // 1. sklop - tip ankete (navadna, forma, glasovanje)
+ echo '<div class="fieldset">';
+
+ echo '<div class="title">'.$lang['srv_newSurvey_survey_copy_title'].'</div>';
+
+ //echo '<input placeholder="'.$lang['srv_newSurvey_survey_copy_text'].'" list="my_surveys" data-list-focus="true" style="width:300px;">';
+ //echo '<datalist id="my_surveys">';
+ echo '<select name="my_surveys" id="my_surveys">';
+ // Pridobimo seznam obstoječih anket
+ $sql = sisplet_query("SELECT id, naslov, akronim FROM srv_anketa WHERE insert_uid='".$global_user_id."' ORDER BY naslov ASC");
+ while($row = mysqli_fetch_array($sql)){
+ echo ' <option value="'.$row['id'].'">'.$row['naslov'].'</option>';
+ }
+ //echo '</datalist>';
+ echo '</select>';
+
+ echo '</div>';
+
+
+ // Gumba naprej in preklici
+ echo '<div class="noSurvey_buttons">';
+
+ echo '<a href="' . $site_url . 'admin/survey/index.php" title="' . $lang['srv_cancel'] . '"><span id="noSurvey_cancel">' . $lang['srv_cancel'] . '</span></a>';
+ echo '<a href="#" onclick="newAnketaCopy();" title="' . $lang['srv_create_survey'] . '"><span id="noSurvey_create">' . $lang['next1'] . '</span></a>';
+
+ echo '</div>';
+ }
+
+ // Vsebina za uvažanje ankete iz arhiva
+ private function displayRightContentArchive(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+
+ // 1. sklop - ime ankete
+ echo '<div class="fieldset">';
+
+ // Naslov
+ echo '<div class="title">' . $lang['srv_newSurvey_survey_archive_title'] . '</div>';
+
+ echo $lang['srv_newSurvey_survey_archive_text2'];
+
+ echo '<div class="setting archive">';
+ echo '<form id="restore" action="ajax.php?a=archive_restore" method="post" name="restorefrm" enctype="multipart/form-data" >';
+
+ echo '<input type="hidden" name="has_data" value="0" />';
+ //echo '<input type="file" name="restore" onchange="document.restorefrm.submit();" />';
+ echo '<input type="file" name="restore" class="pointer" />';
+
+ echo $lang['srv_arhiv_datoteka_save_txt2'].'.';
+
+ echo '<br /><br />'.$lang['srv_newSurvey_survey_archive_text'].'.';
+
+ echo '</form>';
+ echo '</div>';
+
+ // Izpis napake pri uvozu
+ if(isset($_GET['error'])){
+ if($_GET['error'] == '2')
+ echo '<p><span class="red">'.$lang['srv_newSurvey_survey_archive_error2'].'</span></p>';
+ else
+ echo '<p><span class="red">'.$lang['srv_newSurvey_survey_archive_error1'].'</span></p>';
+ }
+
+ echo '</div>';
+
+
+ // Gumba naprej in preklici
+ echo '<div class="noSurvey_buttons">';
+
+ echo '<a href="' . $site_url . 'admin/survey/index.php" title="' . $lang['srv_cancel'] . '"><span id="noSurvey_cancel">' . $lang['srv_cancel'] . '</span></a>';
+ echo '<a href="#" onclick="document.restorefrm.submit();" title="' . $lang['srv_create_survey'] . '"><span id="noSurvey_create">' . $lang['next1'] . '</span></a>';
+
+ echo '</div>';
+ }
+
+
+ /**
+ * Modul za ustvarjanje hierarhije
+ */
+ private function displayRightContentHierarhija(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+
+ // V kolikor nima pravic za ustvarjanje hierarhije je blank page
+ if(!HierarhijaHelper::aliImaDostopDoIzdelovanjaHierarhije()){
+ return false;
+ }
+
+ // 1. sklop - ime ankete
+ echo '<div class="fieldset">';
+
+ // Naslov
+ echo '<div class="title">' . $lang['srv_hierarchy'] . '</div>';
+
+ // Glavno okno za prikaz uvoda in izbire ankete
+ echo '<div class="setting archive" id="hierarhija-opcije-vklopa">';
+
+ if(!empty($_GET['c']) && $_GET['c'] == 'izbira'){
+ global $hierarhija_default_id;
+
+ echo '<h4>'.$lang['srv_hierarchy_intro_select_title'].':</h4>';
+ echo '<div class="izbira">';
+ echo '<label class="strong block" onclick="pridobiKnjiznicoZaHierarhijo(\'nova\')"><input type="radio" id="obstojeca-anketa" name="izberi-anketo" value="nova"/><span class="enka-checkbox-radio"></span>'.$lang['srv_hierarchy_intro_option_new'].'</label>';
+
+ echo '<div class="ime-ankete" style="padding:10px;display: none;">';
+ // Interno ime
+ echo '<div class="setting">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_list_no_data_create'] . ':</span>';
+ echo '<input type="text" id="novaanketa_naslov_1" name="novaanketa_naslov_1" placeholder="' . $lang['srv_novaanketa_polnoime'] . '" value="' . $lang['srv_novaanketa_polnoime'] . '" size="40" maxlength="' . ANKETA_NASLOV_MAXLENGTH . '" onfocus="if(this.value==\'' . $lang['srv_novaanketa_polnoime'] . '\') {this.value=\'\';}" />';
+ echo '<span id="novaanketa_naslov_1_chars">0 / ' . ANKETA_NASLOV_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Objavljeno ime
+ echo '<div class="setting">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_novaanketa_kratkoime'] . ':</span>';
+ echo '<input type="text" id="novaanketa_akronim_1" name="novaanketa_akronim_1" value="' . $lang['srv_novaanketa_ime_respondenti'] . '" placeholder="' . $lang['srv_novaanketa_ime_respondenti'] . '" size="40" maxlength="' . ANKETA_AKRONIM_MAXLENGTH . '" onfocus="$(this).attr(\'changed\',\'1\'); if(this.value==\'' . $lang['srv_novaanketa_ime_respondenti'] . '\') {this.value=\'\';}" changed="0" />';
+ echo '<span id="novaanketa_akronim_1_chars">0 / ' . ANKETA_AKRONIM_MAXLENGTH . '</span>';
+ echo '</div>';
+ echo '</div>';
+
+ echo '<label class="strong block"><input type="radio" id="prevzeta-anketa" name="izberi-anketo" onclick="pridobiKnjiznicoZaHierarhijo(\'privzeta\')" value="prevzeta" /><span class="enka-checkbox-radio"></span>'.$lang['srv_hierarchy_intro_option_default'].'
+ <a href="/main/survey/index.php?anketa='.$hierarhija_default_id.'&amp;preview=on" target="_blank" title="Predogled ankete">
+ <span class="faicon preview"></span>
+ </a>
+ </label>';
+
+ echo '<label class="strong block"><input type="radio" name="izberi-anketo" value="knjiznica" onclick="pridobiKnjiznicoZaHierarhijo(\'vse\')"/><span class="enka-checkbox-radio"></span>'.$lang['srv_hierarchy_intro_option_library'].'</label>';
+ echo '</div>';
+ echo '<div id="hierarhija-knjiznica">';
+ echo '</div>';
+ }else{
+ echo $lang['srv_hierarchy_description'];
+ }
+
+ echo '</div>';
+ echo '</div>';
+
+ // Gumbi
+ echo '<div class="noSurvey_buttons">';
+ if(!empty($_GET['c']) && $_GET['c'] == 'izbira'){
+
+ echo '<a href="' . $site_url . 'admin/survey/index.php?a=ustvari_anketo&b=hierarhija" title="' . $lang['back'] . '"><span id="noSurvey_cancel">' . $lang['back'] . '</span></a>';
+ echo '<a href="#" onclick="potrdiIzbiroAnkete();" title="' . $lang['srv_potrdi'] . '"><span id="noSurvey_create">' . $lang['srv_potrdi'] . '</span></a>';
+
+ }else {
+ echo '<a href="'.$site_url.'admin/survey/index.php" title="'.$lang['srv_cancel'].'"><span id="noSurvey_cancel">'.$lang['srv_cancel'].'</span></a>';
+ echo '<a href="'.$site_url.'admin/survey/index.php?a=ustvari_anketo&b=hierarhija&c=izbira" title="'.$lang['srv_next1'].'"><span id="noSurvey_create">'.$lang['next1'].'</span></a>';
+ }
+
+ echo '</div>';
+
+ }
+
+
+ // Uvoz ankete iz besedila
+ public function displayRightContentFromText(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $global_user_id;
+
+
+ // 1. sklop - ime ankete
+ echo '<div class="fieldset">';
+
+ // Naslov
+ echo '<div class="title">' . $lang['srv_noSurvey_settings'] . '</div>';
+
+ echo '<div class="survey_title_text_holder">';
+
+ // Interno ime
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_list_no_data_create'] . ':</span>';
+ echo '<input type="text" id="novaanketa_naslov_1" name="novaanketa_naslov_1" placeholder="' . $lang['srv_novaanketa_polnoime'] . '" value="' . $lang['srv_novaanketa_polnoime'] . '" size="40" maxlength="' . ANKETA_NASLOV_MAXLENGTH . '" onfocus="if(this.value==\'' . $lang['srv_novaanketa_polnoime'] . '\') {this.value=\'\';}" />';
+ echo '<span id="novaanketa_naslov_1_chars">0 / ' . ANKETA_NASLOV_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Objavljeno ime
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_novaanketa_kratkoime'] . ':</span>';
+ echo '<input type="text" id="novaanketa_akronim_1" name="novaanketa_akronim_1" value="' . $lang['srv_novaanketa_ime_respondenti'] . '" placeholder="' . $lang['srv_novaanketa_ime_respondenti'] . '" size="40" maxlength="' . ANKETA_AKRONIM_MAXLENGTH . '" onfocus="$(this).attr(\'changed\',\'1\'); if(this.value==\'' . $lang['srv_novaanketa_ime_respondenti'] . '\') {this.value=\'\';}" changed="0" />';
+ echo '<span id="novaanketa_akronim_1_chars">0 / ' . ANKETA_AKRONIM_MAXLENGTH . '</span>';
+ echo '</div>';
+
+ // Ce ima uporabnik mape, lahko izbere v katero mapo se anketa uvrsti
+ UserSetting::getInstance()->Init($global_user_id);
+ $show_folders = UserSetting::getInstance()->getUserSetting('survey_list_folders');
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE usr_id='$global_user_id' ORDER BY naslov ASC");
+ if($show_folders == 1 && mysqli_num_rows($sql) > 0){
+ echo '<div class="setting survey_title_text">';
+ echo '<span class="label" style="float:left; width:180px;">' . $lang['srv_newSurvey_survey_new_folder'] . ':</span>';
+
+ echo '<select name="novaanketa_folder" id="novaanketa_folder">';
+ echo '<option value="0">'.$lang['srv_newSurvey_survey_new_folder_def'].'</option>';
+ while($row = mysqli_fetch_array($sql)){
+ echo '<option value="'.$row['id'].'">'.$row['naslov'].'</option>';
+ }
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ echo '</div>';
+ echo '</div>';
+
+
+ // 2. sklop - uvoz iz besedila
+ echo '<div class="fieldset anketa_from_text">';
+
+ // Naslov
+ echo '<div class="title">' . $lang['srv_newSurvey_survey_from_text_title'] . ' '.Help::display('srv_create_survey_from_text').'</div>';
+ echo '<div class="from_text_instructions">' . $lang['srv_newSurvey_survey_from_text_text'] . '</div>';
+
+ // Input okno za text
+ echo '<div id="input_field_holder"><div id="input_field">';
+ //echo '<textarea placeholder="'.$lang['srv_newSurvey_survey_from_text_example'].'" onKeyUp="$(\'#preview_field\').html($(\'textarea\').val());"></textarea>';
+ echo '<textarea id="anketa_from_text_textarea" placeholder="'.$lang['srv_newSurvey_survey_from_text_example'].'" onKeyUp="anketaFromText_preview();"></textarea>';
+ echo '</div></div>';
+
+ // Preview okno
+ echo '<div id="preview_field_holder"><div id="preview_field">';
+ echo '<span class="italic">'.$lang['srv_poglejanketo2'].'</span>';
+ echo '</div></div>';
+
+ echo '</div>';
+
+
+ // Gumba naprej in preklici
+ echo '<div class="noSurvey_buttons">';
+
+ echo '<a href="' . $site_url . 'admin/survey/index.php" title="' . $lang['srv_cancel'] . '"><span id="noSurvey_cancel">' . $lang['srv_cancel'] . '</span></a>';
+ echo '<a href="#" onclick="newAnketaFromText();" title="' . $lang['srv_create_survey'] . '"><span id="noSurvey_create">' . $lang['next1'] . '</span></a>';
+
+ echo '</div>';
+ }
+
+
+ /**
+ * Uporabnik se je ravnokar registriral in se nima nobenih anket
+ *
+ */
+ function displayNoSurveySequence(){
+ global $lang;
+ global $site_url;
+ global $site_path;
+
+ echo '<div class="noSurvey_sequence">';
+
+ // Video
+ if ($_GET['b'] == 'video') {
+
+ echo '<div class="main_holder video">';
+
+ echo '<span class="title">' . $lang['noSurvey_sequence_title'] . '</span>';
+
+ echo '<p style="text-align:center;"><iframe width="700" height="500" style="border:1px #8a9fbf solid;" src="//www.youtube.com/embed/1OeaQErrPrc" frameborder="0" allowfullscreen></iframe></p>';
+
+ echo '</div>';
+ }
+ // Spisek funkcionalnosti
+ elseif ($_GET['b'] == 'features') {
+
+ echo '<div class="main_holder features">';
+
+ echo '<span class="title">' . $lang['noSurvey_sequence_title'] . '</span>';
+
+ echo $lang['noSurvey_sequence_features'];
+
+ echo '<h2>' . $lang['noSurvey_sequence_features_h1'] . '</h2>';
+ echo '<ul class="features">';
+ echo '<li>' . $lang['noSurvey_sequence_features_li1'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li2'] . '</li>';
+ echo '</ul>';
+
+ echo '<h2>' . $lang['noSurvey_sequence_features_h2'] . '</h2>';
+ echo '<ul class="features">';
+ echo '<li>' . $lang['noSurvey_sequence_features_li3'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li4'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li5'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li6'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li7'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li8'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li9'] . '</li>';
+ echo '</ul>';
+
+ echo '<h2>' . $lang['noSurvey_sequence_features_h3'] . '</h2>';
+ echo '<ul class="features">';
+ echo '<li>' . $lang['noSurvey_sequence_features_li10'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li11'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li12'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li13'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li14'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li15'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li16'] . '</li>';
+ echo '<li>' . $lang['noSurvey_sequence_features_li17'] . '</li>';
+ echo '</ul>';
+
+ echo '</div>';
+ }
+ // Prva stran
+ else {
+
+ echo '<div class="main_holder main">';
+
+ // Leva stran
+ echo '<div class="left_holder">';
+ echo '<span class="title">' . $lang['noSurvey_sequence_title'] . '</span>';
+ echo $lang['noSurvey_sequence_main'];
+ echo '</div>';
+
+ // Desna stran
+ echo '<div class="right_holder">';
+ echo '<img src="/public/img/images/first_survey.jpg">';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+
+ // Gumbi na dnu
+ echo '<div class="buttons_holder">';
+
+ // Gumb ustvari anketo
+ echo '<a href="'.$site_url.'/admin/survey/index.php?b=new_survey">';
+ echo ' <div class="button">'.$lang['noSurvey_sequence_button_create'].'</div>';
+ echo '</a>';
+
+ // Gumb videovodic
+ if($_GET['b'] != 'video'){
+ echo '<a href="'.$site_url.'/admin/survey/index.php?b=video">';
+ echo ' <div class="button button_gray">'.$lang['noSurvey_sequence_button_video'].'</div>';
+ echo '</a>';
+ }
+
+ // Gumb ogled funkcionalnosti
+ if($_GET['b'] != 'features'){
+ echo '<a href="'.$site_url.'/admin/survey/index.php?b=features">';
+ echo ' <div class="button button_gray">'.$lang['noSurvey_sequence_button_advanced'].'</div>';
+ echo '</a>';
+ }
+
+ // Gumb ogled cenika
+ if($_GET['b'] == 'features'){
+ $cenik_link = ($lang['id'] == '1') ? 'https://www.1ka.si/d/sl/cenik' : 'https://www.1ka.si/d/en/services/';
+
+ echo '<a href="'.$cenik_link.'" target="_blank">';
+ echo ' <div class="button button_gray">'.$lang['noSurvey_sequence_button_cenik'].'</div>';
+ echo '</a>';
+ }
+
+ echo '</div>';
+
+
+ echo '</div>';
+ }
+
+
+ public function ajax(){
+ global $lang;
+
+ if ($_GET['a'] == 'from_text_preview') {
+
+ $text = (isset($_POST['text'])) ? $_POST['text'] : '';
+ $text = str_replace('\n', '<br />', strip_tags($text));
+
+ // Ce imamo prazno
+ if($text == ''){
+ $text = '<span class="italic">'.$lang['srv_poglejanketo2'].'</span>';
+ }
+ else{
+ // Pobrisemo vmesne odvecne presledke
+ $text = preg_replace(
+ '/(<br \/>){3,}/',
+ '<br /><br />',
+ $text
+ );
+
+ // Wrapamo naslove (prazna vrstica spredaj)
+ $text = preg_replace(
+ '/<br \/><br \/>([^<>]+)/',
+ '<br /><br /><span class="title">$1</span>',
+ $text
+ );
+ // Wrapamo variable (vsaka v novi vrstici)
+ $text = preg_replace(
+ '/<br \/>([^<>]+)/',
+ '<br /><span class="variable"><input type="radio" /><span class="enka-checkbox-radio"></span> $1</span>',
+ $text
+ );
+ // Dodamo se textbox ce je samo vprasanje
+ $text = preg_replace(
+ '/(<span class="title">[^<>]+<\/span>)<br \/><br \/>/',
+ '$1<br /><input type="text" /><br /><br />',
+ $text
+ );
+
+ // Wrapamo se prvo vrstico kot naslov
+ $text = preg_replace(
+ '/([^<>]+)<br \/>/',
+ '<span class="title">$1</span><br />',
+ $text, 1
+ );
+ // Dodamo se textbox na zadnjo vrstico ce je potrebno
+ $text = preg_replace(
+ '/(<span class="title">[^<>]+<\/span>)\Z/',
+ '$1<br /><input type="text" />',
+ $text
+ );
+ // Dodamo se textbox na prvo vrstico ce je potrebno
+ $text = preg_replace(
+ '/(<span class="title">[^<>]+<\/span>)<br \/><br \/>/',
+ '$1<br /><input type="text" /><br /><br />',
+ $text, 1
+ );
+ }
+
+ echo $text.'<br /><br />';
+ }
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.Notifications.php b/admin/survey/classes/class.Notifications.php
new file mode 100644
index 0000000..1a88247
--- /dev/null
+++ b/admin/survey/classes/class.Notifications.php
@@ -0,0 +1,439 @@
+<?php
+/**
+ *
+ *
+ * Class za posiljanje sporocil uporabnikom (v mojih anketah)
+ *
+ *
+ */
+
+
+class Notifications {
+
+ function __construct() {
+ global $admin_type, $global_user_id;
+
+ }
+
+
+ public function display($tab=0){
+ global $admin_type, $global_user_id, $lang;
+
+ // Prikazemo poslana sporocila
+ if((isset($_GET['t']) && $_GET['t']=='sent') || $tab == 1){
+
+ // Izpis vseh poslanih sporocil
+ if($admin_type == 0){
+ echo '<div class="sent_list">';
+ $this->displaySentMessages();
+ echo '</div>';
+
+ // obrazec za posiljanje sporocil
+ $this->sendMessageForm();
+ }
+ else
+ echo $lang['srv_notifications_admin_alert'];
+ }
+ // Prikazemo prejeta sporocila
+ else{
+ echo '<div class="recieved_list">';
+ $this->displayRecievedMessages();
+ echo '</div>';
+
+ echo '<div id="message" style="display:none;"></div>';
+ }
+
+ echo '<div class="clr"></div>';
+ }
+
+ private function displayRecievedMessages($active=0){
+ global $admin_type, $global_user_id, $lang;
+
+ echo '<span class="bold">'.$lang['srv_notifications_recieved'].':</span>';
+
+ // Napolnimo array prejetih sporocil
+ $recievedMessages = array();
+
+ $sql = sisplet_query("SELECT n.id AS id, n.recipient AS recipient, n.viewed AS viewed, m.id AS message_id, m.date AS date, m.title AS title, m.text AS text
+ FROM srv_notifications n, srv_notifications_messages m
+ WHERE n.recipient='".$global_user_id."' AND n.message_id=m.id
+ ORDER BY m.date DESC");
+ while($row = mysqli_fetch_array($sql)){
+ $recievedMessages[$row['id']] = $row;
+ }
+
+
+ echo '<ul>';
+
+ if(count($recievedMessages) > 0){
+ foreach($recievedMessages as $message){
+ echo '<a href="#" onclick="viewMessage(\''.$message['id'].'\'); return false;">';
+ echo '<li class="'.($message['viewed'] == 0 ? ' unread':'').' '.($active > 0 && $message['id'] == $active ? ' active':'').'">';
+
+ echo '<span class="bold">'.$message['title'].' <span class="italic">('.$message['date'].')</span></span>';
+
+ $text = strip_tags((strlen($message['text']) > 70) ? substr($message['text'], 0, 70).'...' : $message['text']);
+ echo '<br />'.$text;
+
+ echo '</li>';
+ echo '</a>';
+ }
+ }
+
+ echo '</ul>';
+ }
+
+ private function displaySentMessages(){
+ global $admin_type, $global_user_id, $lang;
+
+ echo '<span class="bold">'.$lang['srv_notifications_sent'].':</span>';
+
+ // Napolnimo array poslanih sporocil
+ $sentMessages = array();
+
+ $sql = sisplet_query("SELECT * FROM srv_notifications_messages WHERE author='".$global_user_id."' ORDER BY date DESC");
+ while($row = mysqli_fetch_array($sql)){
+ $sentMessages[$row['id']] = $row;
+ }
+
+
+ echo '<ul>';
+
+ if(count($sentMessages) > 0){
+ foreach($sentMessages as $message_id => $message){
+ //echo '<li '.($message['viewed'] == 0 ? ' class="unread"':'').'>';
+ echo '<li>';
+
+ echo '<span class="bold">'.$message['title'].' <span class="italic">('.$message['date'].')</span></span>';
+
+ $text = strip_tags((strlen($message['text']) > 70) ? substr($message['text'], 0, 70).'...' : $message['text']);
+ echo '<br />'.$text;
+
+ // Gumb da se sporocilo razresi vsem (kot da so ga pregledali)
+ $sqlN = sisplet_query("SELECT message_id FROM srv_notifications WHERE message_id='".$message_id."' AND viewed='0'");
+ $count = mysqli_num_rows($sqlN);
+ if($count > 0){
+ echo '<br />';
+ echo '<a href="#" onclick="resolveMessages(\''.$message_id.'\'); return false;"><span class="link">'.$lang['srv_notifications_sent_resolve'].' ('.$count.')'.'</span></a>';
+ }
+
+ echo '</li>';
+ }
+ }
+
+ echo '</ul>';
+ }
+
+ // Obrazec za posiljanje sporocila
+ private function sendMessageForm($note=''){
+ global $admin_type, $global_user_id, $lang;
+
+ echo '<div class="send_form">';
+ echo '<span class="clr bold">'.$lang['srv_notifications_send_reciever'].': </span><input type="text" name="recipient" id="recipient">';
+
+ // Checkboxa za posiljenje vsem uporabnikoom (slo in ang)
+ echo '<div style="padding-top:5px;"><input type="checkbox" value="1" name="recipient_all_slo" id="recipient_all_slo" onClick="recipient_all_disable_email();"> <label for="recipient_all_slo"><span class="clr bold">'.$lang['srv_notifications_send_all_slo'].'</span></label></div>';
+ echo '<div style="padding-top:5px;"><input type="checkbox" value="1" name="recipient_all_ang" id="recipient_all_ang" onClick="recipient_all_disable_email();"> <label for="recipient_all_ang"><span class="clr bold">'.$lang['srv_notifications_send_all_ang'].'</span></label></div><br />';
+
+ echo '<span class="clr bold">'.$lang['srv_notifications_send_title'].': </span><input type="text" name="title"><br /><br />';
+ echo '<span class="clr bold">'.$lang['srv_notifications_send_text'].': </span><textarea name="notification"></textarea><br />';
+
+ // Avtomatsko prikaži obvestilo po prijavi
+ echo '<div style="padding-top:5px;"><input type="checkbox" value="1" name="force_show" id="force_show"> <label for="force_show"><span class="clr bold">'.$lang['srv_notifications_force_show'].'</span></label></div><br />';
+
+ echo '<span class="buttonwrapper floatLeft spaceRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="sendNotification(); return false;">';
+ echo '<span>'.$lang['srv_notifications_send'].'</span>';
+ echo '</a></span>';
+
+ if($note != ''){
+ echo '<br /><br />';
+ echo '<span class="bold red">'.$note.'</span>';
+ }
+
+ echo '</div>';
+ }
+
+
+ // Vrnemo stevilo sporocil
+ public function countMessages($type='unread'){
+ global $global_user_id;
+
+ $count = 0;
+
+ switch($type){
+ case 'recieved':
+ $sql = sisplet_query("SELECT COUNT(*) AS count FROM srv_notifications WHERE recipient='$global_user_id' AND viewed='1'");
+ break;
+
+ case 'sent':
+ $sql = sisplet_query("SELECT COUNT(n.*) AS count FROM srv_notifications n, srv_notifications_messages m WHERE m.author='$global_user_id' AND m.id=n.message_id");
+ break;
+
+ case 'unread':
+ default:
+ $sql = sisplet_query("SELECT COUNT(*) AS count FROM srv_notifications WHERE recipient='$global_user_id' AND viewed='0'");
+ break;
+ }
+
+
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_array($sql);
+ $count = $row['count'];
+ }
+
+ return $count;
+ }
+
+ // Preveri ce avtomatsko prikaze sporocilo po prijavi
+ public function checkForceShow(){
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT m.force_show FROM srv_notifications n, srv_notifications_messages m WHERE n.message_id=m.id AND n.recipient='$global_user_id' AND n.viewed='0' AND m.force_show='1'");
+
+ if(mysqli_num_rows($sql) > 0)
+ return true;
+ else
+ return false;
+ }
+
+
+ public function ajax() {
+ global $global_user_id;
+
+ switch ($_GET['a']) {
+ case 'sendNotification':
+ $this->ajax_sendNotification();
+ break;
+ case 'viewMessage':
+ $this->ajax_viewMessage();
+ break;
+ case 'viewUnreadMessages':
+ $this->ajax_viewUnreadMessages();
+ break;
+ case 'viewGDPRMessage':
+ $this->ajax_viewGDPRMessage();
+ break;
+ case 'saveGDPRAgree':
+ $this->ajax_saveGDPRAgree();
+ break;
+ case 'resolveMessages':
+ $this->ajax_resolveMessages();
+ break;
+ default:
+ break;
+ }
+ }
+
+ public function ajax_sendNotification(){
+ global $lang, $global_user_id;
+
+ if(isset($_POST['recipient']))
+ $recipient = $_POST['recipient'];
+ if(isset($_POST['recipient_all_slo']))
+ $recipient_all_slo = $_POST['recipient_all_slo'];
+ if(isset($_POST['recipient_all_ang']))
+ $recipient_all_ang = $_POST['recipient_all_ang'];
+ if(isset($_POST['title']))
+ $title = $_POST['title'];
+ if(isset($_POST['notification']))
+ $notification = $_POST['notification'];
+ if(isset($_POST['force_show']))
+ $force_show = $_POST['force_show'];
+
+
+ // Ce posiljamo vsem uporabnikom nimamo maila
+ if($recipient_all_slo == 1 || $recipient_all_ang == 1){
+
+ // Dodamo novo sporocilo v bazo
+ $sql = sisplet_query("INSERT INTO srv_notifications_messages (author, date, title, text, force_show) VALUES ('".$global_user_id."', NOW(), '".$title."', '".$notification."', '".$force_show."')");
+ $message_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $note = '';
+
+ // Loop cez vse uporabnike v bazi - vsakemu dodamo sporocilo
+ if($recipient_all_slo == 1 && $recipient_all_ang == 1)
+ $sqlU = sisplet_query("SELECT id, name, surname, email FROM users WHERE status!='0' AND status!='5' AND status!='6'");
+ elseif($recipient_all_ang == 1)
+ $sqlU = sisplet_query("SELECT id, name, surname, email FROM users WHERE status!='0' AND status!='5' AND status!='6' AND lang='2'");
+ else
+ $sqlU = sisplet_query("SELECT id, name, surname, email FROM users WHERE status!='0' AND status!='5' AND status!='6' AND lang='1'");
+ while($rowU = mysqli_fetch_array($sqlU)){
+
+ $sql = sisplet_query("INSERT INTO srv_notifications (message_id, recipient, viewed) VALUES ('".$message_id."', '".$rowU['id']."', '0')");
+ if(!$sql)
+ $note .= mysqli_error($GLOBALS['connect_db']).'<br />';
+ }
+ }
+ // Posiljamo na specificen mail
+ else{
+ // Dobimo user id glede na vnesen mail prejemnika
+ $sqlU = sisplet_query("SELECT id, name, surname, email FROM users WHERE email='$recipient'");
+ if(mysqli_num_rows($sqlU) > 0){
+ $rowU = mysqli_fetch_array($sqlU);
+
+ // Dodamo novo sporocilo v bazo
+ $sql = sisplet_query("INSERT INTO srv_notifications_messages (author, date, title, text, force_show) VALUES ('".$global_user_id."', NOW(), '".$title."', '".$notification."', '".$force_show."')");
+ $message_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ // Dodamo novo sporocilo v bazo
+ $sql = sisplet_query("INSERT INTO srv_notifications (message_id, recipient, viewed) VALUES ('".$message_id."', '".$rowU['id']."', '0')");
+ if(!$sql)
+ $note = mysqli_error($GLOBALS['connect_db']);
+ else
+ $note = 'Sporočilo je bilo uspešno poslano uporabniku '.$recipient.' ('.$rowU['name'].' '.$rowU['surname'].').';
+ }
+ else{
+ $note = 'Vnešeni email ('.$recipient.') ne pripada nobenemu uporabniku!';
+ }
+ }
+
+ // Refresh vseh poslanih sporocil
+ echo '<div class="sent_list">';
+ $this->displaySentMessages();
+ echo '</div>';
+
+ // Refresh obrazca za posiljanje sporocil
+ $this->sendMessageForm($note);
+
+ echo '<div class="clr"></div>';
+ }
+
+ public function ajax_resolveMessages(){
+
+ if(isset($_POST['id']))
+ $message_id = $_POST['id'];
+
+ // Oznacimo sporocila kot pregledana
+ $sql = sisplet_query("UPDATE srv_notifications SET viewed='1' WHERE message_id='$message_id'");
+
+ $this->displaySentMessages();
+ }
+
+ public function ajax_viewMessage(){
+ global $lang, $global_user_id;
+
+ if(isset($_POST['id']))
+ $id = $_POST['id'];
+
+
+ // Oznacimo sporocilo kot pregledano
+ $sql = sisplet_query("UPDATE srv_notifications SET viewed='1' WHERE id='$id'");
+
+ // Dobimo sporocilo
+ $sql = sisplet_query("SELECT n.id AS id, m.title AS title, m.text AS text, m.date AS date
+ FROM srv_notifications n, srv_notifications_messages m
+ WHERE n.id='$id' AND m.id=n.message_id");
+ $row = mysqli_fetch_array($sql);
+
+ // Refresh vseh prejetih sporocil
+ echo '<div class="recieved_list">';
+ $this->displayRecievedMessages($active=$id);
+ echo '</div>';
+
+ // Prikaz izbranega sporocila
+ echo '<div id="message">';
+ echo '<span class="bold">'.$row['title'].' <span class="italic">('.$row['date'].')</span></span>';
+ echo '<p>'.nl2br($row['text']).'</p>';
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+ }
+
+ public function ajax_viewUnreadMessages(){
+ global $lang, $global_user_id;
+
+ echo '<h2>'.$lang['srv_notifications_unread'].'</h2>';
+
+ echo '<ul>';
+
+ // Loop cez vsa neprebrana sporocila
+ $sql = sisplet_query("SELECT n.id AS id, m.title AS title, m.text AS text, m.date AS date, n.viewed AS viewed
+ FROM srv_notifications n, srv_notifications_messages m
+ WHERE n.recipient='".$global_user_id."' AND n.viewed='0' AND m.id=n.message_id
+ ORDER BY m.date DESC");
+ while($row = mysqli_fetch_array($sql)){
+ echo '<li class="'.($row['viewed'] == 0 ? ' unread':'').' '.($active > 0 && $row['id'] == $active ? ' active':'').'">';
+
+ echo '<span class="bold">'.$row['title'].' <span class="italic">('.$row['date'].')</span></span>';
+
+ echo '<br />'.nl2br($row['text']);
+
+ echo '</li>';
+ }
+
+ echo '</ul>';
+
+
+ // Gumb za zapiranje
+ echo '<div class="buttons_holder">';
+ echo '<div class="buttonwrapper" title="'.$lang['srv_zapri'].'">';
+ echo '<a class="ovalbutton ovalbutton" onclick="closeUnreadMessages(); return false;" href="#">';
+ echo '<span>'.$lang['srv_zapri'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+
+ // Oznacimo sporocilo kot pregledano
+ $sql = sisplet_query("UPDATE srv_notifications SET viewed='1' WHERE recipient='".$global_user_id."' AND viewed='0'");
+ }
+
+ public function ajax_viewGDPRMessage(){
+ global $lang, $global_user_id, $aai_instalacija;
+
+ echo '<h2>'.$lang['srv_notifications_unread'].'</h2>';
+
+ echo '<ul>';
+ echo '<li class="unread active">';
+
+ if(isset($aai_instalacija) && $aai_instalacija == true){
+ echo '<span class="bold">'.$lang['srv_gdpr_notification_title_aai'].'</span>';
+ }
+ else{
+ echo '<span class="bold">'.$lang['srv_gdpr_notification_title'].'</span>';
+ }
+
+ echo '<br /><br />';
+
+ echo $lang['srv_gdpr_notification_text1'];
+
+ echo '<br /><br />';
+
+ echo $lang['srv_gdpr_notification_question'];
+ echo '<br />';
+ echo '<div class="spaceLeft gdpr_popup_radio"><input type="radio" name="gdpr_agree" id="gdpr_agree_1" value="1" onClick="enableGDPRPopupButton();"> <label for="gdpr_agree_1">'.$lang['srv_gdpr_notification_da'].'</label></div>';
+ //echo ' <a href="#" onClick="toggleGDPRMore();"><span class="bold">'.$lang['srv_invitation_nonActivated_more'].'</span></a>';
+ echo '<div class="spaceLeft gdpr_popup_radio"><input type="radio" name="gdpr_agree" id="gdpr_agree_0" value="0" onClick="enableGDPRPopupButton();"> <label for="gdpr_agree_0">'.$lang['srv_gdpr_notification_ne'].'</label></div>';
+
+ echo '<div class="italic red gdpr_popup_radio">'.$lang['srv_gdpr_notification_reminder'].'</div>';
+
+ echo '<br />';
+
+ echo $lang['srv_gdpr_notification_pogoji'];
+
+ echo '</li>';
+ echo '</ul>';
+
+
+ // Gumb za zapiranje
+ //echo '<div class="floatRight spaceRight" id="GDPR_popup_button">';
+ echo '<div class="floatRight spaceRight" id="GDPR_popup_button" style="visibility: hidden;">';
+ echo '<div class="buttonwrapper" title="'.$lang['save'].'">';
+ echo '<a class="ovalbutton ovalbutton" onclick="saveGDPRMessage();" href="#">';
+ echo '<span>'.$lang['save'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+ }
+
+ public function ajax_saveGDPRAgree(){
+ global $global_user_id;
+
+ if(isset($_POST['gdpr_agree']))
+ $gdpr_agree = $_POST['gdpr_agree'];
+
+ // Oznacimo sporocila kot pregledana
+ $sql = sisplet_query("UPDATE users SET gdpr_agree='".$gdpr_agree."' WHERE id='".$global_user_id."'");
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.Prevajanje.php b/admin/survey/classes/class.Prevajanje.php
new file mode 100644
index 0000000..7b0ac67
--- /dev/null
+++ b/admin/survey/classes/class.Prevajanje.php
@@ -0,0 +1,1047 @@
+<?php
+
+/**
+*
+* Prevajanje ankete za vecjezikovno podporo
+*
+*/
+
+class Prevajanje {
+
+ var $anketa; // trenutna anketa
+
+ var $db_table = '';
+
+ var $lang_admin; // lang admin
+ var $lang_resp; // lang resp
+
+ var $lang_id = 0; // id languaga, ki ga trenutno prevajamo
+
+ var $Survey = null;
+ var $Branching = null;
+
+ var $user_dostop_edit = null; // aktivni uporabniki, pasivni lahko prevajajo samo dodeljene jezike
+
+ /**
+ * konstruktor
+ *
+ * @param mixed $anketa
+ * @return Vprasanje
+ */
+ function __construct ($anketa = 0) {
+ global $lang; // lang admin
+ global $lang1; // lang resp
+ global $lang2; // lang, ki ga prevajamo
+ global $global_user_id;
+ global $admin_type;
+
+ if (isset ($_GET['anketa']))
+ $this->anketa = $_GET['anketa'];
+ elseif (isset ($_POST['anketa']))
+ $this->anketa = $_POST['anketa'];
+ if ($anketa != 0)
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ SurveySetting::getInstance()->Init($this->anketa);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $this->lang_admin = $row['lang_admin'];
+ $this->lang_resp = $row['lang_resp'];
+
+ if (isset($_REQUEST['lang_id']))
+ $this->lang_id = $_REQUEST['lang_id'];
+
+ $this->include_lang($this->lang_resp);
+ $lang1 = $lang;
+
+ if ($this->lang_id > 0) {
+ $this->include_second_lang();
+ $lang2 = $lang;
+ }
+
+ $this->include_base_lang();
+ }
+
+ function dostop () {
+ global $admin_type;
+ global $global_user_id;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ $manage = '';
+ if ($admin_type <= 1) $manage = " OR uid IN (SELECT user FROM srv_dostop_manage WHERE manager = '$global_user_id')";
+
+ $sql = sisplet_query("SELECT ank_id, uid FROM srv_dostop WHERE ank_id = '$this->anketa' AND dostop LIKE '%edit%' AND (uid='$global_user_id' $manage )");
+ if (mysqli_num_rows($sql) > 0)
+ $this->user_dostop_edit = 1;
+ else
+ $this->user_dostop_edit = 0;
+
+
+ if ($this->user_dostop_edit == 1 || $admin_type <= $rowa['dostop']) {
+ // vse ok
+ $this->user_dostop_edit = 1; // ce je admin in ima dostop, potem je aktiven (ni pa vpisan v srv_dostop)
+ } else {
+ if (count($this->get_all_translation_langs())==0) // ce pasivni uporabnik nima dodeljenega nobenega jezika
+ die('No access language');
+ $this->user_dostop_edit = 0; // to niti ni treba, ampak zarad lepsga, ce je ze zgoraj :)
+ }
+ }
+
+ /**
+ * starting point za prevajanje
+ *
+ */
+ function prevajaj () {
+ global $lang; // admin-default lang
+ global $lang1; // respondent lang
+ global $lang2; // lang ki ga prevajamo
+
+ $this->dostop();
+
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ if ($rowa['multilang'] == 1) {
+
+ // default je pač prvi jezik v seznamu...
+ if ($this->lang_id==0) {
+ $lang_array = $this->get_all_translation_langs();
+ if (count($lang_array) > 0) {
+ list($this->lang_id) = each($lang_array);
+
+ // redirectamo, da je nastavljen tudi v urlju
+ header("Location: index.php?anketa=".$this->anketa."&a=prevajanje&lang_id=".$this->lang_id);
+
+ $this->include_lang($this->lang_resp);
+ $lang1 = $lang;
+
+ $this->include_second_lang();
+ $lang2 = $lang;
+
+ $this->include_base_lang();
+ }
+ }
+ }
+
+
+ $this->top_settings();
+
+ $sql = sisplet_query("SELECT * FROM srv_language WHERE ank_id = '$this->anketa'");
+ if (mysqli_num_rows($sql) == 0) {
+
+ //$this->dodaj_jezik(1);
+
+ } else {
+
+ if ($rowa['multilang'] == 1) {
+
+ $this->urejanje();
+
+ ?><script> var srv_meta_lang_id = <?=$this->lang_id?>; </script><?
+ }
+ }
+ }
+
+ /**
+ * Zgornje nastavitve in opcije pri prevajanju.
+ *
+ */
+ function top_settings () {
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $admin_type;
+ global $global_user_id;
+
+ SurveySetting::getInstance()->Init($this->anketa);
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $lang_admin = $row['lang_admin'];
+ $lang_resp = $row['lang_resp'];
+ $lang_array = array();
+ // Preberemo razpoložljive jezikovne datoteke
+ if ($dir = opendir($site_path . 'lang')) {
+ while (($file = readdir($dir)) !== false) {
+ if ($file != '.' AND $file != '..') {
+ if (is_numeric(substr($file, 0, strpos($file, '.')))) {
+ $i = substr($file, 0, strpos($file, '.'));
+ if ($i > 0) {
+ $file = '../../lang/'.$i.'.php';
+ @include($file);
+ $lang_array[$i] = $lang['language'];
+ }
+ }
+ }
+ }
+ }
+
+ // nastavimo jezik nazaj
+ if ($lang_admin > 0) {
+ $file = '../../lang/'.$lang_admin.'.php';
+ @include($file);
+ }
+
+
+ /**
+ * Leva stran nastavitev
+ */
+
+ echo '<fieldset class="wide prevajanje" style="position:relative">';
+
+ if ($this->user_dostop_edit == 1) {
+
+ echo '<legend>' . $lang['srv_language_settings'] . '</legend>';
+ echo '<form autocomplete="off" method="post" action="ajax.php?a=editanketasettings" name="settingsanketa_'.$row['id'].'">';
+
+ echo ' <input type="hidden" value="'.$row['id'].'" name="anketa">
+ <input type="hidden" value="" name="grupa">
+ <input type="hidden" value="prevajanje" name="location">
+ <input type="hidden" value="1" name="submited">';
+
+
+ asort($lang_array);
+
+ echo '<p><span class="nastavitveSpan1">'.$lang['srv_language_respons_1'].': </span><select name="lang_resp" onchange="document.settingsanketa_' . $row['id'] . '.submit(); return false;">';
+ foreach ($lang_array AS $key => $val) {
+ echo '<option value="'.$key.'" '.($key==$lang_resp?' selected':'').'>'.$val.'</option>';
+ }
+ echo '</select> <a href="index.php?anketa='.$this->anketa.'&a=jezik">'.$lang['srv_extra_translations'].'</a></p>' . "\n\r";
+
+ $resp_change_lang = SurveySetting::getInstance()->getSurveyMiscSetting('resp_change_lang');
+
+ if ($this->lang_id != 0) {
+
+ echo '<p><span class="nastavitveSpan1"><label for="">'.$lang['srv_resp_change_lang'].':</label> </span>
+ <label for="resp_change_lang_0"><input type="radio" name="resp_change_lang" id="resp_change_lang_0" value="0" '.($resp_change_lang==0?' checked':'').' onchange="document.settingsanketa_' . $row['id'] . '.submit(); return false;" />'.$lang['no'].'</label>
+ <label for="resp_change_lang_1"><input type="radio" name="resp_change_lang" id="resp_change_lang_1" value="1" '.($resp_change_lang==1?' checked':'').' onchange="document.settingsanketa_' . $row['id'] . '.submit(); return false;" />'.$lang['yes'].'</label></p>';
+
+ if($resp_change_lang==1){
+ $resp_change_lang_type = SurveySetting::getInstance()->getSurveyMiscSetting('resp_change_lang_type');
+
+ echo '<p>';
+
+ echo '<span class="nastavitveSpan1"><label for="">'.$lang['srv_resp_change_lang_type'].':</label> </span>
+ <label for="resp_change_lang_type_0"><input type="radio" name="resp_change_lang_type" id="resp_change_lang_type_0" value="0" '.($resp_change_lang_type==0?' checked':'').' onchange="document.settingsanketa_' . $row['id'] . '.submit(); return false;" />'.$lang['srv_resp_change_lang_type_0'].'</label>
+ <label for="resp_change_lang_type_1"><input type="radio" name="resp_change_lang_type" id="resp_change_lang_type_1" value="1" '.($resp_change_lang_type==1?' checked':'').' onchange="document.settingsanketa_' . $row['id'] . '.submit(); return false;" />'.$lang['srv_resp_change_lang_type_1'].'</label>';
+
+ echo '</p>';
+ }
+ }
+ else {
+ echo '<a href="index.php?anketa='.$this->anketa.'" style="position:absolute; top:0px; right:10px">'.$lang['srv_back_edit'].'</a>';
+ }
+
+ // Jezik administrativnega vmesnika
+ echo '<div style="position:absolute; right:20px; bottom:10px;"><span class="bold">';
+ //printf ($lang['srv_language_admin_survey2'], 'index.php?anketa='.$this->anketa.'&a=nastavitve');
+ echo '<a href="index.php?anketa='.$this->anketa.'&a=nastavitve">'.$lang['srv_language_admin_survey'].'</a>';
+ echo '</span></div>';
+
+ echo '</form>';
+ }
+
+ echo '</fieldset>';
+
+
+ /**
+ * Desna stran
+ */
+ echo '<fieldset class="wide prevajanje" style="position:relative; float:right;"><legend>'.$lang['srv_multilang'].'</legend>';
+
+ if ($this->lang_id != 0) {
+ $lang_array = $this->get_all_translation_langs();
+
+ foreach ($lang_array AS $key => $l) {
+ echo '<p>';
+
+ echo '<a href="index.php?anketa='.$this->anketa.'&a=prevajanje&lang_id='.$key.'" style="font-size: 1.2em; display:inline-block; min-width: 150px; '.($this->lang_id==$key?' font-weight:bold':'').'">'.$l.'</a> ';
+
+ echo '<span class="prevajanje_settings '.($key!=$this->lang_id?'transparent':'').'">';
+
+ echo '<a href="'.SurveyInfo::getSurveyLink().'?language='.$key.'&preview=on" target="_blank" title="'.$lang['srv_poglejanketo'].': '.$lang['srv_preview_text'].'"><span class="faicon preview large"></span> '.$lang['srv_poglejanketo2'].'</a>&nbsp;&nbsp;-&nbsp;&nbsp;';
+ echo '<a href="'.SurveyInfo::getSurveyLink().'?language='.$key.'&preview=on&testdata=on" target="_blank" title="'.$lang['srv_survey_testdata2'].': '.$lang['srv_testdata_text'].'"><span class="faicon edit_square large"></span> '.$lang['srv_test'].'</a>&nbsp;&nbsp;-&nbsp;&nbsp;';
+ echo '<a href="'.SurveyInfo::getSurveyLink().'?language='.$key.'" target="_blank" title="'.$lang['url'].': '.SurveyInfo::getSurveyLink().'?language='.$key.'"><span class="faicon data_link_small large"></span> '.$lang['url'].'</a>&nbsp;&nbsp;-&nbsp;&nbsp;';
+
+ // Pdf in rtf izvoz vprasalnika v tujem jeziku
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=vprasalnik_pdf&anketa='.$this->anketa.'&type=1&language='.$key).'" target="_blank" title="'.$lang['PDF_Izpis'].'"><span class="faicon pdf large"></span> '.$lang['srv_export_hover_pdf'].'</a>&nbsp;&nbsp;-&nbsp;&nbsp;';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=vprasalnik_rtf&anketa='.$this->anketa.'&type=1&language='.$key).'" target="_blank" title="'.$lang['RTF_Izpis'].'"><span class="faicon rtf large"></span> '.$lang['srv_export_hover_rtf'].'</a>';
+
+ $d = new Dostop();
+ if ($d->checkDostopSub('edit')) {
+
+ echo '<span class="prevajanje_settings_sub">';
+
+ echo '<a href="index.php?anketa='.$this->anketa.'&a=jezik&lang_id='.$key.'"><span class="faicon compress"></span> '.$lang['srv_extra_translations'].'</a>';
+
+ $title = '';
+ $sqlu = sisplet_query("SELECT uid FROM srv_dostop_language WHERE ank_id='$this->anketa' AND lang_id='$key'");
+ while ($rowu = mysqli_fetch_array($sqlu)) {
+ $sql1 = sisplet_query("SELECT name, surname, email FROM users WHERE id = '$rowu[uid]'");
+ $row1 = mysqli_fetch_array($sql1);
+ if ($title != '') $title .= ', ';
+ $title .= $row1['name'].' '.$row1['surname'].' ('.$row1['email'].')';
+ }
+
+ echo '&nbsp;&nbsp;-&nbsp;&nbsp;<a href="index.php?anketa='.$this->anketa.'&a=dostop" title="'.$lang['srv_passive_multilang_1'].': '.$title.'"><span class="faicon users_small"></span> '.$lang['srv_users'].'</a>';
+
+ if ($this->user_dostop_edit == 1)
+ echo '&nbsp;&nbsp;-&nbsp;&nbsp;<a href="ajax.php?anketa='.$this->anketa.'&t=prevajanje&a=brisi_jezik&lang_id='.$key.'" onclick="if (!confirm(\''.$lang['srv_lang_rem_confirm'].'\')) return false"><span class="faicon delete_circle icon-orange"></span> '.$lang['srv_lang_rem'].'</a></span>';
+
+ echo '</span>';
+ }
+
+ echo '</span>';
+
+ echo '</p>';
+ }
+ }
+
+ // Dodajanje novega jezika
+ $this->dodaj_jezik();
+
+ echo '</fieldset>';
+
+
+ echo '<div class="clr"></div><p></p>';
+ }
+
+ /**
+ * opcija za dodajanje novega jezika -- ima svoj <form> zato ne more biti znotraj drugega forma
+ *
+ */
+ function dodaj_jezik ($first_page=0) {
+ global $lang;
+ global $lang1;
+
+ if ($this->user_dostop_edit == 1) {
+ // ok
+ } else return;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $lang_array = $this->get_all_available_langs();
+
+ asort($lang_array);
+
+ //echo '<form action="ajax.php?anketa='.$this->anketa.'&t=prevajanje&a=dodaj_jezik" method="post" name="dodaj_jezik" style="position:absolute; right:10px; top:0">';
+ echo '<form action="ajax.php?anketa='.$this->anketa.'&t=prevajanje&a=dodaj_jezik" method="post" name="dodaj_jezik" >';
+ echo '<p><span class="bold">'.$lang['srv_prevajanje_dodaj'].': </span> ';
+ echo '<select name="lang_id">';
+ echo '<option value="0"></option>';
+ foreach ($lang_array AS $key => $l) {
+ echo '<option value="'.$key.'">'.$l.'</option>';
+ }
+ echo '</select> ';
+
+ echo '<input type="submit" value="'.$lang['srv_add_new_language'].'" />';
+
+ echo '</p>';
+ echo '</form>';
+ }
+
+ /**
+ * spremeni jezik, ki ga trenutno prevajamo
+ *
+ */
+ function spremeni_jezik () {
+ global $lang;
+ global $site_url;
+
+ //echo '<select name="lang_id" onchange="window.location=\'index.php?anketa='.$this->anketa.'&a=prevajanje'.($this->user_aktiven==0?'2':'').'&lang_id=\'+this.value">';
+
+ }
+
+ /**
+ * prikaz seznama za prevajanje
+ *
+ */
+ function urejanje () {
+ global $lang;
+ global $lang1;
+
+ /*echo '<div style="float:right">';
+ $this->dodaj_jezik();
+ echo '</div>';*/
+
+ echo '<fieldset style="margin-top:40px; min-width:1100px;" class="locked">';
+
+ /**
+ * Leva stran
+ */
+ echo '<div class="jezik_left noborder" style="opacity:1; margin-bottom:30px;">';
+ echo '<span class="red" style="font-weight:bold; font-size:1.2em;">'.$lang['srv_base_lang'].': <span style="font-size:1em">'.$lang1['language'];
+ echo '</span></span>';
+ $d = new Dostop();
+ if ($d->checkDostopSub('edit'))
+ echo ' - '.$lang['srv_edit_in_edit'].' <a href="index.php?anketa='.$this->anketa.'">'.$lang['srv_urejanje'].'</a>';
+ echo '</div>';
+
+ /**
+ * Desna stran
+ */
+ echo '<div class="jezik_right noborder">';
+
+ echo '<span class="red" style="font-weight:bold; font-size:1.2em;">'.$lang['srv_trans_lang'].': ';
+
+ $lang_array = $this->get_all_translation_langs();
+ echo '<span style="font-size:1em">'.$lang_array[$this->lang_id].'</span>';
+
+ echo '</span>';
+
+ echo '</div>';
+
+
+ // Prevajanje imena ankete
+ $this->urejanje_texti();
+
+ // Prevajanje vprasanj
+ $this->urejanje_vprasanja();
+
+ echo '</fieldset>';
+
+ echo '<div class="clr"></div>';
+
+ ?><script>
+ prevajanje_bind_click();
+ </script><?
+ }
+
+ /**
+ * urejanje naslova ankete
+ *
+ */
+ function urejanje_texti () {
+ global $lang;
+
+ echo '<div class="clr"></div>';
+ echo '<div class="jezik_left noborder"><h2 class="jezik_page">'.$lang['srv_novaanketa_kratkoime'].'</h2></div>';
+ echo '<div class="jezik_right noborder"><h2 class="jezik_page">'.$lang['srv_novaanketa_kratkoime'].'</h2></div>';
+
+ echo '<strong>';
+ $this->extra_translation('srv_novaanketa_kratkoime');
+ echo '</strong>';
+
+ $this->extra_translation('srv_anketa_opomba');
+ }
+
+ /**
+ * funkcija, ki prikaze polja za nastavitev ekstra prevodov
+ *
+ */
+ function extra_translation ($text) {
+ global $lang;
+ global $lang1;
+ global $lang2;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ if ($text == 'srv_novaanketa_kratkoime') { // akronim pri default jeziku je pac v srv_anketa
+ $value = (($row['akronim'] == null || $row['akronim'] == '') ? $row['naslov'] : $row['akronim'] );
+ } elseif ($text == 'srv_question_comment_text') { // "Vaš komentar k vprašanju" ni v lang, ampak je v settingsih
+ $value = SurveySetting::getInstance()->getSurveyMiscSetting('question_comment_text');
+ } elseif ($text == 'srv_anketa_opomba') {
+ $value = $row['intro_opomba'];
+ } else {
+ $value = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_'.$text);
+ if ($value == '') $value = $lang1[$text];
+ }
+
+ echo '<div class="jezik_left">';
+ echo '<p style="margin-left:10px">'.$value.'</p>';
+ echo '</div>';
+
+ echo '<div class="jezik_right srvlang" id="srvlang_'.$text.'">';
+ $this->edit_extra_translation($text, $value);
+ echo '</div>';
+
+ }
+
+ function edit_extra_translation ($text, $def='') {
+ global $lang;
+ global $lang2;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $value1 = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_'.$text.'_'.$this->lang_id);
+
+ if ($value1 == '' && $text != 'srv_anketa_opomba') $value1 = $def;
+
+ echo '<span style="margin-left: 10px; margin:10px; display:block; width:120px; float:left;">';
+ if ($text == 'srv_novaanketa_kratkoime')
+ echo $lang['srv_naslov'].': ';
+ if ($text == 'srv_anketa_opomba')
+ echo $lang['note'].' ('.$lang['srv_internal'].'): ';
+ echo '</span>';
+
+ echo '<p style="margin-left:10px; min-height:15px; min-width:200px; float:left; outline:1px dashed gray; cursor: text" class="editable" id="srvlang_'.$text.'_'.$this->lang_id.'" contenteditable="true" onblur="extra_translation_save(\''.$text.'\');">'.$value1.'</p>';
+ }
+
+ /**
+ * urejanje/prevajanje vprasanj
+ *
+ */
+ function urejanje_vprasanja () {
+ global $lang;
+
+ Cache::cache_all_srv_spremenljivka($this->anketa);
+
+ echo '<div class="clr"></div>';
+ echo '<div class="jezik_left noborder"><h2 class=" jezik_page">'.$lang['srv_intro_label'].'</h2></div>';
+ echo '<div class="jezik_right noborder"><h2 class=" jezik_page">'.$lang['srv_intro_label'].'</h2></div>';
+
+ $this->urejanje_vprasanje(-1);
+
+ $gru_id = 0;
+
+ $sql = sisplet_query("SELECT s.id, g.naslov, g.id AS gru_id, g.vrstni_red FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.visible='1' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ if ($gru_id != $row['gru_id']) {
+ echo '<div class="clr"></div>';
+ echo '<div class="jezik_left noborder"><h2 class=" jezik_page">'.$lang['srv_stran'].' '.$row['vrstni_red'].'</h2></div>';
+ echo '<div class="jezik_right noborder"><h2 class=" jezik_page">'.$lang['srv_stran'].' '.$row['vrstni_red'].'</h2></div>';
+
+ $gru_id = $row['gru_id'];
+ }
+
+ $this->urejanje_vprasanje($row['id']);
+ }
+
+ echo '<div class="clr"></div>';
+ echo '<div class="jezik_left noborder"><h2 class=" jezik_page">'.$lang['srv_end_label'].'</h2></div>';
+ echo '<div class="jezik_right noborder"><h2 class=" jezik_page">'.$lang['srv_end_label'].'</h2></div>';
+
+ $this->urejanje_vprasanje(-2);
+ }
+
+ /**
+ * prikaze urejanje vprasanja - na levi original in na desni za prevod
+ *
+ * @param mixed $spremenljivka
+ */
+ function urejanje_vprasanje ($spremenljivka) {
+ global $lang;
+ global $lang1;
+ global $lang2;
+
+ //******************************************
+ $row = Cache::srv_spremenljivka($spremenljivka);
+ //******************************************
+
+ // Shranimo originalen jezik vmesnika
+ $lang_bck = $lang;
+
+
+ include_once('../../main/survey/app/global_function.php');
+
+ if (empty($this->Survey->get)){
+ $this->Survey = new \App\Controllers\SurveyController(true);
+ save('forceShowSpremenljivka', true);
+ }
+ if ($this->Branching == null) {
+ $this->Branching = new Branching($this->anketa);
+ }
+
+
+ // LEVA STRAN PREVAJANJA
+ echo '<div class="jezik_left">';
+
+ $lang = $lang1;
+ save('lang_id', null); // null je default aka resp
+ $this->Branching->lang_id = null; // null je default aka resp
+ $this->Branching->locked = true;
+
+ if ($spremenljivka == -1)
+ $this->Branching->introduction_conclusion(-1);
+ elseif ($spremenljivka == -2)
+ $this->Branching->introduction_conclusion(-2);
+ else
+ $this->Branching->vprasanje($spremenljivka);
+
+ echo '</div>';
+
+
+ // DESNA STRAN PREVAJANJA
+ echo '<div class="jezik_right vprlang" id="vprlang_'.$spremenljivka.'">';
+
+ $lang = $lang2; // spremenimo language na language, ki ga prevajamo
+ save('lang_id', $this->lang_id);
+ $this->Branching->lang_id = $this->lang_id;
+ $this->Branching->locked = false;
+
+ if ($spremenljivka == -1)
+ $this->Branching->introduction_conclusion(-1);
+ elseif ($spremenljivka == -2)
+ $this->Branching->introduction_conclusion(-2);
+ else
+ $this->Branching->vprasanje($spremenljivka, true); //poklici izris vprasanja za prevajanje (za enkrat je drugi argument pomemben le za slider)
+
+ echo '</div>';
+
+
+ // Nastavimo nazaj originalen jezik vmesnika
+ $lang = $lang_bck;
+ }
+
+ /**
+ * prikaze formo za vpis prevoda
+ *
+ * @param mixed $spremenljivka
+ */
+ function vprasanje_prevod ($spremenljivka) {
+ global $lang;
+ global $lang2;
+
+ echo '<form name="vprasanje_prevod_'.$spremenljivka.'" id="vprasanje_prevod_'.$spremenljivka.'" method="post" onsubmit="vprasanje_prevod_save(\''.$spremenljivka.'\'); return false;">';
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'" />';
+ echo '<input type="hidden" name="lang_id" value="'.$this->lang_id.'" />';
+ echo '<input type="hidden" name="spremenljivka" value="'.$spremenljivka.'" />';
+
+ if ($spremenljivka < 0)
+ $row['tip'] = -1;
+ else
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ // spremenljivka - to majo vse spremenljivka
+ $this->vprasanje_spremenljivka($spremenljivka);
+
+
+ // grid - vse tabele
+ if ( in_array( $row['tip'], array(6, 16, 19, 20) ) ) {
+
+ $this->vprasanje_grid($spremenljivka);
+
+ }
+
+ // vrednost - vsa vprasanja, ki uporabljajo srv_vrednost
+ if ( in_array( $row['tip'], array(1, 2, 21, 7, 17, 18, 6, 16, 19, 20) ) ) {
+
+ $this->vprasanje_vrednost($spremenljivka);
+
+ }
+
+ // vsota - ma se svoje polje
+ if ( $row['tip'] == 18 ) {
+
+ $this->vprasanje_vsota($spremenljivka);
+
+ }
+
+ echo '<p><input type="submit" value="'.$lang['srv_potrdi'].'" /></p>';
+
+ echo '</form>';
+
+ }
+
+ /**
+ * prevod spremenljivka - naslov in info
+ *
+ * @param mixed $spremenljivka
+ */
+ function vprasanje_spremenljivka ($spremenljivka) {
+ global $lang;
+ global $lang2;
+
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ $sql1 = sisplet_query("SELECT naslov, info FROM srv_language_spremenljivka WHERE ank_id='$this->anketa' AND spr_id='$spremenljivka' AND lang_id='$this->lang_id'");
+ $row1 = mysqli_fetch_array($sql1);
+
+ if (strtolower(substr($row1['naslov'], 0, 3)) == '<p>' && strtolower(substr($row1['naslov'], -4)) == '</p>' && strrpos($row1['naslov'], '<p>') == 0) {
+ $row1['naslov'] = substr($row1['naslov'], 3);
+ $row1['naslov'] = substr($row1['naslov'], 0, -4);
+ }
+
+ if ($spremenljivka == -1) { // uvod
+
+ echo '<p>'.$lang2['srv_intro'].'<br /><textarea name="naslov">'.$row1['naslov'].'</textarea></p>';
+
+ } elseif ($spremenljivka == -2) { // zakljucek
+
+ echo '<p>'.$lang2['srv_end'].'<br /><textarea name="naslov">'.$row1['naslov'].'</textarea></p>';
+
+ } else { // obicna spremenljivka
+
+ echo '<p>'.$row['naslov'].'<br /><textarea name="naslov" style="width:99%">'.$row1['naslov'].'</textarea></p>';
+ echo '<p>'.$row['info'].'<br /><textarea name="info" style="height:12px; width:99%">'.$row1['info'].'</textarea></p>';
+ }
+ }
+
+ /**
+ * prevod vrednosti
+ *
+ * @param mixed $spremenljivka
+ */
+ function vprasanje_vrednost ($spremenljivka) {
+ global $lang;
+ global $lang2;
+
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ $sql1 = sisplet_query("SELECT id, naslov FROM srv_vrednost WHERE spr_id = '$spremenljivka' ORDER BY vrstni_red");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ $sql2 = sisplet_query("SELECT naslov FROM srv_language_vrednost WHERE ank_id='$this->anketa' AND vre_id='$row1[id]' AND lang_id='$this->lang_id'");
+ $row2 = mysqli_fetch_array($sql2);
+
+ echo '<p>'.$row1['naslov'].'<br /><textarea name="naslov_vrednost_'.$row1['id'].'" style="height:12px">'.$row2['naslov'].'</textarea></p>';
+ }
+ }
+
+ /**
+ * prevod za gride
+ *
+ * @param mixed $spremenljivka
+ */
+ function vprasanje_grid ($spremenljivka) {
+ global $lang;
+ global $lang2;
+
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ echo '<table style="padding-left:20px"><tr>';
+
+ $sql1 = sisplet_query("SELECT id, naslov FROM srv_grid WHERE spr_id = '$spremenljivka' ORDER BY vrstni_red");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ $sql2 = sisplet_query("SELECT naslov FROM srv_language_grid WHERE ank_id='$this->anketa' AND spr_id='$spremenljivka' AND grd_id='$row1[id]' AND lang_id='$this->lang_id'");
+ $row2 = mysqli_fetch_array($sql2);
+
+ echo '<td style="width:auto; padding:3px">'.$row1['naslov'].'<br /><textarea name="naslov_grid_'.$row1['id'].'" style="height:12px; width:100%">'.$row2['naslov'].'</textarea></td>';
+
+ }
+
+ echo '</tr></table>';
+ }
+
+ /**
+ * prevod za polje vsota
+ *
+ * @param mixed $spremenljivka
+ */
+ function vprasanje_vsota ($spremenljivka) {
+ global $lang;
+ global $lang2;
+
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ $sql1 = sisplet_query("SELECT vsota FROM srv_language_spremenljivka WHERE ank_id='$this->anketa' AND spr_id='$spremenljivka' AND lang_id='$this->lang_id'");
+ $row1 = mysqli_fetch_array($sql1);
+
+ echo '<p>'.$row['vsota'].'<br /><textarea name="vsota" style="height:12px">'.$row1['vsota'].'</textarea></p>';
+ }
+
+ /**
+ * vrne vse jezikovne datoteke, ki so nam se na voljo
+ *
+ */
+ function get_all_available_langs () {
+ global $lang;
+ global $site_path;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ // Dobimo vse jezike za katere obstaja jezikovna datoteka
+ include_once($site_path.'lang/jeziki.php');
+ $lang_array = $lang_all_global['ime'];
+
+ // pobrisemo jezike, ki so ze dodani, tudi default jezik
+ $sql1 = sisplet_query("SELECT lang_id FROM srv_language WHERE ank_id = '$this->anketa'");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ unset($lang_array[$row1['lang_id']]);
+ }
+ unset($lang_array[$row['lang_resp']]);
+
+ return $lang_array;
+ }
+
+ /**
+ * vrne vse jezike, ki so ze dodani
+ *
+ */
+ function get_all_translation_langs () {
+ global $lang;
+ global $global_user_id;
+ global $admin_type;
+
+ $lang_array = array();
+
+ if ($this->user_dostop_edit == 1)
+ $sql = sisplet_query("SELECT lang_id, language FROM srv_language WHERE ank_id = '$this->anketa'");
+ else
+ $sql = sisplet_query("SELECT * FROM srv_language l, srv_dostop_language d WHERE l.ank_id='$this->anketa' AND d.ank_id=l.ank_id AND d.lang_id=l.lang_id AND d.uid='$global_user_id'");
+
+ while ($row = mysqli_fetch_array($sql)) {
+ $lang_array[$row['lang_id']] = $row['language'];
+ }
+ return $lang_array;
+ }
+
+ /**
+ * nastavi jezik nazaj na osnovnega takrat, ko kaj delamo z includi ostalih jezikov
+ *
+ */
+ function include_base_lang() {
+ global $lang;
+
+ $this->include_lang($this->lang_admin);
+ }
+
+ /**
+ * includa jezik, ki ga prevajamo
+ *
+ */
+ function include_second_lang () {
+ global $lang;
+
+ $this->include_lang($this->lang_id);
+ }
+
+ /**
+ * includa podan jezik
+ *
+ * @param mixed $id
+ */
+ function include_lang ($id) {
+ global $lang;
+
+ if ($id > 0) {
+ $file = '../../lang/'.$id.'.php';
+ @include($file);
+ }
+ }
+
+ /**
+ * pohendla razne nastavitve, ki se postnejo
+ * ne gre nujno vse prek ajaxa, ene so tud navadne post
+ *
+ */
+ function ajax() {
+ global $lang;
+
+ if ($_GET['a'] == 'dodaj_jezik') {
+ $this->ajax_dodaj_jezik();
+
+ } elseif ($_GET['a'] == 'brisi_jezik') {
+ $this->ajax_brisi_jezik();
+
+ } elseif ($_GET['a'] == 'extra_translation') {
+ $this->ajax_extra_translation();
+
+ } elseif ($_GET['a'] == 'extra_translation_save') {
+ $this->ajax_extra_translation_save();
+
+ } elseif ($_GET['a'] == 'vprasanje_prevod') {
+ $this->ajax_vprasanje_prevod();
+
+ } elseif ($_GET['a'] == 'vprasanje_prevod_save') {
+ $this->ajax_vprasanje_prevod_save();
+
+ }
+ }
+
+ function ajax_dodaj_jezik () {
+ global $lang;
+
+ $lang_id = $_POST['lang_id'];
+ if (!$lang_id > 0) { header("Location: index.php?anketa=".$this->anketa."&a=prevajanje"); return; }
+
+ // "Jezik" v originalnem jeziku (preden prklopimo na novega z include)
+ $lang_string = $lang['lang'];
+
+ // Originalni jezik za respondente
+ $this->include_lang($this->lang_resp);
+ $base_lang_resp = $lang['language'];
+
+ $this->include_lang($lang_id);
+ $added_lang = $lang['language'];
+ $s = sisplet_query("UPDATE srv_anketa SET multilang='1' WHERE id='$this->anketa'");
+ $sql = sisplet_query("INSERT INTO srv_language (ank_id, lang_id, language) VALUES ('$this->anketa', '$lang_id', '$lang[language]')");
+
+
+ // Po novem dodamo tudi spremenljivko za jezik (najlazje za upostevanje if-ov in validacij)
+ // Na zacetku moramo ustvarit najprej vprasanje (ce ga se nimamo)
+ $sqlS = sisplet_query("SELECT s.id AS spr_id FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='$this->anketa' AND s.gru_id=g.id AND s.skupine='3'");
+ if(mysqli_num_rows($sqlS) == 0){
+
+ $sqlG = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='$this->anketa' AND vrstni_red='1'");
+ $rowG = mysqli_fetch_array($sqlG);
+ $gru_id = $rowG['id'];
+
+ $b = new Branching($this->anketa);
+ $spr_id = $b->nova_spremenljivka($grupa=$gru_id, $grupa_vrstni_red=1, $vrstni_red=0);
+
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET naslov='".$lang_string."', variable='language', variable_custom='1', skupine='3', sistem='1', visible='0', size='0' WHERE id='$spr_id'");
+
+ Vprasanje::change_tip($spr_id, 1);
+
+ // Dodamo se variablo za originalni jezik
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $spr_id;
+ $vre_id = $v->vrednost_new($base_lang_resp);
+ }
+ else{
+ $rowS = mysqli_fetch_array($sqlS);
+ $spr_id = $rowS['spr_id'];
+ }
+
+ // Dodamo se variablo za dodajani jezik
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $spr_id;
+ $vre_id = $v->vrednost_new($added_lang);
+
+ // Prestevilcimo in popravimo vrstni red
+ Common::repareVrednost($spr_id);
+ Common::prestevilci($spr_id);
+
+ header("Location: index.php?anketa=".$this->anketa."&a=prevajanje&lang_id=".$lang_id);
+
+ $this->include_base_lang();
+ }
+
+ function ajax_brisi_jezik () {
+ global $lang;
+
+ $lang_id = $_REQUEST['lang_id'];
+
+ sisplet_query("DELETE FROM srv_language WHERE ank_id='$this->anketa' AND lang_id='$lang_id'");
+
+ // Pobrisemo variablo iz vprasanja
+ $sqlS = sisplet_query("SELECT s.id AS spr_id FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='$this->anketa' AND s.gru_id=g.id AND s.skupine='3'");
+ $spr_id = 0;
+ if(mysqli_num_rows($sqlS) > 0){
+
+ $rowS = mysqli_fetch_array($sqlS);
+ $spr_id = $rowS['spr_id'];
+
+ $this->include_lang($lang_id);
+ $naslov = $lang['language'];
+ $this->include_base_lang();
+
+ $sqlV = sisplet_query("DELETE FROM srv_vrednost WHERE naslov='".$naslov."' AND spr_id='$spr_id'");
+ }
+
+ // Ce nimamo vec nobenega dodanega jezika
+ $sql = sisplet_query("SELECT * FROM srv_language WHERE ank_id='$this->anketa'");
+ if (mysqli_num_rows($sql) == 0){
+ sisplet_query("UPDATE srv_anketa SET multilang='0' WHERE id='$this->anketa'");
+
+ // Pobrisemo vse vrednosti (za vsak slucaj ce kaksna ostane) in potem se spremenljivko
+ if($spr_id > 0){
+ $sqlVDelete = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$spr_id'");
+ $sqlSDelete = sisplet_query("DELETE FROM srv_spremenljivka WHERE id='$spr_id'");
+ }
+ }
+ // Drugace prestevilcimo in popravimo vrstni red
+ elseif($spr_id > 0){
+ Common::repareVrednost($spr_id);
+ Common::prestevilci($spr_id);
+ }
+
+ header("Location: index.php?anketa=".$this->anketa."&a=prevajanje");
+ }
+
+ function ajax_extra_translation () {
+
+ $text = $_POST['text'];
+
+ $this->edit_extra_translation($text);
+ }
+
+ function ajax_extra_translation_save () {
+ global $lang2;
+
+ $value = $_POST['value'];
+ $text = $_POST['text'];
+
+ if ($value != '') {
+ $value = strip_tags($value);
+ SurveySetting::getInstance()->setSurveyMiscSetting('srvlang_'.$text.'_'.$this->lang_id, $value);
+
+ echo '<p>'.$value.'</p>';
+ }
+ else {
+ SurveySetting::getInstance()->removeSurveyMiscSetting('srvlang_'.$text.'_'.$this->lang_id);
+
+ echo '<p>'.$lang2[$text].'</p>';
+ }
+ }
+
+ function ajax_vprasanje_prevod () {
+
+ $spremenljivka = $_POST['spremenljivka'];
+
+ $this->vprasanje_prevod($spremenljivka);
+ }
+
+ function ajax_vprasanje_prevod_save () {
+ global $lang;
+ global $lang2;
+
+ $spremenljivka = $_POST['spremenljivka'];
+
+ $naslov = $_POST['naslov'];
+ $info = $_POST['info'];
+ $vsota = $_POST['vsota'];
+
+ if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }
+
+ // spremenljivka
+ if ($naslov!='' || $info!='' || $vsota!='')
+ sisplet_query("REPLACE INTO srv_language_spremenljivka (ank_id, spr_id, lang_id, naslov, info, vsota) VALUES ('$this->anketa', '$spremenljivka', '$this->lang_id', '$naslov', '$info', '$vsota')");
+ else
+ sisplet_query("DELETE FROM srv_language_spremenljivka WHERE ank_id='$this->anketa' AND spr_id='$spremenljivka' AND lang_id='$this->lang_id'");
+
+ // vrednost
+ $sql1 = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id = '$spremenljivka'");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ $naslov = $_POST['naslov_vrednost_'.$row1['id']];
+ if ($naslov != '')
+ $s = sisplet_query("REPLACE INTO srv_language_vrednost (ank_id, vre_id, lang_id, naslov) VALUES ('$this->anketa', '$row1[id]', '$this->lang_id', '$naslov')");
+ else
+ $s = sisplet_query("DELETE FROM srv_language_vrednost WHERE ank_id='$this->anketa' AND vre_id='$row1[id]' AND lang_id='$this->lang_id'");
+ }
+
+
+ // grid
+ $sql1 = sisplet_query("SELECT * FROM srv_grid WHERE spr_id = '$spremenljivka'");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ $naslov = $_POST['naslov_grid_'.$row1['id']];
+ if ($naslov != '')
+ $s = sisplet_query("REPLACE INTO srv_language_grid (ank_id, spr_id, grd_id, lang_id, naslov) VALUES ('$this->anketa', '$spremenljivka', '$row1[id]', '$this->lang_id', '$naslov')");
+ else
+ $s = sisplet_query("DELETE FROM srv_language_grid WHERE ank_id='$this->anketa' AND spr_id='$spremenljivka' AND grd_id='$row1[id]' AND lang_id='$this->lang_id'");
+ }
+
+ echo '<a href="" onclick="_vprasanje_prevod_preview=1; preview_spremenljivka(\''.$spremenljivka.'\', \''.$this->lang_id.'\'); return false;" style="float:right; margin:5px"><span class="faicon edit_square"></span></a>';
+
+ include_once('../../main/survey/app/global_function.php');
+ $this->Survey = new \App\Controllers\SurveyController(true);
+ save('forceShowSpremenljivka', true);
+ save('lang_id', $this->lang_id);
+
+ $lang = $lang2;
+ if ($spremenljivka == -1)
+ \App\Controllers\BodyController::getInstance()->displayIntroduction();
+ elseif ($spremenljivka == -2)
+ \App\Controllers\BodyController::getInstance()->displayKonec();
+ else
+ \App\Controllers\Vprasanja\VprasanjaController::getInstance()->displaySpremenljivka($spremenljivka);
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.RecodeValues.php b/admin/survey/classes/class.RecodeValues.php
new file mode 100644
index 0000000..eef65b0
--- /dev/null
+++ b/admin/survey/classes/class.RecodeValues.php
@@ -0,0 +1,971 @@
+<?php
+
+class RecodeValues {
+ private static $anketa = null; # trenutna anketa
+ private static $spremenljivka = null; # trenutna spremenljivka
+ private static $db_table = ''; # aktivnost
+ private static $sprInfo = null; # podatki o trenutni spremenljivki
+ private static $cacheSpremenljivka = null; # zakeširani podatki spremenljivke
+ private static $smv = null; # manjkajoe vrednosti ankete
+ private static $options = null; # možne izbire manjkajočih vrednosti
+ private static $variables = null; # Variable vprašanja
+ private static $_operators = array( # operatorji
+ '0'=>'==', # ==
+ '1'=>'&ne;', # ≠
+ '2'=>'&lt;', # <
+ '3'=>'&gt;', # >
+ '4'=>'&lt;=', # <=
+ '5'=>'&gt;=', # >=
+ '6'=>'interval' # interval
+ );
+
+ /**
+ * konstruktor
+ *
+ * @param mixed $anketa
+ */
+
+ function __construct ($anketa = 0, $spremenljivka = 0) {
+ if ((int)$anketa > 0 && (int)$spremenljivka > 0) {
+ self::$anketa = $anketa;
+ self::$spremenljivka = $spremenljivka;
+
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ self::$db_table = '_active';
+
+ # polovimo manjkajoče privzete vrednosti ankete
+ self::$smv = new SurveyMissingValues(self::$anketa);
+ self::$smv -> Init();
+
+ self::$cacheSpremenljivka = Cache::srv_spremenljivka(self::$spremenljivka);
+ }
+ }
+
+ public static function DisplayMissingValuesForQuestion($displayForm=true) {
+ global $lang;
+
+ echo '<form name="spremenljivka_recode" method="post">';
+ echo '<div id="recodeToNewSpr">';
+ self::displayRecodeType();
+ echo '</div>';
+ echo '</form>';
+ }
+
+
+ /** Naloži manjkajoče vrednosti za spremenljivko
+ *
+ *
+ * Enter description here ...
+ */
+ private static function LoadSpremenljivkaMissingValues($spremenljivka=null) {
+ global $lang;
+ if ($spremenljivka == null) {
+ $spremenljivka = self::$spremenljivka;
+ }
+
+ $cacheSpremenljivka = Cache::srv_spremenljivka($spremenljivka);
+
+ self::$options = array();
+ self::$variables = array();
+ if ((int)$spremenljivka > 0) {
+ self::$options['_0_'] = array('naslov'=>$lang['srv_recode_type0'], 'variable'=>null, 'type'=>0);
+ switch ($cacheSpremenljivka['tip']) {
+ case 1: # radio
+ case 3: # select
+ $sql1 = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id = '".$spremenljivka."' ORDER BY vrstni_red ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql1)) {
+
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+ self::$variables[$row1['id']] = array('naslov'=>$row1['naslov'], 'variable'=>$row1['variable']);
+ self::$options[$row1['id']] = array('naslov'=>$row1['naslov'], 'variable'=>$row1['variable'], 'type'=>0);
+ }
+ }
+ break;
+ case 17: # razvrščanje
+ $sql1 = sisplet_query("SELECT id, naslov, vrstni_red FROM srv_vrednost WHERE spr_id = '".$spremenljivka."' ORDER BY vrstni_red ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql1)) {
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+ self::$variables[$row1['id']] = array('naslov'=>$row1['naslov'], 'variable'=>$row1['vrstni_red']);
+ self::$options[$row1['id']] = array('naslov'=>$row1['naslov'], 'variable'=>$row1['vrstni_red'], 'type'=>0);
+ }
+ }
+ break;
+ case 2: # checkbox
+ self::$variables['1'] = array('naslov'=>'izbran', 'variable'=>'1');
+ self::$variables['0'] = array('naslov'=>'neizbran', 'variable'=>'0');
+ self::$options['1'] = array('naslov'=>'izbran', 'variable'=>'1', 'type'=>0);
+ self::$options['0'] = array('naslov'=>'neizbran', 'variable'=>'0', 'type'=>0);
+ break;
+ case 6: # multiradio
+ case 19: # multitext
+ case 20: # multinumber
+ $sql1 = sisplet_query("SELECT naslov, variable FROM srv_grid WHERE spr_id='".$spremenljivka."' ORDER BY vrstni_red ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql1)) {
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+ self::$variables[$row1['variable']] = array('naslov'=>$row1['naslov'], 'variable'=>$row1['variable']);
+ self::$options[$row1['variable']] = array('naslov'=>$row1['naslov'], 'variable'=>$row1['variable']);
+ }
+ }
+ break;
+ case 16: # multicheckbox
+ self::$variables['0'] = array('naslov'=>'izbran', 'variable'=>'0');
+ self::$variables['1'] = array('naslov'=>'neizbran', 'variable'=>'1');
+ self::$options['0'] = array('naslov'=>'izbran', 'variable'=>'0', 'type'=>0);
+ self::$options['1'] = array('naslov'=>'neizbran', 'variable'=>'1', 'type'=>0);
+ break;
+ }
+ }
+ # dodamo manjkajoče vrednosti če še niso
+ # preberemo možne manjkajoče vrednosti
+ $smvs = self::$smv-> GetSystemFlterByType(array(1));
+ # zgeneriramo matriko izbranih manjkajočih vrednosti za anketo (anketne oz. sistemske mv)
+ self::$options['_1_'] = array('naslov'=>$lang['srv_recode_type1'], 'variable'=>null, 'type'=>0);
+ if (count($smvs)> 0) {
+ foreach ($smvs AS $key => $value) {
+ self::$options[$key] = array('naslov'=>$value, 'variable'=>$key, 'type'=>1);
+ }
+ }
+ $smvs = self::$smv-> GetSystemFlterByType(array(2,3));
+ # zgeneriramo matriko izbranih manjkajočih vrednosti za anketo (anketne oz. sistemske mv)
+ self::$options['_2_'] = array('naslov'=>$lang['srv_recode_type2'], 'variable'=>null, 'type'=>0);
+ if (count($smvs)> 0) {
+ foreach ($smvs AS $key => $value) {
+ self::$options[$key] = array('naslov'=>$value, 'variable'=>$key, 'type'=>2);
+ }
+ }
+ }
+
+ private static function show_new_mv_div() {
+ echo '<div id="vprasanje_recode_new">';
+ self::show_new_mv();
+ echo '</div>';
+ }
+
+ private static function show_new_mv() {
+ global $lang;
+
+ echo 'Izberi vrednost:';
+ echo '<input id="new_mv_value" type="text" size="5" autocomplete="off">';
+
+ echo '<br/>';
+ echo self::$spremenljivka;
+ echo '<br/>';
+
+ echo '<span class="buttonwrapper spaceRight floatRight">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="/" onclick="new_mv_add(\''.self::$spremenljivka.'\'); return false;"><span>'.$lang['add'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper spaceRight floatRight">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="/" onclick="show_new_mv_cancel(); return false;"><span>'.$lang['srv_cancel'].'</span></a>';
+ echo '</span>';
+ }
+
+ private static function new_mv_add() {
+ echo 'Napaka!!!';
+ self::show_new_mv();
+ }
+
+ public static function Ajax() {
+ switch ($_GET['a']) {
+ case 'show_new_mv':
+ self::show_new_mv_div();
+ break;
+ case 'new_mv_add':
+ #self::new_mv_add();
+ break;
+ case 'refresh_mv':
+ self::DisplayMissingValuesForQuestion();
+ break;
+
+ case 'add_new_numeric':
+ self::AddNewNumericRecode();
+ break;
+ case 'changeRecodeType':
+ self::changeRecodeType();
+ break;
+ default:
+# print_r($_POST);
+# print_r($_GET);
+ break;
+ }
+ }
+
+ public function removeRecodeForQuestion() {
+ if ((int)self::$anketa > 0 && (int)self::$spremenljivka > 0) {
+ # odstranimo rekodiranje za spremenljivko
+ $sql = sisplet_query("DELETE FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ # preverimo ali imamo rekodiranje v novo spremenljivko, če ja, kasneje ponudimo tud izbris psremenljivke
+ $qry = sisplet_query("SELECT to_spr_id FROM srv_recode_spremenljivka WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'");
+ list($spr_id) = mysqli_fetch_row($qry);
+ # pobrišemo še zapise v srv_recode_vrednost in srv_recode spremenljika
+ $sql = sisplet_query("DELETE FROM srv_recode_spremenljivka WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $sql = sisplet_query("DELETE FROM srv_recode_vrednost WHERE ank_id = '".self::$anketa."' AND spr1 = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ sisplet_query("COMMIT");
+ return (int)$spr_id;
+ } else {
+ return 0;
+ }
+ }
+
+ public function SetUpMissingValuesForQuestion() {
+ if ((int)self::$anketa > 0 ) {
+ # pobrišemo rekodirane vrednosti za morebitno rekodiranje v novo spremenljivko
+ if (isset($_REQUEST['recodeToSpr']) && (int)$_REQUEST['recodeToSpr'] > 0) {
+ $sql = sisplet_query("DELETE FROM srv_recode_vrednost WHERE ank_id = '".self::$anketa."' AND spr2 = '".(int)$_REQUEST['recodeToSpr']."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+
+ # če imamo spremembe je potrebno na novo zgenerirati datoteko
+ $strSelect = "SELECT search, value, operator FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."' ORDER BY vrstni_red";
+ $sqlSelect = sisplet_query($strSelect);
+ $rowsBefore = array();
+ $rowsAfter = array();
+ while (list($search, $value, $operator) = mysqli_fetch_row($sqlSelect)) {
+ $rowsBefore[] = $search."_".$value."_".(int)$operator;
+ }
+
+ # pobrišemo vse obstoječe zamenjave
+ $sql = sisplet_query("DELETE FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ #rekodiramo kategorije
+ if ( isset($_REQUEST['edit_recode_mv']) ) {
+ # dodamo potrebne zamenjave za
+ $_for_replace = "";
+ foreach ($_REQUEST as $key => $value) {
+ $_tmp_value = substr($key, 5);
+ if (substr($key, 0, 5) == 'MVFQ_' && $_tmp_value != $value) {
+ if ($_for_replace != "") { $_for_replace .= ","; }
+ $_for_replace .= " ('".self::$anketa."', '".self::$spremenljivka."', '$_tmp_value', '$value') ";
+ }
+ }
+
+
+ # če moramo uporabiti zamenjave:
+ if ($_for_replace != "") {
+ $insertString = 'INSERT INTO srv_recode (ank_id, spr_id, search, value) VALUES '.$_for_replace;
+ $sql1 = sisplet_query($insertString);
+ }
+ } else if( isset($_REQUEST['edit_recode_number']) ){
+ # rekodiramo numerične
+ $recoded = array();
+ if (isset($_REQUEST['recode_number_operator'])) {
+ foreach ($_REQUEST['recode_number_operator'] as $key => $value) {
+ $recoded[$key]['operator'] = $value;
+ }
+ }
+ if (isset($_REQUEST['recode_number_search'])) {
+ foreach ($_REQUEST['recode_number_search'] as $key => $value) {
+ $recoded[$key]['search'] = trim($value);
+ }
+ }
+ if (isset($_REQUEST['recode_number_search1'])) {
+ foreach ($_REQUEST['recode_number_search1'] as $key => $value) {
+ $recoded[$key]['search1'] = trim($value);
+ }
+ }
+ if (isset($_REQUEST['recode_number_search2'])) {
+ foreach ($_REQUEST['recode_number_search2'] as $key => $value) {
+ $recoded[$key]['search2'] = trim($value);
+ }
+ }
+ if (isset($_REQUEST['recode_number_value'])) {
+ foreach ($_REQUEST['recode_number_value'] as $key => $value) {
+ $recoded[$key]['value'] = trim($value);
+ }
+ }
+ # pripravimo query
+ if (count($recoded) > 0) {
+ $_for_replace = "";
+ $already_set = array();
+ $vrstni_red = 1;
+ foreach ($recoded AS $rKey => $recode) {
+ $opreand = (int)$recode['operator'];
+ if ( $opreand != 6) {
+ $_search = $recode['search'];
+ } else {
+ $_search = $recode['search1'].','.$recode['search2'];
+ }
+ if ( $_search != '' && $recode['value'] != ''
+ #preprečimo zamenjavo iste vrednosti z istim operatorejm.
+ && !( isset($already_set[$_search.'_'.$recode['operator']] ))
+ ) {
+ if ($_for_replace != "") {
+ $_for_replace .= ",";
+ }
+
+ $_for_replace .= " ('".self::$anketa."', '".self::$spremenljivka."', '$vrstni_red', '$_search', '".trim($recode['value'])."', '".(int)trim($recode['operator'])."') ";
+
+ $already_set[$_search.'_'.$recode['operator']] = true;
+ }
+ $vrstni_red ++;
+ }
+ if ($_for_replace != "") {
+ # izvedemo insert query
+ $insertString = 'INSERT INTO srv_recode (ank_id, spr_id, vrstni_red, search, value, operator) VALUES '.$_for_replace;
+ $sql1 = sisplet_query($insertString);
+ if (!$sql1) {
+ print_r(mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ }
+
+ }
+ sisplet_query("COMMIT");
+
+ # če imamo spremembe je potrebno na novo zgenerirati datoteko
+ $strSelect = "SELECT search, value, operator FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."' ORDER BY vrstni_red";
+ $sqlSelect = sisplet_query($strSelect);
+ while (list($search, $value, $operator) = mysqli_fetch_row($sqlSelect)) {
+ $rowsAfter[] = $search."_".$value."_".(int)$operator;
+ }
+ if ( (count( array_diff($rowsBefore, $rowsAfter) ) + count( array_diff($rowsAfter, $rowsBefore) ) ) > 0) {
+ # array-a nista enaka, imamo spremembe
+ # pobrišimo datoteko, da se podatki zgenerirajo na novo
+ global $site_path;
+ $data_file_name = $site_path.'admin/survey/SurveyData/export_data_'.self::$anketa.'.dat';
+ if (file_exists($data_file_name)) {
+ unlink($data_file_name);
+ }
+ return true;
+
+ }
+ return false;
+ }
+ return false;
+ }
+
+
+ public function SetRecodeNumberNewVrednost() {
+ if ((int)self::$anketa > 0 && (int)$_REQUEST['recode_type']== 1 && (int)$_REQUEST['edit_recode_number'] == 1) {
+
+ # pobrišemo rekodirane vrednosti za morebitno rekodiranje v novo spremenljivko
+ if ((int)self::$spremenljivka > 0) {
+ $sql = sisplet_query("DELETE FROM srv_recode_vrednost WHERE ank_id = '".self::$anketa."' AND spr1 = '".(int)self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ # pobrišemo vse mmorebitne obstoječe zamenjave za normalni number
+ $sql = sisplet_query("DELETE FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ # pobrišemo vse morebitne obstoječe zamenjave za number
+ $sql = sisplet_query("DELETE FROM srv_recode_number WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ if( isset($_REQUEST['recode_number_vrednost']) ){
+ # rekodiramo numerične
+ $recoded = array();
+ if (isset($_REQUEST['recode_number_operator'])) {
+ foreach ($_REQUEST['recode_number_operator'] as $key => $value) {
+ $recoded[$key]['operator'] = $value;
+ }
+ }
+ if (isset($_REQUEST['recode_number_search'])) {
+ foreach ($_REQUEST['recode_number_search'] as $key => $value) {
+ $recoded[$key]['search'] = trim($value);
+ }
+ }
+ if (isset($_REQUEST['recode_number_search1'])) {
+ foreach ($_REQUEST['recode_number_search1'] as $key => $value) {
+ $recoded[$key]['search1'] = trim($value);
+ }
+ }
+ if (isset($_REQUEST['recode_number_search2'])) {
+ foreach ($_REQUEST['recode_number_search2'] as $key => $value) {
+ $recoded[$key]['search2'] = trim($value);
+ }
+ }
+ if (isset($_REQUEST['recode_number_vrednost'])) {
+ foreach ($_REQUEST['recode_number_vrednost'] as $key => $value) {
+ $recoded[$key]['value'] = trim($value);
+ }
+ }
+ # pripravimo query
+ if (count($recoded) > 0) {
+ $_for_replace = "";
+ $already_set = array();
+ $vrstni_red = 1;
+ foreach ($recoded AS $rKey => $recode) {
+ $opreand = (int)$recode['operator'];
+ if ( $opreand != 6) {
+ $_search = $recode['search'];
+ } else {
+ $_search = $recode['search1'].','.$recode['search2'];
+ }
+ if ( $_search != '' && $recode['value'] != ''
+ #preprečimo zamenjavo iste vrednosti z istim operatorejm.
+ && !( isset($already_set[$_search.'_'.$recode['operator']] ))
+ ) {
+ if ($_for_replace != "") {
+ $_for_replace .= ",";
+ }
+
+ $_for_replace .= " ('".self::$anketa."', '".self::$spremenljivka."', '$vrstni_red', '$_search', '".trim($recode['value'])."', '".(int)trim($recode['operator'])."') ";
+
+ $already_set[$_search.'_'.$recode['operator']] = true;
+ }
+ $vrstni_red ++;
+ }
+ if ($_for_replace != "") {
+ # izvedemo insert query
+ $insertString = 'INSERT INTO srv_recode_number (ank_id, spr_id, vrstni_red, search, vred_id, operator) VALUES '.$_for_replace;
+ $sql1 = sisplet_query($insertString);
+ if (!$sql1) {
+ print_r(mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ }
+
+ }
+ sisplet_query("COMMIT");
+ }
+ return false;
+ }
+
+ public function AddNewNumericRecode() {
+ global $lang;
+
+ $recode_type = (int)$_POST['recode_type'];
+
+ self::LoadSpremenljivkaMissingValues();
+
+ if ( $recode_type == 0) {
+ echo '<li>';
+ echo '<span class="faicon move_updown moveY"></span>';
+ printf($lang['srv_recode_number_if'],self::$cacheSpremenljivka['variable']);
+ echo '&nbsp;<select name="recode_number_operator[]" onChange="recode_operator_changed(this);">';
+ foreach (self::$_operators AS $value => $operator) {
+ $selected = ($value == '0') ? ' selected="selected"' : '';
+ echo '<option value="'.$value.'"'.$selected.'>'.$operator.'</option>';
+ }
+ echo '</select>';
+ #echo '&nbsp;<input type="text" name="recode_number_search[]" value="0" size="5" autocomplete="off"/>';
+
+ echo '<span class="recode_int_first">';
+ echo '&nbsp;<input type="text" name="recode_number_search[]" value="0" size="12" autocomplete="off"/>';
+ echo '</span>';
+ echo '<span class="recode_int_seccond hidden">';
+ echo '&nbsp;[<input type="text" name="recode_number_search1[]" value="0" size="5" autocomplete="off"/>,';
+ echo '<input type="text" name="recode_number_search2[]" value="1" size="5" autocomplete="off"/>]';
+ echo '</span>';
+
+ echo '&nbsp;'.$lang['srv_recode_number_to'];
+
+ echo '<select name="recode_number_type[]" onChange="recode_number_type_changed(this);">';
+ foreach (self::$options AS $oKey => $option) {
+ if ($option['variable'] == null && $oKey != '_0_') {
+ echo '<option disabled="disabled">'.$option['naslov'].'</option>';
+ $_value = null;
+ } else {
+ $_value = ($oKey == '_0_') ? '_' : $option['variable'];
+ $_selected = ($oKey == '_0_') ? 'selected="selected"' : '';
+ $_label = ($oKey == '_0_') ? $option['naslov'] : '&nbsp;&nbsp;'.$option['naslov'].' ['.$option['variable'].']';
+ echo '<option value="'.$_value.'" '.$_selected.'>'.$_label.'</option>';
+ }
+ }
+ echo '</select>';
+
+ echo '&nbsp;<input type="text" name="recode_number_value[]" value="0" size="5" autocomplete="off"/>';
+ echo '&nbsp;<span class="floatRight spaceRight faicon delete_circle icon-orange_link" onclick="recode_delete_numeric(\''.self::$spremenljivka.'\',this);"></span>';
+ echo '</li>';
+ } else {
+ # polovimo osnovne lastnosti rekodiranja
+ $selectString = "SELECT to_spr_id FROM srv_recode_spremenljivka WHERE ank_id='".self::$anketa."' AND spr_id='".self::$spremenljivka."'";
+ $sqlSelect = sisplet_query($selectString);
+ if (!$sqlSelect) echo mysqli_error($GLOBALS['connect_db']);
+ list($to_spr_id) = mysqli_fetch_row($sqlSelect);
+
+ self::LoadSpremenljivkaMissingValues($to_spr_id);
+ $new_spr_vrednosti = self::$options;
+ self::LoadSpremenljivkaMissingValues(self::$spremenljivka);
+
+
+ echo '<li>';
+ echo '<span class="faicon move_updown moveY"></span>';
+ printf($lang['srv_recode_number_if'],self::$cacheSpremenljivka['variable']);
+ echo '&nbsp;<select name="recode_number_operator[]" onChange="recode_operator_changed(this);">';
+ foreach (self::$_operators AS $value => $operator) {
+ $selected = ($value == '0') ? ' selected="selected"' : '';
+ echo '<option value="'.$value.'"'.$selected.'>'.$operator.'</option>';
+ }
+ echo '</select>';
+ #echo '&nbsp;<input type="text" name="recode_number_search[]" value="0" size="5" autocomplete="off"/>';
+
+ echo '<span class="recode_int_first">';
+ echo '&nbsp;<input type="text" name="recode_number_search[]" value="0" size="12" autocomplete="off"/>';
+ echo '</span>';
+ echo '<span class="recode_int_seccond hidden">';
+ echo '&nbsp;[<input type="text" name="recode_number_search1[]" value="0" size="5" autocomplete="off"/>,';
+ echo '<input type="text" name="recode_number_search2[]" value="1" size="5" autocomplete="off"/>]';
+ echo '</span>';
+
+ echo '&nbsp;'.$lang['srv_recode_number_to'];
+ # imamo rekodiranje v novo spremenljivko
+ $recode['vred_id'] = '-1';
+
+ echo '<select name="recode_number_vrednost[]">';
+ if (is_array($new_spr_vrednosti) && count($new_spr_vrednosti)>0) {
+ foreach ($new_spr_vrednosti AS $oKey => $option) {
+ if ($option['variable'] == null) {
+ echo '<option disabled="disabled">'.$option['naslov'].'</option>';
+ } else {
+ $_selected = ($recode['vred_id'] == $option['variable']) ? ' selected="selected"' : '';
+ $_label = $option['naslov'].' ['.$option['variable'].']';
+ echo '<option value="'.$option['variable'].'"'.$_selected.'>&nbsp;&nbsp;'.$_label.'</option>';
+ }
+ # $_label = $option['naslov'].' ['.$option['variable'].']';
+ # echo '<option value="'.$option['id'].'" '.$_selected.'>'.$_label.'</option>';
+ }
+ }
+ echo '</select>';
+
+ echo '&nbsp;<span class="floatRight spaceRight faicon delete_circle icon-orange_link" onclick="recode_delete_numeric(\''.self::$spremenljivka.'\',this);"></span>';
+ echo '</li>';
+ }
+
+ return;
+ }
+
+ public function hasRecodedValues() {
+ #preštejemo koliko rekodiranj imamo za spremenljivko
+ $strSelect = "SELECT count(*) FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."'";
+ $sqlSelect = sisplet_query($strSelect);
+ list($count) = mysqli_fetch_row($sqlSelect);
+ return (int)$count;
+ }
+
+
+ public function changeRecodeType() {
+ $insertString = "INSERT INTO srv_recode_spremenljivka (ank_id, spr_id, recode_type, to_spr_id) VALUES ('".self::$anketa."', '".self::$spremenljivka."', '".(int)$_POST['recode_type']."', '".(int)$_POST['recodeToSpr']."') ON DUPLICATE KEY UPDATE recode_type = '".(int)$_POST['recode_type']."', to_spr_id = '".(int)$_POST['recodeToSpr']."'";
+ $sqlInsert = sisplet_query($insertString);
+ self::displayRecodeType();
+ }
+
+ public static function displayRecodeType() {
+ global $lang;
+ $tip = self::$cacheSpremenljivka['tip'];
+ if (in_array($tip, array(
+ 1, # radio
+ 2, # checkbox
+ 3, # select
+ 6, # multiradio
+ 16, # multicheck
+ 17 # razvrščanje
+ ))) {
+ $displayType=1;
+ } else if (in_array($tip, array(
+ 7, # number
+ 18, # vsota
+ 20, # multinumber
+ 22, # multinumber
+ 21, # textovni
+ ))) {
+ $displayType=2;
+ }
+ # polovimo osnovne lastnosti rekodiranja
+ $selectString = "SELECT recode_type, to_spr_id FROM srv_recode_spremenljivka WHERE ank_id='".self::$anketa."' AND spr_id='".self::$spremenljivka."'";
+ $sqlSelect = sisplet_query($selectString);
+ if (!$sqlSelect) echo mysqli_error($GLOBALS['connect_db']);
+ list($recode_type, $to_spr_id) = mysqli_fetch_row($sqlSelect);
+
+ if ((int)$recode_type == 0) {
+ self::LoadSpremenljivkaMissingValues(self::$spremenljivka);
+ # polovimo missinge za spremenljivko
+ $strSelect = "SELECT search, value, operator FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."' ORDER BY vrstni_red";
+ $sqlSelect = sisplet_query($strSelect);
+ if (!$sqlSelect) echo mysqli_error($GLOBALS['connect_db']);
+ $recoded = array();
+ if (mysqli_num_rows($sqlSelect)) {
+ while ($rowSelect = mysqli_fetch_assoc($sqlSelect)) {
+ $recoded[$rowSelect['search'].'_'.$rowSelect['operator']] = array('search'=>$rowSelect['search'],'value'=>$rowSelect['value'],'operator'=>$rowSelect['operator']);
+ }
+ }
+ } else {
+
+ if ($displayType == 1) {
+ # polovimo še vrednosti če imamo rekodirano v drugo spremenljivko
+ $qry_str = "select vre1, spr2, vre2 from srv_recode_vrednost WHERE ank_id = '".self::$anketa."' AND spr1 = '".self::$spremenljivka."'";
+ $sql = sisplet_query($qry_str);
+ $recodedFrom = array();
+ while (list($vre1, $spr1, $vre2) = mysqli_fetch_row($sql)) {
+ $recodedFrom[$vre1] = $vre2;
+ }
+ } else {
+ # polovimo missinge za spremenljivko
+ $strSelect = "SELECT search, vred_id, operator FROM srv_recode_number WHERE ank_id = '".self::$anketa."' AND spr_id = '".self::$spremenljivka."' ORDER BY vrstni_red";
+ $sqlSelect = sisplet_query($strSelect);
+ if (!$sqlSelect) echo mysqli_error($GLOBALS['connect_db']);
+ $recoded = array();
+ if (mysqli_num_rows($sqlSelect)) {
+ while ($rowSelect = mysqli_fetch_assoc($sqlSelect)) {
+ $recoded[$rowSelect['search'].'_'.$rowSelect['operator']] = array('search'=>$rowSelect['search'],'vred_id'=>$rowSelect['vred_id'],'operator'=>$rowSelect['operator']);
+ }
+ }
+ }
+
+ self::LoadSpremenljivkaMissingValues($to_spr_id);
+ $new_spr_vrednosti = self::$options;
+ self::LoadSpremenljivkaMissingValues(self::$spremenljivka);
+
+ # preverimo ali spremenljvka obstaja
+ #$new_spr_vrednosti = array();
+ if ((int)$to_spr_id > 0) {
+ $sqlSpremenljivka = sisplet_query("SELECT s.naslov, s.variable, s.tip FROM srv_spremenljivka s WHERE s.id = '$to_spr_id'");
+ $rowSpremenljivka = mysqli_fetch_assoc($sqlSpremenljivka);
+
+ if (mysqli_num_rows($sqlSpremenljivka) == 0) {
+ $to_spr_id = 0;
+ }
+ }
+ }
+
+ echo '<input type="hidden" name="anketa" value="'.self::$anketa.'" autocomplete="off"/>';
+ echo '<input type="hidden" name="spr_id" value="'.self::$spremenljivka.'" autocomplete="off"/>';
+ echo '<input type="hidden" name="recodeToSpr" value="'.$to_spr_id.'" autocomplete="off"/>';
+ echo '<input type="hidden" id="recIsCharts" value="'.((int)(($_GET['t'] == 'charts')||((int)$_POST['recIsCharts'] == 1)) ).'" autocomplete="off"/>';
+
+
+ if ( $_GET['t'] == 'charts' || $_POST['recIsCharts'] == 1 ) {
+ # če smo v grafih in smo na spremenljivki katera je že rekodirana iz druge, potem onemogočimo nadaljnje kodiranje
+ $strSel = "SELECT count(*) FROM srv_recode_spremenljivka WHERE to_spr_id = '".self::$spremenljivka."'";
+ $qry = sisplet_query($strSel);
+ list($cnt) = mysqli_fetch_row($qry);
+ if ((int)$cnt > 0) {
+ echo $lang['srv_recoded_advancetNote_recoded3'];
+ echo self::$cacheSpremenljivka['variable'].' - '.self::$cacheSpremenljivka['naslov'];
+ echo $lang['srv_recoded_advancetNote_recoded4'];
+ return;
+ }
+ }
+
+
+ if (self::$cacheSpremenljivka['tip'] == 1 || self::$cacheSpremenljivka['tip'] == 3 || self::$cacheSpremenljivka['tip'] == 7) {
+
+ if ( (int)$recode_type == 1 && ((int)(($_GET['t'] == 'charts')||((int)$_POST['recIsCharts'] == 1))) ) {
+ echo '<br/>';
+ echo $lang['srv_recoded_advancetNote'].'<a href="index.php?anketa='.self::$anketa.'&a='.A_COLLECT_DATA.'&m='.M_COLLECT_DATA_RECODING.'">'.$lang['srv_here'].'</a>';
+ echo Help::display('srv_recode_chart_advanced');
+ echo '<br/>';
+ echo '<br/>';
+ echo $lang['srv_recoded_advancetNote_recoded1'];
+ echo self::$cacheSpremenljivka['variable'];
+ echo ' - '.strip_tags(self::$cacheSpremenljivka['naslov']);
+ echo $lang['srv_recoded_advancetNote_recoded2'];
+ echo $rowSpremenljivka['variable'].' - '.$rowSpremenljivka['naslov'];
+ return;
+ }
+ $sugestedName = strip_tags(self::$cacheSpremenljivka['naslov'].' - recoded');
+ echo'<div id="divRecodeSprOption">';
+ echo '<label>'.$lang['srv_recode_to_spr'].'</label>';
+ if ( $_GET['t'] == 'charts' || $_POST['recIsCharts'] == 1 ) {
+ echo $lang['srv_recode_to_spr_same'];
+ } else {
+ echo '<label><input type="radio" name="recode_type" value="0" '.((int)$recode_type == 0 ? ' checked="checked"' : '').'onchange="changeRecodeType();return false;">'.$lang['srv_recode_to_spr_same'].'</label>';
+ echo '<label><input type="radio" name="recode_type" value="1" '.((int)$recode_type == 1 ? ' checked="checked"' : '').'onchange="changeRecodeType();return false;">'.$lang['srv_recode_to_spr_new'].'</label>';
+ }
+ echo '</div>';
+ if ((int)$recode_type == 1) {
+
+ echo'<span id="divRecodeSprNew" class="floatRecodeSpremenljivka">';
+
+ if ((int)$to_spr_id == 0) {
+ echo '<div class="new-spr" style="text-align: right">';
+ echo $lang['srv_recode_to_spr_add_spr'].'<br/>';
+ echo '<div id="coding_spr_new" >';
+ echo '<p>'.$lang['srv_recode_to_spr_name'].' <input type="text" id="rec_spremenljivka_naslov" name="spremenljivka_naslov" default="1" contenteditable="true" value="'.$sugestedName.'" style="width: 123px" />';
+ #echo '<a href="#" onclick="recodeSpremenljivkaNew(); return false;">'.$lang['add'].'</a>';
+ echo '<a href="#" onclick="recodeSpremenljivkaNew(); return false;""><span class="faicon add small" title="'.$lang['add'].'"></span></a>';
+ echo '</p>';
+ echo '</div>';
+ echo '</div>';
+ } else {
+ echo '<strong>'.$rowSpremenljivka['variable'].' - '.skrajsaj(strip_tags($rowSpremenljivka['naslov']), 40).'</strong><br/><br/>';
+ $sql1 = sisplet_query("SELECT naslov FROM srv_vrednost WHERE spr_id='$to_spr_id' ORDER BY vrstni_red ASC");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ if ($rowSpremenljivka['tip'] == 1) {
+ echo '<input type="radio" onclick="return false;" /><label> '.$row1['naslov'].'</label>';
+ echo '<br/>';
+ }
+ }
+ if (mysqli_num_rows($sql1) == 0) {
+ echo '&nbsp;'.$lang['srv_novavrednost'].': '; $margin='0';
+ } else { $margin = '23px';
+ }
+ echo '<input type="text" name="vrednost_new" value="" '.(mysqli_num_rows($sql1)>0?' placeholder="'.$lang['srv_novavrednost'].'" ':'').' style="margin-left:'.$margin.'; width: 80px" /> ';
+ echo '<a href="#" onclick="recodeVrednostNew(); return false;"><span class="faicon add small icon-as_link" title="'.$lang['add'].'"></span></a>';
+ echo '<br>Napredne spremembe:'.Help::display('srv_recode_advanced_edit');
+ }
+ echo '</span>';
+ }
+ echo'<br class="clr" />';
+ }
+ if ( $displayType == 1 ) {
+ if (count(self::$variables)> 0) {
+ if ((int)$recode_type == 0) {
+ echo '<input type="hidden" name="edit_recode_mv" value="1" autocomplete="off"/>';
+ } else {
+ # rekodiramo v novo spremenljivko
+ echo '<input type="hidden" name="edit_recode_nsmv" value="1" autocomplete="off"/>';
+ }
+ //echo '<table style="width:65% !important;">';
+ echo '<table class="question_recode_table">';
+ echo '<tr>';
+ echo '<th class="halfWidth" colspan="2">';
+ echo $lang['srv_recode_original'];
+ echo '</th>';
+ echo '<td rowspan="2" style="vertical-align:top;">&nbsp;<span class="sprites arrow_switch"></span>&nbsp;</td>';
+ echo '<th class="halfWidth" rowspan="2" style="vertical-align:top;">';
+ echo $lang['srv_recode_to'];
+ echo '</th>';
+ echo '</tr>';
+
+ echo '<tr>';
+ echo '<td class="halfWidth anl_ac gray">';
+ echo $lang['srv_recode_to_label'];
+ echo '</td>';
+ echo '<td class="halfWidth anl_ac gray">';
+ echo $lang['srv_recode_to_value'];
+ echo '</td>';
+ echo '</tr>';
+
+ foreach (self::$variables AS $vKey => $variable) {
+ echo '<tr>';
+ echo '<td class="anl_ac">';
+ echo $variable['naslov'];
+ echo '</td>';
+ echo '<td class="anl_ac">';
+ echo '&nbsp;&nbsp;['.$variable['variable'].']';
+ echo '</td>';
+ # spacer
+ echo '<td>&nbsp</td>';
+ #
+ echo '<td>';
+ if ((int)$recode_type == 0) {
+ # imamo klasično rekodiranje
+ echo '<select name="MVFQ_'.$variable['variable'].'">';
+ foreach (self::$options AS $oKey => $option) {
+
+ if ($option['variable'] == null) {
+ echo '<option disabled="disabled">'.$option['naslov'].'</option>';
+ } else {
+ $_selected = ((isset($recoded[$variable['variable'].'_0']) && $recoded[$variable['variable'].'_0']['value'] == $option['variable'])
+ || (!isset($recoded[$variable['variable'].'_0']) && $variable['variable'] == $option['variable'])) ? 'selected="selected"' : '';
+ $_label = (( $variable['variable'] == $option['variable']))
+ ? '('.$lang['srv_recode_valid'].') '.$option['naslov'].' ['.$option['variable'].']'
+ : $option['naslov'].' ['.$option['variable'].']';
+ echo '<option value="'.$option['variable'].'" '.$_selected.'>&nbsp;&nbsp;'.$_label.'</option>';
+ }
+ }
+ echo '</select>';
+ } else {
+ # imamo rekodiranje v novo spremenljivko
+
+ if (!isset($recodedFrom[$vKey])) {
+ $recodedFrom[$vKey] = '-1';
+ }
+ echo '<select name="MVSNFQ_'.$vKey.'">';
+ if (is_array($new_spr_vrednosti) && count($new_spr_vrednosti)>0) {
+ foreach ($new_spr_vrednosti AS $oKey => $option) {
+ if ($option['variable'] == null) {
+ echo '<option disabled="disabled">'.$option['naslov'].'</option>';
+ } else {
+
+ if (is_numeric($oKey)) {
+ $_selected = (isset($recodedFrom[$vKey]) && $recodedFrom[$vKey] == $oKey)
+ ? ' selected="selected"'
+ : '';
+ $_label = $option['naslov'].' ['.$option['variable'].']';
+ $value = (int)$oKey;
+ } else {
+ $_selected = (isset($recodedFrom[$vKey]) && $recodedFrom[$vKey] == $option['variable'])
+ ? ' selected="selected"'
+ : '';
+ $_label = $option['naslov'].' ['.$option['variable'].']';
+ $value = (int)$option['type'] == 0 && (int)$option['id'] > 0 ? $option['id'] : $option['variable'];
+ }
+ echo '<option value="'.$value.'" '.$_selected.'>&nbsp;&nbsp;'.$_label.'</option>';
+ }
+ }
+ }
+ echo '</select>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ }
+ } else if ( $displayType == 2) {
+ # number
+ if ((int)$recode_type == 0) {
+ echo '<input type="hidden" name="edit_recode_number" value="1" autocomplete="off"/>';
+ echo '<ul id="recode_number_sort" class="recode_number_sort">';
+ if (count($recoded)> 0) {
+ foreach ($recoded AS $rKey => $recode) {
+
+ echo '<li>';
+ echo '<span class="faicon move_updown moveY"></span>';
+ printf($lang['srv_recode_number_if'],self::$cacheSpremenljivka['variable']);
+ echo '&nbsp;<select name="recode_number_operator[]" onChange="recode_operator_changed(this);">';
+ foreach (self::$_operators AS $value => $operator) {
+ $selected = ($value == $recode['operator']) ? ' selected="selected"' : '';
+ echo '<option value="'.$value.'"'.$selected.'>'.$operator.'</option>';
+ }
+ echo '</select>';
+ $rSearchInterval = explode(',',$recode['search']);
+
+ echo '<span class="recode_int_first'.($recode['operator'] != 6 ? '' : ' hidden').'">';
+ echo '&nbsp;<input type="text" name="recode_number_search[]" value="'.($rSearchInterval[0]).'" size="12" autocomplete="off"/>';
+ echo '</span>';
+ echo '<span class="recode_int_seccond'.($recode['operator'] != 6 ? ' hidden' : '').'">';
+ echo '&nbsp;[<input type="text" name="recode_number_search1[]" value="'.($rSearchInterval[0]).'" size="5" autocomplete="off"/>,';
+ echo '<input type="text" name="recode_number_search2[]" value="'.($rSearchInterval[1]).'" size="5" autocomplete="off"/>]';
+ echo '</span>';
+
+ echo '&nbsp;'.$lang['srv_recode_number_to'];
+ $is_missing_value = false;
+ echo '<select name="recode_number_type" onChange="recode_number_type_changed(this);">';
+ foreach (self::$options AS $oKey => $option) {
+ if ($oKey == '_0_' || $oKey == '_1_' || $oKey == '_2_') {
+ # privzeto izberemo prvi odgovor - veljavni, nato spodaj popravimo
+ $_value = ($oKey == '_0_') ? '_' : null;
+ $_selected = ($oKey == '_0_' ? 'selected="selected"' : 'disabled="disabled"');
+ $_label = $option['naslov'];
+ } else {
+ $_value = $option['variable'];
+ if ($oKey == $recode['value']) {
+ $is_missing_value = true;
+ $_selected = 'selected="selected"';
+ } else {
+ $_selected = '';
+ }
+ $_label = '&nbsp;&nbsp;'.$option['naslov'].' ['.$option['variable'].']';
+ }
+ echo '<option value="'.$_value.'" '.$_selected.'>'.$_label.'</option>';
+ }
+ echo '</select>';
+
+ echo '&nbsp;<input type="text" name="recode_number_value[]" value="'.$recode['value'].'" size="5" '.($is_missing_value ? ' class="hidden"' : '').' autocomplete="off"/>';
+ echo '&nbsp;<span class="floatRight spaceRight faicon delete_circle icon-orange_link" onclick="recode_delete_numeric(\''.self::$spremenljivka.'\',this);"></span>';
+ echo '</li>';
+ }
+ }
+ echo '</ul>';
+ echo '<script>$(\'#recode_number_sort\').sortable({ items: \'li\', axis: \'y\', scroll: \'false\', handle: \'span.move_updown\', forcePlaceholderSize: \'true\', placeholder: "ui-recode-placeholder"});</script>';
+ echo '<span onclick="recode_add_numeric(\''.self::$spremenljivka.'\');" class="pointer"><span class="faicon add small icon-as_link" title="'.$lang['srv_recode_add_number'].'"></span> '.$lang['srv_recode_add_number'].'</span>';
+ } else {
+
+ # number
+ # recode to new spr
+ echo '<input type="hidden" name="edit_recode_number" value="1" autocomplete="off"/>';
+ echo '<ul id="recode_number_sort" class="recode_number_sort">';
+ if (count($recoded)> 0) {
+ foreach ($recoded AS $rKey => $recode) {
+
+ echo '<li>';
+ echo '<span class="faicon move_updown moveY"></span>';
+ printf($lang['srv_recode_number_if'],self::$cacheSpremenljivka['variable']);
+ echo '&nbsp;<select name="recode_number_operator[]" onChange="recode_operator_changed(this);">';
+ foreach (self::$_operators AS $value => $operator) {
+ $selected = ($value == $recode['operator']) ? ' selected="selected"' : '';
+ echo '<option value="'.$value.'"'.$selected.'>'.$operator.'</option>';
+ }
+ echo '</select>';
+ $rSearchInterval = explode(',',$recode['search']);
+
+ echo '<span class="recode_int_first'.($recode['operator'] != 6 ? '' : ' hidden').'">';
+ echo '&nbsp;<input type="text" name="recode_number_search[]" value="'.($rSearchInterval[0]).'" size="12" autocomplete="off"/>';
+ echo '</span>';
+ echo '<span class="recode_int_seccond'.($recode['operator'] != 6 ? ' hidden' : '').'">';
+ echo '&nbsp;[<input type="text" name="recode_number_search1[]" value="'.($rSearchInterval[0]).'" size="5" autocomplete="off"/>,';
+ echo '<input type="text" name="recode_number_search2[]" value="'.($rSearchInterval[1]).'" size="5" autocomplete="off"/>]';
+ echo '</span>';
+
+ echo '&nbsp;'.$lang['srv_recode_number_to'];
+ if (!isset($recodedFrom[$rKey])) {
+ $recodedFrom[$rKey] = '-1';
+ }
+ # imamo rekodiranje v novo spremenljivko
+ echo '<select name="recode_number_vrednost[]">';
+ if (is_array($new_spr_vrednosti) && count($new_spr_vrednosti)>0) {
+ foreach ($new_spr_vrednosti AS $oKey => $option) {
+ if ($option['variable'] == null) {
+ echo '<option disabled="disabled">'.$option['naslov'].'</option>';
+ } else {
+ if ($option['type'] == 0) {
+ $value = $oKey;
+ $_selected = ($recode['vred_id'] == $oKey) ? ' selected="selected"' : '';
+ } else {
+ $value = $option['variable'];
+ $_selected = ($recode['vred_id'] == $option['variable']) ? ' selected="selected"' : '';
+ }
+
+ $_label = $option['naslov'].' ['.$option['variable'].']';
+ echo '<option value="'.$value.'"'.$_selected.'>&nbsp;&nbsp;'.$_label.'</option>';
+ }
+
+
+
+ # $_label = $option['naslov'].' ['.$option['variable'].']';
+ # echo '<option value="'.$option['id'].'" '.$_selected.'>'.$_label.'</option>';
+ }
+ }
+ echo '</select>';
+ echo '&nbsp;<span class="floatRight spaceRight faicon delete_circle icon-orange_link" onclick="recode_delete_numeric(\''.self::$spremenljivka.'\',this);"></span>';
+ echo '</li>';
+ }
+ }
+ echo '</ul>';
+ echo '<script>$(\'#recode_number_sort\').sortable({ items: \'li\', axis: \'y\', scroll: \'false\', handle: \'span.move_updown\', forcePlaceholderSize: \'true\', placeholder: "ui-recode-placeholder"});</script>';
+ echo '<span onclick="recode_add_numeric(\''.self::$spremenljivka.'\');" class="pointer"><span class="faicon add small icon-as_link" title="'.$lang['srv_recode_add_number'].'"></span> '.$lang['srv_recode_add_number'].'</span>'; }
+ } else {
+ echo '<br>'.$lang['srv_recoding_not_set_jet'].'('.$tip.')<br>';
+ }
+ }
+
+ function SetRecodeNewVrednost() {
+ # pobrišemo morebtne vrednosti v srv_recode (če je bilo predhodno nastavljeno klasično rekodiranje)
+ $sqlD = sisplet_query("DELETE FROM srv_recode WHERE ank_id = '".self::$anketa."' AND spr_id = '".$_REQUEST['spr_id']."'");
+ if (!$sqlD) echo mysqli_error($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+
+ $newSpr = $_REQUEST['recodeToSpr'];
+ $_for_replace = "";
+ if ((int)$newSpr > 0)
+ foreach ($_REQUEST as $key => $newVrednost) {
+ if (substr($key, 0, 7) == 'MVSNFQ_' && trim($newVrednost) != '') {
+ # id stare vrednosti
+ $oldVrednost = substr($key, 7);
+ if ($_for_replace != "") {
+ $_for_replace .= ",";
+ }
+ $_for_replace .= " ('".self::$anketa."','".self::$spremenljivka."','$oldVrednost','$newSpr','$newVrednost') ";
+ }
+
+ }
+ # najprej pobrišemo vse obstoječe vrednosti
+ $sql = sisplet_query("DELETE FROM srv_recode_vrednost WHERE ank_id = '".self::$anketa."' AND spr1 = '".self::$spremenljivka."'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+
+ # če moramo uporabiti zamenjave:
+ if ($_for_replace != "") {
+ $insertString = 'INSERT INTO srv_recode_vrednost (ank_id, spr1, vre1, spr2, vre2) VALUES '.$_for_replace;
+ $sql1 = sisplet_query($insertString);
+ }
+ sisplet_query("COMMIT");
+
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.Setting.php b/admin/survey/classes/class.Setting.php
new file mode 100644
index 0000000..ff39cfb
--- /dev/null
+++ b/admin/survey/classes/class.Setting.php
@@ -0,0 +1,420 @@
+<?php
+// star class. Nasomesti ga class.SurveyMissingValues
+
+/*
+ * Created on 20.5.2009
+ *
+ */
+
+class Setting
+{
+ static private $instance;
+
+ // nastavitve sistema
+ static private $sysSetting = array();
+
+ // nastavitve ankete
+ static private $srvSetting = array();
+
+ // nastavitve uporabnika
+ static private $usrSetting = array();
+
+ // userId
+ static private $uid = null;
+
+ static private $mySqlResult = null;
+ static private $mySqlErrNo = null;
+
+ // konstrutor
+ protected function __construct() {}
+ // kloniranje
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new Setting();
+ }
+ return self::$instance;
+ }
+
+ /** inicializacija */
+
+ static function Init( $_userId = null )
+ {
+ if ( $_userId )
+ { self::$uid = $_userId; }
+ self::refreshData();
+ }
+
+
+ // nastavimo nov User Id
+ static function setUID( $_userId )
+ {
+ if ( $_userId )
+ { self::$uid = $_userId; }
+ $this->refreshData();
+ }
+
+ // osvežimo podatke nastavitev
+ static function refreshData()
+ {
+ // nastavitve sistema
+ self::getSystemSetting();
+ // nastavitve ankete
+
+ // nastavitve uporabika
+ }
+
+ static function getSystemSetting()
+ {
+ //$stringSystemSetting = "SELECT * FROM srv_settng "
+
+ }
+
+ /** @desc: polovi sistemske filtre */
+ private static $_systemFilters = array();
+ private static $_systemFiltersArray;
+ static function GetSystemFilters($filter=null)
+ {
+ if (!$filter) {
+ if (isset(self::$_systemFiltersArray)) {
+ return self::$_systemFiltersArray;
+ }
+ else {
+ $result = array();
+ $stringSystemSetting_filters = "SELECT * FROM srv_sys_filters ORDER BY type, filter ASC";
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ while ( $rowSystemSetting_filters = mysqli_fetch_assoc($sqlSystemSetting_filters) )
+ {
+ $result[] = $rowSystemSetting_filters;
+ }
+ self::$_systemFiltersArray = $result;
+ return self::$_systemFiltersArray;
+ }
+ }
+ else {
+ if (isset(self::$_systemFilters[$filter]))
+ return self::$_systemFilters[$filter];
+ else
+ {
+ $stringSystemSetting_filters = "SELECT * FROM srv_sys_filters where filter = '".$filter."'";
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ $result = mysqli_fetch_assoc($sqlSystemSetting_filters);
+ self::$_systemFilters[$filter] = $result;
+ return $result;
+ }
+ }
+ }
+
+ // vrne array z sistemskimi filtri
+ private static $_systemFiltersValues;
+ static function GetSystemFiltersValues()
+ {
+ if (isset(self::$_systemFiltersValues)) {
+ return self::$_systemFiltersValues;
+ }
+ else {
+ $result = array();
+ $stringSystemSetting_filters = "SELECT filter FROM srv_sys_filters ORDER BY type, filter ASC";
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ while ( $rowSystemSetting_filters = mysqli_fetch_assoc($sqlSystemSetting_filters) )
+ {
+ $result[$rowSystemSetting_filters['filter']] = $rowSystemSetting_filters['filter'];
+ }
+ self::$_systemFiltersValues = $result;
+ return self::$_systemFiltersValues;
+ }
+ }
+
+ private static $_systemFiltersByType = array();
+ static function GetSystemFlterByType($type)
+ {
+ if (isset(self::$_systemFiltersByType[$type]))
+ return self::$_systemFiltersByType[$type];
+ else {
+ $result = array();
+ $stringSystemSetting_filters = "SELECT * FROM srv_sys_filters WHERE type = '".$type."' ORDER BY filter ASC";
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ while ( $rowSystemSetting_filters = mysqli_fetch_assoc($sqlSystemSetting_filters) )
+ {
+ $result[] = $rowSystemSetting_filters;
+ }
+ self::$_systemFiltersByType[$type] = $result;
+ return self::$_systemFiltersByType[$type];
+ }
+ }
+
+ /** desc: vrnemo sistemsko privzete nastavtive filtrov
+ * (v opisnih statistikah so vsi filtri vključeni, v frekvencah pa izključeni)
+ */
+ private static $_systemFiltersDefaultValues = array();
+ static function GetSystemFlterDefaultValues($fid)
+ {
+ if (isset(self::$_systemFiltersDefaultValues[$fid]))
+ return self::$_systemFiltersDefaultValues[$fid];
+ else {
+ $result = array('means'=>false, 'crosstab'=>false, 'frequencies'=>false, 'descriptives'=>true);
+ self::$_systemFiltersByType[$fid] = $result;
+ return self::$_systemFiltersByType[$fid];
+ }
+ }
+
+
+ // vrne true če je $key v tabeli z filtri
+ private static $_systemFiltersValue;
+ static function isSystemFiltersValue($key)
+ {
+ $stringSystemSetting_filters = "SELECT count(id) as cnt FROM srv_sys_filters where filter = '".$key."'";
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ $row = mysqli_fetch_assoc($sqlSystemSetting_filters);
+ return $row['cnt'];
+ }
+
+ static function AddSystemFilters( $filter, $text, $fid)
+ {
+ $insertString = "INSERT INTO srv_sys_filters (fid,filter,text,uid,type) ".
+ "VALUES ('".$fid."', '".$filter."', '".$text."', '".self::$uid."', '3');";
+ self::$mySqlResult = sisplet_query($insertString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+ static function DeleteSystemFilters( $id)
+ {
+ $deleteString = "DELETE FROM srv_sys_filters WHERE id = '".$id."'";
+ self::$mySqlResult = sisplet_query($deleteString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+ static function SaveSystemFilters($id,$filter,$text)
+ {
+ $updateString = "UPDATE srv_sys_filters " .
+ "SET filter = '".$filter."', text = '".$text."' ".
+ "WHERE id = '".$id."'";
+ self::$mySqlResult = sisplet_query($updateString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+
+ private static $_systemSysVarFlterData = array();
+ static function GetSystemSysVarFlterData($id)
+ {
+ if (isset(self::$_systemSysVarFlterData[$id])) {
+ return self::$_systemSysVarFlterData[$id];
+ }
+ else {
+ $stringSystemSetting_filters = "SELECT * FROM srv_sys_filters WHERE id = '".$id."'";
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ $result = mysqli_fetch_assoc($sqlSystemSetting_filters);
+ self::$_systemSysVarFlterData[$id] = $result;
+ return self::$_systemSysVarFlterData[$id];
+ }
+ }
+
+ /** Hendla prikaz filtrov v nastavitvah
+ *
+ */
+ static function DisplaySystemFilters($mode='normal')
+ {
+ global $lang;
+ global $s;
+ $filtri = self::GetSystemFilters();
+ if ( $mode=='normal' )
+ {
+ echo '<a href="#" onClick="sysFilterEditMode(\'edit\'); return false;">';
+ echo '<span class="faicon edit small"></span>'
+ .$lang['srv_settings_filter_edit_mode']. '</a>';
+ echo '<div class="clr"></div>';
+ echo '<div style="clear:both; padding:5px; height:1.2em">';
+
+ echo '<div style="width:40px; float:left; text-align:left; padding-right:15px; text-align:right">';
+ echo '<i style="color:gray; text-align:right">'.$lang['srv_filter_id'].'</i>';
+ echo '</div>';
+
+ echo '<div style="width:50px; float:left; text-align:left; padding-right:15px;">';
+ echo '<i style="color:gray;text-align:right">'.$lang['srv_filter_vrednost'].'</i>';
+ echo '</div>';
+
+ echo '<div class="" style="width:250px; float:left; color: gray">';
+ echo '<i style="color:gray;">'.$lang['srv_filter_variabla'].'</i>';
+ echo '</div>';
+
+ echo '</div>';
+
+ foreach ( $filtri as $key => $filter)
+ {
+ echo '<div id="sysfilter_div_'.$filter['id'].'" style="clear:both; padding-bottom:0px; height:1.2em;">';
+ echo '<div id="sysfilter_filter_'.$filter['id'].'" class="spr_sysFilter'.$filter['type'].'" style="width:40px; float:left; text-align:left; padding-right:15px; color:gray; text-align:right;">'.$filter['fid'].'</div>';
+ echo '<div id="sysfilter_filter_'.$filter['id'].'" class="spr_sysFilter'.$filter['type'].'" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">'.$filter['filter'].'</div>';
+ echo '<div id="sysfilter_text_'.$filter['id'].'" class="spr_sysFilter'.$filter['type'].'" style="width:250px; float:left;">'.$filter['text'].'</div>';
+ echo '</div>';
+ }
+ }
+ else
+ if ( $mode=='edit' || $mode=='new')
+ {
+ echo '<a href="/" onClick="sysFilterEditMode(\'normal\'); return false;">';
+ echo '<span class="faicon mapca anketa small"></span>'
+ .$lang['srv_settings_filter_view_mode']. '</a>';
+
+ echo '<div style="clear:both; padding:5px; height:1.2em">';
+
+ echo '<div style="width:40px; float:left; text-align:left; padding-right:15px; text-align:right">';
+ echo '<i style="color:gray; text-align:right">'.$lang['srv_filter_id'].'</i>';
+ echo '</div>';
+
+ echo '<div style="width:50px; float:left; text-align:left; padding-right:15px;">';
+ echo '<i style="color:gray;">'.$lang['srv_filter_vrednost'].'</i>';
+ echo '</div>';
+
+ echo '<div class="" style="width:250px; float:left; color: gray">';
+ echo '<i style="color:gray;">'.$lang['srv_filter_variabla'].'</i>';
+ echo '</div>';
+
+ echo '</div>';
+ foreach ( $filtri as $key => $filter)
+ {
+
+ echo '<div id="sysfilter_div_'.$filter['id'].'" style="clear:both; padding:5px; height:1.2em">';
+
+ echo '<div id="sysfilter_filter_'.$filter['id'].'" class="" style="width:40px; float:left; text-align:left; padding-right:15px; color:gray; text-align:right;">'.$filter['fid'].'</div>';
+
+ echo '<div id="sysfilter_filter_'.$filter['id'].'" class="" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">';
+ echo '<input id="sysfilter_filter_input_'.$filter['id'].'" type="text" value="'.$filter['filter'].'" title="'.$filter['filter'].'" size="6" maxlength="6">';
+ echo '</div>';
+
+ echo '<div id="sysfilter_text_'.$filter['id'].'" class="" style="width:250px; float:left;">';
+ echo '<input id="sysfilter_text_input_'.$filter['id'].'" type="text" value="'.$filter['text'].'" title="'.$filter['text'].'" size="45" maxlength="100">';
+ echo '</div>';
+
+ if ( $filter['type'] == 3)
+ {
+ echo '<div id="sysfilter_edit_'.$filter['id'].'" class="" style="width:100px; float:left;">';
+ echo '<a href="/" onClick="sysFilterDelete('.$filter['id'].'); return false;">';
+ echo '<img id="sysfilter_delete_'.$filter['id'].'" src="img_'.$s->skin.'/delete_red.png" alt="'.$lang['srv_filtri_izbrisi_filter'].'" style="vertical-align:text-bottom " />';
+ echo '</a>';
+ echo '</div>';
+ }
+ echo '</div>';
+ echo '<script>';
+ echo '$(document).ready(function() {';
+ echo '$("#sysfilter_delete_'.$filter['id'].'").click(function(e) {});';
+ echo '$("#sysfilter_filter_input_'.$filter['id'].'").blur(function(e) {sysFilterSave('.$filter['id'].'); return false;});';
+ echo '$("#sysfilter_text_input_'.$filter['id'].'").blur(function(e) {sysFilterSave('.$filter['id'].'); return false;});';
+ echo '$("#sysfilter_extra_'.$filter['id'].'").click(function(e) {sysFilterExtraSetting('.$filter['id'].'); return false;});';
+
+ echo '});';
+ echo '</script>';
+ }
+ echo '<div class="clr"></div>';
+ // pohendlamo error: duplicate
+ if (self::$mySqlErrNo == 1062)
+ {
+ echo '<div id="error" class="red">';
+ echo $lang['srv_duplicateEntry'];
+ echo '</div>';
+ }
+
+ echo '<div id="sysfilter_new" style="padding-top:10px;">';
+ if ($mode == 'new')
+ {
+ echo '<div id="sysfilter_div_add" style="clear:both; padding:5px; height:1.2em">';
+
+ echo '<div id="sysfilter_filter_add" style="width:40px; float:left; text-align:left; padding-right:15px;">';
+ echo '<input id="sysfilter_fid_input_add" type="text" value="'.$filter['fid'].'" title="'.$filter['fid'].'" size="6" maxlength="6">';
+ echo '</div>';
+
+ echo '<div id="sysfilter_filter_add" class="" style="width:50px; float:left; text-align:left; padding-right:15px;">';
+ echo '<input id="sysfilter_filter_input_add" type="text" value="'.$filter['filter'].'" title="'.$filter['filter'].'" size="6" maxlength="6">';
+ echo '</div>';
+
+ echo '<div id="sysfilter_text_add" class="" style="width:250px; float:left;">';
+ echo '<input id="sysfilter_text_input_add" type="text" value="'.$filter['text'].'" title="'.$filter['text'].'" size="45" maxlength="100">';
+ echo '</div>';
+
+ echo '<div class="" style="width:50px; float:left;">';
+ echo '<img id="sysfilter_add_img" src="icons/icons/accept.png" alt="'.$lang['srv_novfilter'].'" style="vertical-align:text-bottom " />';
+ echo '</div>';
+ }
+ else
+ echo '<img id="sysfilter_new_img" src="img_'.$s->skin.'/add.png" alt="'.$lang['srv_novfilter'].'" style="vertical-align:text-bottom " />'.$lang['srv_novfilter'];
+ echo '</div>';
+ echo '<script>';
+ echo '$(document).ready(function() {';
+ echo '$("#sysfilter_new_img").click(function(e) {sysFilterEditMode(\'new\'); return false;});';
+ echo '$("#sysfilter_add_img").click(function(e) {sysFilterEditMode(\'add\'); return false;});';
+ echo '});';
+ echo '</script>';
+
+ }
+
+ }
+
+ /**
+ * @desc polovimo nastavitev survey sistema
+ */
+ private static $_sysMiscSetting = array();
+ function getSysMiscSetting($what=null)
+ {
+ if (isset(self::$_sysMiscSetting[$what])) {
+ return self::$_sysMiscSetting[$what];
+ }
+ else
+ {
+ $result = null;
+ if (is_string($what))
+ {
+ $stringSelect = "SELECT value FROM srv_misc WHERE what = '".$what."'";
+ $sqlSelect = sisplet_query($stringSelect);
+ $rowSelect = mysqli_fetch_array($sqlSelect);
+ if (mysqli_num_rows($sqlSelect) > 0)
+ $result = $rowSelect['value'];
+ else
+ $result = '';
+ }
+ if($result == ''&&$what == 'export_data_type'){
+ $result = 2;
+ }
+ self::$_sysMiscSetting[$what] = $result;
+ return self::$_sysMiscSetting[$what];
+ }
+ }
+ /**
+ * @desc shranimo nastavitev survey sistema
+ */
+ function setSysMiscSetting($what=null, $value=null)
+ {
+ if ( $what && $value )
+ {
+ if ( is_string($what) && is_string($value) )
+ {
+ $stringInsert = "INSERT INTO srv_misc (what, value) VALUES ('".$what."', '".$value."') ON DUPLICATE KEY UPDATE value = '".$value."'";
+ $sqlInsert = sisplet_query($stringInsert);
+ return mysqli_affected_rows($GLOBALS['connect_db']);
+ }
+ else
+ return false;
+ }
+ else
+ return false;
+ }
+}
+/*
+function getTableNextAutoIncrement($tableName)
+{
+ $next_increment = 0;
+ $qShowStatus = "SHOW TABLE STATUS LIKE '$tableName'";
+ $qShowStatusResult = sisplet_query($qShowStatus) or die ( "Query failed: " . mysqli_error($GLOBALS['connect_db']) . "<br/>" . qShowStatus );
+
+
+ while ($row = mysqli_fetch_assoc($qShowStatusResult)) {
+ $next_increment = $row['Auto_increment'];
+ }
+ mysqli_free_result($qShowStatusResult);
+ return $next_increment;
+
+
+}
+*/
+?>
diff --git a/admin/survey/classes/class.SurveyAapor.php b/admin/survey/classes/class.SurveyAapor.php
new file mode 100644
index 0000000..1418f60
--- /dev/null
+++ b/admin/survey/classes/class.SurveyAapor.php
@@ -0,0 +1,590 @@
+<?php
+
+class SurveyAapor {
+
+ private $userBy = array();
+ private $_surveyId;
+ private $_aapor = array();
+
+ public $usability = array();
+ public $userByStatus = array();
+ //public $cntUserByStatus = array('valid'=>0, 'nonvalid'=>0, 'invitation'=>0);
+ public $cntUserByStatus = array();
+ public $appropriateStatus = array(6,5);
+ public $unAppropriateStatus = array('6l','5l',4,3);
+ public $invitationStatus = array(2,1,0);
+ public $testDataCount = 0;
+
+ public $cntValidRedirections = 0; // Stejemo vlejavne referale (ki vsebujejo tekst)
+ public $cntNonValidRedirections = 0; // Stejemo neveljavne referale (ki ne vsebujejo teksta)
+ public $userRedirections = array(3=>0,4=>0,5=>0,6=>0,'valid' => array('email'=>0),'email'=>0,'direct'=>0); // za porazdelitev redirekcij na anketo
+ public $maxRedirection = 0; // koliko je maksimalno število klikov (za primerno širino diva)
+ public $maxCharRedirection = 0; // max stevilo znakovv v "host" (za lepsi izpis redirekcij)
+
+ public $realUsersByStatus_all = 0; // skupaj frekvenc
+ public $realUsersByStatus = array(); // frekvenca po posameznem statusu (uposeteva da ce je kdo koncal anketo jo je tudi zacel)
+ public $respondentLangArray = array(); # grupiranje po jezikih
+
+ public $tmp_direct = 0;
+ public $emailStatus = array(0,1,2);
+
+ function __construct($cntAnswers,$answers,$surveyId) {
+ global $lang;
+
+ $this->cntUserByStatus = $cntAnswers;
+ $this->userByStatus = $answers;
+ $this->_surveyId = $surveyId;
+ //$this->izracunajPodatke($this->_surveyId);
+ //error_log("ID: ".$surveyId);
+
+ $sur = new SurveyUsableResp($surveyId, $generateDatafile=false);
+
+ if(!$sur->hasDataFile())
+ echo $lang['srv_dashboard_no_file']; // Ce se ni zgenerirana datoteka s podatki izpisemo error
+ else
+ $this->usability = $sur->calculateData(); // Dobimo array z usability podatki
+ //var_dump($this->usability);
+
+ $page = $_GET['m'];
+
+ if(strcmp($page,'aapor2') == 0)
+ $this->calculateFullAapor();
+ else if(strcmp($page,'aapor1') == 0)
+ $this->calculateAapor();
+ }
+
+ function calculateAapor() {
+ global $lang;
+ $s6 = (int)$this->userByStatus['valid'][6];
+ $s5 = (int)$this->userByStatus['valid'][5];
+ $s6l = (int)$this->userByStatus['nonvalid']['6l'];
+ $s5l = (int)$this->userByStatus['nonvalid']['5l'];
+ $s4 = (int)$this->userByStatus['nonvalid'][4];
+ $s3 = (int)$this->userByStatus['nonvalid'][3];
+ $s2 = (int)$this->userByStatus['nonvalid'][2];
+ $s1 = (int)$this->userByStatus['nonvalid'][1];
+ $s0 = (int)$this->userByStatus['nonvalid'][0];
+ $s_1 = (int)$this->userByStatus['nonvalid'][-1];
+
+
+
+ /* debug
+ echo '<br>'.$s6;
+ echo '<br>'.$s5;
+ echo '<br>'.$s6l;
+ echo '<br>'.$s5l;
+ echo '<br>'.$s4;
+ echo '<br>'.$s3;
+ echo '<br>'.$s2;
+ echo '<br>'.$s1;
+ echo '<br>'.$s0;
+ echo '<br>'.$s_1;
+ */
+
+ /* Po starem še
+ * $rr1 = @$s6 / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1)+($s2+$s0));
+ $rr2 = @($s6+$s5) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1)+($s2+$s0));
+ $rr3 = @$s6 / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1)+0.5*($s2+$s0));
+ $rr4 = @($s6+$s5) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1)+0.5*($s2+$s0));
+ $rr5 = @$s6 / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1));
+ $rr6 = @($s6+$s5) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1));
+
+ $con1 = @($s6+$s5+$s6l+$s5l+$s4+$s3) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1)+($s2+$s0));
+ $con2 = @($s6+$s5+$s6l+$s5l+$s4+$s3) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1)+0.5*($s2+$s0));
+ $con3 = @($s6+$s5+$s6l+$s5l+$s4+$s3) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1));
+
+ $pror = @($s6+$s5) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1));
+ $comr = @($s6+$s5) / ( ($s6+$s5)+($s6l+$s5l+$s4+$s3+$s1));
+
+
+
+
+ pregledovanje
+ $crr = $pror * $comr;
+ */
+
+
+ //$this->izracunajPodatke($this->_surveyId);
+ $usable = $this->usability['usable'];
+ $partusable = $this->usability['partusable'];
+ $all = $this->usability['all'];
+ $niodgo = (int)$this->_answwers['invitation'][1];
+ $rr1_apro = 0;
+ $rr2_apro = 0;
+ $rr5_apro = 0;
+ $rr6_apro = 0;
+ if($all > 0){
+ $rr1_apro = $this->formatNumber(($usable)/$all,3,'');
+ //$rr5_apro = $this->formatNumber(($usable)/($all-$niodgo),3,'');
+ $rr2_apro = $this->formatNumber(($usable+$partusable)/$all,3,'');
+ //$rr6_apro = $this->formatNumber(($usable+$partusable)/($all-$niodgo),3,'');
+ }
+
+ echo '<div class="floatLeft">';
+ //echo 'Uporabni: '.$usability['usable'].'<br> Delno uporabni: '.$usability['partusable'].'<br> Vsi:'.$usability['all'].'<br><br>';
+ echo '<b>'.$lang['srv_aapor_show_approximate_calculation'].'</b><br>';
+ echo '<label>RR1\': '.$rr1_apro.'</label><br>';
+ echo '<label>RR2\': '.$rr2_apro.'</label><br>';
+ //echo '<label>RR5\': '.$rr5_apro.'</label><br>';
+ //echo '<label>RR6\': '.$rr6_apro.'</label><br>';
+ echo '</div>';
+ /*echo '<b>AAPOR response rate glede na 1KA statuse:</b>';
+ echo '<br />RR1 = '.$this->formatNumber($rr1,3,'');
+ echo '<br />RR2 = '.$this->formatNumber($rr2,3,'');
+ echo '<br /><span class="red strong">RR3 = '.$this->formatNumber($rr3,3,'').'</span>';
+ echo '<br />RR4 = '.$this->formatNumber($rr4,3,'');
+ echo '<br />RR5 = '.$this->formatNumber($rr5,3,'');
+ echo '<br />RR6 = '.$this->formatNumber($rr6,3,'');
+ echo '<br />';
+ echo '<br /><b>Contact rates:</b>';
+ echo '<br />CON1 = '.$this->formatNumber($con1,3,'');
+ echo '<br />CON2 = '.$this->formatNumber($con2,3,'');
+ echo '<br />CON3 = '.$this->formatNumber($con3,3,'');
+ echo '<br />';
+ echo '<br /><b>AAPOR paneli:</b>';
+ echo '<br />Profile rate: PROR = '.$this->formatNumber($pror,3,'');
+ echo '<br />Completion rate: COMR = '.$this->formatNumber($comr,3,'');
+ echo '<br />';
+ echo '<br /><b>Cumulative response rate:</b>';
+ echo '<br />CUMRR = '.$this->formatNumber($crr,3,'');*/
+
+ //echo '</div>';
+
+ echo '<div class="floatLeft" style="margin-left:50px">';
+ echo '<b>Statusi:</b>';
+ echo '<br/>';
+ $arrayStatusi = array('6'=>$s6,'6l'=>$s6l,'5'=>$s5,'5l'=>$s5l,'4'=>$s4,'3'=>$s3,'2'=>$s2,'1'=>$s1,'0'=>$s0);
+ foreach ($arrayStatusi as $status => $value) {
+ echo '<span class="dashboard_status_span">' . $lang['srv_userstatus_'.$status] . ' ('.$status.') :</span>' . $value
+ . '<br/>';
+ }
+ echo '<br /><br/>';
+
+ echo 'Povezave:<br/>';
+ // echo '<a href="http://www.aapor.org/For_Researchers/4683.htm" target="_blank">';
+ echo '<a href="https://www.esomar.org/knowledge-and-standards/research-resources/aapor-standard-definitions.php" target="_blank">';
+ echo 'Standard Definitions – Final Dispositions of Case Codes and Outcome Rates for Surveys (PDF)';
+ echo '</a>';
+ echo '</div>';
+ echo '<br class="clr"/>';
+ }
+
+ function calculateFullAapor(){
+ global $lang;
+
+ echo '<div class="floatLeft">';
+ echo '<h2>'.$lang['srv_lnk_AAPOR2'].'</h2>';
+ echo'
+ <form id="aaporForm">
+ <input type="hidden" name="anketa" value="'.$this->_surveyId.'" />
+ <table id="aapor_table">
+ <tbody>
+ <tr>
+ <td></td><td><label>'.$lang['srv_aapor_show_approximate'].'</label><input onchange="prikazi('.$this->_surveyId.')" id="prikazipriblizek" type="checkbox" name="prikaziPriblizek" /></td>
+ </tr>
+ <tr>
+ <td><span class="main_title_aapor">Returne questionaire (1.0)</span></td><td><input class="main_aapor main_title_aapor" type="text" name="rq" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Complete (1.1)</span></td><td><input onchange="calculateReturne()" class="input_aapor category_span" type="text" name="complete" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Partial or break-off (1.2)</span></td><td><input onchange="calculateReturne()" class="input_aapor category_span" type="text" name="partial" /></td>
+ </tr>
+ <tr>
+ <td><span class="main_title_aapor">Eligible (2.0)</span></td><td><input class="main_aapor main_title_aapor" type="text" name="eligible" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Refusal (2.11)</span></td><td><input class="read_aapor category_span" type="text" name="refusal" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Explicit refusal (2.111)</span></td><td><input onchange="calculateRefusal()" class="input_aapor subcategory1_span" type="text" name="refusalEx" /></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Implicit refusal (2.112)</span></td><td><input class="read_aapor subcategory1_span" type="text" name="refusalIm" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory2_span">Logged on to survay, did not complete any items (2.1121)</span></td><td><input onchange="calculateRefusalIm()" class="input_aapor subcategory2_span" type="text" name="loggedNotComplete" /></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory2_span">Read receipt confirmation, refusal (2.1122)</span></td><td><input onchange="calculateRefusalIm()" class="input_aapor subcategory2_span" type="text" name="readReceiptConfirmation" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Brak-off or partial with insufficient information (2.12)</span></td><td><input onchange="calculateEligible()" class="input_aapor category_span" type="text" name="breakOff" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Not-Contact (2.20)</span></td><td><input onchange="calculateEligible()" class="read_aapor category_span" type="text" name="nonContact" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Respondenr was unavailable during field period (2.26)</span></td><td><input onchange="calculateNonContact()" class="input_aapor subcategory1_span" type="text" name="respondentUnavailable" /></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Completed questionnaire, but not retuned during field period (2.27)</span></td><td><input onchange="calculateNonContact()" class="input_aapor subcategory1_span" type="text" name="completedNotReturned" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Other (2.30)</span></td><td><input onchange="calculateEligible()" class="read_aapor category_span" type="text" name="otherEligible" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Language barrier (2.33)</span></td><td><input onchange="calculateOtherEligible()" class="input_aapor subcategory1_span" type="text" name="languageBarrier" /></td>
+ </tr>
+ <tr>
+ <td><span class="main_title_aapor">Unknown eligible, "non-interview" (3.0)</span></td><td><input class="main_aapor main_title_aapor" type="text" name="unknownEligible" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Nothing known about respondent or address (3.10)</span></td><td><input onchange="calculateUnknownEligibility()" class="read_aapor category_span" type="text" name="nothingKnown" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">No invitation sent (3.11)</span></td><td><input onchange="calculateNothingKnownRespondent()" class="input_aapor subcategory1_span" type="text" name="noInvitation" /></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Nothing ever returned (3.19)</span></td><td><input onchange="calculateNothingKnownRespondent()" class="input_aapor subcategory1_span" type="text" name="nothingReturned" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Invitation returned undelivered (3.30)</span></td><td><input onchange="calculateUnknownEligibility()" class="input_aapor category_span" type="text" name="invitationReturnedUndelivered" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Invitation returned with forwarding information (3.40)</span></td><td><input onchange="calculateUnknownEligibility()" class="input_aapor category_span" type="text" name="invitationReturnedForwarding" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Other (3.90)</span></td><td><input onchange="calculateUnknownEligibility()" class="read_aapor category_span" type="text" name="otherUnknownEligible" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Returned from a unsampled email address (3.91)</span></td><td><input onchange="calculateOtherUnknownEligibility()" class="input_aapor subcategory1_span" type="text" name="returnedUnsampledEmail" /></td>
+ </tr>
+ <tr>
+ <td><span class="main_title_aapor">Not eligible, Returned (4.0)</span></td><td><input class="main_aapor main_title_aapor" type="text" name="notEligible" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Selected Respondent Screende Out of Sample (4.10)</span></td><td><input onchange="calculateNotEligible()" class="input_aapor category_span" type="text" name="selectedRespondent" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Quota Filled (4.80)</span></td><td><input onchange="calculateNotEligible()" class="read_aapor category_span" type="text" name="quotaFilled" readonly/></td>
+ </tr>
+ <tr>
+ <td><span class="subcategory1_span">Duplicate Listing (4.81)</span></td><td><input onchange="calculateQuotaFilled()" class="input_aapor subcategory1_span" type="text" name="duplicateListing" /></td>
+ </tr>
+ <tr>
+ <td><span class="category_span">Other (4.90)</span></td><td><input onchange="calculateNotEligible()" class="input_aapor category_span" type="text" name="otherNotEligible" /></td>
+ </tr>
+ <tr id="totalSub">
+ <td class="totalSubTd">Skupna vsota:</td><td><span class="totalSubSpan"></span></td>
+ </tr>
+ <tr id="totalSub">
+ <td class="totalSubTd">'.$lang['srv_statistic_sum_all'].'</td><td><span class="totalSubDatabaseSpan"></span></td>
+ </tr>
+ <tr>
+ <td class="aaporSpace"></td>
+ </tr>
+ <tr>
+ <td><span class="main_title_aapor aapor_e">e <span style="font-size: 70%">['.$lang['srv_statistic_e_description'].']<span></span></td><td><input class="input_aapor" type="text" name="e" /></td>
+ </tr>
+ <tr>
+ <td colspan="2"><span class="floatLeft spaceRight aaporButton"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="getCallculationAapor('.$this->_surveyId.')"><span>'.$lang['srv_aapor_calculation'].'</span></a></div></span></td>
+ </tr>
+ </tbody>
+ </table>
+ </form>
+ ';
+ echo '</div>';
+ echo '<div class="floatLeft show_calculation">';
+ echo '<h2>'.$lang['srv_aapor_show_calculation'].'</h2>';
+ echo '<table>
+ <tbody>
+ <tr>
+ <td>RR1:</td><td><span id="rr1"></span></td>
+ </tr>
+ <tr>
+ <td>RR2:</td><td><span id="rr2"></span></td>
+ </tr>
+ <tr>
+ <td>RR3:</td><td><span id="rr3"></span></td>
+ </tr>
+ <tr>
+ <td>RR4:</td><td><span id="rr4"></span></td>
+ </tr>
+ <tr>
+ <td>RR5:</td><td><span id="rr5"></span></td>
+ </tr>
+ <tr>
+ <td>RR6:</td><td><span id="rr6"></span></td>
+ </tr>
+ </tbody>
+ </table>';
+ echo '</div>';;
+ }
+ function calculationForFullAapor(){
+ $data = array();
+ $rr1 = 0;
+ $rr2 = 0;
+ $rr3 = 0;
+ $rr4 = 0;
+ $rr5 = 0;
+ $rr6 = 0;
+
+ $refusal = $_POST['refusal'];
+ $refusal = $refusal=='' || !is_numeric($refusal) ? 0:$refusal;
+
+ $breakOff = $_POST['breakOff'];
+ $breakOff = $breakOff=='' || !is_numeric($breakOff) ? 0:$breakOff;
+
+ $invitationReturnedUndelivered = $_POST['invitationReturnedUndelivered'];
+ $invitationReturnedUndelivered = $invitationReturnedUndelivered=='' || !is_numeric($invitationReturnedUndelivered) ? 0:$invitationReturnedUndelivered;
+
+ $invitationReturnedForwarding = $_POST['invitationReturnedForwarding'];
+ $invitationReturnedForwarding = $invitationReturnedForwarding=='' || !is_numeric($invitationReturnedForwarding) ? 0:$invitationReturnedForwarding;
+
+ $otherUnknownEligible = $_POST['otherUnknownEligible'];
+ $otherUnknownEligible = $otherUnknownEligible=='' || !is_numeric($otherUnknownEligible) ? 0:$otherUnknownEligible;
+
+ $i = $_POST['complete'];
+ $i = $i=='' || !is_numeric($i) ? 0:$i;
+
+ $p = $_POST['partial'];
+ $p = $p=='' || !is_numeric($p) ? 0:$p;
+
+ $r = $refusal+$breakOff;
+
+ $nc = $_POST['nonContact'];
+ $nc = $nc=='' || !is_numeric($nc) ? 0:$nc;
+
+ $o = $_POST['otherEligible'];
+ $o = $o == '' || !is_numeric($o) ? 0:$o;
+
+ $uh = $_POST['nothingKnown'];
+ $uh = $uh=='' || !is_numeric($uh) ? 0:$uh;
+
+ $uo = $invitationReturnedUndelivered + $invitationReturnedForwarding + $otherUnknownEligible;
+
+ $e = $_POST['e'];
+ $e = $e=='' || !is_numeric($e) ? 100:$e;
+ if($e > 100 || $e<0){
+ $e = 100;
+ }
+ $e = $e/100;
+ //error_log("E je ".$e);
+ $sub1 = $i+$p+$r+$nc+$o+$uh+$uo;
+ $sub2 = $i+$p+$r+$nc+$o+$e*($uh+$uo);
+ $sub3 = $i+$p+$r+$nc+$o;
+
+ //error_log($refusal." - ".$breakOff." - ".$invitationReturnedUndelivered." - ".$invitationReturnedForwarding." - ".$otherUnknownEligible." - ".$i."- ".$p." - ".$r." - ".$nc." - ".$o." - ".$uh." - ".$uo." - ".$e);
+
+ if($sub1 > 0){
+ $rr1 = $i/($sub1);
+ $rr2 = ($i+$p)/($sub1);
+ }
+ if($sub2 > 0){
+ $rr3 = $i/($sub2);
+ $rr4 = ($i+$p)/($sub2);
+ }
+ if($sub3 > 0){
+ $rr5 = $i/($sub3);
+ $rr6 = ($i+$p)/($sub3);
+ }
+
+ $data['rr1'] = $this->formatNumber($rr1,3,'');
+ $data['rr2'] = $this->formatNumber($rr2,3,'');
+ $data['rr3'] = $this->formatNumber($rr3,3,'');
+ $data['rr4'] = $this->formatNumber($rr4,3,'');
+ $data['rr5'] = $this->formatNumber($rr5,3,'');
+ $data['rr6'] = $this->formatNumber($rr6,3,'');
+
+ echo json_encode($data);
+ }
+
+ function izracunajPodatke($id){
+ /*$sur = new SurveyUsableResp($id, $generateDatafile=false);
+
+ if($sur->hasDataFile())
+ $this->usability = $sur->calculateData(); // Dobimo array z usability podatki*/
+ $qry_string = "SELECT id, language, last_status, lurker, inv_res_id, referer FROM srv_user WHERE ank_id = '".$id."' AND preview = '0' AND deleted='0'";
+ $qry = sisplet_query($qry_string);
+
+ if (mysqli_num_rows($qry) > 0) {
+ $user_id_to_check_link = array(); # id-ji uporabnikov pri katerih imamo direkten klik. naknadno ugotavljamo ali je slučajno e-mail vabilo
+ while ($row = mysqli_fetch_assoc($qry)) {
+ if ((int)$row['testdata'] > 0) {
+ $this->testDataCount++;
+ }
+ // dodamo statuse
+ if (in_array($row['last_status'], $this->appropriateStatus))
+ {
+ # če ni lurker je ok
+ if ($row['lurker'] == 0)
+ {
+ $this->userByStatus['valid'][$row['last_status']] += 1;
+ $this->cntUserByStatus['valid'] += 1;
+ }
+ else
+ {
+ # če je lurker ga dodamo k neveljavnim
+ $this->userByStatus['nonvalid'][$row['last_status'].'l'] += 1;
+ $this->cntUserByStatus['nonvalid'] += 1;
+ }
+ }
+ # neveljavne enote
+ else if (in_array($row['last_status'], $this->unAppropriateStatus))
+ {
+ $this->userByStatus['nonvalid'][$row['last_status']] += 1;
+ $this->cntUserByStatus['nonvalid'] += 1;
+ }
+ # emaili
+ else if (in_array($row['last_status'], $this->invitationStatus))
+ {
+ $this->userByStatus['invitation'][$row['last_status']] += 1;
+ $this->cntUserByStatus['invitation'] += 1;
+ }
+
+ #polovimo redirekte
+ if (in_array((int)$row['last_status'], $this->invitationStatus))
+ {
+ # email vabila ... ne lovimo redirektov
+ # podatek o referalu je prazen lahko da email ni bil poslan, ali pa gre za direkten link
+ #$this->cntNonValidRedirections += 1;
+ #$this->userRedirections[(int)$row['last_status']] += 1;
+ }
+ else {
+ # če so vabila
+ if ($row['inv_res_id'] != null )
+ {
+ $this->cntValidRedirections += 1;
+ $this->userRedirections["valid"]['email'] += 1;
+ $this->maxRedirection = max($this->maxRedirection , $this->userRedirections["valid"]['email']);
+ }
+ # če imamo referal
+ else if ($row['referer'] != "")
+ {
+ $parsed = parse_url($row['referer']);
+ $this->cntValidRedirections += 1;
+ $this->userRedirections["valid"][$parsed['host']] += 1;
+ $this->maxCharRedirection = max($this->maxCharRedirection , strlen ($parsed['host']) );
+ $this->maxRedirection = max($this->maxRedirection , $this->userRedirections["valid"][$parsed['host']] );
+ }
+ # če ne je najbrž direkten link
+ else
+ {
+ # shranimo id_userjev za katere nato ugotavljamo ali je link res direkten ali obstaja kaksen zapis da je slo preko e-maila
+ $user_id_to_check_link[] = $row['id'];
+ $this->tmp_direct +=1;
+ }
+ }
+ #polovimo jezike
+ if (isset($respondentLangArray[$row['language']]))
+ {
+ $respondentLangArray[$row['language']] ++;
+ }
+ else
+ {
+ $respondentLangArray[$row['language']] = 1;
+ }
+ }
+ }
+
+ # od direktnega klika odštejemo e-mail vabila
+ if (count($user_id_to_check_link)> 0) {
+ $qry_stringEmail = "SELECT COUNT(*) as cnt FROM srv_userstatus WHERE usr_id IN (".implode(',', $user_id_to_check_link).") AND status IN (".implode(',', $this->emailStatus).")";
+ $qryEmail = sisplet_query($qry_stringEmail);
+ $rwsEmail = mysqli_fetch_assoc($qryEmail);
+ $this->userRedirections["email"] = (int)$rwsEmail['cnt'];
+ $this->userRedirections["direct"] = (int)$this->tmp_direct - (int)$rwsEmail['cnt'];
+ }
+ // prestejemo max stevilo klikov za lepsi izris tabele
+ $this->maxRedirection = max($this->maxRedirection , $this->userRedirections["2"], $this->userRedirections["1"], $this->userRedirections["0"],$this->userRedirections["direct"], $this->userRedirections['email']);
+
+ # izracunamo realne frekvence po statusih
+ # Klik na anketo - vsak ki je končal anketo (itd...) je "najbrž" tudi kliknil na anketo..
+ $this->realUsersByStatus_all = $this->userByStatus['valid'][6]
+ + $this->userByStatus['valid'][5]
+ + $this->userByStatus['nonvalid']['5l']
+ + $this->userByStatus['nonvalid']['6l']
+ + $this->userByStatus['nonvalid'][4]
+ + $this->userByStatus['nonvalid'][3]
+ + $this->userByStatus['nonvalid'][-1];
+ // Klik na prvo stran - vsak ki je končal anketo (itd...) je "najbrž" tudi kliknil na anketo..
+ # končal anketo => 6
+ $this->realUsersByStatus[6] = array('cnt'=>$this->userByStatus['valid'][6], 'percent'=>0);
+ # začel izpolnjevat => 5 = 6 + 5
+ $this->realUsersByStatus[5] = array('cnt'=>$this->userByStatus['valid'][5]+$this->realUsersByStatus[6]['cnt'], 'percent'=>0);
+ # Koliko ljudi je dejansko končalo anketo ne glede na to ali so lurkerji 6 + 6l
+ $this->realUsersByStatus['6ll'] = array('cnt'=>$this->userByStatus['nonvalid']['6l']+$this->realUsersByStatus[6]['cnt'], 'percent'=>0);
+ # delno izpolnjena 4ll => 6 + 5 + 6l + 5l
+ $this->realUsersByStatus['5ll'] = array('cnt'=>$this->userByStatus['nonvalid']['6l']+$this->userByStatus['nonvalid']['5l']+$this->realUsersByStatus[5]['cnt'], 'percent'=>0);
+ # klik na prvo stran => 4 = 6 + 6l + 5l + 5 + 4
+ $this->realUsersByStatus['4ll'] = array('cnt'=>$this->userByStatus['nonvalid'][4]+$this->realUsersByStatus['5ll']['cnt'], 'percent'=>0);
+ # klik na anketo => 3 = 6 + 6l + 5l + 5 + 4 + 3
+ $this->realUsersByStatus['3ll'] = array('cnt'=>$this->userByStatus['nonvalid'][3]+$this->userByStatus['nonvalid'][-1]+$this->realUsersByStatus['4ll']['cnt'], 'percent'=>0);
+ //if ($this->emailInvitation == 1)
+ {
+ $this->realUsersByStatus['email']
+ = array('cnt'=>(isset($this->userByStatus['valid']['email'])?$this->userByStatus['valid']['email']:0), 'percent'=>0);
+ }
+
+ $qry_string = "SELECT * FROM srv_invitations_recipients WHERE ank_id='".$id."' AND deleted='0'";
+ $qry = sisplet_query($qry_string);
+ $this->userByStatus['invitation'][0]=0;
+ $this->userByStatus['invitation'][1]=0;
+ $this->userByStatus['invitation'][2]=0;
+ while ($row = mysqli_fetch_assoc($qry)) {
+ if(in_array($row['last_status'], $this->invitationStatus)){
+ $this->userByStatus['invitation'][$row['last_status']] += 1;
+ }
+ }
+ }
+ function prikaziPriblizek(){
+ $data = array();
+ error_log("Id v metodi priblizek: ".$this->_surveyId);
+
+ /*$ss = new SurveyStatistic();
+ $ss->Init($this->_surveyId);
+ $ss->PrepareDateView();
+ $this->userByStatus = $ss->getUserByStatus();*/
+ //$this->izracunajPodatke($id);
+ //var_dump($this->cntUserByStatus);
+
+ $usable = $this->usability['usable'];
+ $partusable = $this->usability['partusable'];
+ $unusable = $this->usability['unusable'];
+ $status3 = $this->userByStatus['nonvalid'][3];
+ $status4 = $this->userByStatus['nonvalid'][4];
+ $status34 = 0;
+ $status0 = $this->userByStatus['invitation'][0];
+ $status2 = $this->userByStatus['invitation'][2];
+ $status02 = 0;
+ $status1 = $this->userByStatus['invitation'][1];
+ //if(!is_null($status3) && !is_null($status4) && is_int($status3) && is_int($status4)){
+ $status34 = $status3+$status4;
+ //}
+ //if(!is_null($status0) && !is_null($status2) && is_int($status0) && is_int($status2)){
+ $status02 = $status0+$status2;
+ //}
+
+ $skupaj = $this->cntUserByStatus['valid']+$this->cntUserByStatus['nonvalid']+$this->cntUserByStatus['invitation'];
+
+ $data['usable'] = is_null($usable) || !is_int($usable) ? 0 : $usable;
+ $data['partusable'] = is_null($partusable) || !is_int($partusable) ? 0 : $partusable;
+ $data['unusable'] = is_null($unusable) || !is_int($unusable) ? 0 : $unusable;
+ $data['status1'] = is_null($status1) || !is_int($status1) ? 0 : $status1;
+ $data['status34'] = $status34;
+ $data['status02'] = $status02;
+ $data['skupaj'] = $skupaj;
+
+ echo json_encode($data);
+ }
+
+ /** Lepo oblikuje number string
+ *
+ * @param float $value
+ * @param int $digit
+ * @param string $sufix
+ * @return string
+ */
+ function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+ $result = number_format($result, $digit, '.', ',') . $sufix;
+
+ return $result;
+ }
+
+}
diff --git a/admin/survey/classes/class.SurveyAktivnost.php b/admin/survey/classes/class.SurveyAktivnost.php
new file mode 100644
index 0000000..28b9e3f
--- /dev/null
+++ b/admin/survey/classes/class.SurveyAktivnost.php
@@ -0,0 +1,911 @@
+<?php
+
+class SurveyAktivnost{
+
+
+ public function __construct(){
+ global $lang;
+
+ //echo '<br><br>Začasno onemogočeno zaradi težav z bazo!';
+ //die();
+ }
+
+
+ /**
+ * @desc prikaze diagnostiko anket
+ */
+ public function diagnostics() {
+ global $lang, $global_user_id, $admin_type, $app_settings;
+
+ $sum = 0;
+ $sum_survey = 0;
+
+ if ($_GET['time'] > 0)
+ $time = $_GET['time'];
+ else
+ $time = '1 month';
+ if (isset ($_GET['type']))
+ $type = $_GET['type'];
+ else
+ $type = 'users';
+ if (isset ($_GET['from']))
+ $from = $_GET['from'];
+ else
+ $from = '';
+ if (isset ($_GET['to']))
+ $to = $_GET['to'];
+ else
+ $to = '';
+
+
+ echo '<form id="diagnostics_form" action="index.php" method="get">';
+
+ echo '<input type="hidden" name="a" value="diagnostics" />';
+
+ $testdata = (isset($_GET['testdata']) && $_GET['testdata']=='1') ? 1 : 0;
+ $testdataauto = (isset($_GET['testdataauto']) && $_GET['testdataauto']=='1') ? 1 : 0;
+ $uvoz = (isset($_GET['uvoz']) && $_GET['uvoz']=='1') ? 1 : 0;
+
+ $ustrezni = (isset($_GET['ustrezni']) && $_GET['ustrezni']=='0') ? 0 : 1;
+ $delnoustrezni = (isset($_GET['delnoustrezni']) && $_GET['delnoustrezni']=='0') ? 0 : 1;
+ $neustrezni = (isset($_GET['neustrezni']) && $_GET['neustrezni']=='1') ? 1 : 0;
+ $mailsent = (isset($_GET['mailsent']) && $_GET['mailsent']=='1') ? 1 : 0;
+
+ $language = (isset($_GET['language'])) ? $_GET['language'] : 0;
+
+ if(isset($app_settings['commercial_packages']) && $app_settings['commercial_packages'] == true){
+
+ $package_1ka = (isset($_GET['package_1ka']) && $_GET['package_1ka']=='0') ? 0 : 1;
+ $package_2ka = (isset($_GET['package_2ka']) && $_GET['package_2ka']=='0') ? 0 : 1;
+ $package_3ka = (isset($_GET['package_3ka']) && $_GET['package_3ka']=='0') ? 0 : 1;
+
+ echo '<span>'.$lang['srv_narocilo_paket'].':</span>';
+
+ echo '<input type="hidden" name="package_1ka" id="package_1ka_hidden" value="'.$package_1ka.'" />';
+ echo '<input type="checkbox" value="1" id="package_1ka" '.($package_1ka == 1 ? ' checked="checked"' : '').'" onchange="$(\'#package_1ka_hidden\').val('.($package_1ka==1 ? '0' : '1').');"><label for="package_1ka">1KA</label>';
+ echo '<input type="hidden" name="package_2ka" id="package_2ka_hidden" value="'.$package_2ka.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="package_2ka" '.($package_2ka == 1 ? ' checked="checked"' : '').' onchange="$(\'#package_2ka_hidden\').val('.($package_2ka==1 ? '0' : '1').');"><label for="package_2ka">2KA</label></span>';
+ echo '<input type="hidden" name="package_3ka" id="package_3ka_hidden" value="'.$package_3ka.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="package_3ka" '.($package_3ka == 1 ? ' checked="checked"' : '').' onchange="$(\'#package_3ka_hidden\').val('.($package_3ka==1 ? '0' : '1').');"><label for="package_3ka">3KA</label></span>';
+
+ echo '<span class="spaceLeft spaceRight bold">|</span>';
+ }
+
+ echo '<input type="checkbox" value="1" id="testdata" name="testdata" '.($testdata == 1 ? ' checked="checked"' : '').'"><label for="testdata">'.$lang['srv_diagnostics_filter_test'].'</label>';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="testdataauto" name="testdataauto" '.($testdataauto == 1 ? ' checked="checked"' : '').'"><label for="testdataauto">'.$lang['srv_diagnostics_filter_autotest'].'</label></span>';
+ echo '<input type="hidden" name="uvoz" id="uvoz_hidden" value="'.$uvoz.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" id="uvoz" '.($uvoz == 1 ? ' checked="checked"' : '').' onchange="$(\'#uvoz_hidden\').val('.($uvoz==1 ? '0' : '1').');"><label for="uvoz">'.$lang['srv_diagnostics_filter_import'].'</label></span>';
+
+ echo '<input type="hidden" name="ustrezni" id="ustrezni_hidden" value="'.$ustrezni.'" />';
+ echo '<span class="spaceLeft bold">|</span><span class="spaceLeft"></span><input type="checkbox" id="ustrezni" '.($ustrezni == 1 ? ' checked="checked"' : '').' onchange="$(\'#ustrezni_hidden\').val('.($ustrezni==1 ? '0' : '1').');"><label for="ustrezni">'.$lang['srv_diagnostics_filter_6'].'</label>';
+ echo '<input type="hidden" name="delnoustrezni" id="delnoustrezni_hidden" value="'.$delnoustrezni.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" id="delnoustrezni" '.($delnoustrezni == 1 ? ' checked="checked"' : '').' onchange="$(\'#delnoustrezni_hidden\').val('.($delnoustrezni==1 ? '0' : '1').');"><label for="delnoustrezni">'.$lang['srv_diagnostics_filter_5'].'</label></span>';
+ echo '<input type="hidden" name="neustrezni" id="neustrezni_hidden" value="'.$neustrezni.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="neustrezni" '.($neustrezni == 1 ? ' checked="checked"' : '').' onchange="$(\'#neustrezni_hidden\').val('.($neustrezni==1 ? '0' : '1').');"><label for="neustrezni">'.$lang['srv_diagnostics_filter_34'].'</label></span>';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="mailsent" name="mailsent" '.($mailsent == 1 ? ' checked="checked"' : '').'><label for="mailsent">'.$lang['srv_diagnostics_filter_012'].'</label></span>';
+
+ echo '<span class="spaceLeft bold">|</span><span class="spaceLeft"></span>'.$lang['lang'].': <select id="language" name="language">';
+ echo '<option value="0" '.($language=='0' ? ' selected' : '').'>'.$lang['srv_diagnostics_filter_lang_all'].'</option>';
+ echo '<option value="1" '.($language=='1' ? ' selected' : '').'>'.$lang['srv_diagnostics_filter_lang_slo'].'</option>';
+ echo '<option value="2" '.($language=='2' ? ' selected' : '').'>'.$lang['srv_diagnostics_filter_lang_ang'].'</option>';
+
+ echo '<input type="button" class="spaceLeft" value="'.$lang['srv_coding_filter'].'" onClick="this.form.submit();">';
+
+ echo '<br /><br />';
+
+ echo ''.$lang['srv_diagnostics_total'].' <select name="type" onchange="this.form.submit();">';
+ echo '<option value="users"' . ($type == 'users' ? ' selected' : '') . '>'.$lang['srv_diagnostics_respondentov'].'</option>';
+ echo '<option value="emails"' . ($type == 'emails' ? ' selected' : '') . '>'.$lang['srv_email-vabila'].'</option>';
+ echo '<option value="pages"' . ($type == 'pages' ? ' selected' : '') . '>'.$lang['srv_diagnostics_strani'].'</option>';
+ echo '<option value="analiza"' . ($type == 'analiza' ? ' selected' : '') . '>'.$lang['srv_diagnostics_analiza'].'</option>';
+ echo '<option value="graph"' . ($type == 'graph' ? ' selected' : '') . '>'.$lang['srv_diagnostics_graph'].'</option>';
+ echo '<option value="editing"' . ($type == 'editing' ? ' selected' : '') . '>'.$lang['srv_diagnostics_editing'].'</option>';
+ echo '</select> '.$lang['srv_diagnostics_in'].' ';
+
+ echo '<select id="diagnostics_date_selected" name="time" onchange="diagnosticsChooseDate()">';
+ echo '<option value="1 minute"' . ($time == '1 minute' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 minute'].'</option>';
+ echo '<option value="5 minute"' . ($time == '5 minute' ? ' selected' : '') . '>'.$lang['srv_diagnostics_5 minute'].'</option>';
+ echo '<option value="10 minute"' . ($time == '10 minute' ? ' selected' : '') . '>'.$lang['srv_diagnostics_10 minute'].'</option>';
+ echo '<option value="30 minute"' . ($time == '30 minute' ? ' selected' : '') . '>'.$lang['srv_diagnostics_30 minute'].'</option>';
+ echo '<option value="1 hour"' . ($time == '1 hour' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 hour'].'</option>';
+ echo '<option value="6 hour"' . ($time == '6 hour' ? ' selected' : '') . '>'.$lang['srv_diagnostics_6 hour'].'</option>';
+ echo '<option value="12 hour"' . ($time == '12 hour' ? ' selected' : '') . '>'.$lang['srv_diagnostics_12 hour'].'</option>';
+ echo '<option value="1 day"' . ($time == '1 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 day'].'</option>';
+ echo '<option value="2 day"' . ($time == '2 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_2 day'].'</option>';
+ echo '<option value="5 day"' . ($time == '5 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_5 day'].'</option>';
+ echo '<option value="7 day"' . ($time == '7 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_7 day'].'</option>';
+ echo '<option value="14 day"' . ($time == '14 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_14 day'].'</option>';
+ echo '<option value="1 month"' . ($time == '1 month' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 month'].'</option>';
+ echo '<option value="3 month"' . ($time == '3 month' ? ' selected' : '') . '>'.$lang['srv_diagnostics_3 month'].'</option>';
+ echo '<option value="6 month"' . ($time == '6 month' ? ' selected' : '') . '>'.$lang['srv_diagnostics_6 month'].'</option>';
+ echo '<option id="option_99date" value="99date"' . ($time == '99date' ? ' selected' : '') . '>'.$lang['srv_diagnostics_choose_date'].'</option>';
+ echo '</select> ';
+
+ // Datum - od
+ echo ''.$lang['srv_diagnostics_orfrom'].' <input type="text" id="from" name="from" value="' . $from . '" '. ($time != '99date' ? ' disabled' : '') .' />';
+ echo ' <span class="faicon calendar_icon icon-as_link" onclick="changeSelectOption()" id="from_img"></span>';
+
+ // Datum - do
+ echo ' '.$lang['srv_diagnostics_to'].' <input type="text" id="to" name="to" value="' . $to . '" '. ($time != '99date' ? ' disabled' : '') .'/>';
+ echo ' <span class="faicon calendar_icon icon-as_link" onclick="changeSelectOption()" id="to_img"></span>';
+
+ echo '<input type="submit" class="spaceLeft pointer" value="'.$lang['hour_show'].'" />';
+ echo '<label class="srv_diagnostic_total_sub">'.$lang['srv_diagnostics_sum_total'].'</label><label class="srv_diagnostic_total_sub_label">'.$sum.'</label>';
+ echo '<label class="srv_diagnostic_total_sub">'.$lang['srv_diagnostics_sum_total_survey'].'</label><label class="srv_diagnostic_total_survey_label">'.$sum_survey.'</label>';
+
+ echo '</form><br />';
+
+ if ($type == 'pages')
+ $time_edit = 'srv_user_grupa_active.time_edit';
+ // ker je time_edit vcasih 0000-00-00 bi mogli v teh primerih pobrat time_insert
+ // $time_edit = 'srv_user_grupa'.$this->db_table.'.time_insert';
+ elseif ($type == 'users')
+ $time_edit = 'srv_user.time_edit';
+ elseif ($type=='analiza')
+ $time_edit = 'srv_tracking_active.datetime';
+ elseif ($type=='editing')
+ $time_edit = 'srv_tracking_active.datetime';
+ elseif ($type=='graph')
+ $time_edit = 'srv_tracking_active.datetime';
+ elseif ($type=='emails')
+ $time_edit = 'date_sent';
+
+
+ if($time == '99date' && $from == '' && $to == ''){
+ if ($type == 'users')
+ $interval = "AND ($time_edit > NOW() - INTERVAL 1 month OR (srv_user.time_edit='0000-00-00 00:00:00' AND srv_user.time_insert > NOW() - INTERVAL 1 month))";
+ else
+ $interval = "AND $time_edit > NOW() - INTERVAL 1 month";
+ }
+ else if ($from == '' && $to == ''){
+ if ($type == 'users')
+ $interval = "AND ($time_edit > NOW() - INTERVAL $time OR (srv_user.time_edit='0000-00-00 00:00:00' AND srv_user.time_insert > NOW() - INTERVAL $time))";
+ else
+ $interval = "AND $time_edit > NOW() - INTERVAL $time";
+ }
+ else{
+ if ($type == 'users')
+ $interval = "AND ('$from' <= $time_edit AND $time_edit <= '$to' OR (srv_user.time_edit='0000-00-00 00:00:00' AND '$from' <= srv_user.time_insert AND srv_user.time_insert <= '$to'))";
+ else
+ $interval = "AND '$from' <= $time_edit AND $time_edit <= '$to' ";
+ }
+
+ if ($type == 'pages') {
+ $sql = sisplet_query("
+ SELECT COUNT(grupe.usr_id) AS responses, grupe.ank_id, srv_anketa.naslov
+ FROM (
+ SELECT *
+ FROM srv_user_grupa_active, srv_grupa
+ WHERE srv_user_grupa_active.gru_id = srv_grupa.id
+ $interval
+ ) AS grupe, srv_anketa
+ WHERE grupe.ank_id=srv_anketa.id
+ AND (srv_anketa.dostop >= '" . $admin_type . "' OR srv_anketa.id IN
+ (SELECT ank_id FROM srv_dostop WHERE uid='" . $global_user_id . "'))
+ GROUP BY grupe.ank_id
+ ORDER BY responses DESC
+ ");
+
+ } elseif ($type == 'users') {
+ $filter = $this->diagnostics_get_user_settings();
+ $filter_package = $this->diagnostics_get_user_package();
+ $filter_lang = $this->diagnostics_get_lang_filter();
+
+ $sql = sisplet_query("
+ SELECT COUNT(srv_user.id) AS responses, users.email, srv_user.ank_id, srv_anketa.naslov, user_access.package_id
+ FROM srv_user, srv_anketa, users
+ LEFT JOIN user_access
+ ON user_access.usr_id=users.id
+ WHERE ".$filter." AND ".$filter_lang." ".$filter_package." srv_user.ank_id > '0'
+ AND srv_anketa.id=srv_user.ank_id
+ AND (srv_anketa.dostop >= '" . $admin_type . "' OR srv_anketa.id IN
+ (SELECT ank_id FROM srv_dostop WHERE uid='" . $global_user_id . "'))
+ $interval
+ AND srv_anketa.insert_uid = users.id
+ GROUP BY ank_id
+ ORDER BY responses DESC
+ ");
+ } elseif ($type == 'analiza') {
+
+ $sql = sisplet_query("
+ SELECT COUNT(srv_tracking_active.ank_id) AS responses, srv_tracking_active.ank_id, srv_anketa.naslov
+ FROM srv_tracking_active, srv_anketa
+ WHERE srv_anketa.id = srv_tracking_active.ank_id
+ AND (`get` LIKE '%analiza%' OR `get` LIKE '%analysis%' )
+ AND NOT (`get` LIKE '%charts%')
+ AND (srv_anketa.dostop >= '" . $admin_type . "' OR srv_anketa.id IN
+ (SELECT ank_id FROM srv_dostop WHERE uid='" . $global_user_id . "'))
+ $interval
+ GROUP BY ank_id
+ ORDER BY responses DESC
+ ");
+
+ } elseif ($type == 'graph') {
+
+ $sql = sisplet_query("
+ SELECT COUNT(srv_tracking_active.ank_id) AS responses, srv_tracking_active.ank_id, srv_anketa.naslov
+ FROM srv_tracking_active, srv_anketa
+ WHERE srv_anketa.id = srv_tracking_active.ank_id
+ AND (`get` LIKE '%analiza%' OR `get` LIKE '%analysis%' )
+ AND (`get` LIKE '%charts%')
+ AND (srv_anketa.dostop >= '" . $admin_type . "' OR srv_anketa.id IN
+ (SELECT ank_id FROM srv_dostop WHERE uid='" . $global_user_id . "'))
+ $interval
+ GROUP BY ank_id
+ ORDER BY responses DESC
+ ");
+
+ } elseif ($type == 'editing') {
+
+ $sql = sisplet_query("
+ SELECT COUNT(srv_tracking_active.ank_id) AS responses, srv_tracking_active.ank_id, srv_anketa.naslov
+ FROM srv_tracking_active, srv_anketa
+ WHERE srv_anketa.id = srv_tracking_active.ank_id
+ AND (srv_anketa.dostop >= '" . $admin_type . "' OR srv_anketa.id IN
+ (SELECT ank_id FROM srv_dostop WHERE uid='" . $global_user_id . "'))
+ $interval
+ GROUP BY ank_id
+ ORDER BY responses DESC
+ ");
+
+ } elseif ($type == 'emails') {
+
+ $sql = sisplet_query("
+ SELECT COUNT(srv_invitations_recipients.id) AS responses, srv_invitations_recipients.ank_id, srv_anketa.naslov
+ FROM srv_invitations_recipients, srv_anketa
+ WHERE srv_anketa.id = srv_invitations_recipients.ank_id AND srv_invitations_recipients.sent = '1'
+ AND (srv_anketa.dostop >= '" . $admin_type . "' OR srv_anketa.id IN
+ (SELECT ank_id FROM srv_dostop WHERE uid='" . $global_user_id . "'))
+ $interval
+ GROUP BY ank_id
+ ORDER BY responses DESC
+ ");
+
+
+ }
+
+ if (!$sql) {
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ global $site_url;
+
+ echo '<table style="width:70%">';
+ $max = -1;
+
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($max == -1)
+ $max = max($row['responses'], $max)*1.3;
+
+ echo '<tr>';
+ echo '<td><a href="'.SurveyInfo::getSurveyLink($row['ank_id']).'?preview=on&pages=all" target="_blank">' . $row['naslov'] . '</a></td>';
+ echo '<td>'.$row['email'].'</td>';
+ $sum = $sum + $row['responses'];
+ $sum_survey = $sum_survey + 1;
+ echo '<td style="width:60%"><div class="graph_lb" style="float: left; width:' . (round($row['responses'] / $max * 100, 0)) . '%">&nbsp;</div><div style="float:left">&nbsp;'.$row['responses'].'</div></td>';
+ echo '</tr>';
+ }
+
+ echo '<script type="text/javascript">
+ function runSubTotal(){
+ $(".srv_diagnostic_total_sub_label").text('.$sum.');
+ $(".srv_diagnostic_total_survey_label").text('.$sum_survey.');
+ }
+ window.onload = runSubTotal;
+ </script>';
+
+
+ echo '</table>';
+ }
+
+ public function diagnostics_time_span () {
+ global $lang;
+
+ $interval = $this->diagnostics_get_interval('month');
+ $filter = $this->diagnostics_get_user_settings();
+ $filter_package = $this->diagnostics_get_user_package();
+ $filter_lang = $this->diagnostics_get_lang_filter();
+
+ $this->diagnostics_show_interval('time_span');
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_anketa] AS datedate, YEAR(insert_time) AS color, insert_time AS date
+ FROM srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE ".$filter_lang." ".$filter_package." insert_time > 0 AND YEAR(insert_time)>=2009
+ GROUP BY datedate
+ ORDER BY insert_time ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_survey'], 'day', 'year', false);
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_sum_survey'], 'day', 'year', true);
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[users] AS datedate, YEAR(when_reg) AS color, when_reg AS date
+ FROM users
+ LEFT JOIN user_access
+ ON user_access.usr_id=users.id
+ WHERE ".$filter_package." when_reg > 0 AND YEAR(when_reg)>=2009
+ GROUP BY datedate
+ ORDER BY when_reg ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_register'], 'day', 'year', false);
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_sum_register'], 'day', 'year', true);
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_user] AS datedate, YEAR(srv_user.time_insert) AS color, srv_user.time_insert AS date
+ FROM srv_user, srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE srv_user.ank_id=srv_anketa.id AND ".$filter." AND ".$filter_lang." ".$filter_package." time_insert > 0 AND YEAR(time_insert)>=2009
+ GROUP BY datedate
+ ORDER BY time_insert ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_answer'], 'day', 'year', false);
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_sum_answer'], 'day', 'year', true);
+ }
+
+ public function diagnostics_time_span_yearly () {
+ global $lang;
+
+ $interval = $this->diagnostics_get_interval('day');
+ $filter = $this->diagnostics_get_user_settings();
+ $filter_package = $this->diagnostics_get_user_package();
+ $filter_lang = $this->diagnostics_get_lang_filter();
+
+ $this->diagnostics_show_interval('time_span_yearly');
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_anketa] AS datedate, MONTH(insert_time) AS color, insert_time AS date
+ FROM srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE ".$filter_lang." ".$filter_package." insert_time > 0 AND insert_time >= '".date("Y-m-1 0:00:00", strtotime("-11 month"))."'
+ GROUP BY datedate
+ ORDER BY insert_time ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_survey'], 'day', 'month', false);
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[users] AS datedate, MONTH(when_reg) AS color, when_reg AS date
+ FROM users
+ LEFT JOIN user_access
+ ON user_access.usr_id=users.id
+ WHERE ".$filter_package." when_reg > 0 AND when_reg >= '".date("Y-m-1 0:00:00", strtotime("-11 month"))."'
+ GROUP BY datedate
+ ORDER BY when_reg ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_register'], 'day', 'month', false);
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_user] AS datedate, MONTH(srv_user.time_insert) AS color, srv_user.time_insert AS date
+ FROM srv_user, srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE srv_user.ank_id=srv_anketa.id AND ".$filter." AND ".$filter_lang." ".$filter_package." time_insert > 0 AND time_insert >= '".date("Y-m-1 0:00:00", strtotime("-11 month"))."'
+ GROUP BY datedate
+ ORDER BY time_insert ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_answer'], 'day', 'month', false);
+ }
+
+ public function diagnostics_time_span_monthly () {
+ global $lang;
+
+ $interval = $this->diagnostics_get_interval('day');
+ $filter = $this->diagnostics_get_user_settings();
+ $filter_package = $this->diagnostics_get_user_package();
+ $filter_lang = $this->diagnostics_get_lang_filter();
+
+ $this->diagnostics_show_interval('time_span_monthly');
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_anketa] AS datedate, MONTH(insert_time) AS color, insert_time AS date
+ FROM srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE ".$filter_lang." ".$filter_package." insert_time > 0 AND insert_time >= '".date("Y-m-1 0:00:00", strtotime("-2 month"))."'
+ GROUP BY datedate
+ ORDER BY insert_time ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_survey'], 'day', 'month', false);
+
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[users] AS datedate, MONTH(when_reg) AS color, when_reg AS date
+ FROM users
+ LEFT JOIN user_access
+ ON user_access.usr_id=users.id
+ WHERE ".$filter_package." when_reg > 0 AND when_reg >= '".date("Y-m-1 0:00:00", strtotime("-2 month"))."'
+ GROUP BY datedate
+ ORDER BY when_reg ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_register'], 'day', 'month', false);
+
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_user] AS datedate, MONTH(srv_user.time_insert) AS color, srv_user.time_insert AS date
+ FROM srv_user, srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE srv_user.ank_id=srv_anketa.id AND ".$filter." AND ".$filter_lang." ".$filter_package." time_insert > 0 AND time_insert >= '".date("Y-m-1 0:00:00", strtotime("-2 month"))."'
+ GROUP BY datedate
+ ORDER BY time_insert ASC
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_month_answer'], 'day', 'month', false);
+
+ }
+
+ public function diagnostics_time_span_daily () {
+ global $lang;
+
+ $interval = $this->diagnostics_get_interval('hour');
+ $filter = $this->diagnostics_get_user_settings();
+ $filter_package = $this->diagnostics_get_user_package();
+ $filter_lang = $this->diagnostics_get_lang_filter();
+
+ $this->diagnostics_show_interval('time_span_daily');
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_anketa] AS datedate, DAYOFWEEK(insert_time) AS color, insert_time AS date
+ FROM srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE ".$filter_lang." ".$filter_package." insert_time >= '".date("Y-m-d 0:00:00", strtotime("-1 week"))."'
+ GROUP BY datedate
+ ORDER BY insert_time
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_week_survey'], 'hour', 'day', false);
+
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_tracking_active] AS datedate, DAYOFWEEK(datetime) AS color, datetime AS date
+ FROM srv_tracking_active
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_tracking_active.user
+ WHERE ".$filter_package." datetime >= '".date("Y-m-d 0:00:00", strtotime("-1 week"))."'
+ GROUP BY datedate
+ ORDER BY datetime
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_week_edit'], 'hour', 'day', false);
+
+
+ $sql = sisplet_query("SELECT COUNT(*) as count, $interval[srv_user] AS datedate, DAYOFWEEK(srv_user.time_insert) AS color, srv_user.time_insert AS date
+ FROM srv_user, srv_anketa
+ LEFT JOIN user_access
+ ON user_access.usr_id=srv_anketa.insert_uid
+ WHERE srv_user.ank_id=srv_anketa.id AND ".$filter." AND ".$filter_lang." ".$filter_package." time_insert >= '".date("Y-m-d 0:00:00", strtotime("-1 week"))."'
+ GROUP BY datedate
+ ORDER BY time_insert
+ ");
+ $this->diagnostics_graph($sql, $lang['srv_diagnostics_graph_week_answer'], 'hour', 'day', false);
+ }
+
+ /**
+ * @desc prikaze diagnostiko anket
+ */
+ public function diagnostics_paradata() {
+ global $lang, $global_user_id, $admin_type, $site_url;
+
+ set_time_limit(1800); # 30 minut
+
+ // Koliko respondentov vzamemo (random)
+ $limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 1000;
+
+ // Obdobje
+ $date_from = (isset($_GET['from'])) ? $_GET['from'] : date('j.n.Y', strtotime("-1 year"));
+ $date_from_mysql = date("Y-m-d", strtotime($date_from)).' 00:00:00';
+ $date_to = (isset($_GET['to'])) ? $_GET['to'] : date('j.n.Y');
+ $date_to_mysql = date("Y-m-d", strtotime($date_to)).' 00:00:00';
+
+ // Forma za filtriranje
+ echo '<form name="diagnostics_paradata" action="index.php" method="get">';
+
+ echo '<input type="hidden" name="a" value="diagnostics">';
+ echo '<input type="hidden" name="t" value="paradata">';
+
+ // Vseh random enot
+ echo '<span>'.$lang['srv_inv_dashboard_tbl_all'].'</span> <input type="text" name="limit" value="'.$limit.'" style="padding:1px 3px; font-size:12px; width:70px; margin-right:20px;" />';
+
+ // Datum
+ echo $lang['s_from'].' <input type="text" id="from" name="from" value="' . $date_from . '" />';
+ echo ' <span class="faicon calendar_icon icon-as_link" onclick="diagnosticsParadataChooseDate();" id="from_img"></span> ';
+
+ echo $lang['s_to'].' <input type="text" id="to" name="to" value="' . $date_to . '" />';
+ echo ' <span class="faicon calendar_icon icon-as_link" onclick="diagnosticsParadataChooseDate();" id="to_img"></span>';
+
+ echo '<script>diagnosticsParadataChooseDate();</script>';
+
+ // Gumb prikazi
+ echo '<input type="button" class="pointer" value="'.$lang['hour_show'].'" onClick="this.form.submit();" style="margin-left:20px;">';
+
+ echo '</form><br />';
+
+
+ // Gledamo vse veljavne respondente iz leta 2016
+ $sql = sisplet_query("SELECT id, ank_id, useragent
+ FROM srv_user
+ WHERE last_status IN ('5', '6') AND lurker='0' AND time_insert<'".$date_to_mysql."' AND time_insert>='".$date_from_mysql."'
+ ORDER BY rand()
+ LIMIT ".$limit."");
+ if (!$sql) {echo mysqli_error($GLOBALS['connect_db']); die();}
+
+
+ $statistics = array();
+
+ while ($row = mysqli_fetch_array($sql)) {
+
+ //var_dump($row);
+
+ $browser_detect = get_browser($row['useragent'], true);
+ //var_dump($browser_detect);
+
+ // Naprava
+ $statistics['device'][$browser_detect['device_type']]++;
+ $statistics['device']['title'] = $lang['srv_para_graph_device'];
+
+ // Mobilnik, tablica...
+ $browser_detect['ismobiledevice'] = ($browser_detect['ismobiledevice'] == '') ? '0' : $browser_detect['ismobiledevice'];
+ $browser_detect['istablet'] = ($browser_detect['istablet'] == '') ? '0' : $browser_detect['istablet'];
+
+ $statistics['mobile'][$browser_detect['ismobiledevice']]++;
+ $statistics['mobile']['title'] = $lang['srv_para_graph_device1'];
+
+ $statistics['tablet'][$browser_detect['istablet']]++;
+ $statistics['tablet']['title'] = $lang['srv_para_graph_device2'];
+
+ // Brskalnik
+ $statistics['browser_name'][$browser_detect['browser']]++;
+ $statistics['browser_name']['title'] = $lang['srv_para_graph_browser'];
+ //$statistics['browser_version'][$browser_detect['version']]++;
+
+ // Operacijski sistem
+ $statistics['os'][$browser_detect['platform']]++;
+ $statistics['os']['title'] = $lang['srv_para_graph_os'];
+
+ // Brskalnik (verzija)
+ $statistics['browser'][$browser_detect['parent']]++;
+ $statistics['browser']['title'] = $lang['srv_para_graph_browser'];
+ }
+
+ foreach($statistics as $key => $vals){
+
+ echo '<fieldset style="width:60%;"><legend>'.$vals['title'].'</legend>';
+
+ // Sortiramo vrednosti po velikosti (od najvecje do najmanjse)
+ //ksort($vals);
+ arsort($vals);
+
+ echo '<table style="width:100%;">';
+
+ $max = -1;
+ foreach($vals as $key2 => $val){
+
+ if($key2 !== 'title'){
+ echo '<tr>';
+
+ if($key2 == '0')
+ $key2 = $lang['no'];
+ elseif($key2 == '1')
+ $key2 = $lang['yes'];
+
+ echo '<td>'.$key2.'</td>';
+
+ $max = max($val, $max) * 1.2;
+ echo '<td style="width:80%"><div class="graph_lb" style="float: left; width:' . (round($val / $max * 100, 0)) . '%">&nbsp;</div><div style="float:left">&nbsp;'.$val.'</div></td>';
+
+ echo '</tr>';
+ }
+ }
+
+ echo '</table>';
+
+ echo '</fieldset><br />';
+ }
+ }
+
+
+ /**
+ * izrise graf za aktivnosti / diagnostiko anket, uporabnikov itd...
+ *
+ * @param mixed $sql
+ * @param mixed $text
+ * @param mixed $interval
+ * @param mixed $color
+ * @param mixed $sumarium
+ */
+ private function diagnostics_graph ($sql, $text, $interval, $color, $sumarium) {
+
+ ob_flush();
+
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) mysqli_data_seek($sql, 0);
+
+ $interval = $_GET['interval'];
+
+ $max = 0;
+ $sum = 0;
+ $prev = 0;
+ $c = 0;
+ $cols = 0;
+ $prev_color = '';
+ $avg = array();
+ $cur_sum = 0;
+ $cur_tot = 0;
+
+ while ($row = mysqli_fetch_assoc($sql)) {
+ if ($row['count'] > $max) $max = $row['count'];
+ $sum += $row['count'];
+
+ if ($prev_color != $row['color']) {
+ if ($cur_tot != 0) $avg[$prev_color] = round($cur_sum/$cur_tot, 1);
+ //echo $cur_tot.' '.$cur_sum.' '.$prev_color.': '.$avg[$prev_color].'<br>';
+ $cur_sum = 0;
+ $cur_tot = 0;
+ $prev_color = $row['color'];
+ }
+ $cur_tot ++;
+ $cur_sum += $row['count'];
+ //echo $cur_tot.' '.$cur_sum.'<br>';
+ }
+ if ($cur_tot != 0) $avg[$prev_color] = round($cur_sum/$cur_tot, 1);
+
+ $prev_color = '';
+
+ $max = $max/100;
+ $sum = $sum/100;
+
+ echo '<div class="time_span_header">'.$text.' ('.($sumarium?'sum':'max').': '.number_format(($sumarium?$sum:$max)*100, 0, ',', '.').')</div>';
+ echo '<div class="time_span_container">';
+
+ if (mysqli_num_rows($sql) > 0) mysqli_data_seek($sql, 0);
+ while ($row = mysqli_fetch_assoc($sql)) {
+
+ if ($interval == 'hour')
+ $plusone = date("Y-m-d G", strtotime('+1 '.$interval.'', strtotime($prev.':00')));
+ elseif ($interval == 'day')
+ $plusone = date("Y-m-d", strtotime('+1 '.$interval.'', strtotime($prev)));
+ elseif ($interval == 'week')
+ $plusone = date("Y-W", strtotime('+1 '.$interval.'', strtotime($prev)));
+ elseif ($interval == 'month')
+ $plusone = date("Y-m", strtotime('+1 '.$interval.'', strtotime($prev.'-1')));
+ elseif ($interval == 'year')
+ $plusone = date("Y", strtotime('+1 '.$interval.'', strtotime($prev.'-1-1')));
+
+ $i=0;
+ while ( $plusone != $row['datedate'] && $prev!=0 ) {
+ if ($interval == 'hour' || $interval == 'day') {} else break;
+
+ echo '<div class="time_span '.$color.'_'.$row['color'].'" style="_WIDTH_; height:'.($sumarium?($c/$sum):'0').'%" title="'.$row['datedate'].' (0)"></div>';
+ $cols++;
+
+ if ($interval == 'hour')
+ $plusone = date("Y-m-d G", strtotime('+1 '.$interval.'', strtotime($plusone.':00')));
+ elseif ($interval == 'day')
+ $plusone = date("Y-m-d", strtotime('+1 '.$interval.'', strtotime($plusone)));
+ elseif ($interval == 'week')
+ $plusone = date("Y-W", strtotime('+1 '.$interval.'', strtotime($plusone)));
+ elseif ($interval == 'month')
+ $plusone = date("Y-m", strtotime('+1 '.$interval.'', strtotime($plusone.'-1')));
+ elseif ($interval == 'year')
+ $plusone = date("Y", strtotime('+1 '.$interval.'', strtotime($plusone.'-1-1')));
+
+ if ($i++ > 100) { break; } // safety break
+ }
+ $prev = $row['datedate'];
+
+ $c += $row['count'];
+
+ if ($prev_color != $row['color']) {
+ if ($color == 'year') $label = date('Y', strtotime($row['date']));
+ if ($color == 'month') $label = date('M Y', strtotime($row['date']));
+ if ($color == 'day') $label = date('j.n.Y', strtotime($row['date']));
+
+ echo '<span style="position: absolute; bottom: -15px; width: 90px;">'.$label;
+ if ( !$sumarium ) echo ' <span style="color:darkgray; font-size:70%" title="x̄ = '.$avg[$row['color']].'">('.$avg[$row['color']].')</span>';
+ echo '</span>';
+ $prev_color = $row['color'];
+ }
+
+ echo '<div class="time_span '.$color.'_'.$row['color'].'" style="_WIDTH_; height:'.($sumarium?($c/$sum):($row['count']/$max)).'%" title="'.$row['datedate'].' ('.number_format(($sumarium?$c:$row['count']), 0, ',', '.').')"></div>';
+ $cols++;
+
+ }
+ echo '</div>';
+
+ // sirino nastavimo na koncu, ko vidimo koliko je stolpcev (zaradi praznih)
+ $var = ob_get_clean();
+ if ($cols == 0) $cols = 1;
+ $var = str_replace('_WIDTH_', 'width:'.(100/$cols).'%', $var);
+ echo $var;
+
+ ob_start();
+ }
+
+ private function diagnostics_show_interval ($t) {
+ global $lang, $app_settings;
+
+ echo '<form name="intr" action="index.php" method="get">';
+ echo '<input type="hidden" name="a" value="diagnostics">';
+ echo '<input type="hidden" name="t" value="'.$t.'">';
+
+ $testdata = (isset($_GET['testdata']) && $_GET['testdata']=='1') ? 1 : 0;
+ $testdataauto = (isset($_GET['testdataauto']) && $_GET['testdataauto']=='1') ? 1 : 0;
+ $uvoz = (isset($_GET['uvoz']) && $_GET['uvoz']=='1') ? 1 : 0;
+
+ $ustrezni = (isset($_GET['ustrezni']) && $_GET['ustrezni']=='0') ? 0 : 1;
+ $delnoustrezni = (isset($_GET['delnoustrezni']) && $_GET['delnoustrezni']=='0') ? 0 : 1;
+ $neustrezni = (isset($_GET['neustrezni']) && $_GET['neustrezni']=='1') ? 1 : 0;
+ $mailsent = (isset($_GET['mailsent']) && $_GET['mailsent']=='1') ? 1 : 0;
+
+ $language = (isset($_GET['language'])) ? $_GET['language'] : 0;
+
+ if(isset($app_settings['commercial_packages']) && $app_settings['commercial_packages'] == true){
+
+ $package_1ka = (isset($_GET['package_1ka']) && $_GET['package_1ka']=='0') ? 0 : 1;
+ $package_2ka = (isset($_GET['package_2ka']) && $_GET['package_2ka']=='0') ? 0 : 1;
+ $package_3ka = (isset($_GET['package_3ka']) && $_GET['package_3ka']=='0') ? 0 : 1;
+
+ echo '<span>'.$lang['srv_narocilo_paket'].':</span>';
+
+ echo '<input type="hidden" name="package_1ka" id="package_1ka_hidden" value="'.$package_1ka.'" />';
+ echo '<input type="checkbox" value="1" id="package_1ka" '.($package_1ka == 1 ? ' checked="checked"' : '').'" onchange="$(\'#package_1ka_hidden\').val('.($package_1ka==1 ? '0' : '1').');"><label for="package_1ka">1KA</label>';
+ echo '<input type="hidden" name="package_2ka" id="package_2ka_hidden" value="'.$package_2ka.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="package_2ka" '.($package_2ka == 1 ? ' checked="checked"' : '').' onchange="$(\'#package_2ka_hidden\').val('.($package_2ka==1 ? '0' : '1').');"><label for="package_2ka">2KA</label></span>';
+ echo '<input type="hidden" name="package_3ka" id="package_3ka_hidden" value="'.$package_3ka.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="package_3ka" '.($package_3ka == 1 ? ' checked="checked"' : '').' onchange="$(\'#package_3ka_hidden\').val('.($package_3ka==1 ? '0' : '1').');"><label for="package_3ka">3KA</label></span>';
+
+ echo '<span class="spaceLeft spaceRight bold">|</span>';
+ }
+
+ echo '<input type="checkbox" value="1" id="testdata" name="testdata" '.($testdata == 1 ? ' checked="checked"' : '').'"><label for="testdata">'.$lang['srv_diagnostics_filter_test'].'</label>';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="testdataauto" name="testdataauto" '.($testdataauto == 1 ? ' checked="checked"' : '').'"><label for="testdataauto">'.$lang['srv_diagnostics_filter_autotest'].'</label></span>';
+ echo '<input type="hidden" name="uvoz" id="uvoz_hidden" value="'.$uvoz.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" id="uvoz" '.($uvoz == 1 ? ' checked="checked"' : '').' onchange="$(\'#uvoz_hidden\').val('.($uvoz==1 ? '0' : '1').');"><label for="uvoz">'.$lang['srv_diagnostics_filter_import'].'</label></span>';
+
+ echo '<input type="hidden" name="ustrezni" id="ustrezni_hidden" value="'.$ustrezni.'" />';
+ echo '<span class="spaceLeft bold">|</span><span class="spaceLeft"></span><input type="checkbox" id="ustrezni" '.($ustrezni == 1 ? ' checked="checked"' : '').' onchange="$(\'#ustrezni_hidden\').val('.($ustrezni==1 ? '0' : '1').');"><label for="ustrezni">'.$lang['srv_diagnostics_filter_6'].'</label>';
+ echo '<input type="hidden" name="delnoustrezni" id="delnoustrezni_hidden" value="'.$delnoustrezni.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" id="delnoustrezni" '.($delnoustrezni == 1 ? ' checked="checked"' : '').' onchange="$(\'#delnoustrezni_hidden\').val('.($delnoustrezni==1 ? '0' : '1').');"><label for="delnoustrezni">'.$lang['srv_diagnostics_filter_5'].'</label></span>';
+ echo '<input type="hidden" name="neustrezni" id="neustrezni_hidden" value="'.$neustrezni.'" />';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="neustrezni" '.($neustrezni == 1 ? ' checked="checked"' : '').' onchange="$(\'#neustrezni_hidden\').val('.($neustrezni==1 ? '0' : '1').');"><label for="neustrezni">'.$lang['srv_diagnostics_filter_34'].'</label></span>';
+ echo '<span class="spaceLeft"><input type="checkbox" value="1" id="mailsent" name="mailsent" '.($mailsent == 1 ? ' checked="checked"' : '').'><label for="mailsent">'.$lang['srv_diagnostics_filter_012'].'</label></span>';
+
+ echo '<span class="spaceLeft bold">|</span><span class="spaceLeft"></span>'.$lang['lang'].': <select id="language" name="language">';
+ echo '<option value="0" '.($language=='0' ? ' selected' : '').'>'.$lang['srv_diagnostics_filter_lang_all'].'</option>';
+ echo '<option value="1" '.($language=='1' ? ' selected' : '').'>'.$lang['srv_diagnostics_filter_lang_slo'].'</option>';
+ echo '<option value="2" '.($language=='2' ? ' selected' : '').'>'.$lang['srv_diagnostics_filter_lang_ang'].'</option>';
+
+ echo '<input type="button" class="spaceLeft" value="'.$lang['srv_coding_filter'].'" onClick="this.form.submit();">';
+
+ echo '<br /><br />';
+
+ echo 'Interval: <select name="interval" onchange="document.intr.submit();">';
+ if ( ! in_array($t, array('time_span_yearly', 'time_span')) ) {
+ echo '<option value="hour" '.($_GET['interval']=='hour'?'selected':'').'>'.$lang['srv_diagnostics_interval_hour'].'</option>';
+ }
+ echo '<option value="day" '.($_GET['interval']=='day'?'selected':'').'>'.$lang['srv_diagnostics_interval_day'].'</option>';
+ echo '<option value="week" '.($_GET['interval']=='week'?'selected':'').'>'.$lang['srv_diagnostics_interval_week'].'</option>';
+ echo '<option value="month" '.($_GET['interval']=='month'?'selected':'').'>'.$lang['srv_diagnostics_interval_month'].'</option>';
+ echo '<option value="year" '.($_GET['interval']=='year'?'selected':'').'>'.$lang['srv_diagnostics_interval_year'].'</option>';
+ echo '</select>';
+
+ echo '</form><br />';
+ }
+
+ private function diagnostics_get_interval ($def = '') {
+
+ if ($_GET['interval'] == '') $_GET['interval'] = $def;
+
+ if ($_GET['interval'] == 'year') {
+ $interval['srv_anketa'] = "YEAR(srv_anketa.insert_time)";
+ $interval['users'] = "YEAR(users.when_reg)";
+ $interval['srv_user'] = "YEAR(srv_user.time_insert)";
+ $interval['srv_tracking_active'] = "YEAR(srv_tracking_active.datetime)";
+ } elseif ($_GET['interval'] == 'month') {
+ $interval['srv_anketa'] = "CONCAT( YEAR(srv_anketa.insert_time), '-', MONTH(srv_anketa.insert_time) )";
+ $interval['users'] = "CONCAT( YEAR(users.when_reg), '-', MONTH(users.when_reg) )";
+ $interval['srv_user'] = "CONCAT( YEAR(srv_user.time_insert), '-', MONTH(srv_user.time_insert) )";
+ $interval['srv_tracking_active'] = "CONCAT( YEAR(srv_tracking_active.datetime), '-', MONTH(srv_tracking_active.datetime) )";
+ } elseif ($_GET['interval'] == 'week') {
+ $interval['srv_anketa'] = "CONCAT( YEAR(srv_anketa.insert_time), '-', WEEKOFYEAR(srv_anketa.insert_time) )";
+ $interval['users'] = "CONCAT( YEAR(users.when_reg), '-', WEEKOFYEAR(users.when_reg) )";
+ $interval['srv_user'] = "CONCAT( YEAR(srv_user.time_insert), '-', WEEKOFYEAR(srv_user.time_insert) )";
+ $interval['srv_tracking_active'] = "CONCAT( YEAR(srv_tracking_active.datetime), '-', WEEKOFYEAR(srv_tracking_active.datetime) )";
+ } elseif ($_GET['interval'] == 'day') {
+ $interval['srv_anketa'] = "DATE(srv_anketa.insert_time)";
+ $interval['users'] = "DATE(users.when_reg)";
+ $interval['srv_user'] = "DATE(srv_user.time_insert)";
+ $interval['srv_tracking_active'] = "DATE(datetime)";
+ } elseif ($_GET['interval'] == 'hour') {
+ $interval['srv_anketa'] = "CONCAT( DATE(srv_anketa.insert_time), ' ', HOUR(srv_anketa.insert_time)) ";
+ $interval['users'] = "CONCAT( DATE(users.when_reg), ' ', HOUR(users.when_reg)) ";
+ $interval['srv_user'] = "CONCAT( DATE(srv_user.time_insert), ' ', HOUR(srv_user.time_insert)) ";
+ $interval['srv_tracking_active'] = "CONCAT( DATE(srv_tracking_active.datetime), ' ', HOUR(srv_tracking_active.datetime)) ";
+ }
+
+ return $interval;
+ }
+
+ // Vrnemo filter za srv_user (filtriranje testnih podatkov, preview, email vabil, ustreznih...)
+ private function diagnostics_get_user_settings(){
+
+ $testdata = (isset($_GET['testdata']) && $_GET['testdata']=='1') ? 1 : 0;
+ $testdataauto = (isset($_GET['testdataauto']) && $_GET['testdataauto']=='1') ? 1 : 0;
+ $uvoz = (isset($_GET['uvoz']) && $_GET['uvoz']=='1') ? 1 : 0;
+
+ $ustrezni = (isset($_GET['ustrezni']) && $_GET['ustrezni']=='0') ? 0 : 1;
+ $delnoustrezni = (isset($_GET['delnoustrezni']) && $_GET['delnoustrezni']=='0') ? 0 : 1;
+ $neustrezni = (isset($_GET['neustrezni']) && $_GET['neustrezni']=='1') ? 1 : 0;
+ $mailsent = (isset($_GET['mailsent']) && $_GET['mailsent']=='1') ? 1 : 0;
+
+ // Vedno filtriramo preview vnose
+ $filter = " srv_user.preview='0'";
+
+ // Filter testnih in avtomatsko generiranih testnih
+ $filter .= " AND (srv_user.testdata='0'";
+ if($testdata == 1)
+ $filter .= " OR srv_user.testdata='1'";
+ if($testdataauto == 1)
+ $filter .= " OR srv_user.testdata='2'";
+ $filter .= ")";
+
+
+ $filter .= " AND srv_user.last_status!='-1' AND (";
+ if($ustrezni == 1){
+ $filter .= " srv_user.last_status='6' OR";
+ }
+ if($delnoustrezni == 1){
+ $filter .= " srv_user.last_status='5' OR";
+ }
+ if($neustrezni == 1){
+ $filter .= " srv_user.last_status='3' OR srv_user.last_status='4' OR";
+ }
+ if($mailsent == 1){
+ $filter .= " srv_user.last_status='0' OR srv_user.last_status='1' OR srv_user.last_status='2' OR";
+ }
+ if(substr($filter, -2) == 'OR'){
+ $filter = substr($filter, 0, -2);
+ $filter .= ")";
+ }
+ else
+ $filter .= "srv_user.last_status NOT IN ('0','1','2','3','4','5','6'))";
+
+ // Filtriramo uvozene podatke
+ if($uvoz == 0){
+ $filter .= " AND !(srv_user.referer='' AND testdata='0' AND ip='' AND recnum='0')";
+ }
+
+ return $filter;
+ }
+
+ // Filter po paketih, ce jih imamo
+ private function diagnostics_get_user_package(){
+ global $app_settings;
+
+ $filter = '';
+
+ if(isset($app_settings['commercial_packages']) && $app_settings['commercial_packages'] == true){
+
+ $package_1ka = (isset($_GET['package_1ka']) && $_GET['package_1ka']=='0') ? 0 : 1;
+ $package_2ka = (isset($_GET['package_2ka']) && $_GET['package_2ka']=='0') ? 0 : 1;
+ $package_3ka = (isset($_GET['package_3ka']) && $_GET['package_3ka']=='0') ? 0 : 1;
+
+ if($package_1ka == 0){
+ $filter .= " ((user_access.package_id='2' OR user_access.package_id='3') AND user_access.time_expire > NOW()) AND ";
+ }
+ if($package_2ka == 0){
+ $filter .= " (user_access.package_id!='2' OR user_access.time_expire < NOW() OR user_access.package_id IS NULL) AND ";
+ }
+ if($package_3ka == 0){
+ $filter .= " (user_access.package_id!='3' OR user_access.time_expire < NOW() OR user_access.package_id IS NULL) AND ";
+ }
+ }
+
+ return $filter;
+ }
+
+ // Vrnemo filter za srv_user (filtriranje testnih podatkov, preview, email vabil, ustreznih...)
+ private function diagnostics_get_lang_filter(){
+
+ $language = (isset($_GET['language'])) ? $_GET['language'] : 0;
+
+ // Filtriramo po jeziku urednika
+ $filter = '';
+ if($language > 0){
+ $filter .= " srv_anketa.lang_admin='".$language."' AND ";
+ }
+
+ return $filter;
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyAppendMerge.php b/admin/survey/classes/class.SurveyAppendMerge.php
new file mode 100644
index 0000000..c16549a
--- /dev/null
+++ b/admin/survey/classes/class.SurveyAppendMerge.php
@@ -0,0 +1,1039 @@
+<?php
+
+/**
+*
+* V tem classu so funkcije, ki se ticejo appenda in merga podatkov
+*
+*/
+
+class SurveyAppendMerge {
+
+ private $anketa;
+
+ private $db_table = '';
+
+
+ /**
+ *
+ *
+ * @param int $anketa ID ankete
+ */
+ function __construct ($anketa) {
+
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ }
+
+ function display ($merge = false) {
+
+ if ( count($_POST) == 0 ) {
+
+ echo '<div id="inv_import">';
+ $this->displayAppendMerge($merge);
+ echo '</div>';
+
+ } else {
+
+ $this->do_append_merge();
+
+ }
+ }
+
+ function displayAppendMerge ( $merge = false ) {
+ global $lang, $site_path, $site_url;
+
+ $field_list = array();
+
+ $sql = sisplet_query("SELECT s.id, s.variable, s.tip FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.tip IN (1, 2, 3, 7, 8, 21) ORDER BY g.vrstni_red, s.vrstni_red");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $field_list[$row['id']] = $row['variable'] . ' ('.($row['tip']==1?'radio':'').($row['tip']==2?'checkbox':'').($row['tip']==3?'dropdown':'').($row['tip']==21?'text':'').($row['tip']==7?'number':'').($row['tip']==8?'date':'').')';
+ }
+
+ $import_type = isset($_POST['import_type']) ? (int)$_POST['import_type'] : 2;
+ session_start();
+
+
+ // Append
+ if (!$merge){
+
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_append'].'</legend>';
+
+ echo '<form id="inv_recipients_upload_form" name="resp_uploader" enctype="multipart/form-data" method="POST" action="'.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m='.$_GET['m'].'">';
+ echo '<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />';
+ echo '<input type="hidden" name="do" value="0">';
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'">';
+
+ # sporočilo za personalizirana e-vabila in respondente iz baze
+ echo $lang['srv_append_note'];
+
+ // Korak 1
+ echo $lang['srv_append_step1'];
+ echo '<div class="append_step">';
+
+ echo $lang['srv_append_step1_note'];
+
+ echo '<div id="inv_field_container">';
+
+ echo '<ul class="connectedSortable">';
+ $field_lang = array();
+ if (count($field_list ) > 0) {
+ foreach ($field_list AS $field => $text_label) {
+ # tukaj polja niso izbrana
+ $is_selected = false;
+
+ # če je polje obkljukano
+ $css = $is_selected ? ' class="inv_field_enabled"' : '';
+
+
+ # labela sproži klik checkboxa
+ $label_for = ' for="'.$field.'_chk"';
+
+ echo '<li id="'.$field.'"'.$css.'>';
+ echo '<input id="'.$field.'_chk" type="checkbox" name="fields[]" value="'.$field.'" class="inv_checkbox' . $hidden_checkbox . '"'.($is_selected == true ? ' checked="checked"' : '').' '.($merge?' onclick="merge_getItems();"':'').'>';
+ echo '<label'.$label_for.' style="display: inline">'.$text_label.'</label>';
+ echo '</li>';
+
+ if ($is_selected == true) {
+ $field_lang[] = $text_label;
+ }
+ }
+ }
+ echo '</ul><br />';
+ echo '</div>';
+ echo '</div>';
+
+
+ // Korak 2
+ echo $lang['srv_append_step2'];
+ echo '<div class="append_step">';
+
+ echo '<script type="text/javascript">';
+ echo "$('ul.connectedSortable').sortable({update : function () { append_refreshFieldsList(); }, forcePlaceholderSize: 'true',tolerance: 'pointer',placeholder: 'inv_field_placeholder',});";
+ echo '</script>';
+
+ echo '<span><label><input name="inv_import_type" id="inv_import_type0" type="radio" value="0" onclick="append_change_import_type(\''.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m='.$_GET['m'].'\');" checked="checked">';
+ echo ''.$lang['srv_iz_seznama'].'</label></span>';
+ echo '<span><label><input name="inv_import_type" id="inv_import_type1" type="radio" value="1" onclick="append_change_import_type(\''.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m=upload_xls\');">';
+ echo ''.$lang['srv_iz_excela'].'</label></span>';
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+
+ echo '<input type="hidden" name="do_merge" value="0" id="do_merge">';
+
+ echo '</div>';
+
+
+ # iz seznama
+ echo '<div id="inv_import_list"'.($import_type != 1 ? '' : ' style="display:none"').'>' ;
+
+ // Korak 3
+ echo $lang['srv_append_step3'];
+ echo '<div class="append_step">';
+
+ echo $lang['srv_append_step3_note'];
+
+ echo '<span class="inv_sample" >';
+ echo $lang['srv_inv_recipiens_sample'].'&nbsp;</span><span class="inv_sample">';
+ echo $lang['srv_inv_recipiens_sample1'];
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo '</span>';
+ echo '<br class="clr" />'.$lang['srv_inv_recipiens_fields'].' <span id="inv_field_list" class="inv_type_0">';
+ echo implode(',',$field_lang);
+ echo '</span>';
+ echo '<br class="clr" /><textarea id="inv_recipients_list" cols="50" rows="9" name="inv_recipients_list" style="margin-bottom: 7px;">';
+ if (is_array($recipients_list) && count($recipients_list) > 0 ) {
+ echo implode("\n",$recipients_list);
+ }
+ echo '</textarea>';
+
+ echo '</div>';
+ echo '</div>'; # id=inv_import_list
+
+
+ # iz datoteke
+ echo '<div id="inv_import_file"'.($import_type == 1 ? '' : ' style="display:none"').'>' ;
+
+ // Korak 3
+ echo $lang['srv_append_step3_xls'];
+ echo '<div class="append_step">';
+
+ echo $lang['srv_mailing_upload_list'];
+ echo ' <input type="file" name="recipientsFile" id="recipientsFile" />';
+
+ echo '<br /><br />';
+
+ echo $lang['srv_excel_upload_note'];
+
+ echo '</div>';
+ echo '</div>'; # id=inv_import_file
+
+ echo '<br class="clr" />';
+ echo '<span id="inv_upload_recipients_nosbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" onclick="append_submit(); return false;">'.$lang['srv_inv_btn_add_recipients_add'].'</a></span>';
+
+ $d = new Dostop();
+ if ($d->checkDostopSub('edit')){
+ echo '<span style="margin: 5px 20px; line-height:24px">';
+ printf($lang['src_coding_alert'], $this->anketa);
+ echo '</span>';
+ }
+
+ echo '</form>';
+
+ echo '<br class="clr"/>';
+
+ //echo '</div>'; # id=inv_import_list_container
+
+ echo '</fieldset>';
+
+ }
+ // Merge
+ else{
+
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_merge'].'</legend>';
+
+ echo '<form id="inv_recipients_upload_form" name="resp_uploader" enctype="multipart/form-data" method="POST" action="'.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m='.$_GET['m'].'">';
+ echo '<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />';
+ echo '<input type="hidden" name="do" value="0">';
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'">';
+
+ # sporočilo za personalizirana e-vabila in respondente iz baze
+ echo $lang['srv_merge_note'];
+
+ // Korak 1
+ echo $lang['srv_merge_step1'];
+ echo '<div class="append_step">';
+
+ echo $lang['srv_merge_step1_note'];
+
+ echo '<div id="inv_field_container">';
+
+ echo '<ul class="connectedSortable">';
+ $field_lang = array();
+ if (count($field_list ) > 0) {
+ foreach ($field_list AS $field => $text_label) {
+ # tukaj polja niso izbrana
+ $is_selected = false;
+
+ # če je polje obkljukano
+ $css = $is_selected ? ' class="inv_field_enabled"' : '';
+
+
+ # labela sproži klik checkboxa
+ $label_for = ' for="'.$field.'_chk"';
+
+ echo '<li id="'.$field.'"'.$css.'>';
+ echo '<input id="'.$field.'_chk" type="checkbox" name="fields[]" value="'.$field.'" class="inv_checkbox' . $hidden_checkbox . '"'.($is_selected == true ? ' checked="checked"' : '').' '.($merge?' onclick="merge_getItems();"':'').'>';
+ echo '<label'.$label_for.' style="display: inline">'.$text_label.'</label>';
+ echo '</li>';
+
+ if ($is_selected == true) {
+ $field_lang[] = $text_label;
+ }
+ }
+ }
+ echo '</ul><br />';
+ echo '</div>';
+ echo '</div>';
+
+
+ // Korak 2
+ echo $lang['srv_merge_step2'];
+ echo '<div class="append_step">';
+
+ echo '<script type="text/javascript">';
+ echo "$('ul.connectedSortable').sortable({update : function () { append_refreshFieldsList(); }, forcePlaceholderSize: 'true',tolerance: 'pointer',placeholder: 'inv_field_placeholder',});";
+ echo '</script>';
+
+ echo '<span><label><input name="inv_import_type" id="inv_import_type0" type="radio" value="0" onclick="append_change_import_type(\''.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m='.$_GET['m'].'\');" checked="checked">';
+ echo ''.$lang['srv_iz_seznama'].'</label></span>';
+ echo '<span><label><input name="inv_import_type" id="inv_import_type1" type="radio" value="1" onclick="append_change_import_type(\''.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m=upload_xls\');">';
+ echo ''.$lang['srv_iz_excela'].'</label></span>';
+
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+
+ echo '</div>';
+
+
+ // Korak 3
+ echo $lang['srv_merge_step3'];
+ echo '<div class="append_step">';
+
+ echo '<input type="hidden" name="do_merge" value="1" id="do_merge">';
+ echo '<p>'.$lang['srv_izberite_identifikator'].'</p>';
+ echo '<ul id="merge">';
+ echo '</ul>';
+ echo '</div>';
+
+
+ # iz seznama
+ echo '<div id="inv_import_list"'.($import_type != 1 ? '' : ' style="display:none"').'>' ;
+
+ // Korak 4
+ echo $lang['srv_merge_step4'];
+ echo '<div class="append_step">';
+
+ echo $lang['srv_merge_step4_note'];
+
+ echo $lang['srv_inv_recipiens_sample'].'&nbsp;</span><span class="inv_sample">';
+ echo $lang['srv_inv_recipiens_sample1'];
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo '</span>';
+ echo '<br class="clr" />'.$lang['srv_inv_recipiens_fields'].' <span id="inv_field_list" class="inv_type_0">';
+ echo implode(',',$field_lang);
+ echo '</span>';
+ echo '<br class="clr" /><textarea id="inv_recipients_list" cols="50" rows="9" name="inv_recipients_list" style="margin-bottom: 7px;">';
+ if (is_array($recipients_list) && count($recipients_list) > 0 ) {
+ echo implode("\n",$recipients_list);
+ }
+ echo '</textarea>';
+ echo '<br class="clr"/>';
+
+ echo '</div>';
+ echo '</div>'; # id=inv_import_list
+
+ # iz datoteke
+ echo '<div id="inv_import_file"'.($import_type == 1 ? '' : ' style="display:none"').'>' ;
+
+ // Korak 4
+ echo $lang['srv_merge_step4'];
+ echo '<div class="append_step">';
+
+ echo $lang['srv_mailing_upload_list'];
+ echo ' <input type="file" name="recipientsFile" id="recipientsFile" />';
+
+ echo '<br class="clr" /><br />';
+
+ echo $lang['srv_excel_upload_note'];
+
+ echo '</div>';
+ echo '</div>'; # id=inv_import_file
+
+
+ echo '<br class="clr" />';
+ echo '<span id="inv_upload_recipients_nosbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" onclick="append_submit(); return false;">'.$lang['srv_inv_btn_add_recipients_add'].'</a></span>';
+
+ $d = new Dostop();
+ if ($d->checkDostopSub('edit')){
+ echo '<span style="margin: 5px 20px; line-height:24px">';
+ printf($lang['src_coding_alert'], $this->anketa);
+ echo '</span>';
+ }
+
+ echo '</form>';
+
+ echo '<br class="clr"/>';
+
+ echo '</fieldset>';
+ }
+ }
+
+ function do_append_merge() {
+ global $lang;
+ global $site_url;
+ global $global_user_id;
+
+ # dodamo uporabnike
+ $fields = $_POST['fields'];
+ $recipients_list = mysql_real_unescape_string( $_POST['inv_recipients_list'] );
+ $merge = (int)$_POST['merge'];
+ $do_merge = (int)$_POST['do_merge'];
+ $import_type = (int)$_POST['inv_import_type'];
+ if ($_POST['do']=='1') $do = true; else $do = false;
+
+
+ // ce uploadamo datoteko
+ if ($import_type == 1) {
+
+ $file_name = $_FILES["recipientsFile"]["tmp_name"];
+
+ $fh = @fopen($file_name, "rb");
+ if ($fh) {
+ $recipients_list = fread($fh, filesize($file_name));
+ fclose($fh);
+ }
+
+ if (isset ($_POST['recipientsDelimiter'])) {
+ $recipients_list = str_replace($_POST['recipientsDelimiter'], "|~|", $recipients_list);
+ }
+ else {
+ $recipients_list = str_replace(",", "|~|", $recipients_list);
+ }
+ }
+
+ // append
+ if ($do_merge == 0) {
+
+ $result = $this->appendData($do, $fields, $recipients_list);
+
+ if ($result == -1) {
+ $output = $lang['srv_append-merge_required_field'];
+ } elseif ($result == -3) {
+ $output = $lang['srv_append-merge_required_data'];
+ } elseif ($result >= 0) {
+ $output = $lang['srv_append-merge_added_1'].' '.$result.' '.$lang['srv_append-merge_added_2'];
+ }
+
+ // merge
+ } elseif ($do_merge == 1) {
+
+ $result = $this->mergeData($do, $fields, $recipients_list, $merge);
+
+ if ($result == -1) {
+ $output = $lang['srv_append-merge_required_field'];
+ } elseif ($result == -2) {
+ $output = $lang['srv_append-merge_required_id'];
+ } elseif ($result == -3) {
+ $output = $lang['srv_append-merge_required_data'];
+ } elseif ($result >= 0) {
+ $output = $lang['srv_append-merge_merged_1'].' '.$result.' '.$lang['srv_append-merge_merged_2'];
+ }
+
+ }
+
+ // prikazemo obvestilo in formo za potrditev
+ if ($import_type == 1){
+ if ($do_merge == 1)
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_merge'].'</legend>';
+ else
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_append'].'</legend>';
+ }
+
+ if ( ! $do ) {
+
+ // napaka
+ if ($result <= 0) {
+ echo '<h2>'.$lang['error'].'</h2>';
+
+ if ($result < 0)
+ echo '<p>'.$output.'</p>';
+ else
+ echo '<p>'.$lang['srv_append-merge_error_value'].'</p>';
+
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_gray" onclick="append_submit_close(); return false;"><span>'.$lang['back'].'</span></a></span>';
+
+ } else {
+
+ echo '<h2>'.$lang['srv_potrditev'].'</h2>';
+
+ if ($do_merge == 0)
+ echo '<p>'.$lang['srv_append-merge_process_1'].' '.$result.' '.$lang['srv_append-merge_process_2'].'. '.'</p>';
+ else
+ echo '<p>'.$lang['srv_append-merge_process_o_1'].' '.$result.' '.$lang['srv_append-merge_process_o_2'].'</p>';
+
+
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_gray" onclick="append_submit_close(); return false;"><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft spaceLeft"><a class="ovalbutton ovalbutton_orange" onclick="append_submit(1); return false;"><span>'.$lang['srv_potrdi'].'</span></a></span>';
+ }
+
+
+ // shranjeno, prikazemo resultat
+ } else {
+
+ echo '<h2>'.$lang['fin_import_ok'].'</h2>';
+
+ echo '<p>'.$output.'</p>';
+ echo '<p>'.$lang['srv_append-merge_fin'].'</p>';
+
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" href="index.php?anketa='.$this->anketa.'&a=data'.(count($this->usr_ids) < 100?'&highlight_usr='.implode('-', $this->usr_ids).'':'').'"><span>'.$lang['data_show'].'</span></a></span>';
+
+ }
+
+ if ($import_type == 1){
+ echo '<br /><br />';
+ echo '</fieldset>';
+ }
+ }
+
+ private $usr_ids = array();
+
+ function appendData($do = true, $fields, $rawdata) {
+ if ($do) TrackingClass::update($this->anketa, 1);
+
+ if (false) {
+ echo 'dumping for append:';
+ echo '<pre>';
+ print_r($fields);
+ echo '</pre>';
+ echo '<pre>';
+ print_r($rawdata);
+ echo '</pre>';
+ }
+
+ $data = explode("\n", $rawdata);
+
+ if (count($fields) <= 0) return -1;
+ if ($rawdata == '') return -3;
+ if (count($data) <= 0) return -3;
+
+ $tip = array();
+ $vre_id = array();
+ $sql = sisplet_query("SELECT id, tip FROM srv_spremenljivka WHERE id IN (".implode(',', $fields).")");
+ while ($row = mysqli_fetch_array($sql)) {
+ $tip[$row['id']] = $row['tip'];
+
+ if ( in_array($row['tip'], array(1, 2, 3)) ) {
+
+ $s = sisplet_query("SELECT id, variable FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red");
+ while ($r = mysqli_fetch_array($s)) {
+ $vre_id[$row['id']][$r['variable']] = $r['id'];
+ }
+
+ } elseif ( in_array($row['tip'], array(7, 21,8)) ) {
+ // v tekstovno spremenljivko pisemo v prvo polje
+ $s = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red");
+ $r = mysqli_fetch_array($s);
+ $vre_id[$row['id']] = $r['id'];
+ }
+ }
+ $added = 0;
+ foreach ($data AS $dataline) {
+ $line = explode(',', $dataline);
+
+ foreach ($line AS $key => $val) {
+ $line[$key] = trim($val);
+ }
+
+ $added += $this->insertLine($line,$fields,$tip,$vre_id,$do);
+ }
+
+ if ($do) SurveyPostProcess::forceRefreshData($this->anketa);
+
+ return $added;
+ }
+
+ function insertLine($line,$fields,$tip,$vre_id,$do,$fromExcel=false){
+
+ $added=0;
+
+ // izberemo random hash, ki se ni v bazi
+ $ip = GetIP();
+ do {
+ $rand = md5(mt_rand(1, mt_getrandmax()).'@'.$ip);
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE cookie = '$rand'");
+ } while (mysqli_num_rows($sql) > 0);
+
+ // nov user
+ if ($do) {
+ $sql = sisplet_query("INSERT INTO srv_user (id, ank_id, cookie, time_insert, time_edit, last_status, lurker) VALUES ('', '$this->anketa', '$rand', NOW(), NOW(), '5', '0')");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ if ($usr_id > 0 || $do==false) {
+
+ $this->usr_ids[] = $usr_id;
+
+ $i = 0;
+ foreach ($fields AS $id) {
+
+ if ($do) {
+
+ if ( in_array($tip[$id], array(1, 3)) ) {
+
+ $vre = $vre_id[$id][$line[$i]];
+
+ if ($vre != '') {
+ $sql = sisplet_query("INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id, loop_id) VALUES ('$id', '$vre', '$usr_id', NULL)");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } elseif ( in_array($tip[$id], array(2)) ) {
+
+ $checks = explode(' ', $line[$i]);
+
+ if ( count($checks) > 0 ) {
+
+ $sql = sisplet_query("DELETE FROM srv_data_vrednost".$this->db_table." WHERE spr_id='$id' AND usr_id='$usr_id' AND loop_id IS NULL");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ foreach ($checks AS $k => $v) {
+
+ $vre = $vre_id[$id][$v];
+
+ if ($vre != '') {
+
+ $sql = sisplet_query("INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id, loop_id) VALUES ('$id', '$vre', '$usr_id', NULL)");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+ }
+
+ } elseif ( in_array($tip[$id], array(7, 21, 8)) ) {
+
+ if ($tip[$id] == 21) {
+ $vre = $vre_id[$id];
+ } elseif ($tip[$id] == 7 || $tip[$id] == 8) {
+ $vre = 0;
+ }
+
+ if ($tip[$id] == 8)
+ {
+ #datum prekodiramo v pravo obliko
+ $value = PHPExcel_Style_NumberFormat::toFormattedString($line[$i], "D.M.YYYY");
+ }
+ else
+ {
+ $value = $line[$i];
+ }
+ $sql = sisplet_query("INSERT INTO srv_data_text".$this->db_table." (id, spr_id, vre_id, text, text2, usr_id, loop_id) VALUES ('', '$id', '$vre', '$value', '', '$usr_id', NULL)");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+
+ $i++;
+ }
+ $added++;
+ }
+ return $added;
+ }
+
+ function mergeData($do = true, $fields, $rawdata, $merge) {
+ if ($do) TrackingClass::update($this->anketa, 1);
+
+ if (false) {
+ echo 'dumping for merge:';
+ echo '<pre>';
+ print_r($fields);
+ echo '</pre>';
+ echo '<pre>';
+ print_r($rawdata);
+ echo '</pre>';
+ echo '<pre>';
+ print_r($merge);
+ echo '</pre>';
+ }
+
+ if (count($fields) <= 0) return -1;
+ if ($merge <= 0) return -2;
+
+ $merge_key = array_keys($fields, $merge);
+ $merge_key = $merge_key[0];
+
+ $data = explode("\n", $rawdata);
+
+ if ($rawdata == '') return -3;
+ if (count($data) <= 0) return -3;
+
+ $tip = array();
+ $vre_id = array();
+ $sql = sisplet_query("SELECT id, tip FROM srv_spremenljivka WHERE id IN (".implode(',', $fields).")");
+ while ($row = mysqli_fetch_array($sql)) {
+ $tip[$row['id']] = $row['tip'];
+
+ if ( in_array($row['tip'], array(1, 2, 3)) ) {
+
+ $s = sisplet_query("SELECT id, variable FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red");
+ while ($r = mysqli_fetch_array($s)) {
+ $vre_id[$row['id']][$r['variable']] = $r['id'];
+ }
+
+ } elseif ( in_array($row['tip'], array(7, 21, 8)) ) {
+ // v tekstovno spremenljivko pisemo v prvo polje
+ $s = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red");
+ $r = mysqli_fetch_array($s);
+ $vre_id[$row['id']] = $r['id'];
+ }
+ }
+
+ $merge_tip = $tip[$merge];
+
+ $merged = 0;
+
+ foreach ($data AS $dataline) {
+
+ $line = explode(',', $dataline);
+
+ foreach ($line AS $key => $val) {
+ $line[$key] = trim($val);
+ }
+
+ if ($line[$merge_key] != '') {
+
+ // poiscemo userja za merge
+ if ( in_array($merge_tip, array(1, 2, 3)) ) {
+
+ $sqlu = sisplet_query("SELECT usr_id FROM srv_data_vrednost".$this->db_table." WHERE spr_id='$merge' AND vre_id='".$vre_id[$merge][$line[$merge_key]]."'");
+
+ } elseif ( in_array($merge_tip, array(7, 21, 8)) ) {
+ if ($merge_tip == 21) {
+ $vre = $vre_id[$merge];
+ } elseif ($merge_tip == 7 || $merge_tip == 8) {
+ $vre = 0;
+ }
+
+ $sqlu = sisplet_query("SELECT usr_id FROM srv_data_text".$this->db_table." WHERE spr_id='$merge' AND vre_id='$vre' AND text='$line[$merge_key]'");
+ }
+ if (!$sqlu) echo mysqli_error($GLOBALS['connect_db']);
+
+ while ($rowu = mysqli_fetch_array($sqlu)) {
+
+ if ($do) {
+ $usr_id = $rowu['usr_id'];
+
+ $s = sisplet_query("UPDATE srv_user SET time_edit=NOW() WHERE id='$usr_id'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->usr_ids[] = $usr_id;
+ }
+
+ $i = 0;
+ foreach ($fields AS $id) {
+
+ if ($id != $merge) {
+
+ if ($do) {
+
+ if ( in_array($tip[$id], array(1, 3)) ) {
+
+ $vre = $vre_id[$id][$line[$i]];
+
+ if ($vre != '') {
+ $sql = sisplet_query("DELETE FROM srv_data_vrednost".$this->db_table." WHERE spr_id='$id' AND usr_id='$usr_id' AND loop_id IS NULL");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $sql = sisplet_query("INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id, loop_id) VALUES ('$id', '$vre', '$usr_id', NULL)");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } elseif ( in_array($tip[$id], array(2)) ) {
+
+ $checks = explode(' ', $line[$i]);
+
+ if ( count($checks) > 0 ) {
+
+ $sql = sisplet_query("DELETE FROM srv_data_vrednost".$this->db_table." WHERE spr_id='$id' AND usr_id='$usr_id' AND loop_id IS NULL");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ foreach ($checks AS $k => $v) {
+
+ $vre = $vre_id[$id][$v];
+
+ if ($vre != '') {
+
+ $sql = sisplet_query("INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id, loop_id) VALUES ('$id', '$vre', '$usr_id', NULL)");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+ } elseif ( in_array($tip[$id], array(7, 21, 8)) ) {
+
+ if ($tip[$id] == 21) {
+ $vre = $vre_id[$id];
+ } elseif ($tip[$id] == 7 || $tip[$id] == 8) {
+ $vre = 0;
+ }
+
+ // ker je primary nastavljen na ID, moramo najprej pobrisat
+ $sql = sisplet_query("DELETE FROM srv_data_text".$this->db_table." WHERE spr_id='$id' AND vre_id='$vre' AND usr_id='$usr_id'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $sql = sisplet_query("INSERT INTO srv_data_text".$this->db_table." (spr_id, vre_id, text, usr_id) VALUES ('$id', '$vre', '$line[$i]', '$usr_id')");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+ $i++;
+ }
+ $merged++;
+ }
+ }
+ }
+
+ if ($do) SurveyPostProcess::forceRefreshData($this->anketa);
+
+ return $merged;
+ }
+
+ function upload_xls(){
+ global $lang, $site_url,$site_path,$global_user_id;
+
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_append'].'</legend>';
+
+ if (isset($_POST['fields']) && count($_POST['fields']) > 0){
+
+ if (isset($_FILES['recipientsFile'])
+ && is_array($_FILES['recipientsFile'])
+ && isset($_FILES['recipientsFile']['size']) && $_FILES['recipientsFile']['size'] > 0
+ && (int)$_FILES['recipientsFile']['error'] == 0
+ && (pathinfo($_FILES['recipientsFile']['name'],PATHINFO_EXTENSION) == 'xls' || pathinfo($_FILES['recipientsFile']['name'],PATHINFO_EXTENSION) == 'xlsx') )
+ {
+
+ $orig_parts = pathinfo($_FILES["recipientsFile"]["name"]);
+ $path_parts = pathinfo($_FILES["recipientsFile"]["tmp_name"]);
+
+ $fileName = $this->anketa.'_'.$global_user_id.'_'.$path_parts['filename'].'.'.$orig_parts['extension'];
+ $file = $site_path.'admin/survey/tmp/'.$fileName;
+ $move = move_uploaded_file($_FILES['recipientsFile']['tmp_name'], $file);
+
+ if ($move == true){
+ #spremenljivke
+ $field_list = array();
+ $sql = sisplet_query("SELECT s.id, s.variable, s.tip FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.tip IN (1, 2, 3, 7, 8, 21) ORDER BY g.vrstni_red, s.vrstni_red");
+ while ($row = mysqli_fetch_array($sql)) {
+ $field_list[$row['id']] = $row['variable'] . ' ('.($row['tip']==1?'radio':'').($row['tip']==2?'checkbox':'').($row['tip']==3?'dropdown':'').($row['tip']==21?'text':'').($row['tip']==7?'number':'').($row['tip']==8?'date':'').')';
+ }
+
+ include_once("./excel/PHPExcel.php");
+ require_once("./excel/PHPExcel/IOFactory.php");
+
+ $result = array();
+ $objPHPExcel = PHPExcel_IOFactory::load($file);
+ $objWorksheet = $objPHPExcel->getActiveSheet();
+
+ // Get worksheet dimensions
+ $highestRow = $objWorksheet->getHighestRow();
+ $highestColumn = $objWorksheet->getHighestColumn();
+ $columns = array();
+
+ $highestColumn++;
+ for ($column = 'A'; $column != $highestColumn; $column++)
+ {
+ $columns[] = $column;
+ }
+
+ echo '<form id="append_xml" name="resp_uploader" enctype="multipart/form-data" method="POST" action="'.$site_url.'admin/survey/index.php?anketa='.$this->anketa.'&a=data&m=append_xls">';
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'">';
+ echo '<input type="hidden" name="file" value="'.$fileName.'">';
+ foreach ($_POST['fields'] AS $field)
+ {
+ echo '<input id="'.$field.'_chk" type="hidden" name="fields[]" value="'.$field.'" />';
+ }
+
+ echo $lang['srv_append_xls_note'];
+
+ echo '<div id="inv_field_container">';
+ echo '<div class="append_step">';
+
+ echo '<ul class="connectedSortable">';
+ foreach ($_POST['fields'] AS $spr_id)
+ {
+ echo '<li class="inv_field_enabled"><label>'.$field_list[$spr_id].'</label></li>';
+ }
+ echo '</ul>';
+ echo '</div>';
+ echo '</div>';
+
+
+ if (count($columns) > 0){
+ echo $lang['srv_append_xls_step1'];
+
+ echo '<div id="inv_field_container">';
+ echo '<div class="append_step">';
+ echo '<ul class="connectedSortable">';
+ foreach ($columns AS $column){
+ echo '<li><label><input type="checkbox" name="xls_column[]" value="'.$column.'">'.$column.'</label></li>';
+ }
+ echo '</ul>';
+ echo '</div>';
+ echo '</div>';
+ }
+
+
+ echo $lang['srv_append_xls_step1'];
+
+ echo '<div class="append_step">';
+ echo '<p>'.$lang['srv_append_xls_step2_begin'].': <input name="start_row" type="number" min="1" max="'.(int)$highestRow.'" value="1"></p>';
+ echo '<p>'.$lang['srv_append_xls_step2_end'].': <input name="end_row" type="number" min="1" max="'.(int)$highestRow.'" value="'.(int)$highestRow.'"></p>';
+ echo '<span id="inv_upload_recipients_nosbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" onclick="$(\'#append_xml\').submit();">'.$lang['srv_inv_btn_add_recipients_add'].'</a></span>';
+ echo '<br /><br />';
+ echo '</div>';
+
+
+ echo '</form>';
+ }
+ }
+ elseif(pathinfo($_FILES['recipientsFile']['name'],PATHINFO_EXTENSION) != 'xls' && pathinfo($_FILES['recipientsFile']['name'],PATHINFO_EXTENSION) != 'xlsx'){
+ echo $lang['srv_iz_excela_xls_error'];
+ }
+ else{
+ echo 'File error. #'.(int)$_FILES['recipientsFile']['error'];
+ }
+ }
+ else
+ {
+ echo 'No list';
+ }
+
+ echo '</fieldset>';
+ }
+
+ function append_xls() {
+ global $lang, $site_url,$site_path,$global_user_id;
+
+ $fileName = $_POST['file'];
+ $file = $site_path.'admin/survey/tmp/'.$fileName;
+
+ $columns = $_POST['xls_column'];
+ $fields = $_POST['fields'];
+
+ $do_merge = (int)$_POST['do_merge'];
+
+ if (file_exists($file)
+ && is_array($columns) && count($columns ) > 0
+ && is_array($fields) && count($fields ) > 0)
+ {
+ $do = 1;
+
+ include_once("./excel/PHPExcel.php");
+ require_once("./excel/PHPExcel/IOFactory.php");
+
+ $objPHPExcel = PHPExcel_IOFactory::load($file);
+ $objWorksheet = $objPHPExcel->getActiveSheet();
+
+ // Get worksheet dimensions
+ $highestRow = $objWorksheet->getHighestRow();
+ $highestColumn = $objWorksheet->getHighestColumn();
+
+
+
+ $start_row = min($_POST['start_row'],$highestRow);
+ $end_row = min($_POST['end_row'],$highestRow);
+ if ($end_row < $start_row)
+ {
+ $end_row = $start_row;
+ }
+
+ #podatki spremenljivk
+ $ids = array();
+ $tip = array();
+ $vre_id = array();
+ $sql = sisplet_query("SELECT id, tip FROM srv_spremenljivka WHERE id IN (".implode(',', $fields).")");
+ while ($row = mysqli_fetch_array($sql)) {
+ $tip[$row['id']] = $row['tip'];
+
+ if ( in_array($row['tip'], array(1, 2, 3)) ) {
+
+ $s = sisplet_query("SELECT id, variable FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red");
+ while ($r = mysqli_fetch_array($s)) {
+ $vre_id[$row['id']][$r['variable']] = $r['id'];
+ }
+
+ } elseif ( in_array($row['tip'], array(7, 21,8)) ) {
+ // v tekstovno spremenljivko pisemo v prvo polje
+ $s = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red");
+ $r = mysqli_fetch_array($s);
+ $vre_id[$row['id']] = $r['id'];
+ }
+ }
+
+ $added = 0;
+
+ for ($row = $start_row; $row <= $end_row; ++$row)
+ {
+ $line=array();
+ foreach ($columns AS $column)
+ {
+ $value = $objWorksheet->getCell("$column$row")->getCalculatedValue();
+ $line[] = mysqli_real_escape_string($GLOBALS['connect_db'], $value);
+ #$line[] = mysqli_real_escape_string($GLOBALS['connect_db'], $objWorksheet->getCell("$column$row")->getValue());
+ }
+ $added += $this->insertLine($line,$fields,$tip,$vre_id,$do);
+ }
+
+ $result = $added;
+ }
+ else
+ {
+ echo $lang['srv_append-merge_error_file'];
+ }
+
+ if ($result == -1) {
+ $output = $lang['srv_append-merge_required_field'];
+ } elseif ($result == -3) {
+ $output = $lang['srv_append-merge_required_data'];
+ } elseif ($result >= 0) {
+ $output = $lang['srv_append-merge_added_1'].' '.$result.' '.$lang['srv_append-merge_added_2'];
+ }
+
+
+ // prikazemo obvestilo in formo za potrditev
+ if ($do_merge == 1)
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_merge'].'</legend>';
+ else
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_append'].'</legend>';
+
+ if ( ! $do ) {
+
+ // napaka
+ if ($result <= 0) {
+ echo '<h2>'.$lang['error'].'</h2>';
+
+ if ($result < 0)
+ echo '<p>'.$output.'</p>';
+ else
+ echo '<p>'.$lang['merge_error_value'].'.</p>';
+
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_gray" onclick="append_submit_close(); return false;"><span>'.$lang['back'].'</span></a></span>';
+
+ } else {
+
+ echo '<h2>'.$lang['srv_potrditev'].'</h2>';
+
+ if ($do_merge == 0)
+ echo '<p>'.$lang['srv_append-merge_process_1'].' '.$result.' '.$lang['srv_append-merge_process_2'].'. </p>';
+ else
+ echo '<p>'.$lang['srv_append-merge_process_o_1'].' '.$result.' '.$lang['srv_append-merge_process_o_2'].'</p>';
+
+
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" onclick="append_submit(1); return false;"><span>'.$lang['srv_potrdi'].'</span></a></span>';
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_gray" onclick="append_submit_close(); return false;"><span>'.$lang['srv_cancel'].'</span></a></span>';
+ }
+
+ // shranjeno, prikazemo resultat
+ } else {
+
+ echo '<h2>'.$lang['fin_import_ok'].'</h2>';
+
+ echo '<p>'.$output.'</p>';
+ echo '<p>'.$lang['fin_import_ok_text'].'</p>';
+
+ echo '<span id="inv_upload_recipients_no_sbmt" class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" href="index.php?anketa='.$this->anketa.'&a=data"><span>'.$lang['data_show'].'</span></a></span>';
+ }
+
+ echo '<br /><br />';
+ echo '</fieldset>';
+ }
+
+ function ajax() {
+
+ $this->anketa = $_REQUEST['anketa'];
+
+ if ($_GET['a'] == 'change_import_type') {
+ $this->ajax_change_import_type();
+
+ } elseif ($_GET['a'] == 'add_recipients') {
+ $this->ajax_addRecipients();
+
+ } elseif ($_GET['a'] == 'submit') {
+ $this->ajax_submit();
+ }
+ }
+
+ function ajax_change_import_type() {
+ $this->displayAppendMerge();
+ }
+
+ function ajax_addRecipients() {
+
+ $this->do_append_merge();
+ }
+
+ function ajax_submit () {
+
+ $this->do_append_merge();
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyBaseSetting.php b/admin/survey/classes/class.SurveyBaseSetting.php
new file mode 100644
index 0000000..8f107db
--- /dev/null
+++ b/admin/survey/classes/class.SurveyBaseSetting.php
@@ -0,0 +1,84 @@
+<?php
+/** Class ki skrbi za osnovne nastavitve ankete - tabela srv_survey
+ * November 2011
+ *
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+class SurveyBaseSetting
+{
+ private $sid;
+ private $return = array('error' => 1, 'msg'=>'','action'=>'0');
+
+ function __construct($sid) {
+ if ((int)$sid > 0) {
+ $this->sid = $sid;
+ $this->return['msg'] = 'Napaka!'; # osnovno sporočilo o napaki
+ } else {
+ echo json_encode(array('error' => 1, 'msg'=>'Invalid Survey ID!'));
+ exit();
+ }
+ }
+
+ function ajax() {
+ switch ($_GET['a']) {
+ case 'radio':
+ $this->saveSettingRadio();
+ break;
+
+ case 'text':
+ $this->saveSettingText();
+ break;
+
+ default:
+ ;
+ break;
+ }
+ echo json_encode($this->return);
+ exit();
+ }
+
+ function saveSettingRadio() {
+ if (isset($_POST['what']) && isset($_POST['value'])) {
+ $what = trim($_POST['what']);
+ $value = trim($_POST['value']);
+
+ # ali refreshamo timestamp, da vsilimo refresh podatkov, oziroma ponastavimo še kakšne druge stvari
+ switch ($what) {
+ case 'show_email':
+ global $global_user_id;
+ $sql = sisplet_query("UPDATE srv_anketa SET edit_uid = '$global_user_id', edit_time=NOW() WHERE id='".$this->sid."'");
+ break;
+ # če nastavimo individualiziran url nazaj na 1 (=DA) potem obvezno vklopimo prikazovanje uvoda
+ case 'individual_invitation':
+ if ((int)$value > 0) {
+ $sql = sisplet_query("UPDATE srv_anketa SET show_intro = '1' WHERE id='".$this->sid."'");
+ }
+ default:
+ ;
+ break;
+ }
+
+ $updateString = "UPDATE srv_anketa SET ".$what."='".$value."' WHERE id='".$this->sid."'";
+ $update = sisplet_query($updateString);
+ sisplet_query("COMMIT");
+ $this->return['msg'] = 'Updated:'.$update;
+ $this->return['error'] = 0;
+ }
+ }
+
+ function saveSettingText() {
+ if (isset($_POST['what']) && isset($_POST['value'])) {
+ $what = trim($_POST['what']);
+ $value = trim($_POST['value']);
+ $updateString = "UPDATE srv_anketa SET ".$what."='".$value."' WHERE id='".$this->sid."'";
+ $update = sisplet_query($updateString);
+ sisplet_query("COMMIT");
+ $this->return['msg'] = 'Updated:'.$update;
+ $this->return['error'] = 0;
+ }
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyCondition.php b/admin/survey/classes/class.SurveyCondition.php
new file mode 100644
index 0000000..08b6239
--- /dev/null
+++ b/admin/survey/classes/class.SurveyCondition.php
@@ -0,0 +1,316 @@
+<?php
+class SurveyCondition
+{
+ private $_sid;
+
+ private $_conditions = array();
+
+ private $_chooseProfileJSAction = null;
+
+ function __construct($sid)
+ {
+ global $lang;
+ $this->_sid = $sid;
+ # polovimo vse obstoječe ife
+ $this->_conditions[0] = array(
+ 'id' => '0',
+ 'name' => $lang['srv_inv_condition_new_filter'],
+ 'number' => '0',
+ 'tip' => '0',
+ 'label' => $lang['srv_inv_condition_new_filter'],
+ 'collapsed' => '0',
+ 'folder' => '0',
+ 'enabled' => '1',
+ 'tab' => '0'
+ );
+ $str = "SELECT sif.*, ssc.name FROM srv_if AS sif JOIN srv_survey_conditions AS ssc ON (sif.id = ssc.if_id) WHERE ssc.ank_id = '$this->_sid'";
+ $qry = sisplet_query($str);
+ while ($row = mysqli_fetch_assoc($qry))
+ {
+ if (isset($row['id']) && (int)$row['id'] > 0)
+ {
+ $this->_conditions[$row['id']] = $row;
+ }
+ }
+ if (isset($_REQUEST['surveyConditionProfileAction']) && !empty($_REQUEST['surveyConditionProfileAction']))
+ {
+ $this->_chooseProfileJSAction = $_REQUEST['surveyConditionProfileAction'];
+ }
+ }
+
+ public function ajax()
+ {
+ switch ($_GET['a']) {
+ case 'showCondition' :
+ $this->displayConditions((int)$_POST['cid']);
+ break;
+ case 'newCondition' :
+ $this->newCondition();
+ break;
+ case 'deleteCondition' :
+ $this->deleteCondition((int)$_POST['cid']);
+ break;
+ case 'showRename' :
+ $this->showRename();
+ break;
+ case 'renameCondition' :
+ $this->renameCondition();
+ break;
+ default:
+ echo 'ERROR! Missing function for action: '.$_GET['a'].'! (SurveyConditionProfile)';
+ break;
+ }
+ }
+
+ public function displayConditions($pid)
+ {
+ global $lang;
+
+ $popUp = new PopUp();
+ $popUp->setId('divConditionProfiles');
+ $popUp->setHeaderText($lang[''].'Filtriranje s pogoji');
+
+ #vsebino shranimo v buffer
+
+ ob_start();
+
+ echo '<input type="hidden" id="chooseProfileJSAction" value="'.$this->_chooseProfileJSAction.'" />';
+ echo '<div class="condition_profile_holder">';
+
+ echo '<div id="condition_profile" class="select">';
+ if (count($this->_conditions) > 0)
+ {
+ foreach ($this->_conditions as $key => $value) {
+ echo '<div class="option' . ( $pid == $value['id'] ? ' active' : '') . '" data-cid="' . $value['id'] . '" onclick="showSurveyCondition(\''.$value['id'].'\')">' . $value['name'] .'</div>';
+ }
+ }
+ echo '</div>';
+ echo '</div>';
+ # tukaj prikazemo vsebino ifa
+ echo '<div id="div_cp_preview">';
+ echo '<div id="div_cp_preview_content">';
+ if ($pid > 0)
+ {
+ $b = new Branching($this->_sid);
+ $b->condition_editing($pid, -2);
+
+ } else {
+ echo 'Dodaj nov pogoj:';
+ echo '<input id="newSurveyConditionName" placeholder="Ime pogoja" >';
+ echo '<a href="#" onclick="newSurveyCondition(); return false;" class="faicon if_add" style="margin-left: 5px;" title="Dodaj nov pogoj"> Dodaj nov pogoj</a>';
+ }
+ echo '</div>';
+ echo '</div>';
+ echo '<div id="surveyConditionCover"></div>';
+ echo '<div id="renameProfileDiv"></div>';
+ $content = ob_get_clean();
+
+ #dodamo vsebino
+ $popUp->setContent($content);
+
+ # dodamo gumb Prekliči
+ $popUp->addButton(new PopUpCancelButton());
+
+ #dodamo gumb izberi profil
+ $confirmAction = 'alert(\'No action set\')';
+ if (isset($this->_chooseProfileJSAction) && !empty($this->_chooseProfileJSAction))
+ {
+ $confirmAction = $this->_chooseProfileJSAction;
+ }
+ $button = new PopUpButton($lang['srv_choose_profile']);
+ $button -> setFloat('right')
+ -> setButtonColor('orange')
+ -> addAction('onClick',$confirmAction.'; return false;');
+ $popUp->addButton($button);
+
+ if ($pid > 0) {
+ # dodamo gumb preimenuj
+ $button = new PopUpButton($lang['srv_rename_profile']);
+ $button -> setFloat('right')
+ -> addAction('onClick','showRenameSurveyCondition(\''.$pid.'\'); return false;');
+ $popUp->addButton($button);
+
+ # dodamo gumb izbriši
+ $button = new PopUpButton($lang['srv_delete_profile']);
+ $button -> setFloat('right')
+ -> addAction('onClick','deleteSurveyCondition(\''.$pid.'\'); return false;');
+ $popUp->addButton($button);
+ }
+
+ echo $popUp;
+
+
+ }
+
+ private function newCondition()
+ {
+ global $lang;
+ $result= array('error'=>1, 'if_id'=>0);
+
+ $name = isset($_POST['name']) && !empty($_POST['name']) ? $_POST['name'] : $lang['srv_inv_condition_new_filter_name'];
+ $result['name'] = $name;
+
+ #kreiramo osnovo za if
+ $str = "INSERT INTO srv_if (id) VALUES (NULL)";
+ $sql = sisplet_query($str);
+ $if_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ((int)$if_id > 0)
+ {
+ $str = "INSERT INTO srv_condition (id, if_id, vrstni_red) VALUES ('', '$if_id', '1')";
+ $sql = sisplet_query($str);
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ((int)$cond_id > 0)
+ {
+ $result['cond_id'] = (int)$cond_id;
+ $str = "INSERT INTO srv_survey_conditions (ank_id, if_id, name) VALUES ('$this->_sid', '$if_id', '$name')";
+ $sql = sisplet_query($str);
+ if (!sql)
+ {
+ }
+ else
+ {
+ $result['error'] = 0;
+ $result['if_id'] = (int)$if_id;
+ }
+ }
+ }
+
+ if ($result['error'] > 0)
+ {
+ # pobrišemo zgoraj kreiran if;
+ if ((int)$if_id > 0)
+ {
+ $sql = sisplet_query("DELETE FROM srv_condition where if_id ='$if_id'");
+ $sql = sisplet_query("DELETE FROM srv_if where id ='$if_id'");
+ }
+ }
+
+
+ echo json_encode($result);
+ return;
+ }
+
+ private function deleteCondition($cid = 0)
+ {
+ global $lang;
+ $result= array('error'=>1, 'cid'=>$cid);
+
+ if ($cid > 0)
+ {
+ /* pobrisemo se za ifom*/
+ $sql = sisplet_query("SELECT * FROM srv_condition WHERE if_id = '$cid'");
+ while ($row = mysqli_fetch_array($sql))
+ {
+ if ((int)$row['id'] > 0)
+ {
+ sisplet_query("DELETE FROM srv_condition_vre WHERE cond_id='".$row['id']."'");
+ }
+ }
+
+ if ((int)$cid> 0)
+ {
+ sisplet_query("DELETE FROM srv_condition WHERE if_id = '$cid'");
+ sisplet_query("DELETE FROM srv_if WHERE id = '$cid'");
+
+ }
+ /*-- pobrisemo se za ifom*/
+
+ $result['error'] = 0;
+ $result['cid'] = 0;
+ }
+
+ # pobrišemo še morebitne seje
+ SurveySession::sessionStart($this->_sid);
+ SurveySession::remove('invitationAdvancedConditionId');
+
+ echo json_encode($result);
+ return;
+ }
+
+ public function setChooseAction($action)
+ {
+ if (!empty($action))
+ {
+ $this->_chooseProfileJSAction = $action;
+ }
+ }
+
+ function getConditionName($if_id)
+ {
+ if (isset($this->_conditions[$if_id]['name']))
+ {
+ return $this->_conditions[$if_id]['name'];
+ }
+ global $lang;
+ return $lang['srv_inv_condition_no_filter'];
+ }
+
+
+ function getConditionString($if_id)
+ {
+ $condition_label = '';
+ ob_start();
+ $b = new Branching($this->_sid);
+
+ if ((int)$if_id > 0)
+ {
+ $b->display_if_label($if_id);
+ #$condition_label = mysqli_escape_string(ob_get_contents());
+ $condition_label = ob_get_contents();
+ ob_end_clean();
+ }
+ return $condition_label;
+ }
+
+ function showRename()
+ {
+ global $lang;
+ // div za preimenovanje
+
+ echo $lang['srv_missing_profile_name'].': ';
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . $this->_conditions[$_POST['cid']]['name'] . '" size="45" />';
+ echo '<input id="renameProfileId" type="hidden" value="' . $_POST['cid'] . '" />';
+ $button = new PopUpButton($lang['srv_rename_profile_yes']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','renameSurveyCondition(); return false;');
+
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','$(\'#divConditionProfiles #renameProfileDiv, #surveyConditionCover\').hide(); return false;');
+ }
+
+ function renameCondition()
+ {
+ global $lang;
+
+ $result = array('error'=>1);
+
+ $name = $_POST['name'];
+ $cid = (int)$_POST['cid'];
+
+ if ($this->_sid > 0 && isset($name) && !empty($name) && (int)$cid > 0)
+ {
+ $str = "UPDATE srv_survey_conditions SET name='$name' WHERE ank_id='$this->_sid' AND if_id='$cid'";
+ $qry = sisplet_query($str);
+ if ($qry)
+ {
+ $result['error'] = 0;
+ $result['errorMsg'] = '';
+ $result['if_id'] = (int)$cid;
+ }
+ else
+ {
+ $result['errorMsg'] = 'Prišlo je do napake!';
+ }
+ }
+ if (!isset($name) || empty($name))
+ {
+ $result['errorMsg'] = 'Ime ne sme biti prazno!';
+ }
+ echo json_encode($result);
+ return;
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyConditionProfiles.php b/admin/survey/classes/class.SurveyConditionProfiles.php
new file mode 100644
index 0000000..20ae21a
--- /dev/null
+++ b/admin/survey/classes/class.SurveyConditionProfiles.php
@@ -0,0 +1,977 @@
+<?php
+/** @author: Gorazd Veselič
+ *
+ * @Desc: za upravljanje z profili statusov za podatke in izvoze
+ *
+ */
+
+session_start();
+
+
+class SurveyConditionProfiles
+{
+ static private $sid = null; # id ankete
+ static private $uid = null; # id userja
+
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+ static private $inited = false; # ali so profili ze inicializirani
+
+ static private $_HEADER = null; # Header podatki
+
+ static private $awkConditions = array(); # array z pogoji za awk
+
+ static function Init($sid, $uid = null) {
+ # nastavimo sid
+ self::$sid = $sid;
+
+ if (isset($uid) && $uid > 0) {
+ self :: $uid = $uid ;
+ } else {
+ global $global_user_id;
+ self :: $uid = $global_user_id;
+ }
+
+ SurveyUserSetting :: getInstance()->Init(self::$sid, self::$uid);
+ if (self::$inited == false) {
+ self::$inited = self :: RefreshData();
+ }
+ }
+
+
+ static function RefreshData() {
+ self::$profiles = array();
+ # dodamo sistemske profile, skreiramo jih "on the fly"
+ self :: addSystemProfiles();
+
+ # preberemo podatke vseh profilov ki so na voljo in jih dodamo v array
+ $stringSelect = "SELECT * FROM srv_condition_profiles WHERE sid='" . self::$sid . "' AND uid='" . self::$uid . "' ";
+ $querySelect = sisplet_query($stringSelect);
+
+ if (mysqli_num_rows($querySelect)) {
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ }
+ }
+ # poiscemo privzet profil
+ self::$currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_condition_profile');
+
+ if (!self::$currentProfileId) {
+ self::$currentProfileId = 1;
+ }
+
+ # ce imamo nastavljen curent pid in profil z tem pid ne obstaja nastavomo na privzet profil
+ if (self::$currentProfileId != 1) {
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ self::$currentProfileId = 1;
+ self::setDefaultProfileId(self::$currentProfileId);
+ }
+ }
+
+ # ce ne obstajajo podatki za cpid damo error
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ die("Profile data is missing!");
+ return false;
+ } else {
+ return true;
+ }
+
+ }
+
+ public static function getSystemDefaultProfile() {
+ return (int)1;
+ }
+
+ public static function getCurentProfileId() {
+ return (int)self::$currentProfileId;
+ }
+
+ public static function setCurrentProfileId($id) {
+ if (isset(self::$profiles[$id]))
+ {
+ self::$currentProfileId = $id;
+ }
+ }
+
+ public function getProfileName($pid) {
+ return self::$profiles[$pid]['name'];
+ }
+
+ /* Vrne ID in ime trenutno izbranega profila
+ *
+ */
+ function getCurentProfile() {
+ return array('id'=>self::$currentProfileId,'name'=>self::$profiles[self::$currentProfileId]['name']);
+ }
+
+
+ static function setDefaultProfileId($pid = 0) {
+ if (!$pid) {
+ $pid = 1;
+ }
+
+ # profila inspect ne pustimo nastavit za privzetega, ker je tako izbran preko inspect, pustimo pa urejanje
+ if( self::$profiles[$pid]['type'] != 'inspect') {
+ # če smo izbrali drug profil resetiramo še profil profilov na trenutne nastavitve
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', '0');
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_condition_profile', $pid);
+ self::$currentProfileId = $pid;
+ }
+ return true;
+ }
+
+ static function addSystemProfiles() {
+ global $lang;
+
+ # skreiramo sistemske profile za vse spremenljivke
+ self::$profiles['1'] = array('id'=>'1','uid'=>self::$uid,'name'=>$lang['srv_condition_profile_all'],'system'=>1, 'if_id'=>0);
+ }
+
+ static function DisplayLink($hideAdvanced = true) {
+ global $lang;
+ // profili statusov
+ $allProfiles = self :: $profiles;
+ $css = (self :: $currentProfileId == SCP_DEFAULT_PROFILE ? ' gray' : '');
+
+ if ($hideAdvanced == false || self :: $currentProfileId != SCP_DEFAULT_PROFILE) {
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="link_condition_profile" title="' . $lang['srv_condition'] . '" onClick="conditionProfileAction(\'showProfiles\');">' . $lang['srv_condition'] . '</span>'."\n";
+ echo '</li>';
+ }
+ }
+
+ static function getProfileData($pid) {
+ // preverimo ali smo v razredu že lovili podatke za ta profil, potem jih preberemo čene jih osvežimo
+ if ( isset( self::$profiles[$pid] ) ) {
+ return self::$profiles[$pid];
+ } else {
+ self::$inited = self :: RefreshData();
+ return self::$profiles[$pid];
+ }
+ }
+
+
+ static function ajax() {
+ $pid = $_POST['pid'];
+ switch ($_GET['a']) {
+ case 'show_condition_profile' :
+ self :: showProfiles($pid);
+ break;
+ case 'change_condition_profile' :
+# if (isset($_POST['condition_label']) && $_POST['condition_label'] != '') {
+# self :: setConditionLabel($pid,$_POST['condition_label']);
+# }
+ if (isset($_POST['condition_error']) && $_POST['condition_error'] != '') {
+ self :: setConditionError($pid,$_POST['condition_error']);
+ }
+ self :: setDefaultProfileId($pid);
+ break;
+ case 'condition_remove' :
+ self :: conditionRemove();
+ break;
+ case 'create_condition_profile' :
+ self :: createNewProfile();
+ break;
+ case 'delete_condition_profile' :
+ self :: deleteProfile();
+ break;
+ case 'rename_condition_profile' :
+ self :: renameProfile();
+ break;
+ default:
+ echo 'ERROR! Missing function for action: '.$_GET['a'].'! (SurveyConditionProfile)';
+ break;
+ }
+ }
+
+ static function showProfiles ($pid = -1) {
+ global $global_user_id, $lang;
+
+ if ($pid > 0) {
+ $_currMPID = $pid;
+ } else {
+ // poiščmo uporabniški privzeti profil
+ $_currMPID = self::$currentProfileId;
+ }
+
+ // Naslov
+ echo '<h2>'.$lang['srv_condition_settings'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="conditionProfileAction(\'cancle\'); return false;">✕</a></div>';
+
+ if ( self :: $currentProfileId != SCP_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+ echo '<div class="condition_profile_holder">';
+
+ echo '<div id="condition_profile" class="select">';
+ foreach (self :: $profiles as $key => $value) {
+
+ echo ' <div class="option' . ( $_currMPID == $value['id'] ? ' active' : '') . '" id="condition_profile_' . $value['id'] . '" value="'.$value['id'].'">';
+
+ echo $value['name'];
+
+ if($_currMPID == $value['id']){
+ if ( self :: $profiles[$_currMPID]['if_id'] != 0) {
+ echo '<a href="#" title="'.$lang['srv_delete_profile'].'" onclick="conditionProfileAction(\'deleteAsk\'); return false;"><span class="faicon delete floatRight"></span></a>';
+ }
+ if ( self :: $profiles[$_currMPID]['if_id'] != 0) {
+ echo '<a href="#" title="'.$lang['srv_rename_profile'].'" onclick="conditionProfileAction(\'renameAsk\'); return false;"><span class="faicon edit floatRight spaceRight"></span></a>';
+ }
+ }
+
+ echo '</div>';
+ }
+ echo '</div>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+
+
+ // tukaj prikazemo vsebino ifa
+ echo '<div id="div_cp_preview">';
+ echo ' <div id="div_cp_preview_content">';
+
+ if (self :: $profiles[$_currMPID]['if_id'] > 0) {
+ $b = new Branching(self::$sid);
+ $b->condition_editing(self :: $profiles[$_currMPID]['if_id'], -2);
+ }
+ else {
+ echo $lang['srv_filter_profiles_note'];
+ }
+
+ echo ' </div>';
+ echo '</div>';
+
+
+ echo '</div>';
+
+
+ echo '<div id="conditionProfileButtons">';
+ // gumbi: preklici, ustvari nov, pozeni trenutni
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="conditionProfileAction(\'run\'); return false;"><span>'.$lang['srv_run_selected_profile'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="conditionProfileAction(\'newName\'); return false;"><span>'.$lang['srv_create_new_profile'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="conditionProfileAction(\'cancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '</div>';
+
+
+ // cover Div
+ echo '<div id="conditionProfileCoverDiv"></div>';
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfile">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="conditionProfileAction(\'newCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="conditionProfileAction(\'newCreate\'); return false;"><span>'.$lang['srv_save_profile'].'</span></a></span></span>';
+ echo '</div>';
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . self :: $profiles[$_currMPID]['name'] . '" size="45" />';
+ echo '<input id="renameProfileId" type="hidden" value="' . self :: $profiles[$_currMPID]['id'] . '" />';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="conditionProfileAction(\'renameCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="conditionProfileAction(\'renameConfirm\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>';
+ echo '</div>';
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . self :: $profiles[$_currMPID]['name'] . '</b>?';
+ echo '<input id="deleteProfileId" type="hidden" value="' . self :: $profiles[$_currMPID]['id'] . '" />';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="conditionProfileAction(\'deleteCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="conditionProfileAction(\'deleteConfirm\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>';
+ echo '</div>';
+ }
+
+
+ static function createNewProfile() {
+ $name = isset($_POST['name']) ? $_POST['name'] : 'Nov profil';
+
+ $sql = sisplet_query("INSERT INTO srv_if (id) VALUES ('')");
+ if (!$sql) echo '-1';
+ $if_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ sisplet_query("INSERT INTO srv_condition (id, if_id, vrstni_red) VALUES ('', '$if_id', '1')");
+
+ $sql = sisplet_query("INSERT INTO srv_condition_profiles (id, sid, uid, name, if_id) VALUES ('', '".self::$sid."', '".self::$uid."', '$name', '$if_id')");
+ if (!$sql) echo '-2';
+
+ $pid = mysqli_insert_id($GLOBALS['connect_db']);
+ echo $pid;
+ }
+
+ static function deleteProfile() {
+ $pid = $_POST['pid'];
+ if ($pid > 0 ) {
+ $sql = sisplet_query("SELECT * FROM srv_condition_profiles WHERE id = '$pid'");
+ $row = mysqli_fetch_array($sql);
+ $if = $row['if_id'];
+
+ # če je inspect pobrišemo inspect profil
+ if ($row['type'] == 'inspect') {
+ #preverimi ali imamo nastavljen pogoj za inspect
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ if ($if_id > 0) {
+ #odstranimo zapis za inspect
+ SurveyUserSetting :: getInstance()->removeSettings('inspect_if_id');
+ }
+ }
+
+ /* pobrisemo se za ifom*/
+ $sql = sisplet_query("SELECT * FROM srv_condition WHERE if_id = '$if'");
+ while ($row = mysqli_fetch_array($sql)) {
+ if ((int)$row[id] > 0) {
+ sisplet_query("DELETE FROM srv_condition_vre WHERE cond_id='$row[id]'");
+ }
+ }
+ if ((int)$if > 0) {
+ sisplet_query("DELETE FROM srv_condition WHERE if_id = '$if'");
+ sisplet_query("DELETE FROM srv_if WHERE id = '$if'");
+ }
+ /*-- pobrisemo se za ifom*/
+
+ $deleteString = "DELETE FROM srv_condition_profiles WHERE id = '" . $pid . "' ";
+ $sqlDelete = sisplet_query($deleteString);
+ if (!$sqlDelete) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $pid = 1;
+ SurveyUserSetting :: getInstance()->saveSettings('default_condition_profile', $pid);
+
+ self::$currentProfileId = $pid;
+
+ }
+
+ static function renameProfile() {
+ global $lang;
+ $sqlInsert = -1;
+
+ $name = isset($_POST['name']) ? $_POST['name'] : 'Nov profil';
+ $pid = $_POST['pid'];
+
+ if ( $pid != null && $pid != "" && $pid > 1) {
+ if ( $name == null || $name == "" ) {
+ $name = $lang['srv_new_profile_ime'];
+ }
+
+ $updateString = "UPDATE srv_condition_profiles SET name = '" . $name . "' WHERE id = '" . $pid . "'";
+ $sqlInsert = sisplet_query($updateString);
+ }
+ return $sqlInsert;
+ }
+
+ static public function setHeader($_header) {
+ self::$_HEADER = $_header;
+ }
+
+ static function getAwkConditionString($if_id = null) {
+
+ $awkFilter = '';
+ if ($if_id != null)
+ {
+ $awkFilter = self :: generateAwkCondition($if_id);
+ }
+ else
+ if (self :: $currentProfileId > 1 && (int)self::$profiles[self :: $currentProfileId]['condition_error'] == 0)
+ {
+ $awkFilter = self :: $currentProfileId;
+ $stringSelect = "SELECT if_id from srv_condition_profiles where id = '".self :: $currentProfileId."'";
+ $querySelect = sisplet_query($stringSelect);
+ list($if_id) = mysqli_fetch_row($querySelect);
+ if ($if_id > 0) {
+ $awkFilter = self :: generateAwkCondition($if_id);
+ }
+ }
+ return $awkFilter;
+ }
+
+ /**
+ * @desc zgenerira pogoje za AWK branching
+ */
+ static function generateAwkCondition ($if) {
+ global $lang;
+
+ $echo = '';
+
+ $sql = Cache::srv_condition($if);
+
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i = 0;
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $_spr_id = $row['spr_id'];
+
+ if ($i++ != 0)
+ if ($row['conjunction'] == 0)
+ $echo .= '&&';
+ else
+ $echo .= '||';
+
+
+ for ($i=1; $i<=$row['left_bracket']; $i++)
+ $echo .= '(';
+
+ # imamo spremenljivke (ni kalkulacija ali modercnum)
+ if ($_spr_id > 0) {
+ $echo .= self::getAWKSpremenljivka($row);
+
+ // recnum
+ } elseif ($_spr_id == -1) {
+
+ $echo .= '('.MOD_REC_FIELD.' % '.$row['modul'].'=='.$row['ostanek'].')';
+
+ // naprava
+ } elseif ($_spr_id == -4) {
+
+ foreach (self::$_HEADER['meta']['grids'] as $vkey => $variables) {
+
+ if ($variables['variables'][0]['variable'] == 'Device') {
+
+ $sequence = $variables['variables'][0]['sequence'];
+ $echo .= '($'.$sequence.' == ';
+
+ $device = $lang['srv_para_graph_device'.$row['text']];
+
+ # ta tekstovne
+ if (IS_WINDOWS) {
+ # za windows
+ $echo .= "\\\"".$device."\\\"";
+ }
+ else {
+ # za linux
+ $echo .= '"'.$device.'"';
+ }
+
+ $echo .= ')';
+ }
+ }
+
+ // calculations - TODO
+ } elseif ($_spr_id == -2) {
+
+ /*$_calc = self :: generateCalculationAWK($row['id']);
+
+ $echo .= '(';
+ $echo .= $_calc;
+
+ # dodoamo operacijo
+ $echo .= self::echoOperator($row['negation'], $row['operator']);
+
+ $echo .= $row['text'];
+
+ $echo .= ')';*/
+ }
+
+ for ($i=1; $i<=$row['right_bracket']; $i++)
+ $echo .= ')';
+
+ }
+
+ // failsafe, ce se poklika if, pa se ne nastavi pogoja
+ if ($echo == '') {
+ $echo .= ' true ';
+ }
+ else {
+ $echo = '('.$echo.')';
+ }
+
+ return $echo;
+ }
+
+ private static function getAWKSpremenljivka($row) {
+ $_spr_id = $row['spr_id'];
+
+ $row2 = self :: select_from_srv_spremenljivka($_spr_id);
+
+ $_spr_tip = $row2['tip'];
+
+ $echo = '';
+ // radio, checkbox, dropdown in multigrid, in multi check
+ if ( $_spr_tip <= 3 || $_spr_tip == 6 || $_spr_tip == 16 || $_spr_tip == 17) {
+
+ #radio, drop, checkbox
+ if ($_spr_tip <= 3) {
+ $sql3 = sisplet_query("SELECT * FROM srv_condition_vre c, srv_vrednost v WHERE cond_id='$row[id]' AND c.vre_id=v.id");
+ if (!$sql3) echo mysqli_error($GLOBALS['connect_db']);
+
+ $j = 0;
+
+ # pogoje z več opcijami združenimi z OR dodamo v oklepaj zaradi pravilnosti
+ if (mysqli_num_rows($sql3) > 1) {
+ $echo .= '(';
+ }
+
+ while ($row3 = mysqli_fetch_assoc($sql3)) {
+ if ($j++ != 0) {
+ $echo .= '||';
+ }
+
+ if ($_spr_tip == 1 || $_spr_tip == 3|| $_spr_tip == 17) { # radio, dropdown
+ $seq = self ::getSequenceForAWKCondition(array('spr'=>$_spr_id));
+ } else if ($_spr_tip == 2) { # checkbox
+ $seq = self ::getSequenceForAWKCondition(array('spr'=>$_spr_id,'vre'=>$row3['vre_id']));
+ }
+
+ $echo .= '$'.$seq;
+
+ # dodoamo operacijo
+ $echo .= self::echoOperator($row['negation'], $row['operator']);
+
+ # dodamo vrednost ali 1 za checkbox
+ if ($_spr_tip == 1 || $_spr_tip == 3 || $_spr_tip == 17) {
+ $echo .= $row3['variable'];
+ } else if ($_spr_tip == 2) {
+ $echo .='1';
+ }
+ }
+
+ # pogoje z več opcijami združenimi z OR dodamo v oklepaj zaradi pravilnosti
+ if (mysqli_num_rows($sql3) > 1) {
+ $echo .= ')';
+ }
+
+
+ // multigrid tip = 6,16
+ } elseif ( $_spr_tip == 6 || $_spr_tip == 16 || $_spr_tip == 17) {
+
+ $sql3 = sisplet_query("SELECT * FROM srv_condition_grid c WHERE cond_id='$row[id]'");
+ if (!$sql3) echo mysqli_error($GLOBALS['connect_db']);
+
+ $sqlMgrid = sisplet_query("SELECT id FROM srv_vrednost WHERE id = '$row[vre_id]'");
+ if (!$sqlMgrid) echo mysqli_error($GLOBALS['connect_db']);
+ $rowMgrid = mysqli_fetch_assoc($sqlMgrid);
+
+ $j = 0;
+
+ # pogoje z več opcijami združenimi z OR dodamo v oklepaj zaradi pravilnosti
+ if (mysqli_num_rows($sql3) > 1) {
+ $echo .= '(';
+ }
+ # preverimo ali je dvojna tabela
+ $isDouble == false;
+ if ($row2['enota'] == 3 ) {
+ $isDouble=true;
+ }
+ while ($row3 = mysqli_fetch_assoc($sql3)) {
+ if ($j++ != 0) $echo .= '||';
+
+ if ($isDouble == false || 1) {
+ $seq = self ::getSequenceForAWKCondition(array('spr'=>$_spr_id, 'vre'=>$rowMgrid['id'], 'grd'=>$row3['grd_id'], 'isDouble' => $isDouble));
+ $echo .= '$'.$seq;
+
+ # dodoamo operacijo
+ $echo .= self::echoOperator($row['negation'], $row['operator']);
+
+ if ($row2['tip'] == 16) {
+ $echo .= '1';
+ } else {
+ if (!$isDouble) {
+ $echo .= $row3['grd_id'];
+ } else {
+ $str = "select variable from srv_grid where spr_id='$_spr_id' AND id= '$row3[grd_id]'";
+ $qry = sisplet_query($str);
+ list($variable) = mysqli_fetch_row($qry);
+ $echo .= $variable;
+ }
+
+ }
+ } else {
+ echo 'Error! (SurveyConditionProdiles)';
+ var_dump($_spr_id);
+ var_dump($rowMgrid['id']);
+ var_dump($row3['grd_id']);
+
+ }
+ }
+ # pogoje z več opcijami združenimi z OR dodamo v oklepaj zaradi pravilnosti
+ if (mysqli_num_rows($sql3) > 1) {
+ $echo .= ')';
+ }
+ }
+
+ // textbox, number in compute majo drugacne pogoje in opcije
+ }
+ elseif ($_spr_tip == 4 || $_spr_tip == 7 || $_spr_tip == 18 || $_spr_tip == 19 || $_spr_tip == 20 || $_spr_tip == 21 || $_spr_tip == 22 || $_spr_tip == 25)
+ {
+
+ if ($_spr_tip == 7 || $_spr_tip == 18 || $_spr_tip == 19 || $_spr_tip == 20 ) {
+ $grd = $row['grd_id'];
+ } else {
+ $grd = null;
+ }
+ if (isset($row['vre_id'])) {
+ $vre = $row['vre_id'];
+ } else {
+ $vre = null;
+ }
+
+ $seq = self ::getSequenceForAWKCondition(array('spr'=>$_spr_id, 'vre'=>$vre, 'grd'=> $grd));
+
+ $echo .= '$'.$seq;
+
+ # dodoamo operacijo
+ $echo .= self::echoOperator($row['negation'], $row['operator']);
+
+ # za numerične
+ if ($_spr_tip == 7 || $_spr_tip == 18)
+ {
+ $echo .= $row['text'];
+ }
+ else
+ {
+ # ta tekstovne
+ if (IS_WINDOWS) {
+ # za windows
+ $echo .= "\\\"".$row['text']."\\\"";
+ } else {
+ # za linux
+ $echo .= '"'.$row['text'].'"';
+ }
+ }
+ }
+ #DATUM
+ elseif ($_spr_tip == 8)
+ {
+ $grd = $row['grd_id'];
+ if (isset($row['vre_id'])) {
+ $vre = $row['vre_id'];
+ } else {
+ $vre = null;
+ }
+
+ $seq = self ::getSequenceForAWKCondition(array('spr'=>$_spr_id, 'vre'=>$vre, 'grd'=> $grd));
+
+ $echo .= 'substr($'.$seq.',7,4)substr($'.$seq.',4,2)substr($'.$seq.',1,2)';
+
+ # dodoamo operacijo
+ $echo .= self::echoOperator($row['negation'], $row['operator']);
+
+ $echo .= date("Ymd", strtotime($row['text']));;
+ #$echo .= $row['text'];
+ }
+ return $echo;
+ }
+
+ /** Vrne awk matematični operator glede na polje operator in negacijo
+ *
+ * @param (0,1) $negation
+ * @param (0,1) $operator
+ */
+ private static function echoOperator($negation = 0, $operator= 0) {
+ $echo = '==';
+ if ($negation == 0) {
+ if ($operator == 0)
+ $echo = '==';
+ elseif ($operator == 1)
+ $echo = '!=';
+ elseif ($operator == 2)
+ $echo = '<';
+ elseif ($operator == 3)
+ $echo = '<=';
+ elseif ($operator == 4)
+ $echo = '>';
+ elseif ($operator == 5)
+ $echo = '>=';
+ } else {
+ if ($operator == 0)
+ $echo = '!=';
+ elseif ($operator == 1)
+ $echo = '==';
+ elseif ($operator == 2)
+ $echo = '>';
+ elseif ($operator == 3)
+ $echo = '>=';
+ elseif ($operator == 4)
+ $echo = '<';
+ elseif ($operator == 5)
+ $echo = '<=';
+ }
+ return $echo;
+ }
+
+ private static $select_from_srv_spremenljivka = array();
+ /**
+ * pobere in zakesira podatke o spremenljivki (ker se to zlo velikokrat bere)
+ *
+ * @param mixed $spremenljivka
+ */
+ static function select_from_srv_spremenljivka ($spremenljivka) {
+
+ if (array_key_exists($spremenljivka, self::$select_from_srv_spremenljivka)) {
+ return self::$select_from_srv_spremenljivka[$spremenljivka];
+ }
+
+ // tole se splaca tam kjer se itak vse spremenljivke preberejo, sam vprasanje, ce se povsod??
+ $sql = sisplet_query("SELECT s.* FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='".self::$sid."'");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ self :: $select_from_srv_spremenljivka[$row['id']] = $row;
+ }
+
+ if (array_key_exists($spremenljivka, self :: $select_from_srv_spremenljivka)) {
+ return self :: $select_from_srv_spremenljivka[$spremenljivka];
+ }
+
+ $sql = sisplet_query("SELECT * FROM srv_spremenljivka WHERE id = '$spremenljivka'");
+
+ self::$select_from_srv_spremenljivka[$spremenljivka] = mysqli_fetch_assoc($sql);
+
+ return self::$select_from_srv_spremenljivka[$spremenljivka];
+
+ }
+
+ static function getSequenceForAWKCondition ($options = array()) {
+ $spr_id = (isset($options['spr']) && $options['spr'] != null) ? $options['spr'] : null;
+ $vre_id = (isset($options['vre']) && $options['vre'] != null) ? $options['vre'] : null;
+ $grd_id = (isset($options['grd']) && $options['grd'] != null) ? $options['grd'] : null;
+ $isDouble = (isset($options['isDouble']) && $options['isDouble'] != null) ? $options['isDouble'] : false;
+ $tip = self::$_HEADER[$spr_id.'_0']['tip'];
+ if ( $spr_id != null && count(self::$_HEADER[$spr_id.'_0']['grids']) > 0 ) {
+ switch ($tip) {
+ case 1 :
+ case 3 :
+ $grd = 0;
+ $var = 0;
+ break;
+ case 2:
+ case 21:
+ case 17:
+ case 18:
+ $grd = 0;
+ if ($vre_id > 0 && count(self::$_HEADER[$spr_id.'_0']['grids'][$grd]['variables']) > 0) {
+ foreach (self::$_HEADER[$spr_id.'_0']['grids'][$grd]['variables'] AS $vkey =>$variables) {
+ if ($variables['vr_id'] == $vre_id && $variables['other'] != 1) {
+ $var = $vkey;
+ }
+ }
+ } else {
+ $var = 0;
+ }
+ break;
+ case 7:
+ $grd = 0;
+ $var = $grd_id;
+ break;
+ case 8:
+ $grd = 0;
+ $var = $grd_id;
+ break;
+
+ case 6:
+ case 16:
+ case 19:
+ case 20:
+ if ($isDouble == true) {
+ #polovimo part
+ $str = "select part from srv_grid where spr_id='$spr_id' AND id= '$grd_id'";
+ $qry = sisplet_query($str);
+ list($part) = mysqli_fetch_row($qry);
+ } else {
+ $part = 1;
+ }
+
+ if (count(self::$_HEADER[$spr_id.'_0']['grids']) > 0) {
+
+ foreach (self::$_HEADER[$spr_id.'_0']['grids'] AS $gkey => $grids) {
+ if (count ($grids['variables']) > 0) {
+ foreach ($grids['variables'] AS $vkey => $variables) {
+ if (($tip == 6 && $variables['vr_id'] == $vre_id && $variables['other'] != 1 && $part == $grids['part'])
+ || (
+ ($tip == 16 || $tip == 19 || $tip == 20)
+ && $variables['vr_id'] == $vre_id && $grd_id == $variables['gr_id']) && $variables['other'] != 1) {
+ $grd = $gkey;
+ $var = $vkey;
+ }
+ }
+ }
+ }
+ }
+ break;
+ }
+
+ if ($grd !== null && $var !== null) {
+ return self::$_HEADER[$spr_id.'_0']['grids'][$grd]['variables'][$var]['sequence'];
+ }
+ }
+ return;
+
+ }
+
+# static function setConditionLabel($pid,$condition_label) {
+# if ((int)$pid > 0 ) {
+# $updateString = "UPDATE srv_condition_profiles SET condition_label = '" . $condition_label . "' WHERE id = '" . $pid . "'";
+# $sqlInsert = sisplet_query($updateString);
+# }
+# }
+
+ static function setConditionError($pid,$condition_error) {
+ if ((int)$pid > 0 ) {
+ $updateString = "UPDATE srv_condition_profiles SET condition_error = '" . $condition_error . "' WHERE id = '" . $pid . "'";
+ $sqlInsert = sisplet_query($updateString);
+ }
+ }
+
+ static function getConditionString($if_id = null)
+ {
+ global $lang;
+
+ # $condition_label = self::$profiles[self::$currentProfileId]['condition_label'];
+ ob_start();
+ $b = new Branching(self::$sid );
+
+ if ($if_id == null || (int)$if_id == 0)
+ {
+ $if_id = (int)self::$profiles[self :: $currentProfileId]['if_id'];
+ }
+ $b->display_if_label($if_id);
+ #$condition_label = mysqli_escape_string(ob_get_contents());
+ $condition_label = ob_get_contents();
+ ob_end_clean();
+
+ if ( $if_id > 0 && $condition_label != '') {
+
+ echo '<div id="conditionProfileNote">';
+ #if (self::$profiles[self :: $currentProfileId]['type'] == 'inspect') {
+ # echo '<span class="floatLeft">'.$lang['srv_profile_data_is_filtred_zoom'].'</span>';
+ #} else {
+ echo '<span class="floatLeft">'.$lang['srv_profile_data_is_filtred'].'</span>';
+ #}
+ echo '<span class="floatLeft spaceLeft clr_if"><b>('.self::$profiles[self :: $currentProfileId]['name'].')</b></span>';
+ echo '<span class="floatLeft spaceLeft">'.$condition_label.'</span>';
+ // ali imamo napake v ifu
+ if ((int)self::$profiles[$if_id]['condition_error'] != 0) {
+ echo '<br>';
+ echo '<span style="border:1px solid #009D91; background-color: #34D0B6; padding:5px; width:auto;"><img src="img_0/error.png" /> ';
+ echo '<span class="red strong">'.$lang['srv_profile_condition_has_error'].'</span>';
+ echo '</span>';
+ }
+ echo '<span class="as_link spaceLeft" id="link_condition_edit">'.$lang['srv_profile_edit'].'</span>';
+ echo '<span class="as_link spaceLeft" id="link_condition_remove">'.$lang['srv_profile_remove'].'</span>';
+ #if (self::$profiles[self :: $currentProfileId]['type'] == 'inspect') {
+ # echo '<span class="as_link spaceLeft" onclick="window.location=\'index.php?anketa='.self::$sid.'&a=data&m=quick_edit&quick_view=1\'">'.$lang['srv_zoom_link_whoisthis'].'</span>';
+ #}
+ echo '</div>';
+ echo '<br class="clr" />';
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @desc zgenerira kalkulacijo za vstavitev v AWK
+ */
+ # TODO!!!!
+ # kalkulacije so rešene samo za silo (delujejo samo za tip radio
+ function generateCalculationAWK ($condition) {
+ $result = '';
+ $sql = sisplet_query("SELECT * FROM srv_calculation WHERE cnd_id = '$condition' ORDER BY vrstni_red ASC");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i = 0;
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $_tmp_result = '';
+ $_valid = false;
+ $_spr_id = $row['spr_id'];
+
+ if ($i++ != 0) {
+ if ($row['operator'] == 0)
+ $_tmp_result .= '+';
+ elseif ($row['operator'] == 1)
+ $_tmp_result .= '-';
+ elseif ($row['operator'] == 2)
+ $_tmp_result .= '*';
+ elseif ($row['operator'] == 3)
+ $_tmp_result .= '/';
+ }
+ for ($j=1; $j<=$row['left_bracket']; $j++) {
+ $_tmp_result .= '(';
+ }
+
+ // obi�ajne spremenljivke
+ if ($_spr_id > 0) {
+
+ $_tmp_result .= self::getAWKSpremenljivka($row);
+
+ // konstante
+ } elseif ($row['spr_id'] == -1) {
+ $_tmp_result .= $row['number'];
+ $_valid = true;
+
+ }
+
+ for ($j=1; $j<=$row['right_bracket']; $j++) {
+ $_tmp_result .= ')';
+ }
+
+ if ($_valid === true) {
+ $result .= $_tmp_result;
+ }
+ }
+
+ return $result;
+ }
+
+ static function conditionRemove() {
+ # nastavimo privzet profil oziroma brez pogojev.
+ #Če pa je izbran profil bil slučajno inspect, ga v celoti odstranimo, da pobrišemo predhodne nastavitve zaradi gnezdenja
+ if (isset($_POST['pid']) && (int)$_POST['pid'] > 0) {
+ $currentProfileId = (int)$_POST['pid'];
+ } else {
+ $currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_condition_profile');
+ }
+
+ echo ($currentProfileId);
+
+ # preberemo podatke o profilu
+ $stringSelect = "SELECT * FROM srv_condition_profiles WHERE sid='" . self::$sid . "' AND uid='" . self::$uid . "' AND id = '".$currentProfileId."'";
+ $querySelect = sisplet_query($stringSelect);
+
+ # če je if_profil inspect, ga v celoti zbrišemo
+ if (mysqli_num_rows($querySelect)) {
+ $rowSelect = mysqli_fetch_assoc($querySelect);
+ # če je inspect
+ if ($rowSelect['type'] == 'inspect') {
+ $if_id = $rowSelect['if_id'];
+ if ((int)$if_id > 0) {
+ $delStr = "DELETE FROM srv_if WHERE if = '".(int)$if_id."'";
+ sisplet_query($delStr);
+ }
+ # zbrišemo še condition_profil
+ if ($currentProfileId > 0) {
+ $delStr = "DELETE FROM srv_condition_profiles WHERE sid='" . self::$sid . "' AND uid='" . self::$uid . "' AND id = '".$currentProfileId."'";
+ sisplet_query($delStr);
+ }
+ sisplet_query("COMMIT");
+ }
+
+ # če smo izbrali drug profil resetiramo še profil profilov na trenutne nastavitve
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', '0');
+
+ SurveyUserSetting :: getInstance()->removeSettings('default_condition_profile');
+
+ }
+ # drugače samo nastavimo na privzet profil = 1
+ $currentProfileId = 1;
+ SurveyUserSetting :: getInstance()->saveSettings('default_condition_profile', $currentProfileId);
+
+ self::$currentProfileId = $currentProfileId;
+
+ }
+
+
+ /** preveri obstoj profila in vrne enak id če obstaja, če ne vrne id privzetega profila
+ *
+ * @param unknown_type $pid
+ * @return unknown
+ */
+ function checkProfileExist($pid)
+ {
+ if (isset(self::$profiles[$pid]))
+ {
+ return true;
+ }
+ return false;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyConnect.php b/admin/survey/classes/class.SurveyConnect.php
new file mode 100644
index 0000000..e8fa818
--- /dev/null
+++ b/admin/survey/classes/class.SurveyConnect.php
@@ -0,0 +1,147 @@
+<?php
+
+/**
+* Class, ki se uporablja za povezovanje podatkov iz razlicnih anket
+* zaenkrat je opcija, da se povezuje podatke na podlagi identifikatorja (npr. emaila)
+*
+*/
+
+class SurveyConnect {
+
+ var $anketa; // trenutna anketa
+
+ var $db_table;
+
+ function __construct () {
+
+ // polovimo anketa ID
+ if (isset ($_GET['anketa']))
+ $this->anketa = $_GET['anketa'];
+ elseif (isset ($_POST['anketa']))
+ $this->anketa = $_POST['anketa'];
+ elseif ($anketa != 0)
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+ }
+
+ function ajax () {
+
+ if ( $_GET['a'] == 'display' ) {
+ $this->ajax_display();
+ }
+
+ }
+
+ function ajax_display () {
+ global $global_user_id;
+ global $site_url;
+ global $lang;
+
+ $usr_id = $_POST['usr_id'];
+
+ $dostop = array();
+ $sqld = sisplet_query("SELECT ank_id FROM srv_dostop WHERE uid = '$global_user_id' AND dostop LIKE '%data%' ORDER BY ank_id DESC");
+ while ($rowd = mysqli_fetch_assoc($sqld)) {
+ $dostop[] = $rowd['ank_id'];
+ }
+ unset($sqld, $rowd);
+
+ $anydata = false;
+
+ // izberemo vse sistemske spremenljivke
+ $sql = sisplet_query("SELECT s.id, s.tip, s.naslov, s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.tip IN (1,2,3,21) AND s.sistem='1' AND s.gru_id=g.id AND g.ank_id='$this->anketa' ORDER BY g.vrstni_red, s.vrstni_red");
+ while ($row = mysqli_fetch_assoc($sql)) {
+
+ $hasdata = false;
+
+ // besedilo
+ if ( $row['tip'] == 21 ) {
+
+ // poiscemo identifikator za trenutno spremenljivko (glede na userja)
+ $sql1 = sisplet_query("SELECT text FROM srv_data_text".$this->db_table." WHERE spr_id='$row[id]' AND usr_id='$usr_id'");
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+
+ $unikat = $row1['text'];
+
+ if ($unikat != '') {
+ $echo = '<p><b>('.$row['variable'].') '.strip_tags($row['naslov']).'</b><br>';
+ $echo .= '('.$unikat.')<br>';
+ $echo .= '';
+
+ foreach ($dostop AS $anketa) {
+
+ $subsql = sisplet_query("SELECT s.id, a.naslov FROM srv_spremenljivka s, srv_grupa g, srv_anketa a WHERE s.tip IN (21) AND s.sistem='1' AND s.variable='$row[variable]' AND s.gru_id=g.id AND g.ank_id='$anketa' AND g.ank_id=a.id AND g.ank_id != '$this->anketa' AND a.active>='0'");
+ if (!$subsql) echo mysqli_error($GLOBALS['connect_db']);
+ while ($subrow = mysqli_fetch_assoc($subsql)) {
+
+ $subsql1 = sisplet_query("SELECT t.* FROM srv_data_text".$this->db_table." t, srv_user u WHERE t.spr_id='$subrow[id]' AND t.text = '$unikat' AND u.id=t.usr_id AND u.deleted='0'");
+ while ($subrow1 = mysqli_fetch_assoc($subsql1)) {
+
+ $echo .= '<a href="'.$site_url.'admin/survey/index.php?anketa='.$anketa.'&a=data&m=quick_edit&usr_id='.$subrow1['usr_id'].'&quick_view=1">'.strip_tags($subrow['naslov']).'</a><br>';
+ $hasdata = true;
+ }
+ }
+ }
+
+ $echo .= '</p>';
+ }
+ }
+
+ // radio, checkbox, roleta
+ } elseif ( $row['tip'] == 1 || $row['tip'] == 2 || $row['tip'] == 3 ) {
+
+ // poiscemo identifikator za trenutno spremenljivko (glede na userja)
+ $sql1 = sisplet_query("SELECT v.variable FROM srv_data_vrednost".$this->db_table." d, srv_vrednost v WHERE d.spr_id='$row[id]' AND d.usr_id='$usr_id' AND d.vre_id=v.id");
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+
+ $unikat = $row1['variable'];
+
+ if ($unikat != '') {
+ $echo = '<p><b>('.$row['variable'].') '.strip_tags($row['naslov']).'</b><br>';
+ //$echo .= '('.$unikat.')<br>';
+ $echo .= '';
+
+ foreach ($dostop AS $anketa) {
+
+ $subsql = sisplet_query("SELECT s.id, a.naslov, a.db_table FROM srv_spremenljivka s, srv_grupa g, srv_anketa a WHERE s.tip IN (1, 2, 3) AND s.sistem='1' AND s.variable='$row[variable]' AND s.gru_id=g.id AND g.ank_id='$anketa' AND g.ank_id=a.id AND g.ank_id != '$this->anketa' AND a.active>='0'");
+ if (!$subsql) echo mysqli_error($GLOBALS['connect_db']);
+ while ($subrow = mysqli_fetch_assoc($subsql)) {
+
+ $db_table = ($subrow['db_table'] == 1) ? '_active' : '';
+
+ $subsql1 = sisplet_query("SELECT d.* FROM srv_data_vrednost".$db_table." d, srv_vrednost v, srv_user u WHERE d.spr_id='$subrow[id]' AND d.vre_id=v.id AND v.variable='$unikat' AND u.id=d.usr_id AND u.deleted='0'");
+ if (!$subsql1) echo mysqli_error($GLOBALS['connect_db']);
+ while ($subrow1 = mysqli_fetch_assoc($subsql1)) {
+ $echo .= '<a href="'.$site_url.'admin/survey/index.php?anketa='.$anketa.'&a=data&m=quick_edit&usr_id='.$subrow1['usr_id'].'&quick_view=1">'.strip_tags($subrow['naslov']).'</a><br>';
+ $hasdata = true;
+ }
+
+ }
+
+ }
+
+ $echo .= '</p>';
+ }
+ }
+
+ }
+
+ if ($hasdata) {
+ echo $echo;
+ $anydata = true;
+ }
+ }
+
+ if ( $anydata == false ) {
+ #echo '<tr><td class="left"></td><td class="right">'.$lang['srv_no_data'].'</td></tr>';
+ echo ''.$lang['srv_no_data'].'';
+ }
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyCopy.php b/admin/survey/classes/class.SurveyCopy.php
new file mode 100644
index 0000000..08f685a
--- /dev/null
+++ b/admin/survey/classes/class.SurveyCopy.php
@@ -0,0 +1,1373 @@
+<?php
+
+/* Za potrebe kopiranja ankete
+ *
+ * lahko v okviru istega strežnika ali pa iz strežnika na strežnik oz v datoteko
+ *
+ * Tabele ki se avtomatsko prilagajajo in kopirajo:
+ * - fixed, sedaj se vse prilagajajo
+ *
+ *
+ * Created on 23.02.2010
+ *
+ * UPDATES:
+ * 24.02.2001 - nov način kopiranja, večina tabel se avtomatsko prilagodi (razen pogojev)
+ * 23.11.2010 - spremenjeno, da se vse tabele klicejo preko preformCopyTable() - funkcijo sem tudi malo spremenil, je komentar -mitja
+ * 24.11.2010 - dela z bazo ver. 10.11.24 za naprej je treba dodajati samo nove tabele. obstojece tabele se vse cele kopirajo
+ * 04.04.2011 - spremenljen način kopiranja, da gre najprej vse v 1 array, potem pa se bere iz arraya (da omogocimo export - import v datoteko)
+ *
+ *
+ * TODO:
+ *
+ * preimenovat funckijo preform.. v perform... :)
+ *
+ */
+
+class SurveyCopy {
+
+ static private $inited = null; #je inicializiran, ali imamo vse podatke
+
+ static private $src_survey = null; #izvorna anketa
+ static private $src_connect_db = null; #db povezava na izvorna streznik
+ static private $dest_connect_db = null; #db povezava na streznik kamor kopiramo
+ static private $destSite = 0;
+ static private $errors = null; #array z napakami
+
+ static private $source_array = null;
+
+ public static function setSrcSurvey($srcSurvey){
+ self :: $src_survey = $srcSurvey;
+ }
+
+ public static function setSrcConectDb($src_connect_db){
+ self :: $src_connect_db = $src_connect_db;
+ }
+
+ public static function setDestSite($destSite = 0) {
+ $connect_db2 = null;
+
+ // mitja - kopiranje na localhost
+ if ($destSite == -1 && isset ($_GET['ip'])) {
+ self::$destSite = -1;
+
+ $ip = $_GET['ip'];
+ $connect_db2 = $GLOBALS['connect_db'] = mysqli_connect($ip, 'mitja', 'geslo');
+ $sql = mysqli_select_db($GLOBALS['connect_db'], "sisplet", $connect_db2);
+ if (!$sql) {
+ self :: $errors[] = mysqli_error($GLOBALS['connect_db']);
+ }
+ } elseif ($destSite == 0) { // backup
+ self::$destSite = 0;
+
+ if ( self :: $src_connect_db != null )
+ $connect_db2 = self :: $src_connect_db;
+ else {
+ self :: $errors[] = "Src connection is missing! ".mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } elseif ($destSite > 0) { // kopiranje na drug server
+ self::$destSite = $destSite;
+
+ // Predlagam da se tole da v locen config fajl!
+ // v /etc/hosts (windows: %SystemRoot%\System32\drivers\etc\hosts ) vpisi serverje (server1, server2,...)
+ // da se ne bo v kodi vleklo ime pravega serverja!!!
+ global $site_path;
+
+ $servers_array = array (
+ '1' => array('mirisorg', 'server1'),
+ '2' => array('www1kasi', 'server4'),
+ '3' => array('wwwrisorg', 'server1'),
+ '4' => array('wwwfdvinfonet', 'server1'),
+ '5' => array('wwwsafesi', 'server1'),
+ '6' => array('praksafdvinfonet', 'server1'),
+ '7' => array('skin1kasi', 'server2'),
+ '8' => array('back1kasi', 'server2'),
+ '9' => array('back14031kasi', 'server2'),
+ '10' => array('back30031kasi', 'server2'),
+ '11' => array('pizza1kasi', 'server3'),
+ '12' => array('fdv1kasi', 'server2'),
+ '13' => array('ef1kasi', 'server2'),
+ '14' => array('20101kasi', 'server2'),
+ '15' => array('new1kasi', 'server2'),
+ '16' => array('beta1kasi', 'server4'),
+ '17' => array('www1cssi', 'server4')
+ );
+
+ $server = $servers_array[$destSite][1];
+ $db = $servers_array[$destSite][0];
+
+ $connect_db2 = $GLOBALS['connect_db'] = mysqli_connect($server, 'survey_push', 'survey_push');
+ $sql = mysqli_select_db($GLOBALS['connect_db'],$db, $connect_db2);
+ if (!$sql) {
+ self :: $errors[] = '0'.mysqli_error($GLOBALS['connect_db']);
+ }
+ } else {
+ self :: $errors[] = "Invalid site ID";
+ }
+
+ if ($connect_db2 != null) {
+ # povezava do drugega streznikla dela
+ self :: $dest_connect_db = $connect_db2;
+
+ } else {
+ self :: $errors[] = "Could not connect to dest server";
+ }
+
+ }
+
+ static function getErrors() {
+ return self :: $errors;
+ }
+
+ /**
+ * shrani array ankete kot datoteko
+ *
+ */
+ static function saveArrayFile ( $data = false ) {
+
+ // pocistimo, ce se ze prej kaj izpisuje
+ ob_end_clean();
+
+ // preberemo array
+ $array = self::getArraySource( $data );
+
+ $array['srv_anketa'][0]['naslov'] = $array['srv_anketa'][0]['naslov'].' '.date("j.n.Y");
+
+ // zapisemo file na disk
+ $fp = fopen( dirname(__FILE__) . '/../SurveyBackup/'.$array['srv_anketa'][0]['id'].'-'.date("d.m.Y-H.i.s").'.1ka', 'w');
+ fwrite($fp, serialize($array));
+ fclose($fp);
+
+ }
+
+
+ /**
+ * restavrira anketo iz datoteke na strezniku
+ *
+ * @param mixed $filename
+ */
+ static function restoreArrayFile ( $filename ) {
+
+ $handle = fopen(dirname(__FILE__) . '/../SurveyBackup/'.$filename, "rb");
+ $contents = fread($handle, filesize(dirname(__FILE__) . '/../SurveyBackup/'.$filename));
+ fclose($handle);
+
+ $array = unserialize($contents);
+
+ self::setSourceArray($array);
+
+ return self::doCopy();
+ }
+
+ /**
+ * vrne array ankete kot datoteko
+ *
+ */
+ static function downloadArrayFile ( $data = false ) {
+
+ // Samo za ekstremne primere (zelo velike ankete) :)
+ //ini_set('memory_limit', '1000M');
+
+ // pocistimo, ce se ze prej kaj izpisuje
+ ob_end_clean();
+
+ // preberemo array
+ $array = self::getArraySource( $data );
+
+ // nastavimo attachment header
+ header('Content-Disposition: attachment; filename="'.$array['srv_anketa'][0]['naslov'].' '.date("j.n.Y").'.1ka"');
+
+ $array['srv_anketa'][0]['naslov'] = $array['srv_anketa'][0]['naslov'].' '.date("j.n.Y");
+
+ // izpisemo serializiran array
+ //echo serialize($array);
+ echo base64_encode(serialize($array));
+ }
+
+ /**
+ * vrne array ankete kot datoteko
+ *
+ */
+ static function downloadArrayVar ( $data = false ) {
+
+ // pocistimo, ce se ze prej kaj izpisuje
+ ob_end_clean();
+
+ // preberemo array
+ $array = self::getArraySource( $data );
+
+ $array['srv_anketa'][0]['naslov'] = $array['srv_anketa'][0]['naslov'].' '.date("j.n.Y");
+
+ // izpisemo serializiran array
+ return $array;
+
+ }
+
+ static function setSourceArray ($array) {
+ self::$source_array = $array;
+ }
+
+ /**
+ * vrne array z vsebino celotne ankete
+ *
+ */
+ public static function getArraySource ( $data = false ) {
+
+ $arr_src = array();
+
+ // subqueryji mysql cist ubijejo zato sem razbil v 2 locena queryja... v bistvu si zakesiramo seznam spremenljivk in ifov
+ // TODO ko se MySQL upgrada na 5.6 mogoce prestavit nazaj na navaden subquery, ali pa tut ne - bo za sprobat
+
+
+ $qry_src_survey = sisplet_query("SELECT * FROM srv_anketa WHERE id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $anketa_array = self::sql2array($qry_src_survey);
+
+ //Če imamo vklopljeno hierarhijo, potem vrednosti spremenljivk od hierarhije ne kopiramo
+ // V kolikor imamo vklopljeno hierarhijo potem ne kopiramo spremenljivke od hierarhije
+ $hierarhija_sql = null;
+ $hierarhija_not_in = null;
+
+ SurveyInfo::getInstance()->SurveyInit(self::$src_survey);
+ if(SurveyInfo::getInstance()->checkSurveyModule('hierarhija')) {
+ $hierarhija_sql = "AND s.variable!='vloga' AND s.variable NOT LIKE 'nivo%'";
+ $hierarhija_not_in = "AND element_spr NOT IN (SELECT s.id AS spr_id
+ FROM srv_spremenljivka s, srv_grupa g
+ WHERE
+ g.ank_id='" . self::$src_survey . "'
+ AND g.id=s.gru_id
+ AND (s.variable='vloga' OR s.variable LIKE 'nivo%'))";
+ }
+
+ // pripravimo si seznam spremenljivk in IF stavkov
+ $qry_cache_spr_id = self::prepareSubquery(sisplet_query("SELECT element_spr AS spr_id FROM srv_branching
+ WHERE ank_id='" . self::$src_survey . "' AND element_spr>0 ".$hierarhija_not_in."
+ UNION SELECT s.id AS spr_id FROM srv_spremenljivka s, srv_grupa g
+ WHERE g.ank_id='" . self::$src_survey . "' AND g.id=s.gru_id AND s.skupine='1' ".$hierarhija_sql."
+ UNION SELECT s.id AS spr_id FROM srv_spremenljivka s, srv_grupa g
+ WHERE g.ank_id='" . self::$src_survey . "' AND g.id=s.gru_id AND s.skupine='3'
+ UNION SELECT spr_id FROM srv_grid_multiple
+ WHERE ank_id='" . self::$src_survey . "'", self::$src_connect_db));
+
+ // pripravimo si seznam IFov, ker se pogosto rabijo
+ $qry_cache_if_id = self::prepareSubquery( sisplet_query("SELECT element_if FROM srv_branching
+ WHERE element_if>0 AND ank_id = '".self::$src_survey."'
+ UNION SELECT v.if_id AS element_if FROM srv_vrednost v, srv_spremenljivka s, srv_grupa g
+ WHERE v.if_id>0 AND v.spr_id=s.id AND s.gru_id=g.id AND g.ank_id='".self::$src_survey."'", self::$src_connect_db) );
+
+
+ $qry_src_version = sisplet_query("SELECT * FROM misc WHERE what = 'version'");
+ $row_src_version = mysqli_fetch_assoc($qry_src_version);
+ $arr_src['version'] = $row_src_version['value'];
+
+ $qry_src_survey = sisplet_query("SELECT * FROM srv_anketa WHERE id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_anketa'] = self::sql2array($qry_src_survey);
+
+ $qry_src_alert = sisplet_query("SELECT * FROM srv_alert WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_alert'] = self::sql2array($qry_src_alert);
+
+ $qry_src_call_setting = sisplet_query("SELECT * FROM srv_call_setting WHERE survey_id = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_call_setting'] = self::sql2array($qry_src_call_setting);
+
+ $qry_src_dostop = sisplet_query("SELECT * FROM srv_dostop WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_dostop'] = self::sql2array($qry_src_dostop);
+
+ $qry_src_dostop_language = sisplet_query("SELECT * FROM srv_dostop_language WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_dostop_language'] = self::sql2array($qry_src_dostop_language);
+
+ $qry_language = sisplet_query("SELECT * FROM srv_language WHERE ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_language'] = self::sql2array($qry_language);
+
+ $qry_src_grupa = sisplet_query("SELECT * FROM srv_grupa WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_grupa'] = self::sql2array($qry_src_grupa);
+
+ $qry_src_spremenljivke = sisplet_query("SELECT s.* FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id = g.id AND g.ank_id = '".self :: $src_survey."' ".$hierarhija_sql." UNION SELECT s.* FROM srv_spremenljivka s, srv_grid_multiple gm WHERE s.id=gm.spr_id AND gm.ank_id = '".self::$src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_spremenljivka'] = self::sql2array($qry_src_spremenljivke);
+
+ //$qry_src_vrednosti = sisplet_query("SELECT v.* FROM srv_vrednost v WHERE v.spr_id IN (SELECT element_spr FROM srv_branching WHERE ank_id='".self::$src_survey."' AND element_spr>0 UNION SELECT spr_id FROM srv_grid_multiple WHERE ank_id='".self::$src_survey."')", self :: $src_connect_db);
+ $qry_src_vrednosti = sisplet_query("SELECT v.* FROM srv_vrednost v WHERE v.spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_vrednost'] = self::sql2array($qry_src_vrednosti);
+
+ $qry_src_hotspot_regions = sisplet_query("SELECT hr.* FROM srv_hotspot_regions hr WHERE hr.spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_hotspot_regions'] = self::sql2array($qry_src_hotspot_regions);
+
+ $qry_src_vrednosti_map = sisplet_query("SELECT vm.* FROM srv_vrednost_map vm WHERE vm.spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_vrednost_map'] = self::sql2array($qry_src_vrednosti_map);
+
+ //$qry_src_grid = sisplet_query("SELECT gr.* FROM srv_grid gr WHERE gr.spr_id IN (SELECT element_spr FROM srv_branching WHERE ank_id='".self::$src_survey."' AND element_spr>0 UNION SELECT spr_id FROM srv_grid_multiple WHERE ank_id='".self::$src_survey."')", self :: $src_connect_db);
+ $qry_src_grid = sisplet_query("SELECT gr.* FROM srv_grid gr WHERE gr.spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_grid'] = self::sql2array($qry_src_grid);
+
+ $qry_src_grid_multiple = sisplet_query("SELECT * FROM srv_grid_multiple WHERE ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_grid_multiple'] = self::sql2array($qry_src_grid_multiple);
+
+ $qry_src_language_spremenljivka = sisplet_query("SELECT * FROM srv_language_spremenljivka WHERE ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_language_spremenljivka'] = self::sql2array($qry_src_language_spremenljivka);
+
+ $qry_src_language_vrednost = sisplet_query("SELECT * FROM srv_language_vrednost WHERE ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_language_vrednost'] = self::sql2array($qry_src_language_vrednost);
+
+ $qry_src_language_grid = sisplet_query("SELECT * FROM srv_language_grid WHERE ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_language_grid'] = self::sql2array($qry_src_language_grid);
+
+ $qry_missing_values = sisplet_query("SELECT * FROM srv_missing_values WHERE sid = '".self::$src_survey."'", self::$src_connect_db);
+ $arr_src['srv_missing_values'] = self::sql2array($qry_missing_values);
+
+ // v cnd_id je -spr_id OR cnd_id = srv_condition.id
+ $qry_calculation = sisplet_query("SELECT * FROM srv_calculation WHERE cnd_id IN ( SELECT (0 - s.id) AS id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id = g.id AND g.ank_id = '".self :: $src_survey."' ) OR cnd_id IN ( SELECT id FROM srv_condition WHERE if_id IN (".$qry_cache_if_id.") ) ", self::$src_connect_db);
+ $arr_src['srv_calculation'] = self::sql2array($qry_calculation);
+
+ $qry_src_misc = sisplet_query("SELECT * FROM srv_survey_misc WHERE sid = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_survey_misc'] = self::sql2array($qry_src_misc);
+
+ $qry_src_glasovanje = sisplet_query("SELECT * FROM srv_glasovanje WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_glasovanje'] = self::sql2array($qry_src_glasovanje);
+
+ $qry_src_if = sisplet_query("SELECT i.* FROM srv_if i, srv_branching b WHERE b.element_if=i.id AND b.element_if>0 AND b.ank_id='".self :: $src_survey."' UNION SELECT i.* FROM srv_if i, srv_vrednost v, srv_spremenljivka s, srv_grupa g WHERE i.id=v.if_id AND v.if_id>0 AND v.spr_id=s.id AND s.gru_id=g.id AND g.ank_id='".self::$src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_if'] = self::sql2array($qry_src_if);
+
+ //$qry_condition = sisplet_query("SELECT * FROM srv_condition WHERE if_id IN (SELECT element_if FROM srv_branching WHERE element_if>0 AND ank_id = '".self::$src_survey."' UNION SELECT v.if_id AS element_if FROM srv_vrednost v, srv_spremenljivka s, srv_grupa g WHERE v.if_id>0 AND v.spr_id=s.id AND s.gru_id=g.id AND g.ank_id='".self::$src_survey."')", self :: $src_connect_db);
+ $qry_condition = sisplet_query("SELECT * FROM srv_condition WHERE if_id IN (".$qry_cache_if_id.")", self :: $src_connect_db);
+ $arr_src['srv_condition'] = self::sql2array($qry_condition);
+
+ //$qry_src_condition_grid = sisplet_query("SELECT cg.* FROM srv_condition_grid cg, srv_condition c WHERE cg.cond_id = c.id AND c.if_id IN (SELECT element_if FROM srv_branching WHERE element_if>0 AND ank_id = '".self::$src_survey."' UNION SELECT v.if_id AS element_if FROM srv_vrednost v, srv_spremenljivka s, srv_grupa g WHERE v.if_id>0 AND v.spr_id=s.id AND s.gru_id=g.id AND g.ank_id='".self::$src_survey."')", self :: $src_connect_db);
+ $qry_src_condition_grid = sisplet_query("SELECT cg.* FROM srv_condition_grid cg, srv_condition c WHERE cg.cond_id = c.id AND c.if_id IN (".$qry_cache_if_id.")", self :: $src_connect_db);
+ $arr_src['srv_condition_grid'] = self::sql2array($qry_src_condition_grid);
+
+ //$qry_src_condition_vre = sisplet_query("SELECT cv.* FROM srv_condition_vre cv, srv_condition c WHERE cv.cond_id = c.id AND c.if_id IN (SELECT element_if FROM srv_branching WHERE element_if>0 AND ank_id = '".self::$src_survey."' UNION SELECT v.if_id AS element_if FROM srv_vrednost v, srv_spremenljivka s, srv_grupa g WHERE v.if_id>0 AND v.spr_id=s.id AND s.gru_id=g.id AND g.ank_id='".self::$src_survey."')", self :: $src_connect_db);
+ $qry_src_condition_vre = sisplet_query("SELECT cv.* FROM srv_condition_vre cv, srv_condition c WHERE cv.cond_id = c.id AND c.if_id IN (".$qry_cache_if_id.")", self :: $src_connect_db);
+ $arr_src['srv_condition_vre'] = self::sql2array($qry_src_condition_vre);
+
+ $qry_src_loop = sisplet_query("SELECT * FROM srv_loop WHERE if_id IN (".$qry_cache_if_id.")", self::$src_connect_db);
+ $arr_src['srv_loop'] = self::sql2array($qry_src_loop);
+
+ $qry_src_loop_vre = sisplet_query("SELECT * FROM srv_loop_vre WHERE if_id IN (".$qry_cache_if_id.")", self::$src_connect_db);
+ $arr_src['srv_loop_vre'] = self::sql2array($qry_src_loop_vre);
+
+ $qry_src_loop_data = sisplet_query("SELECT * FROM srv_loop_data WHERE if_id IN (".$qry_cache_if_id.")", self::$src_connect_db);
+ $arr_src['srv_loop_data'] = self::sql2array($qry_src_loop_data);
+
+ $qry_src_branching = sisplet_query("SELECT * FROM srv_branching WHERE ank_id = '".self :: $src_survey."' ".$hierarhija_not_in, self :: $src_connect_db);
+ $arr_src['srv_branching'] = self::sql2array($qry_src_branching);
+
+
+ // Vklopljeni moduli in njihove nastavitve
+ $qry_src_anketa_module = sisplet_query("SELECT * FROM srv_anketa_module WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_anketa_module'] = self::sql2array($qry_src_anketa_module);
+
+ $qry_src_chat_settings = sisplet_query("SELECT * FROM srv_chat_settings WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_chat_settings'] = self::sql2array($qry_src_chat_settings);
+
+ $qry_src_panel_settings = sisplet_query("SELECT * FROM srv_panel_settings WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_panel_settings'] = self::sql2array($qry_src_panel_settings);
+
+ $qry_src_quiz_settings = sisplet_query("SELECT * FROM srv_quiz_settings WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_quiz_settings'] = self::sql2array($qry_src_quiz_settings);
+
+ $qry_src_quiz_vrednost = sisplet_query("SELECT v.* FROM srv_quiz_vrednost v WHERE v.spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_quiz_vrednost'] = self::sql2array($qry_src_quiz_vrednost);
+
+ $qry_src_slideshow_settings = sisplet_query("SELECT * FROM srv_slideshow_settings WHERE ank_id = '".self :: $src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_slideshow_settings'] = self::sql2array($qry_src_slideshow_settings);
+
+
+ if ( $data ) {
+
+ // pripravimo si se seznam respondentov
+ $qry_cache_usr_id = self::prepareSubquery( sisplet_query("SELECT id FROM srv_user WHERE ank_id = '".self::$src_survey."'", self::$src_connect_db) );
+
+ $arr_src['data'] = true;
+
+ $qry_src_user = sisplet_query("SELECT * FROM srv_user WHERE ank_id = '".self::$src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_user'] = self::sql2array($qry_src_user);
+
+ $qry_src_data_checkgrid = sisplet_query("SELECT * FROM srv_data_checkgrid WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_checkgrid'] = self::sql2array($qry_src_data_checkgrid);
+
+ $qry_src_data_checkgrid_active = sisplet_query("SELECT * FROM srv_data_checkgrid_active WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_checkgrid_active'] = self::sql2array($qry_src_data_checkgrid_active);
+
+ $qry_src_data_glasovanje = sisplet_query("SELECT * FROM srv_data_glasovanje WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_glasovanje'] = self::sql2array($qry_src_data_glasovanje);
+
+ $qry_src_data_grid = sisplet_query("SELECT * FROM srv_data_grid WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_grid'] = self::sql2array($qry_src_data_grid);
+
+ $qry_src_data_grid_active = sisplet_query("SELECT * FROM srv_data_grid_active WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_grid_active'] = self::sql2array($qry_src_data_grid_active);
+
+ $qry_src_data_rating = sisplet_query("SELECT * FROM srv_data_rating WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_rating'] = self::sql2array($qry_src_data_rating);
+
+ $qry_src_data_text = sisplet_query("SELECT * FROM srv_data_text WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_text'] = self::sql2array($qry_src_data_text);
+
+ $qry_src_data_text_active = sisplet_query("SELECT * FROM srv_data_text_active WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_text_active'] = self::sql2array($qry_src_data_text_active);
+
+ $qry_src_data_textgrid = sisplet_query("SELECT * FROM srv_data_textgrid WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_textgrid'] = self::sql2array($qry_src_data_textgrid);
+
+ $qry_src_data_textgrid_active = sisplet_query("SELECT * FROM srv_data_textgrid_active WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_textgrid_active'] = self::sql2array($qry_src_data_textgrid_active);
+
+ $qry_src_data_upload = sisplet_query("SELECT * FROM srv_data_upload WHERE ank_id='".self::$src_survey."'", self :: $src_connect_db);
+ $arr_src['srv_data_upload'] = self::sql2array($qry_src_data_upload);
+
+ $qry_src_data_vrednost = sisplet_query("SELECT * FROM srv_data_vrednost WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_vrednost'] = self::sql2array($qry_src_data_vrednost);
+
+ $qry_src_data_vrednost_active = sisplet_query("SELECT * FROM srv_data_vrednost_active WHERE spr_id IN (".$qry_cache_spr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_vrednost_active'] = self::sql2array($qry_src_data_vrednost_active);
+
+ $qry_src_user_grupa = sisplet_query("SELECT * FROM srv_user_grupa WHERE usr_id IN (".$qry_cache_usr_id.")", self::$src_connect_db);
+ $arr_src['srv_user_grupa'] = self::sql2array($qry_src_user_grupa);
+
+ $qry_src_user_grupa_active = sisplet_query("SELECT * FROM srv_user_grupa_active WHERE usr_id IN (".$qry_cache_usr_id.")", self::$src_connect_db);
+ $arr_src['srv_user_grupa_active'] = self::sql2array($qry_src_user_grupa_active);
+
+ $qry_src_data_map = sisplet_query("SELECT * FROM srv_data_map WHERE spr_id IN (".$qry_cache_spr_id.") AND ank_id='".self::$src_survey."' AND usr_id IN (".$qry_cache_usr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_map'] = self::sql2array($qry_src_data_map);
+
+ $qry_src_data_heatmap = sisplet_query("SELECT * FROM srv_data_heatmap WHERE spr_id IN (".$qry_cache_spr_id.") AND ank_id='".self::$src_survey."' AND usr_id IN (".$qry_cache_usr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_heatmap'] = self::sql2array($qry_src_data_heatmap);
+
+ /*$qry_src_data_hotspot_regions = sisplet_query("SELECT * FROM srv_hotspot_regions WHERE spr_id IN (".$qry_cache_spr_id.") AND ank_id='".self::$src_survey."' AND usr_id IN (".$qry_cache_usr_id.")", self :: $src_connect_db);
+ $arr_src['srv_data_hotspot_regions'] = self::sql2array($qry_src_data_hotspot_regions); */
+
+ }
+
+ return $arr_src;
+ }
+
+ // Vrne implodan rezultat querija primeren za vstavit v subquery - to delamo ponavadi zarad performanca
+ static function prepareSubquery ($sql_resorce) {
+
+ if (!$sql_resorce) echo 'sub-q-error: '.mysqli_error($GLOBALS['connect_db']);
+
+ $src_prepare = array();
+ while ($row_src = mysqli_fetch_row($sql_resorce)) {
+ $src_prepare[] = $row_src[0];
+ }
+
+ if (count($src_prepare) == 0)
+ return 'null';
+
+ return implode(',', $src_prepare);
+ }
+
+ static function doCopy( $data = false ){
+ global $global_user_id;
+
+ if ( self::$source_array == null ) {
+ $arr_src = self::getArraySource( $data );
+ }
+ else {
+ $arr_src = self::$source_array;
+ }
+
+ if (!(self::$dest_connect_db != null)) {
+ self :: $errors[] = "Mandatory data missing!";
+ }
+ else {
+
+ // iz izvorne ankete preberemo vsa polja
+ if ( count($arr_src['srv_anketa']) > 0) {
+
+ // predefinirana polja (vsilimo vrednosti)
+ $pre_set = array('id' => "NULL",
+ 'backup' => "'0'",
+ 'active' => "'0'",
+ 'locked' => "'0'",
+ 'db_table' => "'1'",
+ 'insert_uid' => "'".$global_user_id."'",
+ 'insert_time' => "NOW()",
+ 'edit_uid' => "'".$global_user_id."'",
+ 'edit_time' => "NOW()",
+ 'folder' => "'1'",
+ 'forum' => "'0'",
+ 'thread' => "'0'");
+
+ # user_id ni enak če je anketa na drugem strežniku zato v tem primeru damo -1 da na drugem strežniku vemo da je to kopija od drugod
+ if (self::$destSite != 0) {
+ $pre_set['insert_uid'] = "'-1'";
+ $pre_set['edit_uid'] = "'-1'";
+ }
+
+ $new_survey_ids = self :: preformCopyTable('srv_anketa', 'id', $arr_src['srv_anketa'], $pre_set);
+
+ if ( isset($new_survey_ids[$arr_src['srv_anketa'][0]['id']]) && $new_survey_ids[$arr_src['srv_anketa'][0]['id']] != $arr_src['srv_anketa'][0]['id'] ) {
+ // novo anketo smo uspesno skreirali
+ $new_survey_id = $new_survey_ids[$arr_src['srv_anketa'][0]['id']];
+
+ // tabela srv_alert
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'finish_respondent_if' => "NULL",
+ 'finish_respondent_cms_if' => "NULL",
+ 'finish_other_if' => "NULL");
+ $new_alert_ids = self :: preformCopyTable('srv_alert', null, $arr_src['srv_alert'], $pre_set);
+
+ // tabela srv_call_setting
+ $pre_set = array('survey_id' => "'".$new_survey_id."'");
+ $new_call_setting_ids = self::preformCopyTable('srv_call_setting', null, $arr_src['srv_call_setting'], $pre_set);
+
+ // tabela srv_language
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ $new_language_ids = self::preformCopyTable('srv_language', null, $arr_src['srv_language'], $pre_set);
+
+
+ // tale zgornji if pogoj ne vem ce takole dela
+ if (self::$destSite == 0 && self::$src_survey > 0) { // to je smiselno samo na istem strezniku, kjer so user_id-ji enaki
+ // dostop userjev, tabela srv_dostop
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ $new_dostop_ids = self :: preformCopyTable('srv_dostop', null, $arr_src['srv_dostop'], $pre_set);
+
+ // dostop userjev do prevodov, tabela srv_dostop_language
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ $new_dostop_language_ids = self :: preformCopyTable('srv_dostop_language', null, $arr_src['srv_dostop_language'], $pre_set);
+
+ // kopiranje iz datoteke (vse user IDje nastavimo na ID userja, ki uploada)
+ } elseif ( self::$src_survey == -1 ) {
+
+ $new_users_ids = array();
+
+ foreach ($arr_src['srv_dostop'] AS $dostop) {
+ $new_users_ids[$dostop['uid']] = $global_user_id;
+ }
+ foreach ($arr_src['srv_dostop_language'] AS $dostop) {
+ $new_users_ids[$dostop['uid']] = $global_user_id;
+ }
+
+ // da damo dostop samo 1 userju
+ $tmp = $arr_src['srv_dostop'][0];
+ $arr_src['srv_dostop'] = null;
+ $arr_src['srv_dostop'][0] = $tmp;
+
+ if ( count($arr_src['srv_dostop_language']) > 0 ) {
+ $tmp = $arr_src['srv_dostop_language'][0];
+ $arr_src['srv_dostop_language'] = null;
+ $arr_src['srv_dostop_language'][0] = $tmp;
+ }
+
+ // dostop userjev, tabela srv_dostop
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'uid' => array('field'=>'uid', 'from'=>$new_users_ids));
+ $new_dostop_ids = self :: preformCopyTable('srv_dostop', null, $arr_src['srv_dostop'], $pre_set);
+
+ // dostop userjev do prevodov, tabela srv_dostop_language
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'uid' => array('field'=>'uid', 'from'=>$new_users_ids));
+ $new_dostop_language_ids = self :: preformCopyTable('srv_dostop_language', null, $arr_src['srv_dostop_language'], $pre_set);
+
+ // ce kopiramo na drug streznik, probamo najti iste uporabnike na drugem strezniku
+ } else {
+ $sql_dostop = sisplet_query("SELECT u.id, u.email FROM srv_dostop d, users u WHERE u.id=d.uid AND d.ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ $new_users_ids = array();
+ while ($row_dostop = mysqli_fetch_array($sql_dostop)) {
+ $sql_dostop_new = sisplet_query("SELECT id FROM users WHERE email='$row_dostop[email]'");
+
+ if (mysqli_num_rows($sql_dostop_new) > 0) {
+ $row_dostop_new = mysqli_fetch_array($sql_dostop_new);
+ $new_users_ids[$row_dostop['id']] = $row_dostop_new['id'];
+ }
+ }
+
+ $sql_dostop = sisplet_query("SELECT u.id, u.email FROM srv_dostop_language d, users u WHERE u.id=d.uid AND d.ank_id = '".self::$src_survey."'", self::$src_connect_db);
+ while ($row_dostop = mysqli_fetch_array($sql_dostop)) {
+ $sql_dostop_new = sisplet_query("SELECT id FROM users WHERE email='$row_dostop[email]'");
+
+ if (mysqli_num_rows($sql_dostop_new) > 0) {
+ $row_dostop_new = mysqli_fetch_array($sql_dostop_new);
+ $new_users_ids[$row_dostop['id']] = $row_dostop_new['id'];
+ }
+ }
+
+ // dostop userjev, tabela srv_dostop
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'uid' => array('field'=>'uid', 'from'=>$new_users_ids));
+ $new_dostop_ids = self :: preformCopyTable('srv_dostop', null, $arr_src['srv_dostop'], $pre_set);
+
+ // dostop userjev do prevodov, tabela srv_dostop_language
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'uid' => array('field'=>'uid', 'from'=>$new_users_ids));
+ $new_dostop_language_ids = self :: preformCopyTable('srv_dostop_language', null, $arr_src['srv_dostop_language'], $pre_set);
+ }
+
+
+ // grupe - strani, tabela srv_grupa
+ $pre_set = array('id' => "NULL",
+ 'ank_id' => "'".$new_survey_id."'");
+ $new_grupa_ids = self :: preformCopyTable('srv_grupa', 'id', $arr_src['srv_grupa'], $pre_set);
+
+ $new_grupa_ids[-1] = -1; // spremenljivke v knjiznici imajo -1 (ampak tega tukaj niti nebi smel bit...)
+ $new_grupa_ids[-2] = -2; // spremenljivke v multiple gridu imajo gru_id -2
+ $new_grupa_ids[0] = 0; // pri srv_user_grupa je 0 za prvo stran
+
+ $new_spremenljivke_ids = array();
+ if (count($new_grupa_ids) > 0) {
+ foreach ($new_grupa_ids as $old_grupa_id => $new_grupa_id) {
+
+ // spremenljivke, tabela srv_spremenljivka
+ $src_srv_spremenljivka = self::arrayfilter($arr_src['srv_spremenljivka'], 'gru_id', $old_grupa_id);
+
+ $pre_set = array('id' => "NULL",
+ 'gru_id' => "'".$new_grupa_id."'",
+ 'thread' => "'0'");
+ $tmp_spremenljivke_ids = self :: preformCopyTable('srv_spremenljivka', 'id', $src_srv_spremenljivka, $pre_set);
+
+ // shranimo stare in nove id-je spremenljivk
+ if ( is_countable($tmp_spremenljivke_ids) && count($tmp_spremenljivke_ids) > 0 )
+
+ foreach ($tmp_spremenljivke_ids as $key => $value)
+ $new_spremenljivke_ids[$key] = $value;
+ }
+ }
+
+
+ // gridi - srv_grid
+ $new_grid_ids = array();
+ if (count($new_spremenljivke_ids) > 0) {
+ foreach ($new_spremenljivke_ids AS $old_spremenljivka_id => $new_spremenljivka_id) {
+
+ // gridi, tabela srv_grid
+ $src_srv_grid = self::arrayfilter($arr_src['srv_grid'], 'spr_id', $old_spremenljivka_id);
+ $pre_set = array('spr_id' => "'".$new_spremenljivka_id."'");
+ $tmp_grid_ids = self :: preformCopyTable('srv_grid', 'variable', $src_srv_grid, $pre_set);
+
+ // shranimo stare in nove id-je spremenljivk
+ if ( count($tmp_grid_ids) > 0 )
+
+ foreach ($tmp_grid_ids as $key => $value)
+ $new_grid_ids[$new_spremenljivka_id][$key] = $value;
+
+ }
+ }
+
+ // srv_grid_multiple
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'parent' => array('field'=>'parent','from'=>$new_spremenljivke_ids), # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ 'spr_id' => array('field'=>'spr_id','from'=>$new_spremenljivke_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_grid_multiple_ids = self::preformCopyTable('srv_grid_multiple', null, $arr_src['srv_grid_multiple'], $pre_set);
+
+
+ // srv_language_spremenljivka
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'spr_id' => array('field'=>'spr_id','from'=>$new_spremenljivke_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_language_spremenljivka_ids = self::preformCopyTable('srv_language_spremenljivka', null, $arr_src['srv_language_spremenljivka'], $pre_set);
+
+ // srv_language_grid
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'spr_id' => array('field'=>'spr_id','from'=>$new_spremenljivke_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_language_grid_ids = self::preformCopyTable('srv_language_grid', null, $arr_src['srv_language_grid'], $pre_set);
+
+
+ // srv_missing_values
+ $pre_set = array('sid' => "'".$new_survey_id."'");
+ $new_missing_values_ids = self::preformCopyTable('srv_missing_values', null, $arr_src['srv_missing_values'], $pre_set);
+
+
+ // vrednosti - prestavljeno pod srv_if da se ne porusijo notranji pogoji! Patrik - zakaj je bilo to prestavljeno višje??
+ /*$new_vrednosti_ids = array();
+ if ( count($new_spremenljivke_ids) > 0) {
+ foreach( $new_spremenljivke_ids AS $old_spremenljivka_id => $new_spremenljivka_id) {
+
+ // vrednosti, tabela srv_vrednost
+ $src_srv_vrednost = self::arrayfilter($arr_src['srv_vrednost'], 'spr_id', $old_spremenljivka_id);
+ $pre_set = array('id' => "NULL",
+ 'spr_id' => array('field'=>'spr_id', 'from'=>$new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ $tmp_vrednosti_ids = self :: preformCopyTable('srv_vrednost', 'id', $src_srv_vrednost, $pre_set);
+
+ // shranimo stare in nove id-je spremenljivk
+ if ( count($tmp_vrednosti_ids) > 0 )
+
+ foreach ($tmp_vrednosti_ids as $key => $value){
+ $new_vrednosti_ids[$key] = $value;
+ }
+ }
+ }*/
+
+
+ // splosne nastavitve ankete, tabela srv_survey_misc
+ $pre_set = array('sid' => "'".$new_survey_id."'");
+ $new_misc_ids = self :: preformCopyTable('srv_survey_misc', null, $arr_src['srv_survey_misc'], $pre_set);
+
+
+ // glasovanje, tabela srv_glasovanje
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'spr_id' => array('field'=>'spr_id','from'=>$new_spremenljivke_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_glasovanje_ids = self :: preformCopyTable('srv_glasovanje', null, $arr_src['srv_glasovanje'], $pre_set);
+
+
+ // IF-im tabela srv_if
+ // Mora biti pred kopiranjem srv_vrednost, ker drugace wswe porusijo notranji pogoji!
+ $new_if_ids = array ();
+ $srv_if = $arr_src['srv_if'];
+
+ foreach ($srv_if AS $row) {
+ // IF-i, tabela srv_if
+ //$qry_src_if = sisplet_query("SELECT * FROM srv_if WHERE id = '".$row[id]."'", self :: $src_connect_db);
+ $qry_src_if = self::arrayfilter($arr_src['srv_if'], 'id', $row['id']);
+ $pre_set = array('id' => "NULL");
+ $tmp_if_ids = self :: preformCopyTable('srv_if', 'id', $qry_src_if, $pre_set);
+
+ $new_if_ids += $tmp_if_ids;
+ }
+
+ // vrednosti
+ $new_vrednosti_ids = array();
+ if ( count($new_spremenljivke_ids) > 0) {
+ foreach( $new_spremenljivke_ids AS $old_spremenljivka_id => $new_spremenljivka_id) {
+
+ // vrednosti, tabela srv_vrednost
+ $src_srv_vrednost = self::arrayfilter($arr_src['srv_vrednost'], 'spr_id', $old_spremenljivka_id);
+ $pre_set = array('id' => "NULL",
+ 'spr_id' => "'".$new_spremenljivka_id."'",
+ 'if_id' => array('field'=>'if_id', 'from'=>$new_if_ids));
+ $tmp_vrednosti_ids = self :: preformCopyTable('srv_vrednost', 'id', $src_srv_vrednost, $pre_set);
+
+ // shranimo stare in nove id-je spremenljivk
+ if ( count($tmp_vrednosti_ids) > 0 )
+
+ foreach ($tmp_vrednosti_ids as $key => $value)
+ $new_vrednosti_ids[$key] = $value;
+
+ }
+ }
+
+ // srv_calculation
+ // za vsak condition , če je spr_id > 0 priredimo novo, če ne damo enako (-1,-2)
+ if (count($new_spremenljivke_ids) > 0) {
+
+ foreach ($new_spremenljivke_ids AS $old_spremenljivka_id => $new_spremenljivka_id) {
+ $srv_calculation = self::arrayfilter($arr_src['srv_calculation'], 'cnd_id', -$old_spremenljivka_id);
+
+ foreach ($srv_calculation AS $row) {
+
+ $new_spr = $row['spr_id'] > 0
+ ? $new_spremenljivke_ids[$row['spr_id']] #naredimo preslikavo
+ : $row['spr_id']; # uporabimo staro vrednost
+ $new_vre = $row['vre_id'] > 0
+ ? $new_vrednosti_ids[$row['vre_id']]
+ : $row['vre_id'];
+
+ $src_srv_calculation = self::arrayfilter($arr_src['srv_calculation'], 'id', $row['id']);
+ $pre_set = array('id' => "NULL",
+ 'cnd_id' => -$new_spremenljivka_id,
+ 'spr_id' => $new_spr,
+ 'vre_id' => $new_vre);
+ $new_calculation_ids = self::preformCopyTable('srv_calculation', 'id', $src_srv_calculation, $pre_set);
+ }
+ }
+ }
+
+
+ // srv_hotspot_regions
+ $pre_set = array('id' => "NULL",
+ 'spr_id' => array('field'=>'spr_id', 'from'=>$new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ $hotspot_regions = self::preformCopyTable('srv_hotspot_regions', 'id', $arr_src['srv_hotspot_regions'], $pre_set);
+
+
+ // srv_vrednost_map
+ $pre_set = array('id' => "NULL",
+ 'spr_id' => array('field'=>'spr_id', 'from'=>$new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ self::preformCopyTable('srv_vrednost_map', 'id', $arr_src['srv_vrednost_map'], $pre_set);
+
+
+ // srv_language_vrednost
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'vre_id' => array('field'=>'vre_id','from'=>$new_vrednosti_ids)); # uporabimo dinamično preslikavo iz stare vre_id na novo vre_id za vsako vrstico
+ $new_language_vrednost_ids = self::preformCopyTable('srv_language_vrednost', null, $arr_src['srv_language_vrednost'], $pre_set);
+
+
+ // srv_condition
+ $pre_set = array('id' => "NULL",
+ 'if_id' => array('field'=>'if_id', 'from'=>$new_if_ids),
+ 'spr_id' => array('field'=>'spr_id', 'from'=>$new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ $condition = self::preformCopyTable('srv_condition', 'id', $arr_src['srv_condition'], $pre_set);
+
+
+ // condtition grid, tabela srv_condition_grid
+ if (count($condition) > 0) {
+ foreach ($condition AS $orig => $bckp) {
+ // condtition grid, tabela srv_condition_grid
+ //$qry_src_condition_grid = sisplet_query("SELECT * FROM srv_condition_grid WHERE cond_id = '".$orig."'", self :: $src_connect_db);
+ $src_srv_condition_grid = self::arrayfilter($arr_src['srv_condition_grid'], 'cond_id', $orig);
+ $pre_set = array('id'=>"NULL",
+ 'cond_id' => "'".$bckp."'");
+ $new_condition_grid_ids = self :: preformCopyTable('srv_condition_grid', 'id', $src_srv_condition_grid, $pre_set);
+
+ }
+ }
+
+ // condtition vrednost, tabela srv_condition_vre
+ if (count($condition) > 0) {
+ foreach ($condition AS $orig => $bckp) {
+ //$qry_src_condition_vre = sisplet_query("SELECT * FROM srv_condition_vre WHERE cond_id = '$orig'", self :: $src_connect_db);
+ $src_srv_condition_vre = self::arrayfilter($arr_src['srv_condition_vre'], 'cond_id', $orig);
+ $pre_set = array('cond_id' => $bckp,
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ self::preformCopyTable('srv_condition_vre', null, $src_srv_condition_vre, $pre_set);
+ }
+ }
+
+ // srv_loop
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'if_id' => array('field'=>'if_id','from'=>$new_if_ids), # uporabimo dinamično preslikavo iz stare if_id na novo if_id za vsako vrstico
+ 'spr_id' => array('field'=>'spr_id','from'=>$new_spremenljivke_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_loop_ids = self::preformCopyTable('srv_loop', null, $arr_src['srv_loop'], $pre_set);
+
+ // srv_loop_vre
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'if_id' => array('field'=>'if_id','from'=>$new_if_ids), # uporabimo dinamično preslikavo iz stare if_id na novo if_id za vsako vrstico
+ 'vre_id' => array('field'=>'vre_id','from'=>$new_vrednosti_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_loop_vre_ids = self::preformCopyTable('srv_loop_vre', null, $arr_src['srv_loop_vre'], $pre_set);
+
+ // srv_loop_data
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'id' => "NULL",
+ 'if_id' => array('field'=>'if_id','from'=>$new_if_ids), # uporabimo dinamično preslikavo iz stare if_id na novo if_id za vsako vrstico
+ 'vre_id' => array('field'=>'vre_id','from'=>$new_vrednosti_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ $new_loop_data_ids = self::preformCopyTable('srv_loop_data', 'id', $arr_src['srv_loop_data'], $pre_set);
+
+
+ // srv_branching
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'parent' => array('field'=>'parent', 'from' => $new_if_ids),
+ 'element_spr' => array('field'=>'element_spr', 'from' => $new_spremenljivke_ids),
+ 'element_if' => array('field' => 'element_if', 'from' => $new_if_ids));
+ self::preformCopyTable('srv_branching', null, $arr_src['srv_branching'], $pre_set);
+
+
+ // srv_calculation
+ // za vsak condition , če je spr_id > 0 priredimo novo, če ne damo enako (-1,-2)
+ if (count($condition) > 0) {
+ foreach ($condition AS $orig => $bckp) {
+ //$qry_src_calculation = sisplet_query("SELECT * FROM srv_calculation WHERE cnd_id = '$orig'", self :: $src_connect_db);
+ $src_srv_calculation = self::arrayfilter($arr_src['srv_calculation'], 'cnd_id', $orig);
+ $pre_set = array('id' => "NULL",
+ 'cnd_id' => $bckp,
+ 'spr_id' => array('field'=>'spr_id', 'from'=>$new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ self::preformCopyTable('srv_calculation', 'id', $src_srv_calculation, $pre_set);
+ }
+ }
+
+
+ // srv_anketa_module - skopiramo samo nekatere module
+ $copy_modules = array('social_network', 'quiz', 'uporabnost', 'slideshow', 'chat', 'panel');
+ foreach($copy_modules as $copy_module){
+ $src_srv_modules = self::arrayfilter($arr_src['srv_anketa_module'], 'modul', $copy_module);
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ self::preformCopyTable('srv_anketa_module', null, $src_srv_modules, $pre_set);
+ }
+
+ // srv_chat_settings
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ self::preformCopyTable('srv_chat_settings', null, $arr_src['srv_chat_settings'], $pre_set);
+
+ // srv_panel_settings
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ self::preformCopyTable('srv_panel_settings', null, $arr_src['srv_panel_settings'], $pre_set);
+
+ // srv_slideshow_settings
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ self::preformCopyTable('srv_slideshow_settings', null, $arr_src['srv_slideshow_settings'], $pre_set);
+
+ // srv_quiz_settings
+ $pre_set = array('ank_id' => "'".$new_survey_id."'");
+ self::preformCopyTable('srv_quiz_settings', null, $arr_src['srv_quiz_settings'], $pre_set);
+
+ // srv_quiz_vrednost
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from'=>$new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from'=>$new_vrednosti_ids));
+ self::preformCopyTable('srv_quiz_vrednost', null, $arr_src['srv_quiz_vrednost'], $pre_set);
+
+
+ /**
+ * PODATKI
+ */
+ if ( $arr_src['data'] ) {
+ $ip = GetIP();
+
+ // srv_user
+ $new_user_ids = array();
+ foreach ( $arr_src['srv_user'] AS $row_array ) {
+
+ do {
+ $rand = md5(mt_rand(1, mt_getrandmax()).'@'.$ip);
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE cookie = '$rand'");
+ } while (mysqli_num_rows($sql) > 0);
+
+ $pre_set = array('id' => "NULL",
+ 'cookie' => "'$rand'",
+ 'pass' => "'".substr($rand, 0, 6)."'",
+ 'ank_id' => "'".$new_survey_id."'");
+ $src_srv_user = self::arrayfilter($arr_src['srv_user'], 'id', $row_array['id']);
+ $tmp_user_ids = self::preformCopyTable('srv_user', 'id', $src_srv_user, $pre_set);
+ if ( count($tmp_user_ids) > 0 )
+ foreach ($tmp_user_ids as $key => $value)
+ $new_user_ids[$key] = $value;
+ }
+
+ // srv_data_checkgrid - VSE VEDNO KOPIRAMO V ACTIVE TABELE
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'grd_id' => array('field'=>'grd_id', 'from' => $new_grid_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_checkgrid_active', null, $arr_src['srv_data_checkgrid'], $pre_set);
+
+ // srv_data_checkgrid_active
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'grd_id' => array('field'=>'grd_id', 'from' => $new_grid_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_checkgrid_active', null, $arr_src['srv_data_checkgrid_active'], $pre_set);
+
+ // srv_data_glasovanje
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids));
+ self::preformCopyTable('srv_data_glasovanje', null, $arr_src['srv_data_glasovanje'], $pre_set);
+
+ // srv_data_grid - VSE VEDNO KOPIRAMO V ACTIVE TABELE
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'grd_id' => array('field'=>'grd_id', 'from' => $new_grid_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_grid_active', null, $arr_src['srv_data_grid'], $pre_set);
+
+ // srv_data_grid_active
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'grd_id' => array('field'=>'grd_id', 'from' => $new_grid_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_grid_active', null, $arr_src['srv_data_grid_active'], $pre_set);
+
+ // srv_data_rating
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_rating', null, $arr_src['srv_data_rating'], $pre_set);
+
+ // srv_data_text - VSE VEDNO KOPIRAMO V ACTIVE TABELE
+ $pre_set = array('id' => "NULL",
+ 'spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_text_active', 'id', $arr_src['srv_data_text'], $pre_set);
+
+ // srv_data_text_active
+ $pre_set = array('id' => "NULL",
+ 'spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_text_active', 'id', $arr_src['srv_data_text_active'], $pre_set);
+
+ // srv_data_textgrid - VSE VEDNO KOPIRAMO V ACTIVE TABELE
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'grd_id' => array('field'=>'grd_id', 'from' => $new_grid_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_textgrid_active', null, $arr_src['srv_data_textgrid'], $pre_set);
+
+ // srv_data_textgrid_active
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'grd_id' => array('field'=>'grd_id', 'from' => $new_grid_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_textgrid_active', null, $arr_src['srv_data_textgrid_active'], $pre_set);
+
+ // srv_data_upload
+ $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids));
+ self::preformCopyTable('srv_data_upload', null, $arr_src['srv_data_upload'], $pre_set);
+
+ // srv_data_vrednost - VSE VEDNO KOPIRAMO V ACTIVE TABELE
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_vrednost_active', null, $arr_src['srv_data_vrednost'], $pre_set);
+
+ // srv_data_vrednost_active
+ $pre_set = array('spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'vre_id' => array('field'=>'vre_id', 'from' => $new_vrednosti_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_vrednost_active', null, $arr_src['srv_data_vrednost_active'], $pre_set);
+
+ // srv_user_grupa - VSE VEDNO KOPIRAMO V ACTIVE TABELE
+ $pre_set = array('gru_id' => array('field'=>'gru_id', 'from' => $new_grupa_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids));
+ self::preformCopyTable('srv_user_grupa_active', null, $arr_src['srv_user_grupa'], $pre_set);
+
+ // srv_user_grupa_active
+ $pre_set = array('gru_id' => array('field'=>'gru_id', 'from' => $new_grupa_ids),
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids));
+ self::preformCopyTable('srv_user_grupa_active', null, $arr_src['srv_user_grupa_active'], $pre_set);
+
+ // srv_data_map
+ $pre_set = array('id' => "NULL",
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'ank_id' => "'".$new_survey_id."'",
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_map', 'id', $arr_src['srv_data_map'], $pre_set);
+
+ // srv_data_heatmap
+ $pre_set = array('id' => "NULL",
+ 'usr_id' => array('field'=>'usr_id', 'from' => $new_user_ids),
+ 'spr_id' => array('field'=>'spr_id', 'from' => $new_spremenljivke_ids),
+ 'ank_id' => "'".$new_survey_id."'",
+ 'loop_id' => array('field'=>'loop_id', 'from' => $new_loop_data_ids));
+ self::preformCopyTable('srv_data_heatmap', 'id', $arr_src['srv_data_heatmap'], $pre_set);
+
+ }
+ }
+ else {
+ self :: $errors[] = "Survey could not be copied! Please contact web admin. (Error code: 2)";
+ }
+ }
+ else {
+ self :: $errors[] = "Survey could not be copied! Source survey does not exist. Please contact web admin. (Error code: 1)";
+ }
+ }
+
+
+ return $new_survey_id;
+ }
+
+ // query SHOW COLUMS si kesiramo, ker se lahko izvaja zelo pogosto na istih tabelah (in se zlo pozna)
+ static $show_columns = array();
+
+ /** Prekopira samo polja ki so v dest tabeli pred tem popravi $pre_set polja
+ *
+ * @param $table_name
+ * @param $id_field (insert_id polje)
+ * @param $array_source - tole smo spremenili, da ne podamo sql querija, ampak array s podatki
+ * @param $pre_set
+
+ * @return array(oldId=>newId) Id-ji vpisanega zapisa
+ */
+ static function preformCopyTable($table_name, $id_field, $array_source, $pre_set) {
+
+ //if (!$array_source)
+ // self :: $errors[] = 'Qry src string error: ' . mysqli_error($GLOBALS['connect_db']);
+
+ $result = null;
+ if (isset(self::$show_columns[$table_name])) {
+ $dest_table_fields = self::$show_columns[$table_name];
+ mysqli_data_seek($dest_table_fields, 0);
+ } else {
+ self::$show_columns[$table_name] = sisplet_query("SHOW COLUMNS FROM ".$table_name, self::$dest_connect_db);
+ $dest_table_fields = self::$show_columns[$table_name];
+ }
+ if (!$dest_table_fields) {
+ self :: $errors[] = 'Could not run query: ' . mysqli_error($GLOBALS['connect_db']);
+ }
+
+ if ( count($array_source) > 0 ) {
+ // zloopamo skozi polja druge tabele in predpripravimo insert string polja
+ if (mysqli_num_rows($dest_table_fields) > 0) {
+
+ $insert_fields = '';
+ $insert_fields_prefix = '';
+ // vsebuje polja
+ while ($row_dest_table_fields = mysqli_fetch_assoc($dest_table_fields)) {
+ // polja dodamo v insert string
+ $dest_field = $row_dest_table_fields['Field'];
+ $insert_fields .= $insert_fields_prefix . $dest_field;
+ $insert_fields_prefix = ',';
+ }
+
+ // zloopamo skozi zapise izvorne tabele
+ // lahko updejtamo več zapisov, nove id-je damo v array, star_id=>nov_id
+ //while ( $row_src = mysqli_fetch_assoc($qry_src_string)) {
+ foreach ( $array_source AS $row_src ) {
+ // pripravimo prvi del insert stringa
+ $insert_string = 'INSERT INTO '.$table_name.' ('.$insert_fields.') VALUES (';
+ $insert_values = '';
+ $insert_values_prefix = '';
+ // zloopamo skozi polja druge tabele in dodamo vrednosti
+ mysqli_data_seek($dest_table_fields, 0);
+ while ($row_dest_table_fields = mysqli_fetch_assoc($dest_table_fields)) {
+ // ime polja v drugi tabeli
+ $dest_field = $row_dest_table_fields['Field'];
+
+ /* vrednosti se lahko dodeljujejo dinamično preko pre_set
+ * se pravi za preslikavo starege vrednosti "spr_id" na novo vrednost "spr_id"
+ * je kot pre_set polje potrebno navesti ime polja ('field') in array z preslikavami (stara_vrednost=>nova_vrednost)
+ *
+ * primer:
+ * $pre_set = array('ank_id' => "'".$new_survey_id."'",
+ * 'spr_id' => array('field'=>'spr_id','from'=>$new_spremenljivke_ids)); # uporabimo dinamično preslikavo iz stare spr_id na novo spr_id za vsako vrstico
+ */
+
+ // ce polje v src datoteki ni nastavljeno ga damo na praznega
+ if ( ! isset($row_src[$dest_field]) && ! isset($pre_set[$dest_field]) ) {
+ $dest_value = "''";
+
+ // ce je polje NULL, ga moramo rocno nastavit na NULL
+ } elseif ($row_src[$dest_field] === NULL) {
+ $dest_value = "NULL";
+
+ } else {
+
+ $dest_value = isset($pre_set[$dest_field])
+ ? ( !(is_array($pre_set[$dest_field]) && isset($pre_set[$dest_field]['field']) && isset($pre_set[$dest_field]['from']))
+ ? $pre_set[$dest_field]
+ : ( isset($pre_set[$dest_field]['from'][$row_src[$pre_set[$dest_field]['field']]]) # dodal sem se preverjenje, ce ID v tabeli preslikav obstaja - cene se uporabi original (kje se uporablja -1, -2...) -mitja
+ ? $pre_set[$dest_field]['from'][$row_src[$pre_set[$dest_field]['field']]] # je array in sta potrebni polji preberemo iz arraya "from" za source polja "field"
+ : "'".mysqli_real_escape_string($GLOBALS['connect_db'], $row_src[$dest_field])."'"
+ )
+ )
+ : "'".mysqli_real_escape_string($GLOBALS['connect_db'], $row_src[$dest_field])."'";
+
+ }
+
+ $insert_values .= $insert_values_prefix . $dest_value;
+ $insert_values_prefix = ',';
+
+ }
+ // dodamo zaklepaj
+ $insert_values .= ')';
+
+ $insert_string .= $insert_values;
+
+ $updated = sisplet_query($insert_string, self::$dest_connect_db);
+ if (!$updated) self::$errors[] = "Insert failed (".$table_name."): ".mysqli_error(self::$dest_connect_db).'('.$insert_string.')';
+ $insert_id = mysqli_insert_id(self::$dest_connect_db);
+
+ if ($insert_id > 0) {
+
+ if (isset($row_src[$id_field])) {
+ // poiscemo source id
+ $result[$row_src[$id_field]] = $insert_id;
+ } else {
+ $result[] = $insert_id;
+ }
+ } else {
+ // lahko da je sql ne vrne id-ja (kadar ni primary key-a)
+ $result[$row_src[$id_field]] = $row_src[$id_field];
+ }
+ }
+
+ } else {
+ self :: $errors[] = "Dest fields missing for table:".$table_name;
+ }
+ } else {
+ // nothing to copy
+ }
+ return $result;
+ }
+
+ /**
+ * @desc Naredi kopijo respondenta v podatkih
+ */
+ public static function copyRespondent($usr_id){
+ global $global_user_id;
+
+ // Dobimo podatke o respondentu ki ga kopiramo
+ $sqlU = sisplet_query("SELECT preview, testdata, last_status, lurker, unsubscribed, language FROM srv_user WHERE ank_id='".self::$src_survey."' AND id='".$usr_id."'");
+ $rowU = mysqli_fetch_array($sqlU);
+
+ // Nastavimo nov cookie - izberemo random hash, ki se ni v bazi
+ do {
+ $rand = md5(mt_rand(1, mt_getrandmax()) . '@' . $global_user_id);
+
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE cookie = '$rand'");
+
+ } while (mysqli_num_rows($sql) > 0);
+
+ // Kopiramo respondenta
+ $sql = sisplet_query("INSERT INTO srv_user
+ (
+ ank_id,
+ preview,
+ testdata,
+ cookie,
+ time_insert,
+ time_edit,
+ recnum,
+ last_status,
+ lurker,
+ unsubscribed,
+ language
+ )
+ VALUES (
+ '".self::$src_survey."',
+ '".$rowU['preview']."',
+ '".$rowU['testdata']."',
+ '".$rand."',
+ NOW(),
+ NOW(),
+ MAX_RECNUM('".self::$src_survey."'),
+ '".$rowU['last_status']."',
+ '".$rowU['lurker']."',
+ '".$rowU['unsubscribed']."',
+ '".$rowU['language']."'
+ )
+ ");
+ $new_usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+
+ // Kopiramo odgovore
+ // srv_data_vrednost
+ $sqlD = sisplet_query("SELECT * FROM srv_data_vrednost WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_vrednost', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_vrednost_active
+ $sqlD = sisplet_query("SELECT * FROM srv_data_vrednost_active WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_vrednost_active', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_text
+ $sqlD = sisplet_query("SELECT * FROM srv_data_text WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'id' => "NULL",
+ 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_text', 'id', self::sql2array($sqlD), $pre_set);
+
+ // srv_data_text_active
+ $sqlD = sisplet_query("SELECT * FROM srv_data_text_active WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'id' => "NULL",
+ 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_text_active', 'id', self::sql2array($sqlD), $pre_set);
+
+ // srv_data_checkgrid
+ $sqlD = sisplet_query("SELECT * FROM srv_data_checkgrid WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_checkgrid', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_checkgrid_active
+ $sqlD = sisplet_query("SELECT * FROM srv_data_checkgrid_active WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_checkgrid_active', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_grid
+ $sqlD = sisplet_query("SELECT * FROM srv_data_grid WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_grid', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_grid_active
+ $sqlD = sisplet_query("SELECT * FROM srv_data_grid_active WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_grid_active', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_textgrid
+ $sqlD = sisplet_query("SELECT * FROM srv_data_textgrid WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_textgrid', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_textgrid_active
+ $sqlD = sisplet_query("SELECT * FROM srv_data_textgrid_active WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_textgrid_active', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_rating
+ $sqlD = sisplet_query("SELECT * FROM srv_data_rating WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_rating', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_upload
+ $sqlD = sisplet_query("SELECT * FROM srv_data_upload WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id);
+ self::preformCopyTable('srv_data_upload', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_glasovanje
+ $sqlD = sisplet_query("SELECT * FROM srv_data_glasovanje WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id);
+ self::preformCopyTable('srv_data_glasovanje', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_user_grupa
+ $sqlD = sisplet_query("SELECT * FROM srv_user_grupa WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'time_edit' => "NOW()");
+ self::preformCopyTable('srv_user_grupa', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_user_grupa_active
+ $sqlD = sisplet_query("SELECT * FROM srv_user_grupa_active WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'time_edit' => "NOW()");
+ self::preformCopyTable('srv_user_grupa_active', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_map
+ $sqlD = sisplet_query("SELECT * FROM srv_data_map WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_map', null, self::sql2array($sqlD), $pre_set);
+
+ // srv_data_heatmap
+ $sqlD = sisplet_query("SELECT * FROM srv_data_heatmap WHERE usr_id='".$usr_id."'");
+ $pre_set = array( 'usr_id' => $new_usr_id,
+ 'loop_id' => "NULL");
+ self::preformCopyTable('srv_data_heatmap', null, self::sql2array($sqlD), $pre_set);
+
+ return $new_usr_id;
+ }
+
+
+ /**
+ * sql result vrne kot multi array
+ *
+ * @param mixed $sql
+ */
+ static function sql2array($sql) {
+
+ $array = array();
+
+ while ($row = mysqli_fetch_assoc($sql)) {
+
+ $array[] = $row;
+
+ }
+
+ return $array;
+ }
+
+ /**
+ * pofilitira array in vrne samo vrstice, ki ustrezajo field == value
+ *
+ * @param mixed $array
+ * @param mixed $field
+ * @param mixed $value
+ */
+ static function arrayfilter ($array, $field, $value) {
+
+ $arr = array();
+
+ foreach ($array AS $row) {
+
+ if ($row[$field] == $value){
+ $arr[] = $row;
+ }
+ }
+
+ return $arr;
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyCustomReport.php b/admin/survey/classes/class.SurveyCustomReport.php
new file mode 100644
index 0000000..c0d9acf
--- /dev/null
+++ b/admin/survey/classes/class.SurveyCustomReport.php
@@ -0,0 +1,2618 @@
+<?php
+/**
+* @author Peter Hrvatin
+* @date May 2012
+*
+*/
+
+
+class SurveyCustomReport {
+
+ private $ank_id; // id ankete
+
+ private $classInstance; // Instanca razreda za izris tabele (crosstab, mean, ttest)
+
+ public $returnAsHtml = false; // ali vrne rezultat analiz kot html ali ga izpiše
+ public $isArchive = false; // nastavimo na true če smo v arhivu
+ public $publicCReport = false; // ali smo preko public povezave
+
+ public $creportProfile = 0; // trenutno izbrani profil porocila
+ public $creportAuthor = 0; // trenutno izbrani avtor porocila ki se ga ureja
+
+ public $expanded = 0; // skrcen(0) ali razsirjen(1) nacin
+
+ function __construct($anketa) {
+ global $global_user_id, $site_path, $lang;
+
+ if ((int)$anketa > 0) {
+ $this->ank_id = $anketa;
+
+ // polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->ank_id);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+
+ // Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->ank_id);
+ SurveyUserSetting::getInstance()->Init($this->ank_id, $global_user_id);
+
+ SurveyStatusProfiles::Init($this->ank_id);
+ SurveyMissingProfiles :: Init($this->ank_id,$global_user_id);
+ SurveyConditionProfiles :: Init($this->ank_id, $global_user_id);
+ SurveyZankaProfiles :: Init($this->ank_id, $global_user_id);
+ SurveyTimeProfiles :: Init($this->ank_id, $global_user_id);
+
+ SurveyDataSettingProfiles :: Init($this->ank_id);
+
+ #inicializiramo class za datoteke
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($anketa);
+ $this->headFileName = $SDF->getHeaderFileName();
+ $this->dataFileName = $SDF->getDataFileName();
+ $this->dataFileStatus = $SDF->getStatus();
+
+
+ SurveyAnalysis::Init($this->ank_id);
+
+ //polovimo podatke o nastavitvah trenutnega profila (missingi..)
+ SurveyAnalysis::$missingProfileData = SurveyMissingProfiles::getProfile(SurveyAnalysis::$currentMissingProfile);
+ #preberemo HEADERS iz datoteke
+ SurveyAnalysis::$_HEADERS = unserialize(file_get_contents($this->headFileName));
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ SurveyAnalysis::removeSystemVariables();
+ # polovimo frekvence
+ SurveyAnalysis::getFrequencys();
+
+ $this->creportProfile = SurveyUserSetting :: getInstance()->getSettings('default_creport_profile');
+ $this->creportProfile = isset($this->creportProfile) && $this->creportProfile != '' ? $this->creportProfile : 0;
+
+ $this->creportAuthor = SurveyUserSetting :: getInstance()->getSettings('default_creport_author');
+ $this->creportAuthor = isset($this->creportAuthor) && $this->creportAuthor != '' ? $this->creportAuthor : $global_user_id;
+
+ $this->expanded = (isset($_GET['expanded'])) ? $_GET['expanded'] : 0;
+ }
+ else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+
+ // Izrisemo izdelano porocilo
+ function displayReport(){
+ global $lang;
+ global $global_user_id;
+
+ # zakeširamo vsebino, in jo nato po potrebi zapišpemo v html
+ if ($this->returnAsHtml != false) {
+ ob_start();
+ }
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+
+ echo '<input type="hidden" value="'.$this->expanded.'" id="creport_expanded" />';
+
+ $this->displayProfilePopups();
+
+ // Prva vrstica - seznam poročil
+ echo '<div>';
+ echo '<span class="pointer blue bold" style="font-size:14px;" onClick="showCReportProfiles();">'.$lang['srv_custom_report_list'].'</span>';
+ echo ' <span id="creport_profile_setting_plus" class="pointer faicon add icon-as_link spaceLeft" title="'.$lang['srv_custom_report_create'].'" style="padding-bottom:1px;"></span>';
+ echo '</div>';
+
+ // Naslov
+ echo '<h2 style="display:inline-block; color:#333;">';
+
+ // Profil
+ if($this->creportProfile == 0){
+
+ $what = 'creport_default_profile_name';
+ $sql = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$this->creportAuthor' AND what='$what'");
+
+ if(mysqli_num_rows($sql) == 0){
+ $name = $lang['srv_custom_report_default'];
+ }
+ else{
+ $row = mysqli_fetch_array($sql);
+ $name = $row['value'];
+ }
+ }
+ else{
+ $profile = $this->getProfile($this->creportProfile);
+ $name = $profile['name'];
+ }
+ echo '<span style="font-weight: normal;">';
+ echo $lang['srv_custom_report_profile'].': <span class="bold pointer blue" onClick="showCReportProfiles();">"'.$name.'"</span>';
+ echo '</span>';
+
+ echo '</h2>';
+
+ // Edit in add porocilo
+ echo '<div style="display:inline-block; line-height:10px;">';
+ echo ' <span id="creport_profile_setting_edit" class="faicon edit icon-as_link spaceLeft" style="margin-bottom:1px;" title="'.$lang['srv_custom_report_edit'].'"></span>';
+
+ // Osnova porocila (prazna, vsi grafi, vse frekvence...) - prikazemo samo ce je porocilo prazno
+ if($this->checkEmpty($this->ank_id)){
+ echo '<span style="font-size:14px; font-weight: normal; margin-left: 20px;">';
+ echo $lang['srv_custom_report_base'].': ';
+
+ echo '<select name="custom_report_base" id="custom_report_base" onChange="addCustomReportAllElementsAlert(this.value);">';
+ echo ' <option value="0">'.$lang['srv_custom_report_base_0'].'</option>';
+ echo ' <option value="1">'.$lang['srv_sumarnik'].'</option>';
+ echo ' <option value="2">'.$lang['srv_frequency'].'</option>';
+ echo ' <option value="3">'.$lang['srv_descriptor'].'</option>';
+ echo ' <option value="4">'.$lang['srv_analiza_charts'].'</option>';
+ echo '</select>';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ // Stevilo vseh porocil
+ $sqlC = sisplet_query("SELECT id FROM srv_custom_report_profiles WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+ $report_count = mysqli_num_rows($sqlC);
+ if($report_count > 0)
+ echo '<div style="margin:-12px 0 20px 0; color:#555555; font-size:10px;">'.$lang['srv_custom_report_count'].': '.($report_count + 1).'</div>';
+
+
+ // Preklop na skrcen/razsirjen pogled in predogled
+ if ($this->isArchive == false && $this->publicCReport == false) {
+
+ echo '<div id="custom_report_view">';
+
+ if($this->expanded == 0)
+ echo '<a href="index.php?anketa='.$this->ank_id.'&a=analysis&m=analysis_creport&expanded=1"><span class="faicon compress"></span> '.$lang['srv_custom_report_expanded_0'].'</a>';
+ else
+ echo '<a href="index.php?anketa='.$this->ank_id.'&a=analysis&m=analysis_creport&expanded=0"><span class="faicon expand"></span> '.$lang['srv_custom_report_expanded_1'].'</a>';
+
+ // Preview
+ echo ' &nbsp;<a title="'.$lang['srv_custom_report_preview'].'" onClick="showCReportPreview(); return false;" href="#"><span class="faicon preview pointer"></span> '.$lang['srv_custom_report_preview_short'].'</a>';
+
+ echo '</div>';
+ }
+
+ }
+
+ echo '<div id="custom_report_elements">';
+
+
+
+ // ce arhiviramo imamo razsirjene elemente
+ $this->expanded = ($this->isArchive == false && $this->publicCReport == false) ? $this->expanded : 1;
+
+ // Naslov porocila
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ $this->displayTitle();
+ }
+
+ $sql = sisplet_query("SELECT * FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile' ORDER BY vrstni_red ASC");
+ $counter = mysqli_num_rows($sql);
+ if($counter > 0){
+
+ echo '<ul id="custom_report_sortable">';
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ echo '<div class="report_element_separator '.($this->expanded == 1 ? 'expanded' : '').'">';
+ echo '<div class="add_element">';
+ $this->addNewElement(-1);
+ echo '</div>';
+ echo '</div>';
+ }
+
+ // Loop po vseh dodanih elementih porocila
+ while($row = mysqli_fetch_array($sql)){
+ echo '<li id="sortable_report_element_'.$row['id'].'">';
+
+ // Pagebreak
+ if($row['type'] == '-1'){
+ if ($this->isArchive == false && $this->publicCReport == false){
+ $this->displayBreak($row);
+ }
+ }
+ else{
+ echo '<div class="report_element '.($this->expanded == 1 && $this->isArchive == false && $this->publicCReport == false ? ' active':'').'" id="report_element_'.$row['id'].'">';
+ $this->displayReportElement($row['id'], $this->expanded);
+ echo '</div>';
+ }
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ echo '<div class="report_element_separator '.($this->expanded == 1 ? 'expanded' : '').'" id="report_element_separator_'.$row['id'].'">';
+ if($row['vrstni_red'] < $counter){
+ echo '<div class="add_element">';
+ $this->addNewElement($row['id']);
+ echo '</div>';
+ }
+ echo '</div>';
+ }
+
+ echo '</li>';
+ }
+
+ echo '</ul>';
+ }
+ else
+ echo '<br /><br />';
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ // Dodajanje novega porocila
+ echo '<br />';
+ echo '<div class="add_element">';
+ $this->addNewElement();
+ echo '</div>';
+ }
+
+ echo '</div>';
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ // izpisi na dnu
+ $this->displayBottomSettings();
+ }
+
+
+ if ($this->returnAsHtml != false) {
+ $result = ob_get_clean();
+ ob_flush(); flush();
+ return $result;
+ }
+ }
+
+ // Izrisemo posamezen element porocila
+ function displayReportElement($element_id, $expanded){
+ global $lang;
+
+ $sql = sisplet_query("SELECT * FROM srv_custom_report WHERE id='$element_id' AND ank_id='$this->ank_id' AND profile='$this->creportProfile'");
+ $reportElement = mysqli_fetch_array($sql);
+
+ switch($reportElement['type']){
+
+ case '0':
+ $this->displayReportElementHead($reportElement, $expanded, $lang['srv_custom_report_select_type']);
+ $this->displayReportElementSettings($reportElement, $expanded);
+ break;
+
+ case '1':
+ $this->displaySum($reportElement, $expanded);
+ break;
+ case '2':
+ $this->displayFreq($reportElement, $expanded);
+ break;
+ case '3':
+ $this->displayDesc($reportElement, $expanded);
+ break;
+ case '4':
+ $this->displayChart($reportElement, $expanded);
+ break;
+ case '5':
+ $this->displayCrosstab($reportElement, $expanded);
+ break;
+ case '6':
+ $this->displayMean($reportElement, $expanded);
+ break;
+ case '7':
+ $this->displayTTest($reportElement, $expanded);
+ break;
+ case '9':
+ $this->displayRazbitje($reportElement, $expanded);
+ break;
+ case '10':
+ $this->displayMulticrosstab($reportElement, $expanded);
+ break;
+
+ case '8':
+ $this->displayText($reportElement, $expanded);
+ break;
+
+ default:
+ break;
+ }
+
+ // Komentar pod elementom
+ if($reportElement['type'] != 8)
+ $this->displayReportElementText($reportElement, $expanded);
+ }
+
+ // Izpis nastavitev posameznega elementa (tip izpisa, izbira spremenljivk...)
+ function displayReportElementSettings($reportElement, $expanded){
+ global $lang;
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ echo '<div class="report_element_settings" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ // Tip izpisa (sums, freq, opisne...)
+ echo '<select name="report_element_type_'.$reportElement['id'].'" id="report_element_type_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'type\', this.value)">';
+
+ // Ce ni izbrana
+ if ( $reportElement['type'] == null || $reportElement['type'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_custom_report_select_type'] . '</option>';
+ }
+ echo '<option value="1" '.($reportElement['type'] == 1 ? 'selected="selected"' : '').'>'.$lang['srv_sumarnik'].'</option>';
+ echo '<option value="2" '.($reportElement['type'] == 2 ? 'selected="selected"' : '').'>'.$lang['srv_frequency'].'</option>';
+ echo '<option value="3" '.($reportElement['type'] == 3 ? 'selected="selected"' : '').'>'.$lang['srv_descriptor_short'].'</option>';
+ echo '<option value="4" '.($reportElement['type'] == 4 ? 'selected="selected"' : '').'>'.$lang['srv_chart'].'</option>';
+ echo '<option value="5" '.($reportElement['type'] == 5 ? 'selected="selected"' : '').'>'.$lang['srv_crosstabs'].'</option>';
+ echo '<option value="10" '.($reportElement['type'] == 10 ? 'selected="selected"' : '').'>'.$lang['srv_multicrosstab'].'</option>';
+ echo '<option value="6" '.($reportElement['type'] == 6 ? 'selected="selected"' : '').'>'.$lang['srv_means_label'].'</option>';
+ echo '<option value="7" '.($reportElement['type'] == 7 ? 'selected="selected"' : '').'>'.$lang['srv_ttest'].'</option>';
+ echo '<option value="9" '.($reportElement['type'] == 9 ? 'selected="selected"' : '').'>'.$lang['srv_break'].'</option>';
+
+ echo '</select>';
+
+
+ // Izbira spremenljivke za enojne elemente
+ if($reportElement['type'] > 0 && $reportElement['type'] < 5){
+
+ // Izbira spremneljivke
+ echo ' <select style="margin-left:20px;" name="report_element_spr_id_'.$reportElement['id'].'" id="report_element_spr_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr1\', this.value)">';
+
+ // Ce ni izbrana
+ if ( $reportElement['spr1'] == null || $reportElement['spr1'] == '' ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_select_spr'] . '</option>';
+ }
+ # preberemo header
+ foreach (SurveyAnalysis::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if (($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], SurveyAnalysis::$_FILTRED_TYPES ))
+ /*&& in_array($spremenljivka['tip'],array(1,2,3,6,7,8,16,17,18,20) )*/) {
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+
+ // Ce ja kaksen veljaven oz ce prikazujemo tudi prazne
+ if(SurveyDataSettingProfiles :: getSetting('hideEmpty') != 1 || $only_valid > 0){
+ $text = (strlen($spremenljivka['naslov']) > 60) ? substr($spremenljivka['naslov'], 0, 57).'...' : $spremenljivka['naslov'];
+ $text = '('.$spremenljivka['variable'].') '.$text;
+ echo '<option value="'.$spid.'" '.($reportElement['spr1'] == $spid ? 'selected="selected"' : '').'>'.$text.'</option>';
+ }
+ }
+ }
+ echo '</select>';
+ }
+
+ // Nastavitve za CROSSTABE
+ elseif($reportElement['type'] == 5){
+
+ $variables = $this->classInstance->getVariableList();
+
+ // Nastavljeni variabli
+ $crossData1 = explode("-", $reportElement['spr1']);
+ $crossData2 = explode("-", $reportElement['spr2']);
+
+ // Izbira spremneljivke 1
+ echo ' <select style="margin-left:20px;" name="report_element_spr_id_'.$reportElement['id'].'" id="report_element_spr_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr1\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr1'] == null || $reportElement['spr1'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_izberi_prvo'] . '</option>';
+ }
+ foreach ($variables as $variable) {
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($crossData1[0] == $variable['sequence'] && $crossData1[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+
+ echo '</select>';
+
+
+ // Izbira spremneljivke 2
+ echo ' <select name="report_element_spr2_id_'.$reportElement['id'].'" id="report_element_spr2_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr2\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr2'] == null || $reportElement['spr2'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_izberi_drugo'] . '</option>';
+ }
+ foreach ($variables as $variable) {
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-'.$variable['grd_id'];
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($crossData2[0] == $variable['sequence'] && $crossData2[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+
+ echo '</select>';
+
+ // Izbira podtipa (tabela / graf)
+ echo ' <input style="margin-left:20px;" type="radio" value="0" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 0 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />Tabela ';
+ echo '<input type="radio" value="1" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 1 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />Graf';
+ }
+
+ // Nastavitve za MULTICROSSTABE
+ elseif($reportElement['type'] == 10){
+
+ $mc_tables = $this->classInstance->getTables();
+
+ if(count($mc_tables) == 0){
+ echo '<span class="spaceLeft">'.$lang['srv_multicrosstab_exist'].'</span>';
+ }
+ else{
+ // Izbira ze ustvarjene tabele
+ echo ' <select style="margin-left:20px;" name="report_element_spr_id_'.$reportElement['id'].'" id="report_element_spr_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr1\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr1'] == null || $reportElement['spr1'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_multicrosstab_select'] . '</option>';
+ }
+ foreach($mc_tables as $table){
+ echo '<option value="'.$table['id'].'" '.($reportElement['spr1'] == $table['id'] ? ' selected="selected"' : '').'>'.$table['name'].'</option>';
+ }
+
+ echo '</select>';
+ }
+ }
+
+ // Nastavitve za MEANS
+ elseif($reportElement['type'] == 6){
+
+ $variables1 = $this->classInstance->getVariableList(1);
+ $variables2 = $this->classInstance->getVariableList(2);
+
+ // Nastavljeni variabli
+ $meanData1 = explode("-", $reportElement['spr1']);
+ $meanData2 = explode("-", $reportElement['spr2']);
+
+ // Izbira spremneljivke 1
+ echo ' <select style="margin-left:20px;" name="report_element_spr_id_'.$reportElement['id'].'" id="report_element_spr_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr1\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr1'] == null || $reportElement['spr1'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_means_izberi_prvo'] . '</option>';
+ }
+ foreach ($variables1 as $variable) {
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($meanData1[0] == $variable['sequence'] && $meanData1[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+
+ echo '</select>';
+
+
+ // Izbira spremneljivke 2
+ echo ' <select name="report_element_spr2_id_'.$reportElement['id'].'" id="report_element_spr2_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr2\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr2'] == null || $reportElement['spr2'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_means_izberi_drugo'] . '</option>';
+ }
+ foreach ($variables2 as $variable) {
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($meanData2[0] == $variable['sequence'] && $meanData2[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+
+ echo '</select>';
+
+
+ // Izbira podtipa (tabela / graf)
+ echo ' <input style="margin-left:20px;" type="radio" value="0" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 0 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />Tabela ';
+ echo '<input type="radio" value="1" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 1 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />Graf';
+ }
+
+ // Nastavitve za TTEST
+ elseif($reportElement['type'] == 7){
+
+ $numerus = $this->classInstance->getVariableList(1);
+ $variables = $this->classInstance->getVariableList(2);
+ //$selectedVar = $this->classInstance->getSelectedVariables();
+
+ // Nastavljeni variabli
+ $ttestData1 = explode("-", $reportElement['spr1']);
+ $ttestData2 = explode("-", $reportElement['spr2']);
+
+ // Izbira spremneljivke 1
+ echo ' <select style="margin-left:20px;" name="report_element_spr_id_'.$reportElement['id'].'" id="report_element_spr_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr1\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr1'] == null || $reportElement['spr1'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_ttest_select1_option'] . '</option>';
+ }
+ foreach ($variables as $variable) {
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($ttestData1[0] == $variable['sequence'] && $ttestData1[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+
+ echo '</select>';
+
+
+ // Izbira spremneljivke 2
+ echo ' <select name="report_element_spr2_id_'.$reportElement['id'].'" id="report_element_spr2_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr2\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr2'] == null || $reportElement['spr2'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_ttest_select2_option'] . '</option>';
+ }
+ foreach ($numerus as $variable) {
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($ttestData2[0] == $variable['sequence'] && $ttestData2[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+
+ echo '</select>';
+
+
+ // Izbira podtipa (tabela / graf)
+ echo ' <input style="margin-left:20px;" type="radio" value="0" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 0 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />Tabela ';
+ echo '<input type="radio" value="1" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 1 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />Graf';
+
+
+ // Izbira dveh podvariabel za prvo variablo
+ if($reportElement['spr1'] != null && $reportElement['spr1'] != 0)
+ $this->displayTTestSubVar($reportElement);
+ }
+
+ // Nastavitve za BREAK
+ elseif($reportElement['type'] == 9){
+
+ // Nastavljeni variabli
+ $breakData1 = explode("-", $reportElement['spr1']);
+ $breakData2 = explode("-", $reportElement['spr2']);
+
+
+ // Izbira spremneljivke 1
+ $variables = $this->classInstance->getVariableList(2);
+
+ echo ' <select style="margin-left:20px;" name="report_element_spr_id_'.$reportElement['id'].'" id="report_element_spr_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr1\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr1'] == null || $reportElement['spr1'] == 0){
+ echo '<option value="0" selected="selected" >'. $lang['srv_break_select1_option'] . '</option>';
+ }
+
+ if (count($variables)) {
+ foreach ($variables as $variable) {
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ echo '<option value="'.$value.'"'
+ . ((int)$variable['canChoose'] == 1 ? '' : ' disabled="disabled" ')
+ . ($breakData1[0] == $variable['sequence'] && $breakData1[0] != null ? ' selected="selected"':''). '> ';
+
+ $text = ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' )) . $variable['variableNaslov'];
+ $text = (strlen($text) > 60) ? substr($text, 0, 57).'...' : $text;
+ echo $text;
+
+ echo '</option>';
+ }
+ }
+
+ echo '</select>';
+
+
+ // Izbira spremneljivke 2
+ $variables = $this->getBreakDependentVariableList();
+
+ echo ' <select name="report_element_spr2_id_'.$reportElement['id'].'" id="report_element_spr2_id_'.$reportElement['id'].'" onChange="editCustomReportElement(\''.$reportElement['id'].'\', \'spr2\', this.value)">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $reportElement['spr2'] == null || $reportElement['spr2'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_break_select2_option'] . '</option>';
+ }
+ foreach ($variables as $variable) {
+
+ // Ce ni ista kot prva izbrana
+ if($variable['spr_id'] != $breakData1[1]){
+ $text = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ $value = $variable['sequence'].'-'.$variable['spr_id'].'-'.$variable['grd_id'];
+
+ echo '<option value="'.$value.'" '
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($breakData2[0] == $variable['sequence'] && $breakData2[0] != null) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $text . '</option>';
+ }
+ }
+
+ echo '</select>';
+
+ // Izbira podtipa (tabela / graf)
+ echo ' <input style="margin-left:20px;" type="radio" value="0" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 0 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />'.$lang['srv_table'];
+ echo ' <input type="radio" value="1" name="report_element_sub_type_'.$reportElement['id'].'" '.($reportElement['sub_type'] == 1 ? 'checked="checked"' : '').' onClick="editCustomReportElement(\''.$reportElement['id'].'\', \'sub_type\', this.value)" />'.$lang['srv_chart'];
+ }
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve na dnu
+ function displayBottomSettings(){
+ global $site_path;
+ global $lang;
+
+ echo '<div class="creport_bottom_settings">';
+
+ echo '<a href="#" onclick="doArchiveCReport();" title="'.$lang['srv_analiza_arhiviraj_ttl'].'"><span class="faicon arhiv black very_large"></span></a>';
+ echo '<a href="#" onclick="createArchiveCReportBeforeEmail();" title="'.$lang['srv_analiza_arhiviraj_email_ttl'] . '"><span class="faicon arhiv_mail black very_large"></span></a>';
+
+ echo '<a href="#" onClick="printAnaliza(\'CReport\'); return false;" title="'.$lang['hour_print2'].'"><span class="faicon print icon-grey_dark_link"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=creport_pdf&anketa=' . $this->ank_id) . '" target="_blank" title="'.$lang['PDF_Izpis'].'"><span class="faicon pdf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=creport_rtf&anketa=' . $this->ank_id) . '" target="_blank" title="'.$lang['RTF_Izpis'].'"><span class="faicon rtf black very_large"></span></a>';
+
+ echo '</div>';
+ }
+
+
+ function displayTTestSubVar($reportElement){
+ global $lang;
+
+ echo '<div id="ttestVariablesSpan" style="margin: 10px 0 10px 80px;">';
+
+ $ttestData1 = explode("-", $reportElement['spr1']);
+ $spr = $ttestData1[1];
+ $check1 = $ttestData1[3];
+ $check2 = $ttestData1[4];
+
+
+ # poiscemo pripadajoce variable
+ $_spr_data = $this->classInstance->_HEADERS[$spr];
+ echo $lang['srv_ttest_kategories_note'].' ('.$_spr_data['variable'].') '.$_spr_data['naslov'];
+ echo '<br/>';
+ switch ($_spr_data['tip']) {
+ case 1: #radio
+ case 3: #dropdown
+ case 17: #dropdown
+ #nardimo inpute za vse opcije
+ $sekvenca = $_spr_data['sequences'];
+ foreach ($_spr_data['options'] as $value => $option) {
+ $checked = ($check1 == $spr.'_'.$sekvenca.'_'.$value || $check2 == $spr.'_'.$sekvenca.'_'.$value) ? true : false;
+ $disabled = ($check1 != null && $check2 != null && !$checked) ? ' disabled="disabled"' : '';
+
+ echo '<label '.($disabled == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" class="subTtest_'.$reportElement['id'].'" type="checkbox" value="'.$spr.'_'.$sekvenca.'_'.$value.'" '.($checked ? ' checked="checked"' : '').' onchange="editCustomReportTTestVar(\''.$reportElement['id'].'\');" '.$disabled.' />('.$value.') - '.$option.'</label><br/>';
+ }
+ break;
+
+ case 2: #checkbox
+ #nardimo inpute za vse opcije
+ $option = '1';
+ foreach ($_spr_data['grids'][0]['variables'] as $vid => $variable) {
+ $checked = ($check1 == $spr.'_'.$variable['sequence'].'_'.$option || $check2 == $spr.'_'.$variable['sequence'].'_'.$option) ? true : false;
+ $disabled = ($check1 != null && $check2 != null && !$checked) ? ' disabled="disabled"' : '';
+
+ echo '<label '.($disabled == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" class="subTtest_'.$reportElement['id'].'" type="checkbox" value="'.$spr.'_'.$variable['sequence'].'_'.$option.'" '.($checked ? ' checked="checked"' : '').' onchange="editCustomReportTTestVar(\''.$reportElement['id'].'\');" '.$disabled.' />('.$variable['variable'].') - '.$variable['naslov'].'</label><br/>';
+ }
+ break;
+
+ case 6: #mgrid
+ #nardimo inpute za vse opcije
+ foreach ($_spr_data['options'] as $value => $option) {
+ $sekvenca = $_spr_data['grids'][$value]['variables'][0]['sequence'];
+
+ $checked = ($check1 == $spr.'_'.$sekvenca.'_'.$value || $check2 == $spr.'_'.$sekvenca.'_'.$value) ? true : false;
+ $disabled = ($check1 != null && $check2 != null && !$checked) ? ' disabled="disabled"' : '';
+
+ echo '<label '.($disabled == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" class="subTtest_'.$reportElement['id'].'" type="checkbox" value="'.$spr.'_'.$sekvenca.'_'.$value.'" '.($checked ? ' checked="checked"' : '').' onchange="editCustomReportTTestVar(\''.$reportElement['id'].'\');" '.$disabled.' />('.$value.') - '.$option.'</label><br/>';
+ }
+ break;
+
+ case 16: #mcheck
+ #nardimo inpute za vse opcije
+ # poi��emo pripadajo�o sekvenco
+ #nardimo inpute za vse opcije
+ $option = '1';
+ foreach ($_spr_data['grids'][$grid]['variables'] as $vid => $variable) {
+ $checked = ($check1 == $spr.'_'.$variable['sequence'].'_'.$option || $check2 == $spr.'_'.$variable['sequence'].'_'.$option) ? true : false;
+ $disabled = ($check1 != null && $check2 != null && !$checked) ? ' disabled="disabled"' : '';
+
+ echo '<label '.($disabled == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" class="subTtest_'.$reportElement['id'].'" type="checkbox" value="'.$spr.'_'.$variable['sequence'].'_'.$option.'" '.($checked ? ' checked="checked"' : '').' onchange="editCustomReportTTestVar(\''.$reportElement['id'].'\');" '.$disabled.' />('.$variable['variable'].') - '.$variable['naslov'].'</label><br/>';
+ }
+ break;
+
+ default:
+ if ((int)$_spr_data['tip'] > 0)
+ echo'TODO for type:'.$_spr_data['tip'];
+ break;
+ }
+
+
+
+ echo '</div>';
+ }
+
+ function displayReportElementHead($reportElement, $expanded, $title='&nbsp;'){
+ global $lang;
+
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ echo '<div class="report_element_head '.($reportElement['type'] == 8 ? ' text':'').' '.($expanded == 1 ? ' active':'').'">';
+
+ // Popravimo naslov ce je textovni element
+ if($reportElement['type'] == 8){
+ $title = substr(strip_tags($reportElement['text']), 0, 30);
+
+ if(strlen(strip_tags($reportElement['text'])) > 30)
+ $title .= '...';
+
+ $subtitle = '('.$lang['text'].')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+ }
+
+ echo '<div class="report_element_title">';
+ echo $title;
+ echo '</div>';
+
+
+ // Ikone za razsiritev, kopiranje, brisanje posameznega elementa
+ echo '<div class="report_element_icons '.($expanded == 1 ? ' active' : '').'">';
+
+ // Print element
+ echo ' <span class="faicon print_small icon-grey_dark_link" style="margin-left: 10px;" title="'.$lang['PRN_Izpis'].'" onClick="printCustomReportElement(\''.strip_tags($title).'\', \'report_element_'.$reportElement['id'].'\'); return false;"></span>';
+ // Kopiraj element
+ echo ' <span class="faicon copy icon-grey_dark_link" style="margin-left: 10px;" title="'.$lang['srv_custom_report_copy'].'" onClick="copyCustomReportElement(\''.$reportElement['id'].'\');"></span>';
+ // Brisi element
+ echo ' <span class="faicon delete icon-grey_dark_link" style="margin-left: 10px;" title="'.$lang['srv_custom_report_delete'].'" onClick="deleteCustomReportElement(\''.$reportElement['id'].'\');"></span>';
+
+ // Uredi element
+ /*if($reportElement['type'] != 8)
+ if($expanded == 1)
+ echo ' <span class="sprites pointer arrow_contract" style="margin-left: 10px;" title="'.$lang['srv_custom_report_contract'].'" onClick="expandCustomReportElement(\''.$reportElement['id'].'\');"></span>';
+ else
+ echo ' <span class="sprites pointer arrow_expand" style="margin-left: 10px;" title="'.$lang['srv_custom_report_expand'].'" onClick="expandCustomReportElement(\''.$reportElement['id'].'\');"></span>';
+ */
+
+ echo '</div>';
+
+
+ echo '</div>';
+ }
+ }
+
+
+ // Urejanje naslova porocila
+ function displayTitle(){
+ global $lang;
+ global $global_user_id;
+
+ echo '<div class="custom_report_title">';
+
+ $what = 'creport_title_profile_'.$this->creportProfile;
+ $sql = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$this->creportAuthor' AND what='$what'");
+
+ if(mysqli_num_rows($sql) == 0){
+ $titleString = $lang['export_analisys_creport'].': '.SurveyInfo::getInstance()->getSurveyTitle();
+ }
+ else{
+ $row = mysqli_fetch_array($sql);
+ $titleString = $row['value'];
+ }
+
+ echo '<div class="creport_title_inline" contenteditable="true">';
+ echo $titleString;
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ // Urejanje dodatnega besedila za posamezen element
+ function displayReportElementText($reportElement, $expanded){
+ global $lang;
+
+ echo '<div class="report_element_text report_element_comment" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded == 1 && $this->isArchive == false && $this->publicCReport == false){
+ echo '<span class="bold">'.$lang['srv_inv_archive_comment'].':</span>';
+
+ echo '<span class="faicon edit2" title="'.$lang['srv_editor_title'].'" style="cursor:pointer; float:right; margin:20px 18px 0 0;" onclick="creport_load_editor(this); return false;"></span>';
+
+ /*echo '<textarea style="width:100%; height:80px;" class="creport_textarea" el_id="'.$reportElement['id'].'" id="report_element_text_'.$reportElement['id'].'" onBlur="editCustomReportElement(\''.$reportElement['id'].'\', \'text\', this.value)">';
+ echo $reportElement['text'];
+ echo '</textarea>';*/
+
+ echo '<div class="creport_text_inline" contenteditable="true" el_id="'.$reportElement['id'].'">';
+ echo $reportElement['text'];
+ echo '</div>';
+ }
+ elseif($reportElement['text'] != ''){
+ echo '<div class="creport_text_inline" '.($this->isArchive == false && $this->publicCReport == false ? ' contenteditable="true"':'').' el_id="'.$reportElement['id'].'">';
+ echo $reportElement['text'];
+ echo '</div>';
+ }
+
+ echo '</div>';
+ }
+
+ // Izrisemo sumarnik element
+ function displaySum($reportElement, $expanded){
+ global $lang;
+
+ // Naslov
+ $spr = SurveyAnalysis::$_HEADERS[$reportElement['spr1']];
+
+ if($reportElement['spr1'] == '')
+ $title = $lang['srv_select_spr'];
+ else
+ $title = $spr['variable'].' - '.$spr['naslov'];
+
+ $subtitle = '('.$lang['srv_sumarnik'].')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded != 0)
+ SurveyAnalysis::displaySums($reportElement['spr1']);
+
+ echo '</div>';
+ }
+
+ // Izrisemo sumarnik element
+ function displayFreq($reportElement, $expanded){
+ global $lang;
+
+ // Naslov
+ $spr = SurveyAnalysis::$_HEADERS[$reportElement['spr1']];
+
+ if($reportElement['spr1'] == '')
+ $title = $lang['srv_select_spr'];
+ else
+ $title = $spr['variable'].' - '.$spr['naslov'];
+
+ $subtitle = '('.$lang['srv_frequency'].')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded != 0)
+ SurveyAnalysis::displayFrequency($reportElement['spr1']);
+
+ echo '</div>';
+ }
+
+ // Izrisemo sumarnik element
+ function displayDesc($reportElement, $expanded){
+ global $lang;
+
+ // Naslov
+ $spr = SurveyAnalysis::$_HEADERS[$reportElement['spr1']];
+
+ if($reportElement['spr1'] == '')
+ $title = $lang['srv_select_spr'];
+ else
+ $title = $spr['variable'].' - '.$spr['naslov'];
+
+ $subtitle = '('.$lang['srv_descriptor'].')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded != 0){
+
+ SurveyAnalysis::displayDescriptives($reportElement['spr1']);
+
+ // Na novo napolnimo headers ker se resetira??
+ SurveyAnalysis::$_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ echo '</div>';
+ }
+
+ // Izrisemo sumarnik element
+ function displayChart($reportElement, $expanded){
+ global $lang;
+
+ // Naslov
+ $spr = SurveyAnalysis::$_HEADERS[$reportElement['spr1']];
+
+ if($reportElement['spr1'] == '')
+ $title = $lang['srv_select_spr'];
+ else
+ $title = $spr['variable'].' - '.$spr['naslov'];
+
+ $subtitle = '('.$lang['srv_chart'].')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded != 0){
+
+ SurveyChart::Init($this->ank_id);
+
+ if ($this->returnAsHtml != false) {
+ SurveyChart::setUpReturnAsHtml(true);
+ SurveyChart::setUpIsForArchive(true);
+ }
+
+ SurveyChart::displaySingle($reportElement['spr1']);
+ }
+
+ echo '</div>';
+
+ echo '<script>charts_init();</script>';
+ }
+
+ //izrisemo crosstab element
+ function displayCrosstab($reportElement, $expanded){
+ global $lang;
+
+ // Ustvarimo instanco razreda
+ $this->classInstance = new SurveyCrosstabs();
+ $this->classInstance->Init($this->ank_id);
+
+ // Napolnimo podatke crosstabu
+ $crossData1 = explode("-", $reportElement['spr1']);
+ $crossData2 = explode("-", $reportElement['spr2']);
+
+ $this->classInstance->setVariables($crossData1[0],$crossData1[1],$crossData1[2],$crossData2[0],$crossData2[1],$crossData2[2]);
+
+ // Naslov
+ if($reportElement['spr1'] == '' || $reportElement['spr2'] == '')
+ $title = $lang['srv_select_spr'];
+ else{
+ $show_variables_values = true;
+
+ $spr1 = $this->classInstance->_HEADERS[$crossData1[1]];
+ $spr2 = $this->classInstance->_HEADERS[$crossData2[1]];
+
+ # za multicheckboxe popravimo naslov, na podtip
+ $sub_q1 = null;
+ $sub_q2 = null;
+ if ($spr1['tip'] == '6' || $spr1['tip'] == '7' || $spr1['tip'] == '16' || $spr1['tip'] == '17' || $spr1['tip'] == '18' || $spr1['tip'] == '19' || $spr1['tip'] == '20' || $spr1['tip'] == '21' ) {
+ foreach ($spr1['grids'] AS $grid) {
+ foreach ($grid['variables'] AS $variable) {
+ if ($variable['sequence'] == $v_first['seq']) {
+ $sub_q1 .= strip_tags($spr1['naslov']);
+ if ($show_variables_values == true ) {
+ $sub_q1 .= ' ('.strip_tags($spr1['variable']).')';
+ }
+ if ($spr1['tip'] == '16') {
+ $sub_q1 .= '<br />'. strip_tags($grid1['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($grid1['variable']) . ')' : '');
+ } else {
+ $sub_q1 .= '<br />' . strip_tags($variable['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($variable['variable']) . ')' : '');
+ }
+ }
+ }
+ }
+ }
+ if ($sub_q1 == null) {
+ $sub_q1 .= strip_tags($spr1['naslov']);
+ $sub_q1 .= ($show_variables_values == true ? '&nbsp;('.strip_tags($spr1['variable']).')' : '');
+ }
+ if ($spr2['tip'] == '6' || $spr2['tip'] == '7' || $spr2['tip'] == '16' || $spr2['tip'] == '17' || $spr2['tip'] == '18' || $spr2['tip'] == '19' || $spr2['tip'] == '20' || $spr2['tip'] == '21') {
+ foreach ($spr2['grids'] AS $grid) {
+ foreach ($grid['variables'] AS $variable) {
+ if ($variable['sequence'] == $v_second['seq']) {
+ $sub_q2 .= strip_tags($spr2['naslov']);
+ if ($show_variables_values == true) {
+ $sub_q2 .= ' ('.strip_tags($spr2['variable']).')';
+ }
+ if ($spr2['tip'] == '16') {
+ $sub_q2.= '<br />' . strip_tags($grid2['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($grid2['variable']) . ')' : '');
+ } else {
+ $sub_q2.= '<br />' . strip_tags($variable['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($variable['variable']) . ')' : '');
+ }
+ }
+ }
+ }
+ }
+ if ($sub_q2 == null) {
+ $sub_q2 .= strip_tags($spr2['naslov']);
+ $sub_q2 .= ($show_variables_values == true ? ' ('.strip_tags($spr2['variable']).')' : '');
+ }
+
+ $title = $sub_q1 . ' / ' . $sub_q2;
+ }
+
+ $subtitle = '('.$lang['srv_crosstabs']. ($reportElement['sub_type'] == 1 ? ' - '.$lang['srv_chart'] : '') .')';
+
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($reportElement['spr1'] != '' && $reportElement['spr2'] != '' && $expanded != 0){
+ // Izrisemo tabelo
+ if($reportElement['sub_type'] == 0){
+ $this->classInstance->showChart = false;
+ $this->classInstance->displayCrosstabsTable();
+ }
+ // Izrisemo graf
+ else{
+ $tableChart = new SurveyTableChart($this->ank_id, $this->classInstance, 'crosstab');
+ $tableChart->display();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ // Izrisemo multicrosstab tabelo
+ function displayMulticrosstab($reportElement, $expanded){
+ global $lang;
+ global $global_user_id;
+
+ // Ustvarimo instanco razreda
+ $this->classInstance = new SurveyMultiCrosstabs($this->ank_id);
+
+ // Naslov
+ if($reportElement['spr1'] == '')
+ $title = $lang['srv_select_spr'];
+ else{
+ // Trenutna aktivna tabela
+ $sql = sisplet_query("SELECT * FROM srv_mc_table WHERE id='$reportElement[spr1]' AND ank_id='$this->ank_id' AND usr_id='$this->creportAuthor'");
+ $current_table = mysqli_fetch_array($sql);
+
+ $title = $current_table['name'];
+ }
+
+ $subtitle = '('.$lang['srv_multicrosstabs'].')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded != 0 && $current_table != null){
+
+ $this->classInstance->table_id = $current_table['id'];
+ $this->classInstance->table_settings[$current_table['id']] = array(
+ 'title' => $current_table['title'],
+ 'numerus' => $current_table['numerus'],
+ 'percent' => $current_table['percent'],
+ 'sums' => $current_table['sums'],
+ 'navVsEno' => $current_table['navVsEno'],
+ 'avgVar' => $current_table['avgVar'],
+ 'delezVar' => $current_table['delezVar'],
+ 'delez' => $current_table['delez']
+ );
+
+ $this->classInstance->getVariableList();
+
+ // Izris tabele
+ echo '<div id="mc_table_holder_'.$current_table['id'].'" class="mc_table_holder">';
+ $this->classInstance->displayTable();
+ echo '</div>';
+ }
+
+ echo '</div>';
+ }
+
+ //izrisemo crosstab element
+ function displayMean($reportElement, $expanded){
+ global $lang;
+
+ // Ustvarimo instanco razreda
+ $this->classInstance = new SurveyMeans($this->ank_id);
+
+ // Napolnimo podatke meansom
+ $meanData1 = explode("-", $reportElement['spr2']);
+ $v_first = array('seq' => $meanData1[0], 'spr' => $meanData1[1], 'grd' => $meanData1[2]);
+ $meanData2 = explode("-", $reportElement['spr1']);
+ $v_second = array('seq' => $meanData2[0], 'spr' => $meanData2[1], 'grd' => $meanData2[2]);
+
+ $means[0] = $this->classInstance->createMeans($v_first, $v_second);
+
+ // Nastavimo variable (potrebno za grafe
+ $this->classInstance->variabla1[0] = $v_second;
+ $this->classInstance->variabla2[0] = $v_first;
+
+ // Naslov
+ if($reportElement['spr1'] == '' || $reportElement['spr2'] == ''){
+ $title = $lang['srv_select_spr'];
+ }
+ else{
+ $label2 = strip_tags($this->classInstance->getSpremenljivkaTitle($means[0]['v1']));
+ $label1 = strip_tags($this->classInstance->getSpremenljivkaTitle($means[0]['v2']));
+
+ $title = $label1 . ' / ' . $label2;
+ }
+
+ $subtitle = '('.$lang['srv_means']. ($reportElement['sub_type'] == 1 ? ' - '.$lang['srv_chart'] : '') .')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($reportElement['spr1'] != '' && $reportElement['spr2'] != '' && $expanded != 0){
+
+ // Izrisemo tabelo
+ if($reportElement['sub_type'] == 0){
+ $this->classInstance->displayMeansTable($means);
+ }
+ // Izrisemo graf
+ else{
+ $tableChart = new SurveyTableChart($this->ank_id, $this->classInstance, 'mean');
+ $tableChart->display();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ //izrisemo ttest element
+ function displayTTest($reportElement, $expanded){
+ global $lang;
+
+ // Ustvarimo instanco razreda
+ $this->classInstance = new SurveyTTest($this->ank_id);
+
+ // Naslov
+ if($reportElement['spr1'] == '' || $reportElement['spr2'] == ''){
+ $title = $lang['srv_select_spr'];
+ }
+ else{
+ $label2 = strip_tags($this->getTTestLabel($reportElement['spr2']));
+ $label1 = strip_tags($this->getTTestLabel($reportElement['spr1']));
+
+ $title = $label1 . ' / ' . $label2;
+ }
+
+ $subtitle = '('.$lang['srv_ttest']. ($reportElement['sub_type'] == 1 ? ' - '.$lang['srv_chart'] : '') .')';
+
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($expanded != 0){
+
+ // Nastavimo session da lahko pravilno izrisemo tabelo/graf
+ $ttestData1 = explode("-", $reportElement['spr1']);
+ $ttestData2 = explode("-", $reportElement['spr2']);
+
+ if(count($ttestData1) == 5 && count($ttestData2) == 3){
+ $dataArray = array();
+
+ $dataArray['spr2'] = $ttestData1[1];
+ $dataArray['grid2'] = $ttestData1[2];
+ $dataArray['seq2'] = $ttestData1[0];
+ $dataArray['label2'] = $label1;
+
+ $dataArray['sub_conditions'][0] = $ttestData1[3];
+ $dataArray['sub_conditions'][1] = $ttestData1[4];
+
+ $dataArray['variabla'][0]['seq'] = $ttestData2[0];
+ $dataArray['variabla'][0]['spr'] = $ttestData2[1];
+ $dataArray['variabla'][0]['grd'] = $ttestData2[2];
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::Init($this->ank_id);
+ $sessionData = SurveyUserSession::getData('ttest');
+ $sessionData = $dataArray;
+ SurveyUserSession::saveData($sessionData, 'ttest');
+
+ // Ustvarimo instanco razreda
+ $this->classInstance = new SurveyTTest($this->ank_id);
+
+ // Izrisemo tabelo
+ if($reportElement['sub_type'] == 0){
+ $variables1 = $this->classInstance->getSelectedVariables();
+ foreach ($variables1 AS $v_first) {
+ $ttest = $this->classInstance->createTTest($v_first, $sessionData['sub_conditions']);
+ $this->classInstance->displayTtestTable($ttest);
+ }
+ }
+ // Izrisemo graf
+ else{
+ $tableChart = new SurveyTableChart($this->ank_id, $this->classInstance, 'ttest');
+ $tableChart->display();
+ }
+ }
+ }
+
+ echo '</div>';
+ }
+
+ function getTTestLabel($spr){
+
+ $data = explode("-", $spr);
+
+ $spid = $data[1];
+ $seq = $data[0];
+ $grid = $data[2];
+
+ $spr_data = $this->classInstance->_HEADERS[$spid];
+ if ($grid == 'undefined') {
+
+ # imamp lahko ve� variabel
+ foreach ($spr_data['grids'] as $gkey => $grid ) {
+
+ foreach ($grid['variables'] as $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($sequence == $seq) {
+ $sprLabel = '('.$variable['variable'].') '. $variable['naslov'];
+ }
+ }
+ }
+ } else {
+ # imamo subgrid
+ $sprLabel = '('.$spr_data['grids'][$grid]['variable'].') '. $spr_data['grids'][$grid]['naslov'];
+ }
+
+ return $sprLabel;
+ }
+
+ function displayRazbitje($reportElement, $expanded){
+ global $lang;
+
+ // Ustvarimo instanco razreda
+ $this->classInstance = new SurveyBreak($this->ank_id);
+
+ // Naslov
+ if($reportElement['spr1'] == '' || $reportElement['spr2'] == ''){
+ $title = $lang['srv_select_spr'];
+ }
+ else{
+ $breakData1 = explode("-", $reportElement['spr1']);
+ $breakData2 = explode("-", $reportElement['spr2']);
+
+ $label1 = '';
+ $variables = $this->classInstance->getVariableList(2);
+ foreach ($variables as $variable) {
+
+ if($breakData1[0] == $variable['sequence']){
+ $label1 = ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' )) . $variable['variableNaslov'];
+ $label1 = (strlen($label1) > 60) ? substr($label1, 0, 57).'...' : $label1;
+
+ break;
+ }
+ }
+
+ $label2 = '';
+ $variables = $this->getBreakDependentVariableList();
+ foreach ($variables as $variable) {
+
+ if($breakData2[0] == $variable['sequence']){
+ //$label2 = $variable['variableNaslov'];
+ $label2 = (strlen($variable['variableNaslov']) > 60) ? substr($variable['variableNaslov'], 0, 57).'...' : $variable['variableNaslov'];
+
+ break;
+ }
+ }
+
+ $title = $label1 . ' / ' . $label2;
+ }
+
+ $subtitle = '('.$lang['srv_break']. ($reportElement['sub_type'] == 1 ? ' - '.$lang['srv_chart'] : '') .')';
+ $title .= ' <span class="anl_ita">'.$subtitle.'</span>';
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded, $title);
+
+ // Nastavitve elementa
+ $this->displayReportElementSettings($reportElement, $expanded);
+
+
+ // Izpis tabele ali grafa za posamezen vnos
+ echo '<div class="report_element_data" '.($expanded == 0 ? ' style="display:none;"' : '').'>';
+
+ if($reportElement['spr1'] != '' && $reportElement['spr2'] != '' && $expanded != 0){
+
+ # ali prikazujemo procente
+ $this->classInstance->break_percent = true; /*isset($_SESSION['break_percent']) && (int)$_SESSION['break_percent'] == 0 ? false : true;*/
+
+ $spr = $breakData1[1];
+
+ # poiščemo pripadajoče variable
+ $_spr_data = $this->classInstance->_HEADERS[$breakData1[1]];
+
+ # poiščemo sekvenco
+ $sekvenca = $breakData1[0];
+
+ # poiščemo opcije
+ $opcije = $_spr_data['options'];
+
+ if ((int)$_spr_data['tip'] != 2) {
+ $seqences[] = $sekvenca;
+ $options = $opcije;
+ } else {
+ # za checkboxe imamo več sekvenc
+ $seqences = explode('_',$_spr_data['sequences']);
+ $options[1] = $opcije[1];
+ }
+
+ # za vsako opcijo posebej izračunamo povprečja za vse spremenljivke
+ $frequencys = array();
+ if (count($seqences) > 0) {
+ foreach ($seqences as $seq) {
+
+ if (count($options) > 0) {
+ foreach ($options as $oKey => $option) {
+ # zloopamo skozi variable
+ $oKeyfrequencys = $this->classInstance->getAllFrequencys($oKey, $seq, $spr);
+ if ($oKeyfrequencys != null) {
+ $frequencys[$seq][$oKey] = $oKeyfrequencys;
+ }
+ }
+ }
+ }
+ }
+
+ // Nastavimo odvisno spremenljivko
+ $spr2 = $this->classInstance->_HEADERS[$breakData2[1]];
+ $spr2['id'] = $breakData2[1];
+
+ // Nastavimo se katero podtabelo izrisemo (sekvenca odvisne spr)
+ $spr2['break_sub_table']['sequence'] = $breakData2[0];
+ foreach ($spr2['grids'] AS $gkey => $grid) {
+ if($spr2['break_sub_table']['sequence'] == $grid['variables'][0]['sequence']){
+ $spr2['break_sub_table']['key'] = $gkey;
+ break;
+ }
+ }
+
+ // Nastavimo se prvo spremenljivko in sekvenco (potrebno pri crosstabih ker se drugace to vlece iz SESSIONA)
+ $spr2['creport_first_spr']['seq'] = $breakData1[0];
+ $spr2['creport_first_spr']['spr'] = $breakData1[1];
+
+
+ // Izrisemo tabelo
+ if($reportElement['sub_type'] == 0){
+ $this->classInstance->break_charts = 0;
+ $this->classInstance->displayBreakSpremenljivka($spr,$frequencys,$spr2);
+ }
+ // Izrisemo graf
+ else{
+ $this->classInstance->break_charts = 1;
+ $this->classInstance->displayBreakSpremenljivka($spr,$frequencys,$spr2);
+ }
+ }
+
+ echo '</div>';
+ }
+
+ /** funkcija vrne seznam primern variabel za crostabe
+ *
+ */
+ function getBreakDependentVariableList() {
+
+ $variablesList = array();
+
+ # zloopamo skozi header in dodamo variable (potrebujemo posamezne sekvence)
+ foreach ($this->classInstance->_HEADERS AS $skey => $spremenljivka) {
+
+ $tip = $spremenljivka['tip'];
+
+ $_dropdown_condition = (is_numeric($tip) && $tip != 5 && $tip != 8 && $tip != 9) ? true : false;
+ if ($_dropdown_condition) {
+
+ $cnt_all = (int)$spremenljivka['cnt_all'];
+ if ( $cnt_all == '1' || in_array($tip, array(1,2,3,4,7,17,18,21,22,25)) || ($tip == 6 && $spremenljivka['enota'] == 2) ) {
+
+ # pri tipu radio ali select dodamo tisto variablo ki ni polje "drugo"
+ if ($tip == 1 || $tip == 3 ) {
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][$vid]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+
+ }
+ }
+ }
+ }
+ }
+
+ else {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+ }
+ else if ($cnt_all > 1){
+ # imamo več skupin ali podskupin, zato zlopamo skozi gride in variable
+ if (count($spremenljivka['grids']) > 0 ) {
+ $variablesList[] = array(
+ 'tip'=>$tip,
+
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # ali imamo en grid, ali več (tabele
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } elseif($tip == 6) {
+ # imamo več gridov - tabele
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $variablesList[] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>$sub);
+ }
+ if (count ($grid['variables']) > 0) {
+ $sub++;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>$sub);
+ }
+ }
+ }
+ }
+ } else {
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>$gid,
+ 'sequence'=>$grid['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return $variablesList;
+ }
+
+ // Izrisemo page break med elementi
+ function displayBreak($reportElement){
+ global $lang;
+
+ echo '<span class="report_element_pb" title="'.$lang['srv_rem_pagebreak'].'" onClick="deleteCustomReportElement(\''.$reportElement['id'].'\');">';
+
+ echo '</span>';
+ }
+
+ // Izrisemo element z besedilom
+ function displayText($reportElement, $expanded){
+ global $lang;
+
+ // Glava elementa (naslov, ikone...)
+ $this->displayReportElementHead($reportElement, $expanded);
+
+ echo '<div class="report_element_text" style="padding-top:15px; '.($expanded == 0 ? ' display:none;' : '').'">';
+
+ /*if($expanded == 1){
+
+ echo '<span class="faicon edit2" title="'.$lang['srv_editor_title'].'" style="cursor:pointer; display:block; float:right;" onclick="creport_load_editor(this); return false;"></span>';
+
+ echo '<textarea style="width:100%; height:80px;" class="creport_textarea" el_id="'.$reportElement['id'].'" id="report_element_text_'.$reportElement['id'].'" onBlur="editCustomReportElement(\''.$reportElement['id'].'\', \'text\', this.value)">';
+ echo $reportElement['text'];
+ echo '</textarea>';
+ }*/
+ //else{
+ if ($this->isArchive == false && $this->publicCReport == false) {
+ echo '<span class="faicon edit2" title="'.$lang['srv_editor_title'].'" style="cursor:pointer; display:block; float:right; margin:20px 18px 0 0;" onclick="creport_load_editor(this); return false;"></span>';
+ }
+
+ echo '<br /><div class="creport_text_inline" '.($this->isArchive == false && $this->publicCReport == false ? ' contenteditable="true"':'').' el_id="'.$reportElement['id'].'">';
+ echo $reportElement['text'];
+ echo '</div>';
+ //}
+
+ echo '</div>';
+ }
+
+
+ // Dodajanje elementa porocila
+ function addNewElement($id=0){
+ global $lang;
+
+ // Dodajanje vmes in na zacetku
+ if($id != 0){
+ echo '<span class="pointer" title="'.$lang['srv_custom_report_add'].'" style="margin-left: 20px; " onClick="addEmptyCustomReportElement(\''.$id.'\');"><span class="faicon add small icon-blue_light"></span> '.$lang['srv_custom_report_add'].'</span>';
+
+ echo '<span class="pointer" title="'.$lang['srv_custom_report_add_text'].'" style="margin-left: 20px;" onClick="addTextCustomReportElement(\''.$id.'\');"><span class="faicon add small icon-blue_dark"></span> '.$lang['srv_custom_report_add_text'].'</span>';
+
+ if($id > 0)
+ echo '<span class="pointer" title="'.$lang['srv_add_pagebreak'].'" style="margin-left: 20px;" onClick="addPBCustomReportElement(\''.$id.'\');"><span class="faicon paragraph icon-blue"></span> '.$lang['srv_add_pagebreak'].'</span>';
+ }
+
+ // Dodajanje na dnu (brez page breaka)
+ if($id == 0){
+ echo '<span class="pointer" style="margin:-10px 0 10px 20px;" onClick="addEmptyCustomReportElement(\''.$id.'\');"><span class="faicon add small icon-blue_light" title="'.$lang['srv_custom_report_add'].'"></span> '.$lang['srv_custom_report_add'].'</span>';
+
+ echo '<span class="pointer" style="margin:-10px 0 10px 20px;" onClick="addTextCustomReportElement(\''.$id.'\');"><span class="faicon add small icon-blue_dark" title="'.$lang['srv_custom_report_add_text'].'"></span> '.$lang['srv_custom_report_add_text'].'</span>';
+ }
+ }
+
+ public static function checkEmpty($ank_id){
+ global $global_user_id;
+
+ $creportProfile = SurveyUserSetting :: getInstance()->getSettings('default_creport_profile');
+ $creportProfile = isset($creportProfile) ? $creportProfile : 0;
+
+ $creportAuthor = SurveyUserSetting :: getInstance()->getSettings('default_creport_author');
+ $creportAuthor = isset($creportAuthor) ? $creportAuthor : $global_user_id;
+
+ // preverimo ce je ze kaksen element v porocilu
+ $sql = sisplet_query("SELECT id FROM srv_custom_report WHERE ank_id='$ank_id' AND usr_id='$creportAuthor' AND profile='$creportProfile' ");
+
+ if(mysqli_num_rows($sql) > 0){
+ $empty = false;
+ }
+ else{
+ $empty = true;
+ }
+
+ return $empty;
+ }
+
+
+ function setUpReturnAsHtml($returnAsHtml = false) {
+ $this->returnAsHtml = $returnAsHtml; # ali vrne rezultat analiz kot html ali ga izpiše
+ SurveyAnalysis::setUpReturnAsHtml($returnAsHtml);
+ }
+
+ function setUpIsForArchive($isArchive = false) {
+ $this->isArchive = $isArchive; # nastavimo da smo v arhivu
+ SurveyAnalysis::setUpIsForArchive($isArchive);
+ }
+
+ function setUpIsForPublic($publicCReport = false) {
+ $this->publicCReport = $publicCReport;
+
+ SurveyAnalysis::$publicAnalyse = $publicCReport;
+ SurveyAnalysis::$printPreview = $publicCReport;
+
+ SurveyChart::$publicChart = $publicCReport;
+ }
+
+
+ function displaySettingsProfiles(){
+ global $site_path;
+ global $global_user_id;
+ global $lang;
+
+ $time_created = '';
+ $time_edit = '';
+
+
+ $what = 'creport_default_profile_name';
+ $sql = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$global_user_id' AND what='$what'");
+ if(mysqli_num_rows($sql) == 0){
+ $default_name = $lang['srv_custom_report_default'];
+ }
+ else{
+ $row = mysqli_fetch_array($sql);
+ $default_name = $row['value'];
+ }
+
+ $profile = $this->getProfile($this->creportProfile);
+ $name = $profile['name'];
+
+
+ echo '<h2>'.$lang['srv_custom_report_profile_title'].'</h2>';
+
+ echo '<div id="creport_settings_profiles_left">';
+
+ // Prednastavljen profil
+ echo '<span id="creport_profiles" class="creport_profiles select">';
+
+ echo '<div class="option'.($this->creportProfile == 0 && $this->creportAuthor == $global_user_id ? ' active' : '').'" id="creport_profile_0_'.$global_user_id.'" author="'.$global_user_id.'" value="0">'.$default_name.'</div>';
+
+ // Loop po lastnih porocilih
+ $sql = sisplet_query("SELECT * FROM srv_custom_report_profiles WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+ while($row = mysqli_fetch_array($sql)){
+ echo '<div class="option'.($this->creportProfile == $row['id'] && $this->creportAuthor == $global_user_id ? ' active' : '').'" id="creport_profile_'.$row['id'].'_'.$global_user_id.'" author="'.$global_user_id.'" value="'.$row['id'].'">'.$row['name'].'</div>';
+
+ // Preberemo cas kreiranja porocila
+ if($this->creportProfile == $row['id'])
+ $time_created = $row['time_created'];
+ }
+
+ // Loop po deljenih porocilih drugih urednikov ankete
+ $sqlA = sisplet_query("SELECT s.*, u.email FROM srv_custom_report_share s, users u WHERE ank_id='$this->ank_id' AND share_usr_id='$global_user_id' AND u.id=s.author_usr_id");
+ while($rowA = mysqli_fetch_array($sqlA)){
+
+ // Ce gre za osnovno porocilo ki ga ne more pobrisati
+ if($rowA['profile_id'] == 0){
+
+ // Dobimo ime osnovnega porocila
+ $what = 'creport_default_profile_name';
+ $sqlN = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='".$rowA['author_usr_id']."' AND what='$what'");
+ if(mysqli_num_rows($sqlN) == '0'){
+ $default_name = $lang['srv_custom_report_default'];
+ }
+ else{
+ $rowN = mysqli_fetch_array($sqlN);
+ $default_name = ($rowN['value'] == '') ? $lang['srv_custom_report_default'] : $rowN['value'];
+ }
+
+ echo '<div class="option'.($this->creportProfile == 0 && $this->creportAuthor == $rowA['author_usr_id'] ? ' active' : '').'" id="creport_profile_0_'.$rowA['author_usr_id'].'" author="'.$rowA['author_usr_id'].'" value="0">';
+ echo $default_name . ' ('.$rowA['email'].')';
+ echo '</div>';
+ }
+ // Ce gre za dodatno porocilo ga imamo normalno v bazi
+ else{
+ $sql = sisplet_query("SELECT * FROM srv_custom_report_profiles WHERE ank_id='$this->ank_id' AND usr_id='".$rowA['author_usr_id']."'");
+ while($row = mysqli_fetch_array($sql)){
+ echo '<div class="option'.($this->creportProfile == $row['id'] && $this->creportAuthor == $rowA['author_usr_id'] ? ' active' : '').'" id="creport_profile_'.$row['id'].'_'.$rowA['author_usr_id'].'" author="'.$rowA['author_usr_id'].'" value="'.$row['id'].'">';
+ echo $row['name'] . ' ('.$rowA['email'].')';
+ echo '</div>';
+
+ // Preberemo cas kreiranja porocila
+ if($this->creportProfile == $row['id'])
+ $time_created = $row['time_created'];
+ }
+ }
+ }
+
+ echo '</span>';
+
+
+ // Ce je izbran custom profil imamo na dnu gumba brisi in preimenuj, pri default pa samo preimenuj
+ // Preimenuje, brise in share lahko samo za lastna porocila
+ if($this->creportAuthor == $global_user_id){
+ echo '<div style="float:left; margin-bottom:10px;">';
+ echo '<a href="#" onclick="creport_profile_action(\'show_rename\'); return false;">'.$lang['srv_rename_profile'].'</a>'."\n";
+
+ if($this->creportProfile > 0)
+ echo '<br /><a href="#" onclick="creport_profile_action(\'show_delete\'); return false;">'.$lang['srv_delete_profile'].'</a>'."\n";
+
+ // Deli poročilo z drugimi uredniki
+ echo '<br /><a href="#" onclick="creport_profile_action(\'show_share\'); return false;">'.$lang['srv_custom_report_share'].'</a>'."\n";
+ echo '</div>';
+ }
+
+
+ // Preberemo najkasneje editiran element (cas spreminjanja)
+ $sqlt = sisplet_query("SELECT MAX(time_edit) FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile'");
+ if(mysqli_num_rows($sqlt) > 0){
+ $rowt = mysqli_fetch_array($sqlt);
+ $time_edit = $rowt['MAX(time_edit)'];
+ }
+ else
+ $time_edit = $time_created;
+
+ // Cas kreirranja in urejanja profila
+ echo '<div style="float:right; text-align:right;">';
+
+ if($time_created != '' && $time_created != '0000-00-00 00:00:00'){
+ $time_created = strtotime($time_created);
+ echo $lang['srv_custom_report_time_created'].': <span class="bold">'.date("d.m.Y H:i", $time_created).'</span><br />';
+ }
+ if($time_edit != '' && $time_edit != '0000-00-00 00:00:00'){
+ $time_edit = strtotime($time_edit);
+ echo $lang['srv_custom_report_time_edited'].': <span class="bold">'.date("d.m.Y H:i", $time_edit).'</span>';
+ }
+
+ echo '</div>';
+
+ echo '</div>';
+
+
+ // Komentar profila
+ echo '<div id="creport_settings_profiles_comment">';
+
+ $what = 'creport_comment_profile_'.$this->creportProfile;
+ $sql = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$this->creportAuthor' AND what='$what'");
+ if(mysqli_num_rows($sql) == 0){
+ $comment = '';
+ }
+ else{
+ $row = mysqli_fetch_array($sql);
+ $comment = $row['value'];
+ }
+
+ echo '<span class="bold clr">'.$lang['srv_inv_archive_comment'].':</span>';
+ // Komentar lahko popravlja samo avtor porocila
+ if($this->creportAuthor == $global_user_id)
+ echo '<textarea onBlur="creport_profile_comment(this.value)">'.$comment.'</textarea>';
+ else
+ echo '<span>'.$comment.'</span>';
+
+ echo '</div>';
+
+
+ // cover Div
+ echo '<div id="dsp_cover_div"></div>'."\n";
+
+ echo '<span class="clr"></span>';
+
+ echo '<div style="position:absolute; bottom:20px; right:20px;">';
+ echo '<span class="floatRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="use_creport_profile(); return false;"><span>'.$lang['srv_save_and_run_profile'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_custom_report_create'].'"><div class="buttonwrapper"><a class="ovalbutton" href="#" onclick="creport_profile_action(\'show_new\'); return false;"><span>'.$lang['srv_custom_report_create'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton" href="#" onclick="close_creport_profile(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+
+ echo '</div>';
+ }
+
+ function displayProfilePopups(){
+ global $lang;
+ global $global_user_id;
+
+ $profile = $this->getProfile($this->creportProfile);
+ $name = $profile['name'];
+
+ // div za kreacijo novega
+ echo '<div id="newCReportProfile">';
+ echo '<div style="float:left; width:410px; text-align:right;">'.$lang['srv_custom_report_name'].': '."\n";
+ echo '<input id="newCReportProfileName" name="newCReportProfileName" type="text" value="" size="50" /></div>'."\n";
+ echo '<div style="float:left; width:410px; text-align:right; padding:5px 0px;">'.$lang['srv_inv_archive_comment'].': '."\n";
+ echo '<input id="newCReportProfileComment" name="newCReportProfileComment" type="text" value="" size="50" /></div>'."\n";
+ echo '<br /><br /><br /><br /><span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="creport_profile_action(\'new\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="creport_profile_action(\'cancel_new\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameCReportProfile">'.$lang['srv_custom_report_name'].': '."\n";
+ echo '<input id="renameCReportProfileName" name="renameCReportProfileName" type="text" size="45" />'."\n";
+ echo '<input id="renameCReportProfileId" type="hidden" value="' . $this->creportProfile . '" />'."\n";
+ echo '<br /><br /><span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="creport_profile_action(\'rename\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="creport_profile_action(\'cancel_rename\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteCReportProfile">'.$lang['srv_custom_report_delete_confirm'].': <span id="deleteCReportProfileName" style="font-weight:bold;"></span>?'."\n";
+ echo '<input id="deleteCReportProfileId" type="hidden" value="' . $this->creportProfile . '" />'."\n";
+ echo '<br /><br /><span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="creport_profile_action(\'delete\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="creport_profile_action(\'cancel_delete\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za deljenje z drugimi uredniki
+ echo '<div id="shareCReportProfile">';
+ echo '</div>'."\n";
+ }
+
+ public function getProfile($profile_id){
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT * FROM srv_custom_report_profiles WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$profile_id'");
+ $profile = mysqli_fetch_array($sql);
+
+ return $profile;
+ }
+
+ public function getTitle(){
+ global $global_user_id;
+ global $lang;
+
+ $what = 'creport_title_profile_'.$this->creportProfile;
+ $sql = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$this->creportAuthor' AND what='$what'");
+
+ if(mysqli_num_rows($sql) == 0){
+ $titleString = $lang['export_analisys_creport'].': '.SurveyInfo::getInstance()->getSurveyTitle();
+ }
+ else{
+ $row = mysqli_fetch_array($sql);
+ $titleString = $row['value'];
+ }
+
+ return $titleString;
+ }
+
+
+ public function displayPublicCReport($properties) {
+ global $lang;
+ global $site_url;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+
+ $anketa = $this->ank_id;
+
+ $this->creportProfile = $properties['creportProfile'];
+ $this->creportAuthor = $properties['creportAuthor'];
+
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body style="margin:5px; padding:5px;" >';
+
+ $what = 'creport_title_profile_'.$this->creportProfile;
+ $sql = sisplet_query("SELECT value FROM srv_user_setting_for_survey WHERE sid='$anketa' AND uid='$this->creportAuthor' AND what='$what'");
+ if(mysqli_num_rows($sql) == 0){
+ $titleString = $lang['srv_publc_creport_title_for'].SurveyInfo::getInstance()->getSurveyTitle();
+ }
+ else{
+ $row = mysqli_fetch_array($sql);
+ $titleString = $row['value'];
+ }
+ //echo '<h2>'.$lang['srv_publc_creport_title_for'] .$titleString.'</h2>';
+ echo '<h2>'.$titleString.'</h2>';
+
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $anketa . '" />';
+ echo '<div id="analiza_data">';
+
+ # ponastavimo nastavitve- filter
+ self::displayReport();
+ echo '</div>';
+
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/printer.png" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+
+ echo '</body>';
+ echo '</html>';
+ }
+
+
+ // Funkcije ajaxa
+ public function ajax() {
+ global $lang;
+ global $global_user_id;
+ global $site_url;
+
+ $_GET['m'] = 'analysis_creport';
+
+ if (isset ($_POST['anketa']))
+ $this->ank_id = $_POST['anketa'];
+ if (isset ($_POST['element_id']))
+ $element_id = $_POST['element_id'];
+
+ if (isset ($_POST['what']))
+ $what = $_POST['what'];
+ if (isset ($_POST['value']))
+ $value = $_POST['value'];
+
+ // Nastavimo se nacin (skrcen/razsirjen)
+ $this->expanded = (isset($_POST['expanded']) ? $_POST['expanded'] : 0);
+
+ // Dodajanje praznega elementa v report
+ if($_GET['a'] == 'add_empty_element'){
+
+ // dodajanje vmes
+ if($element_id > 0){
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$element_id' AND profile='$this->creportProfile'");
+
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] + 1;
+
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red+1 WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND vrstni_red>='$vrstni_red' AND profile='$this->creportProfile'");
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '$vrstni_red', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $el_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ //dodajanje na zacetku
+ elseif($element_id == -1){
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red+1 WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile'");
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '1', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $el_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ // dodajanje na koncu
+ else{
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile' ORDER BY vrstni_red DESC");
+
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] + 1;
+ }
+ else
+ $vrstni_red = 1;
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '$vrstni_red', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $el_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ $this->displayReport();
+
+ echo '<input type="hidden" el_id="'.$el_id.'" id="added_element" />';
+ }
+
+ // Dodajanje ze nastavljenega elementa v report (klik na zvezdico)
+ if($_GET['a'] == 'add_element'){
+
+ if (isset ($_POST['type']))
+ $type = $_POST['type'];
+ if (isset ($_POST['sub_type']))
+ $sub_type = $_POST['sub_type'];
+ if (isset ($_POST['spr1']))
+ $spr1 = $_POST['spr1'];
+ if (isset ($_POST['spr2']))
+ $spr2 = $_POST['spr2'];
+ if (isset ($_POST['insert']))
+ $insert = $_POST['insert'];
+
+
+ // Vstavljanje
+ if($insert == 1){
+ // Razberemo vrstni red
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile' ORDER BY vrstni_red DESC");
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] + 1;
+ }
+ else
+ $vrstni_red = 1;
+
+ $sql = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, type, sub_type, spr1, spr2, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '$vrstni_red', '$type', '$sub_type', '$spr1', '$spr2', '$this->creportProfile', NOW())");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo $vrstni_red;
+ }
+
+ // brisanje
+ else{
+ // Preberemo vrstni red elementa, ki ga brisemo
+ $sql = sisplet_query("SELECT id, vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND type='$type' AND sub_type='$sub_type' AND spr1='$spr1' AND spr2='$spr2' AND profile='$this->creportProfile'");
+ $row = mysqli_fetch_array($sql);
+ $vrstni_red = $row['vrstni_red'];
+ $element_id = $row['id'];
+
+ $sql = sisplet_query("DELETE FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$element_id' AND profile='$this->creportProfile'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red-1, time_edit=NOW() WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND vrstni_red>'$vrstni_red' AND profile='$this->creportProfile'");
+
+ echo -1;
+ }
+ }
+
+ // Brisanje elementa
+ if($_GET['a'] == 'delete_element'){
+
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$element_id' AND profile='$this->creportProfile'");
+ $row = mysqli_fetch_array($sql);
+ $vrstni_red = $row['vrstni_red'];
+
+ $sql = sisplet_query("DELETE FROM srv_custom_report WHERE ank_id='$this->ank_id' AND id='$element_id' AND profile='$this->creportProfile'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red-1, time_edit=NOW() WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND vrstni_red>'$vrstni_red' AND profile='$this->creportProfile'");
+
+ $this->displayReport();
+ }
+
+ // Editiranje elementa v reportu
+ if($_GET['a'] == 'edit_element'){
+
+ // Preklop na navaden tip (freq, sums, graf, desc)
+ if($what == 'type' && $value < 5){
+
+ $sql = sisplet_query("SELECT type FROM srv_custom_report WHERE ank_id='$this->ank_id' AND id='$element_id' AND profile='$this->creportProfile'");
+ $row = mysqli_fetch_array($sql);
+
+ // Ce preklapljamo iz crosstabov, meansov ali ttesta - resetiramo spremenljivke
+ if($row['type'] > 4){
+ $s = sisplet_query("UPDATE srv_custom_report SET $what='$value', spr1='', spr2='', time_edit=NOW() WHERE ank_id='$this->ank_id' AND id='$element_id' AND profile='$this->creportProfile'");
+ }
+ else{
+ $s = sisplet_query("UPDATE srv_custom_report SET $what='$value', time_edit=NOW() WHERE ank_id='$this->ank_id' AND id='$element_id' AND profile='$this->creportProfile'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ // Ce preklopimo na crosstabe, means ali ttest resetiramo vse spremenljivke
+ elseif($what == 'type' && $value > 4){
+ $s = sisplet_query("UPDATE srv_custom_report SET $what='$value', spr1='', spr2='', time_edit=NOW() WHERE ank_id='$this->ank_id' AND id='$element_id' AND profile='$this->creportProfile'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // Ostali preklopi
+ else{
+ $s = sisplet_query("UPDATE srv_custom_report SET $what='$value', time_edit=NOW() WHERE ank_id='$this->ank_id' AND id='$element_id' AND profile='$this->creportProfile'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+
+ $expanded = isset($_POST['expanded']) ? $_POST['expanded'] : 1;
+
+ $this->displayReportElement($element_id, $expanded);
+ }
+
+ if($_GET['a'] == 'copy_element'){
+
+ $sql = sisplet_query("SELECT * FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$element_id' AND profile='$this->creportProfile'");
+ $row = mysqli_fetch_array($sql);
+
+ // najprej prestevilcimo elemente ki so za kopiranim
+ $sql2 = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red+1 WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND vrstni_red>'$row[vrstni_red]' AND profile='$this->creportProfile'");
+
+ $vrstni_red = $row['vrstni_red'] + 1;
+
+ $sqlInsert = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, type, sub_type, spr1, spr2, text, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '$vrstni_red', '$row[type]', '$row[sub_type]', '$row[spr1]', '$row[spr2]', '$row[text]', '$row[profile]', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+
+ $this->displayReport();
+ }
+
+ // Sortiranje elementov
+ if($_GET['a'] == 'change_order'){
+
+ $sortable = $_POST['sortable'];
+ $exploded = explode('&', $sortable);
+
+ $i = 1;
+ foreach ($exploded AS $key) {
+ $key = str_replace('variabla_', '', $key);
+ $explode = explode('[]=', $key);
+
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red = '$i', time_edit = NOW() WHERE id = '$explode[1]' AND profile='$this->creportProfile'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i++;
+ }
+ }
+
+ // Alert pri dodajanju prvega
+ if($_GET['a'] == 'first_alert'){
+
+ echo $lang['srv_custom_report_first'];
+ /*Ozna�eni element (tabela/graf) se je prenesel v poro�ilo po meri, kjer lahko prilagajate prikaz in zaporedje elementov*/
+
+ echo '<a href="#" onClick="window.location = \''.$site_url.'admin/survey/index.php?anketa='.$this->ank_id.'&a=analysis&m=analysis_creport\';"><span style="display: block; padding-top: 10px;">'.$lang['srv_custom_report_link'].'</span></a>';
+
+ echo '<div class="buttons">';
+
+ //echo '<span class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_blue" href="#" onClick="window.location = \''.$site_url.'admin/survey/index.php?anketa='.$this->ank_id.'&a=analysis&m=analysis_creport\';"><span>'.$lang['srv_custom_report'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton" href="#" onClick="$(\'#fade\').fadeOut(\'slow\'); $(\'#custom_report_alert\').fadeOut();"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+
+ echo '</div>';
+ }
+
+ // razsiritev / skrcenje elementa
+ if($_GET['a'] == 'expand_element'){
+
+ if (isset ($_POST['expanded']))
+ $expanded = $_POST['expanded'];
+
+ $this->displayReportElement($element_id, $expanded);
+ }
+
+ // Dodajanje text elementa v report
+ if($_GET['a'] == 'add_text_element'){
+
+ // dodajanje vmes
+ if($element_id > 0){
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$element_id' AND profile='$this->creportProfile'");
+
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] + 1;
+
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red+1 WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND vrstni_red>='$vrstni_red' AND profile='$this->creportProfile'");
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, type, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '8', '$vrstni_red', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $el_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ //dodajanje na zacetku
+ elseif($element_id == -1){
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red+1 WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile'");
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, type, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '8', '1', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $el_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ // dodajanje na koncu
+ else{
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile' ORDER BY vrstni_red DESC");
+
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] + 1;
+ }
+ else
+ $vrstni_red = 1;
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, type, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '8', '$vrstni_red', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $el_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ $this->displayReport();
+
+ echo '<input type="hidden" el_id="'.$el_id.'" id="added_element" />';
+ }
+
+ // Dodajanje page breaka v report
+ if($_GET['a'] == 'add_pb_element'){
+
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND id='$element_id' AND profile='$this->creportProfile'");
+
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] + 1;
+
+ // Prestevilcimo elemente
+ $sql = sisplet_query("UPDATE srv_custom_report SET vrstni_red=vrstni_red+1 WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND vrstni_red>='$vrstni_red' AND profile='$this->creportProfile'");
+
+ $s = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, type, vrstni_red, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '-1', '$vrstni_red', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->displayReport();
+ }
+
+ // Urejanje naslova porocila
+ if($_GET['a'] == 'edit_title'){
+
+ $what = 'creport_title_profile_'.$this->creportProfile;
+
+ if($value != ''){
+ $s = sisplet_query("INSERT INTO srv_user_setting_for_survey (sid, uid, what, value) VALUES ('$this->ank_id', '$this->creportAuthor', '$what', '$value') ON DUPLICATE KEY UPDATE value='$value'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ else{
+ $s = sisplet_query("DELETE FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$this->creportAuthor' AND what='$what'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ // prikaz previewja
+ if($_GET['a'] == 'report_preview'){
+
+ echo '<h1 style="text-align: center; margin-top: 20px;">'.$lang['export_analisys_creport'].': '.SurveyInfo::getInstance()->getSurveyTitle().'</h1>';
+
+ $this->setUpReturnAsHtml(false);
+ $this->setUpIsForArchive(true);
+
+ $this->expanded = 1;
+
+ $this->displayReport();
+
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="window.close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ //echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="icons/icons/printer.png" alt="'.$lang['hour_print2'].'" vartical-align="middle" />'.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ }
+
+ // Alert pri dodajanju vseh elementov istega tipa v report
+ if($_GET['a'] == 'all_elements_alert'){
+
+ $type = (isset($_POST['type'])) ? $_POST['type'] : 0;
+
+ echo '<div style="margin-bottom: 10px;">'.$lang['srv_custom_report_comments_alert'.$type].'</div>';
+
+ echo '<div class="buttons">';
+
+ echo '<span class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton" href="#" onClick="$(\'#fade\').fadeOut(\'slow\'); $(\'#custom_report_alert\').fadeOut();"><span>'.$lang['srv_custom_report_alert_no'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onClick="addCustomReportAllElements(\''.$type.'\');"><span>'.$lang['srv_custom_report_alert_yes'].'</span></a></div></span>';
+
+ echo '</div>';
+ }
+
+ // Dodajanje vseh elementov istega tipa v report
+ if($_GET['a'] == 'all_elements_add'){
+
+ $type = (isset($_POST['type'])) ? $_POST['type'] : 0;
+
+ $sql = sisplet_query("SELECT MAX(vrstni_red) FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$this->creportAuthor' AND profile='$this->creportProfile'");
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['MAX(vrstni_red)'] + 1;
+ }
+ else
+ $vrstni_red = 1;
+
+
+ // Vstavljamo BREAK
+ if($type == 9){
+
+ // Ustvarimo instanco breaka
+ $this->classInstance = new SurveyBreak($this->ank_id);
+
+ $spr1 = (isset($_POST['spr1'])) ? $_POST['spr1'] : 0;
+ $spremenljivka = explode("-", $spr1);
+
+ $sub_type = (isset($_POST['sub_type'])) ? $_POST['sub_type'] : 0;
+
+ // Loop po odvisnih spremenljivkah in variablah
+ $variables = $this->getBreakDependentVariableList();
+ foreach ($variables as $variable) {
+
+ // Ce ne gre za disablan element in ne gre za isto spremenljivko kot spr1
+ if((int)$variable['canChoose'] == 1 && $variable['spr_id'] != $spremenljivka[1]){
+ $spr2 = $variable['sequence'].'-'.$variable['spr_id'].'-undefined';
+
+ // Vstavimo element v bazo
+ $sqlInsert = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, type, sub_type, spr1, spr2, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '$vrstni_red', '9', '$sub_type', '$spr1', '$spr2', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $vrstni_red++;
+ }
+ }
+ }
+
+ // Vstavljamo ostale osnove (sums, grafi, freq, desc)
+ else{
+ # preberemo header
+ foreach (SurveyAnalysis::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if ($spremenljivka['tip'] != 'm' && in_array($spremenljivka['tip'], SurveyAnalysis::$_FILTRED_TYPES )){
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+
+ // Ce ja kaksen veljaven oz ce prikazujemo tudi prazne
+ if(SurveyDataSettingProfiles :: getSetting('hideEmpty') != 1 || $only_valid > 0){
+ $sqlInsert = sisplet_query("INSERT INTO srv_custom_report (ank_id, usr_id, vrstni_red, type, spr1, profile, time_edit) VALUES('$this->ank_id', '$this->creportAuthor', '$vrstni_red', '$type', '$spid', '$this->creportProfile', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $vrstni_red++;
+ }
+ }
+ }
+ }
+
+ //$this->displayReport();
+ }
+
+ // Odpremo okno za izbiro/save profila
+ if($_GET['a'] == 'creport_show_profiles') {
+
+ $this->displaySettingsProfiles();
+ }
+
+ // Spreminjamo profil
+ if($_GET['a'] == 'creport_change_profile') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+
+ if (isset ($_POST['author']))
+ $author = $_POST['author'];
+
+ $this->creportProfile = $id;
+ $this->creportAuthor = $author;
+
+ $this->displaySettingsProfiles();
+ }
+
+ // preimenujemo profil
+ if($_GET['a'] == 'renameProfile') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+ if (isset ($_POST['name']))
+ $name = $_POST['name'];
+
+
+ // Default profil shranimo drugam ker ga ni v bazi (prevec komplikacij ker je bilo to naknadno delano)
+ if($id == 0){
+ $what = 'creport_default_profile_name';
+ $sql = sisplet_query("INSERT INTO srv_user_setting_for_survey (sid, uid, what, value) VALUES ('$this->ank_id', '$global_user_id', '$what', '$name') ON DUPLICATE KEY UPDATE value='$name'");
+ }
+ else
+ $sql = sisplet_query("UPDATE srv_custom_report_profiles SET name='$name' WHERE id='$id'");
+
+ $this->displaySettingsProfiles();
+ }
+
+ // pobrisemo profil
+ if($_GET['a'] == 'deleteProfile') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+
+ $sql = sisplet_query("DELETE FROM srv_custom_report_profiles WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id' AND id='$id'");
+
+ $sql = sisplet_query("DELETE FROM srv_custom_report WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id' AND profile='$id'");
+
+ $this->displaySettingsProfiles();
+ }
+
+ // shranimo kot nov profil
+ if($_GET['a'] == 'newProfile') {
+
+ if (isset ($_POST['name']))
+ $name = $_POST['name'];
+ if (isset ($_POST['comment']))
+ $comment = $_POST['comment'];
+
+ $sql = sisplet_query("INSERT INTO srv_custom_report_profiles (ank_id, usr_id, name, time_created) VALUES('$this->ank_id', '$global_user_id', '$name', NOW())");
+ $profile_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_creport_profile', $profile_id);
+ $this->creportProfile = $profile_id;
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_creport_author', $global_user_id);
+ $this->creportAuthor = $global_user_id;
+
+ // Dodamo se komentar porocila
+ $what = 'creport_comment_profile_'.$this->creportProfile;
+ if($comment != ''){
+ $s = sisplet_query("INSERT INTO srv_user_setting_for_survey (sid, uid, what, value) VALUES ('$this->ank_id', '$global_user_id', '$what', '$comment') ON DUPLICATE KEY UPDATE value='$comment'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ else{
+ $s = sisplet_query("DELETE FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$global_user_id' AND what='$what'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ //$this->displaySettingsProfiles();
+ }
+
+ // pozenemo izbran profil
+ if($_GET['a'] == 'use_creport_profile') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+
+ if (isset ($_POST['author']))
+ $author = $_POST['author'];
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_creport_profile', $id);
+ SurveyUserSetting :: getInstance()->saveSettings('default_creport_author', $author);
+
+ //$this->displayReport();
+ }
+
+ // urejanje komentarja profila
+ if($_GET['a'] == 'edit_profile_comment') {
+
+ $what = 'creport_comment_profile_'.$this->creportProfile;
+
+ if($value != ''){
+ $s = sisplet_query("INSERT INTO srv_user_setting_for_survey (sid, uid, what, value) VALUES ('$this->ank_id', '$global_user_id', '$what', '$value') ON DUPLICATE KEY UPDATE value='$value'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ else{
+ $s = sisplet_query("DELETE FROM srv_user_setting_for_survey WHERE sid='$this->ank_id' AND uid='$global_user_id' AND what='$what'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ // prikazemo deljenje profila z drugimi uredniki
+ if($_GET['a'] == 'shareProfileShow') {
+
+ echo '<span class="bold clr" style="display:block; margin-bottom:25px;">'.$lang['srv_custom_report_share_long'].':</span>'."\n";
+
+ if (isset ($_POST['id'])){
+ $id = $_POST['id'];
+
+ // Loop cez vse urednike ankete z dostopom do analiz
+ $d = new Dostop();
+ $users = $d->getUsersDostop();
+ foreach($users as $user){
+
+ if($user['id'] != $global_user_id){
+ $sql = sisplet_query("SELECT * FROM srv_custom_report_share WHERE ank_id='".$this->ank_id."' AND profile_id='".$id."' AND author_usr_id='".$global_user_id."' AND share_usr_id='".$user['id']."' LIMIT 1");
+ $checked = (mysqli_num_rows($sql) > 0) ? ' checked="checked"' : '';
+
+ echo '<input type="checkbox" '.$checked.' name="share_usr_id[]" id="share_usr_id'.$user['id'].'" value="'.$user['id'].'"> ';
+ echo '<label for="share_usr_id'.$user['id'].'">'.$user['email'].'</label><br />';
+ }
+ }
+ }
+
+ echo '<input id="shareCReportProfileId" type="hidden" value="' . $id . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="creport_profile_action(\'share\'); return false;"><span>'.$lang['srv_custom_report_share'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="creport_profile_action(\'cancel_share\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ }
+
+ // delimo profil z drugimi uredniki
+ if($_GET['a'] == 'shareProfile') {
+
+ if (isset ($_POST['id']) && isset ($_POST['users'])){
+ $id = $_POST['id'];
+ $users = $_POST['users'];
+
+ // Dodamo dostop ostalim urednikom za to porocilo
+ foreach($users as $user_id){
+ $sql = sisplet_query("INSERT INTO srv_custom_report_share
+ (ank_id, profile_id, author_usr_id, share_usr_id)
+ VALUES
+ ('".$this->ank_id."', '".$id."', '".$global_user_id."', '".$user_id."')");
+ }
+
+ // Pobrisemo dostop neoznacenim urednikom do tega porocila
+ $sql = sisplet_query("DELETE FROM srv_custom_report_share
+ WHERE ank_id='".$this->ank_id."' AND profile_id='".$id."' AND author_usr_id='".$global_user_id."' AND share_usr_id NOT IN (".implode(',', $users).")");
+ }
+ elseif(isset($_POST['id'])){
+ $id = $_POST['id'];
+
+ // Pobrisemo dostop vsem urednikom do tega porocila
+ $sql = sisplet_query("DELETE FROM srv_custom_report_share
+ WHERE ank_id='".$this->ank_id."' AND profile_id='".$id."' AND author_usr_id='".$global_user_id."'");
+ }
+
+ $this->displaySettingsProfiles();
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyDataSettingProfiles.php b/admin/survey/classes/class.SurveyDataSettingProfiles.php
new file mode 100644
index 0000000..5b48f41
--- /dev/null
+++ b/admin/survey/classes/class.SurveyDataSettingProfiles.php
@@ -0,0 +1,1442 @@
+<?php
+/**
+ * Created on 17.02.2011
+ *
+ * @author: Gorazd Veselič
+ */
+
+
+session_start();
+
+class SurveyDataSettingProfiles {
+
+ static private $surveyId = null;
+ static private $uId = null;
+
+ static private $currentProfileId = 0; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+
+ static private $analysisGoToArray = array( '0'=>M_ANALYSIS_CHARTS, '1'=>M_ANALYSIS_SUMMARY); # Kam gre analiza
+
+ static private $seperators = array( 0=>array('decimal_point'=>'.', 'thousands'=>','),
+ 1=>array('decimal_point'=>',', 'thousands'=>'.')); # Kako izpisujemo decimalke in tisočice
+ static private $defaultSeperator = 0; # privzete nastavitve
+
+ static public $spr_type = array('showCategories'=>Array(1,2,3,6,16,17), 'showNumbers'=>array(7,18,20,22,25), 'showText'=>array(4,5,8,19,21,26,27));
+
+ static public $textAnswersMore = array('0'=>'10','10'=>'30','30'=>'100','100'=>'300','300'=>'600','600'=>'900','900'=>'9999999');
+
+ static function getSurveyId() { return self::$surveyId; }
+ static function getGlobalUserId() { return self::$uId; }
+ static function getCurentProfileId() { return self::$currentProfileId; }
+
+
+ /** Inizializacija, poišče id privzetega profila in prebere vse profiel ki jih ima uporabnik na voljo
+ *
+ * @param $_surveyId
+ */
+ static function Init($_surveyId)
+ {
+
+ global $global_user_id, $lang;
+
+ if ($_surveyId && $global_user_id)
+ {
+ self::$surveyId = $_surveyId;
+ self::$uId = $global_user_id;
+
+ # inicializiramo datoteko z nastavitvami
+ SurveyUserSetting :: getInstance()->Init(self::$surveyId, self::$uId);
+
+ # preverimo ali ima uporabnik nastavljen privzet profil
+ $dsp = SurveyUserSetting :: getInstance()->getSettings('default_dataSettingProfile_profile');
+ if ($dsp == -1 || $dsp > 0 ) {
+ self::$currentProfileId = $dsp;
+ } else {
+ self::$currentProfileId = 0;
+ self::SetDefaultProfile(0);
+ }
+
+ #dodamo profil iz seje
+ if ( isset($_SESSION['dataSetting_profile'][self::$surveyId])) {
+ #dodamo profil iz seje
+ self::$profiles['-1'] = $_SESSION['dataSetting_profile'][self::$surveyId];
+ # ime damo iz lang fajla
+ self::$profiles['-1']['id'] = '-1';
+ self::$profiles['-1']['name'] =$lang['srv_temp_profile'];
+ } else if($dsp == -1 ) {
+ // #seja ne obstaja zato privzet profil popravimo na 0
+ $dsp = 0;
+ self::$currentProfileId = 0;
+ self::SetDefaultProfile(0);
+ }
+ #dodamo privzet sistemski profil
+ self::$profiles['0'] = array('id'=>0,
+ 'name'=>$lang['srv_default_profile1'],
+ 'dsp_ndp' => NUM_DIGIT_PERCENT, # stevilo digitalnih mest za odstotek
+ 'dsp_nda' => NUM_DIGIT_AVERAGE, # stevilo digitalnih mest za povprecje
+ 'dsp_ndd' => NUM_DIGIT_DEVIATION, # stevilo digitalnih mest za odklon
+ 'dsp_res' => NUM_DIGIT_RESIDUAL, # stevilo digitalnih mest za residual
+ 'dsp_sep' => self::$defaultSeperator, # privzet seperator
+ 'crossChk0' => '1', # izpis frekvenc
+ 'crossChk1' => '0', # izpis procentov po vrsticah
+ 'crossChk2' => '0', # izpis procentov po stolpcih
+ 'crossChk3' => '0', # izpis skupnih procentov
+ 'crossChkEC' => '0', # izpis skupnih procentov
+ 'crossChkRE' => '0', # izpis skupnih procentov
+ 'crossChkSR' => '0', # izpis skupnih procentov
+ 'crossChkAR' => '0', # izpis skupnih procentov
+ 'doColor' => '1', # barvanje celic
+ 'doValues' => '1', # prikaz vrednosti
+ 'showCategories' => '1', # prikaz kategorij
+ 'showOther' => '1', # prikaz polj drugo
+ 'showNumbers' => '1', # prikaz števil
+ 'showText' => '1', # prikaz tekstovnih odgovorov
+ 'chartNumbering' => '0', # ostevilcevanje grafov
+ 'chartFontSize' => '8', # velikost fonta grafov
+ 'chartFP' => '0', # izpis prve strani pri izvozu grafov (PDF/RTF)
+ 'chartTableAlign' => '0', # default poravnava tabel pri grafih (0->sredinska, 1->leva)
+ 'chartTableMore' => '0', # prikaz vseh textovnih odg. v tabelah (0->ne prikazi vseh, 1->vsi)
+ 'chartNumerusText' => '0', # pozicija numerusa
+ 'chartAvgText' => '1', # prikaz povprecja
+ 'chartPieZeros' => '0', # prikaz nicelnih vrednosti v kroznih grafih
+ 'hideEmpty' => '1', # skrivanje spremenljivke, ki nima veljavnih vnosov
+ 'hideAllSystem' => '0', # skrivanje vseh sistemskih spremenljivk
+ 'numOpenAnswers' => self::$textAnswersMore['10'], # koliko odprtih odgovorov prikažemo privzeto
+# 'enableInspect' => '0', # ali je Inspect vklopljen
+ 'dataPdfType' => '0', # način izpisa pdf - navaden, dolg, kratek pri izviozu podatkov v pdf/rtf
+ 'exportDataNumbering' => '1', # ostevilcevanje vprasanj pri izvozu ankete s podatki v pdf/rtf
+ 'exportDataShowIf' => '1', # prikaz if stavkov pri izvozu ankete s podatki v pdf/rtf
+ 'exportDataFontSize' => '10', # velikost fonta pri izvozu ankete spodatki v pdf/rtf
+ 'exportDataShowRecnum' => '1', # prikaz recnuma respondenta pri izvozu ankete s podatki v pdf/rtf
+ 'exportDataPB' => '0', # vsak respondent na svoji strani pri izvozu ankete s podatki v pdf/rtf
+ 'exportDataSkipEmpty' => '0', # izpusti vprasanja brez odgovora pri izvozu ankete s podatki v pdf/rtf
+ 'exportDataSkipEmptySub' => '0', # izpusti podvprasanja (multigridi) brez odgovora pri izvozu ankete s podatki v pdf/rtf
+ 'exportDataLandscape' => '0', # landscape postavitev pri izvozu ankete s podatki v pdf/rtf
+ 'exportNumbering' => '1', # ostevilcevanje vprasanj pri izvozu ankete v pdf/rtf
+ 'exportShowIf' => '1', # prikaz if stavkov pri izvozu ankete v pdf/rtf
+ 'exportFontSize' => '10', # velikost fonta pri izvozu ankete v pdf/rtf
+ 'exportShowIntro' => '0', # prikaz uvoda pri izvozu ankete v pdf/rtf
+ 'dataShowIcons' => '1', # ali prikazujemo ikone za urejanje pri podatkih
+ 'analysisGoTo' => '1', # Privzeto gremo na grafe
+ 'analiza_legenda' => '0', # Privzeto ne prikazujemo legende
+ );
+
+ # poiščemo še seznam vseh ostalih profilov uporabnika
+
+ $stringSelect = "SELECT * FROM srv_datasetting_profile WHERE uid = '".self::getGlobalUserId()."' || uid = '0' ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+ if(mysqli_num_rows($querySelect) > 0){
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = array( 'id'=>$rowSelect['id'],
+ 'name'=>$rowSelect['name'],
+ 'dsp_ndp' => $rowSelect['dsp_ndp'],
+ 'dsp_nda' => $rowSelect['dsp_nda'],
+ 'dsp_ndd' => $rowSelect['dsp_ndd'],
+ 'dsp_res' => $rowSelect['dsp_res'],
+ 'dsp_sep' => $rowSelect['dsp_sep'],
+ 'crossChk0' => 1, // $rowSelect['crossChk0'],
+ 'crossChk1' => $rowSelect['crossChk1'],
+ 'crossChk2' => $rowSelect['crossChk2'],
+ 'crossChk3' => $rowSelect['crossChk3'],
+ 'crossChkEC' => $rowSelect['crossChkEC'],
+ 'crossChkRE' => $rowSelect['crossChkRE'],
+ 'crossChkSR' => $rowSelect['crossChkSR'],
+ 'crossChkAR' => $rowSelect['crossChkAR'],
+ 'doColor' => $rowSelect['doColor'],
+ 'doValues' => $rowSelect['doValues'],
+ 'showCategories' => $rowSelect['showCategories'],
+ 'showOther' => $rowSelect['showOther'],
+ 'showNumbers' => $rowSelect['showNumbers'],
+ 'showText' => $rowSelect['showText'],
+ 'chartNumbering' => $rowSelect['chartNumbering'],
+ 'chartFontSize' => $rowSelect['chartFontSize'],
+ 'chartFP' => $rowSelect['chartFP'],
+ 'chartTableAlign' => $rowSelect['chartTableAlign'],
+ 'chartTableMore' => $rowSelect['chartTableMore'],
+ 'chartNumerusText' => $rowSelect['chartNumerusText'],
+ 'chartAvgText' => $rowSelect['chartAvgText'],
+ 'chartPieZeros' => $rowSelect['chartPieZeros'],
+ 'hideEmpty' => $rowSelect['hideEmpty'],
+ 'hideAllSystem' => $rowSelect['hideAllSystem'],
+ 'numOpenAnswers' => $rowSelect['numOpenAnswers'],
+ # 'enableInspect' => $rowSelect['enableInspect'],
+ 'dataPdfType' => $rowSelect['dataPdfType'],
+ 'exportDataNumbering' => $rowSelect['exportDataNumbering'],
+ 'exportDataShowIf' => $rowSelect['exportDataShowIf'],
+ 'exportDataFontSize' => $rowSelect['exportDataFontSize'],
+ 'exportDataShowRecnum' => $rowSelect['exportDataShowRecnum'],
+ 'exportDataPB' => $rowSelect['exportDataPB'],
+ 'exportDataSkipEmpty' => $rowSelect['exportDataSkipEmpty'],
+ 'exportDataSkipEmptySub' => $rowSelect['exportDataSkipEmptySub'],
+ 'exportDataLandscape' => $rowSelect['exportDataLandscape'],
+ 'exportNumbering' => $rowSelect['exportNumbering'],
+ 'exportShowIf' => $rowSelect['exportShowIf'],
+ 'exportFontSize' => $rowSelect['exportFontSize'],
+ 'exportShowIntro' => $rowSelect['exportShowIntro'],
+ 'dataShowIcons' => $rowSelect['dataShowIcons'],
+ 'analysisGoTo' => $rowSelect['analysisGoTo'],
+ 'analiza_legenda' => $rowSelect['analiza_legenda'],
+ );
+ }
+ }
+
+ # preverimo ali profil obstaja
+ if (!isset(self::$profiles[$dsp])) {
+ # če profil ne obstaja ga nastavimo na 0
+ $dsp = 0;
+ self::SetDefaultProfile($dsp);
+ }
+
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ /** Vrne podatke trenutno izbranega profofila
+ *
+ */
+ static function GetCurentProfileData() {
+ return self::$profiles[self::$currentProfileId];
+ }
+
+ /** Vrne podatke podanega profofila
+ *
+ */
+ static function GetProfileData($pid) {
+ return self::$profiles[$pid];
+ }
+
+ /** Pridobimo seznam vseh list uporabnika
+ * v obliki arraya
+ */
+ static function getProfiles() {
+ return self::$profiles;
+ }
+
+ /** Funkcija vrne posamezno nastavitev
+ *
+ */
+ static function getSetting($what = null) {
+
+ switch ($what){
+ case 'name' :
+ return self :: $profiles[self::$currentProfileId]['name'];
+ break;
+ case 'NUM_DIGIT_PERCENT' :
+ return self :: $profiles[self::$currentProfileId]['dsp_ndp'];
+ break;
+ case 'NUM_DIGIT_AVERAGE' :
+ return self :: $profiles[self::$currentProfileId]['dsp_nda'];
+ break;
+ case 'NUM_DIGIT_DEVIATION' :
+ return self :: $profiles[self::$currentProfileId]['dsp_ndd'];
+ break;
+ case 'NUM_DIGIT_RESIDUAL' :
+ return self :: $profiles[self::$currentProfileId]['dsp_res'];
+ break;
+ case 'decimal_point' :
+ return self::$seperators[self :: $profiles[self::$currentProfileId]['dsp_sep']]['decimal_point'];
+ break;
+ case 'thousands' :
+ return self::$seperators[self :: $profiles[self::$currentProfileId]['dsp_sep']]['thousands'];
+ break;
+ case 'showOther' :
+ return self::$profiles[self::$currentProfileId]['showOther'];
+ break;
+ case 'spr_types' :
+ $result = array();
+ #kategorije
+ if (self::$profiles[self::$currentProfileId]['showCategories']) {
+ $result = array_merge ($result, self::$spr_type['showCategories']);
+ }
+ #numbers
+ if (self::$profiles[self::$currentProfileId]['showNumbers']) {
+ $result = array_merge ($result, self::$spr_type['showNumbers']);
+ }
+ #text
+ if (self::$profiles[self::$currentProfileId]['showText']) {
+ $result = array_merge ($result, self::$spr_type['showText']);
+ }
+ return $result;
+ break;
+ case 'chartNumbering' :
+ return self::$profiles[self::$currentProfileId]['chartNumbering'];
+ break;
+ case 'chartFontSize' :
+ return self::$profiles[self::$currentProfileId]['chartFontSize'];
+ break;
+ case 'chartFP' :
+ return self::$profiles[self::$currentProfileId]['chartFP'];
+ break;
+ case 'chartTableAlign' :
+ return self::$profiles[self::$currentProfileId]['chartTableAlign'];
+ break;
+ case 'chartTableMore' :
+ return self::$profiles[self::$currentProfileId]['chartTableMore'];
+ break;
+ case 'chartNumerusText' :
+ return self::$profiles[self::$currentProfileId]['chartNumerusText'];
+ break;
+ case 'chartAvgText' :
+ return self::$profiles[self::$currentProfileId]['chartAvgText'];
+ break;
+ case 'chartPieZeros' :
+ return self::$profiles[self::$currentProfileId]['chartPieZeros'];
+ break;
+ case 'hideEmpty' :
+ return self::$profiles[self::$currentProfileId]['hideEmpty'];
+ break;
+ case 'hideAllSystem' :
+ return self::$profiles[self::$currentProfileId]['hideAllSystem'];
+ break;
+ case 'numOpenAnswers' :
+ return self::$profiles[self::$currentProfileId]['numOpenAnswers'];
+ break;
+# case 'enableInspect' :
+# return self::$profiles[self::$currentProfileId]['enableInspect'];
+# break;
+ case 'dataPdfType' :
+ return self::$profiles[self::$currentProfileId]['dataPdfType'];
+ break;
+ case 'exportDataNumbering' :
+ return self::$profiles[self::$currentProfileId]['exportDataNumbering'];
+ break;
+ case 'exportDataShowIf' :
+ return self::$profiles[self::$currentProfileId]['exportDataShowIf'];
+ break;
+ case 'exportDataFontSize' :
+ return self::$profiles[self::$currentProfileId]['exportDataFontSize'];
+ break;
+ case 'exportDataShowRecnum' :
+ return self::$profiles[self::$currentProfileId]['exportDataShowRecnum'];
+ break;
+ case 'exportDataPB' :
+ return self::$profiles[self::$currentProfileId]['exportDataPB'];
+ break;
+ case 'exportDataSkipEmpty' :
+ return self::$profiles[self::$currentProfileId]['exportDataSkipEmpty'];
+ break;
+ case 'exportDataSkipEmptySub' :
+ return self::$profiles[self::$currentProfileId]['exportDataSkipEmptySub'];
+ break;
+ case 'exportDataLandscape' :
+ return self::$profiles[self::$currentProfileId]['exportDataLandscape'];
+ break;
+ case 'exportNumbering' :
+ return self::$profiles[self::$currentProfileId]['exportNumbering'];
+ break;
+ case 'exportShowIf' :
+ return self::$profiles[self::$currentProfileId]['exportShowIf'];
+ break;
+ case 'exportFontSize' :
+ return self::$profiles[self::$currentProfileId]['exportFontSize'];
+ break;
+ case 'exportShowIntro' :
+ return self::$profiles[self::$currentProfileId]['exportShowIntro'];
+ break;
+ case 'dataShowIcons' :
+ session_start();
+ $dataIcons_quick_view = (isset($_SESSION['sid_'.self::$surveyId]['dataIcons_quick_view']) && $_SESSION['sid_'.self::$surveyId]['dataIcons_quick_view'] == false) ? false : true;
+ $dataIcons_write = (isset($_SESSION['sid_'.self::$surveyId]['dataIcons_write']) && $_SESSION['sid_'.self::$surveyId]['dataIcons_write'] == true) ? true : false;
+ $dataIcons_edit = (isset($_SESSION['sid_'.self::$surveyId]['dataIcons_edit']) && $_SESSION['sid_'.self::$surveyId]['dataIcons_edit'] == true) ? true: false;
+ $dataIcons_labels = (isset($_SESSION['sid_'.self::$surveyId]['dataIcons_labels']) && $_SESSION['sid_'.self::$surveyId]['dataIcons_labels'] == true) ? true: false;
+ $dataIcons_multiple = (isset($_SESSION['sid_'.self::$surveyId]['dataIcons_multiple']) && $_SESSION['sid_'.self::$surveyId]['dataIcons_multiple'] == true) ? true: false;
+ return array('dataIcons_edit' => $dataIcons_edit, 'dataIcons_write'=>$dataIcons_write, 'dataIcons_quick_view'=>$dataIcons_quick_view, 'dataIcons_labels'=>$dataIcons_labels, 'dataIcons_multiple'=>$dataIcons_multiple);
+ #return self::$profiles[self::$currentProfileId]['dataShowIcons'];
+ break;
+ case 'showCategories' :
+ return self::$profiles[self::$currentProfileId]['showCategories'];
+ break;
+ case 'analysisGoTo' :
+ return self::$analysisGoToArray[self::$profiles[self::$currentProfileId]['analysisGoTo']];
+ break;
+ case 'analiza_legenda' :
+ return (int)self::$profiles[self::$currentProfileId]['analiza_legenda'] == 1;
+ break;
+ case 'showNumbers' :
+ return self::$profiles[self::$currentProfileId]['showNumbers'];
+ break;
+ case 'showText' :
+ return self::$profiles[self::$currentProfileId]['showText'];
+ break;
+
+ default:
+ return self :: $profiles[self::$currentProfileId];
+ break;
+ }
+ }
+
+ /** Ponastavi id privzetega profila
+ *
+ */
+ static function SetDefaultProfile($pid) {
+ self::$currentProfileId = $pid;
+ $saved = SurveyUserSetting :: getInstance()->saveSettings('default_dataSettingProfile_profile',$pid);
+ }
+
+ static function SaveProfile($pid = 0) {
+ global $lang;
+
+ if ($pid==0)
+ $pid = -1;
+
+ # omejimo podatke
+ $dsp_ndp = (isset($_POST['dsp_ndp']) && (int)$_POST['dsp_ndp'] >= 0) ? $_POST['dsp_ndp'] : NUM_DIGIT_PERCENT;
+ $dsp_nda = (isset($_POST['dsp_nda']) && (int)$_POST['dsp_ndp'] >= 0) ? $_POST['dsp_nda'] : NUM_DIGIT_AVERAGE;
+ $dsp_ndd = (isset($_POST['dsp_ndd']) && (int)$_POST['dsp_ndp'] >= 0)? $_POST['dsp_ndd'] : NUM_DIGIT_DEVIATION;
+ $dsp_res = (isset($_POST['dsp_res']) && (int)$_POST['dsp_res'] >= 0)? $_POST['dsp_res'] : NUM_DIGIT_RESIDUAL;
+
+ $dsp_sep = isset($_POST['dsp_sep']) ? $_POST['dsp_sep'] : self::$defaultSeperator;
+
+ $crossChk0 = isset($_POST['crossChk0']) && $_POST['crossChk0'] == '1' ? '1' : '1'; // je vedno 1
+ $crossChk1 = isset($_POST['crossChk1']) && $_POST['crossChk1'] == '1' ? '1' : '0';
+
+ # odstranimo sejo za procent po odstotkih če je nastavljena
+ if (isset($_SESSION['crossChk1'])) {
+ unset($_SESSION['crossChk1']);
+ }
+
+ $crossChk2 = isset($_POST['crossChk2']) && $_POST['crossChk2'] == '1' ? '1' : '0';
+ $crossChk3 = isset($_POST['crossChk3']) && $_POST['crossChk3'] == '1' ? '1' : '0';
+ $crossChkEC = isset($_POST['crossChkEC']) && $_POST['crossChkEC'] == '1' ? '1' : '0';
+ $crossChkRE = isset($_POST['crossChkRE']) && $_POST['crossChkRE'] == '1' ? '1' : '0';
+ $crossChkSR = isset($_POST['crossChkSR']) && $_POST['crossChkSR'] == '1' ? '1' : '0';
+ $crossChkAR = isset($_POST['crossChkAR']) && $_POST['crossChkAR'] == '1' ? '1' : '0';
+ $doColor = isset($_POST['doColor']) && $_POST['doColor'] == '1' ? '1' : '0';
+ $doValues = isset($_POST['doValues']) && $_POST['doValues'] == '1' ? '1' : '0';
+ $showCategories = isset($_POST['showCategories']) && $_POST['showCategories'] == '1' ? '1' : '0';
+ $showOther = isset($_POST['showOther']) && $_POST['showOther'] == '1' ? '1' : '0';
+ $showNumbers = isset($_POST['showNumbers']) && $_POST['showNumbers'] == '1' ? '1' : '0';
+ $showText = isset($_POST['showText']) && $_POST['showText'] == '1' ? '1' : '0';
+ $chartNumbering = isset($_POST['chartNumbering']) && $_POST['chartNumbering'] == '1' ? '1' : '0';
+ $chartFontSize = isset($_POST['chartFontSize']) && (int)$_POST['chartFontSize'] > 0 ? (int)$_POST['chartFontSize'] : '0';
+ $chartFP = isset($_POST['chartFP']) && $_POST['chartFP'] == '1' ? '1' : '0';
+ $chartTableAlign = isset($_POST['chartTableAlign']) && $_POST['chartTableAlign'] == '1' ? '1' : '0';
+ $chartTableMore = isset($_POST['chartTableMore']) && $_POST['chartTableMore'] == '1' ? '1' : '0';
+ $chartNumerusText = isset($_POST['chartNumerusText']) && (int)$_POST['chartNumerusText'] > 0 ? (int)$_POST['chartNumerusText'] : '0';
+ $chartAvgText = isset($_POST['chartAvgText']) && (int)$_POST['chartAvgText'] > 0 ? (int)$_POST['chartAvgText'] : '0';
+ $chartPieZeros = isset($_POST['chartPieZeros']) && $_POST['chartPieZeros'] == '1' ? '1' : '0';
+ $hideEmpty = isset($_POST['hideEmpty']) && $_POST['hideEmpty'] == '1' ? '1' : '0';
+ $hideAllSystem = isset($_POST['hideAllSystem']) && $_POST['hideAllSystem'] == '1' ? '1' : '0';
+ $numOpenAnswers = isset($_POST['numOpenAnswers']) && (int)$_POST['numOpenAnswers'] > 0 ? (int)$_POST['numOpenAnswers'] : self::$textAnswersMore['10'];
+# $enableInspect = isset($_POST['enableInspect']) && $_POST['enableInspect'] == '1' ? '1' : '0';
+ $dataPdfType = isset($_POST['dataPdfType']) && (int)$_POST['dataPdfType'] > 0 ? (int)$_POST['dataPdfType'] : '0';
+ $exportDataNumbering = isset($_POST['exportDataNumbering']) && $_POST['exportDataNumbering'] == '1' ? '1' : '0';
+ $exportDataShowIf = isset($_POST['exportDataShowIf']) && $_POST['exportDataShowIf'] == '1' ? '1' : '0';
+ $exportDataFontSize = isset($_POST['exportDataFontSize']) && (int)$_POST['exportDataFontSize'] > 0 ? (int)$_POST['exportDataFontSize'] : '0';
+ $exportDataShowRecnum = isset($_POST['exportDataShowRecnum']) && $_POST['exportDataShowRecnum'] == '1' ? '1' : '0';
+ $exportDataPB = isset($_POST['exportDataPB']) && $_POST['exportDataPB'] == '1' ? '1' : '0';
+ $exportDataSkipEmpty = isset($_POST['exportDataSkipEmpty']) && $_POST['exportDataSkipEmpty'] == '1' ? '1' : '0';
+ $exportDataSkipEmptySub = isset($_POST['exportDataSkipEmptySub']) && $_POST['exportDataSkipEmptySub'] == '1' ? '1' : '0';
+ $exportDataLandscape = isset($_POST['exportDataLandscape']) && $_POST['exportDataLandscape'] == '1' ? '1' : '0';
+ $exportNumbering = isset($_POST['exportNumbering']) && $_POST['exportNumbering'] == '1' ? '1' : '0';
+ $exportShowIf = isset($_POST['exportShowIf']) && $_POST['exportShowIf'] == '1' ? '1' : '0';
+ $exportShowIntro = isset($_POST['exportShowIntro']) && $_POST['exportShowIntro'] == '1' ? '1' : '0';
+ $exportFontSize = isset($_POST['exportFontSize']) && (int)$_POST['exportFontSize'] > 0 ? (int)$_POST['exportFontSize'] : '0';
+ $dataShowIcons = isset($_POST['dataShowIcons']) && $_POST['dataShowIcons'] == '1' ? '1' : '0';
+ $analysisGoTo = isset($_POST['analysisGoTo']) && (int)$_POST['analysisGoTo'] != 1 ? (int)$_POST['analysisGoTo'] : '1';
+ $analiza_legenda = isset($_POST['analiza_legenda']) && $_POST['analiza_legenda'] == '1' ? '1' : '0';
+
+ $dsp_ndp = (int)$dsp_ndp > NUM_DIGIT_PERCENT_MAX ? NUM_DIGIT_PERCENT_MAX : $dsp_ndp;
+ $dsp_nda = (int)$dsp_nda > NUM_DIGIT_AVERAGE_MAX ? NUM_DIGIT_AVERAGE_MAX : $dsp_nda;
+ $dsp_ndd = (int)$dsp_ndd > NUM_DIGIT_DEVIATION_MAX ? NUM_DIGIT_DEVIATION_MAX : $dsp_ndd;
+ $dsp_res = (int)$dsp_res > NUM_DIGIT_RESIDUAL_MAX ? NUM_DIGIT_RESIDUAL_MAX : $dsp_res;
+
+
+ if ((int)$pid == 0 ) {
+ # imamo privzet profil
+ self :: SetDefaultProfile(0);
+ } else if ((int)$pid > 0) {
+ # shranimo v bazo
+
+ $updateString = "UPDATE srv_datasetting_profile SET dsp_ndp = '".$dsp_ndp."', dsp_nda = '".$dsp_nda."', dsp_ndd = '".$dsp_ndd."', dsp_res = '".$dsp_res."', dsp_sep = '".$dsp_sep.
+ "', crossChk0 = '".$crossChk0."', crossChk1 = '".$crossChk1."', crossChk2 = '".$crossChk2."', crossChk3 = '".$crossChk3."', crossChkEC = '".$crossChkEC."', crossChkRE = '".$crossChkRE."', crossChkSR = '".$crossChkSR."', crossChkAR = '".$crossChkAR."',"
+ ." doColor = '".$doColor."', doValues = '".$doValues."', showCategories = '".$showCategories."', showOther = '".$showOther."', showNumbers = '".$showNumbers."', showText = '".$showText."',"
+ ." chartNumbering = '".$chartNumbering."', chartFontSize = '".$chartFontSize."', chartFP = '".$chartFP."', chartTableAlign = '".$chartTableAlign."', chartTableMore = '".$chartTableMore."', chartNumerusText = '".$chartNumerusText."', chartAvgText = '".$chartAvgText."', chartPieZeros = '".$chartPieZeros."', hideEmpty = '".$hideEmpty."', hideAllSystem = '".$hideAllSystem."', numOpenAnswers='".$numOpenAnswers
+ #."', enableInspect='".$enableInspect
+ ."', dataPdfType='".$dataPdfType."', exportDataNumbering='".$exportDataNumbering."', exportDataShowIf='".$exportDataShowIf."', exportDataFontSize='".$exportDataFontSize."', exportDataShowRecnum='".$exportDataShowRecnum."', exportDataPB='".$exportDataPB."', exportDataSkipEmpty='".$exportDataSkipEmpty."', exportDataSkipEmptySub='".$exportDataSkipEmptySub."', exportDataLandscape='".$exportDataLandscape."',"
+ ." exportNumbering='".$exportNumbering."', exportShowIf='".$exportShowIf."', exportFontSize='".$exportFontSize."', exportShowIntro='".$exportShowIntro."',"
+ ." dataShowIcons='".$dataShowIcons."', analysisGoTo='".$analysisGoTo."', analiza_legenda='".$analiza_legenda."' WHERE id = '".$pid."'";
+ $updatequery = sisplet_query($updateString);
+ if (!$updatequery) echo mysqli_error($GLOBALS['connect_db']);
+
+ sisplet_query('COMMIT');
+ # nastavimo privzet profil na trenutnega
+ self :: SetDefaultProfile($pid);
+
+ } else {
+
+ # shranjujenmo v sejo
+ #self::$profiles[$pid]['starts'] = $startDate;
+
+# #shranimo nastavljene variable
+# $InspectListVars = $_SESSION['dataSetting_profile'][self::$surveyId]['InspectListVars'];
+
+ $_SESSION['dataSetting_profile'][self::$surveyId] = array('id'=>'-1',
+ 'name'=>$lang['srv_temp_profile'],
+ 'dsp_ndp' => $dsp_ndp,
+ 'dsp_nda' => $dsp_nda,
+ 'dsp_ndd' => $dsp_ndd,
+ 'dsp_res' => $dsp_res,
+ 'dsp_sep' => $dsp_sep,
+
+ 'crossChk0' => '1', // $crossChk0,
+ 'crossChk1' => $crossChk1,
+ 'crossChk2' => $crossChk2,
+ 'crossChk3' => $crossChk3,
+ 'crossChkEC' => $crossChkEC,
+ 'crossChkRE' => $crossChkRE,
+ 'crossChkSR' => $crossChkSR,
+ 'crossChkAR' => $crossChkAR,
+ 'doColor' => $doColor,
+ 'doValues' => $doValues,
+ 'showCategories' => $showCategories,
+ 'showOther' => $showOther,
+ 'showNumbers' => $showNumbers,
+ 'showText' => $showText,
+ 'chartNumbering' => $chartNumbering,
+ 'chartFontSize' => $chartFontSize,
+ 'chartFP' => $chartFP,
+ 'chartTableAlign' => $chartTableAlign,
+ 'chartTableMore' => $chartTableMore,
+ 'chartNumerusText' => $chartNumerusText,
+ 'chartAvgText' => $chartAvgText,
+ 'chartPieZeros' => $chartPieZeros,
+ 'hideEmpty' => $hideEmpty,
+ 'hideAllSystem' => $hideAllSystem,
+ 'numOpenAnswers' => $numOpenAnswers,
+# 'enableInspect' => $enableInspect,
+# 'InspectListVars' => $InspectListVars,
+ 'dataPdfType' => $dataPdfType,
+ 'exportDataNumbering' => $exportDataNumbering,
+ 'exportDataShowIf' => $exportDataShowIf,
+ 'exportDataFontSize' => $exportDataFontSize,
+ 'exportDataShowRecnum' => $exportDataShowRecnum,
+ 'exportDataPB' => $exportDataPB,
+ 'exportDataSkipEmpty' => $exportDataSkipEmpty,
+ 'exportDataSkipEmptySub' => $exportDataSkipEmptySub,
+ 'exportDataLandscape' => $exportDataLandscape,
+ 'exportNumbering' => $exportNumbering,
+ 'exportShowIf' => $exportShowIf,
+ 'exportFontSize' => $exportFontSize,
+ 'exportShowIntro' => $exportShowIntro,
+ 'dataShowIcons' => $dataShowIcons,
+ 'analysisGoTo' => $analysisGoTo,
+ 'analiza_legenda' => $analiza_legenda,
+ );
+
+ self :: SetDefaultProfile(-1);
+ }
+
+ return $updatequery;
+ }
+
+ static function RenameProfile($pid = 0, $name = '') {
+
+ if (isset($pid) && $pid > 0 && isset($name) && trim($name) != "") {
+ // popravimo podatek za variables
+ $stringUpdate = "UPDATE srv_datasetting_profile SET name = '".$name."' WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ sisplet_query('COMMIT');
+ return $updated;
+ } else {
+ return -1;
+ }
+ }
+
+ static function DeleteProfile($pid = 0) {
+ self :: SetDefaultProfile('0');
+ if (isset($pid) && $pid == -1) {
+ unset($_SESSION['dataSetting_profile'][self::$surveyId] );
+ } else if (isset($pid) && $pid > 0) {
+ // Izbrišemo profil in nastavimo privzetega
+ $stringUpdate = "DELETE FROM srv_datasetting_profile WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ sisplet_query('COMMIT');
+ }
+ # nastavimo privzet profil
+ self::SetDefaultProfile('0');
+ }
+
+
+ /** prikažemo dropdown z izbranim profilom in link do nastavitev profila
+ *
+ *
+ */
+ static function DisplayLink($hideAdvanced = true) {
+ global $lang;
+
+ $css = (self::$currentProfileId == SDS_DEFAULT_PROFILE ? ' gray' : '');
+
+ if ($hideAdvanced == false || self::$currentProfileId != SDS_DEFAULT_PROFILE) {
+ if ($_GET['a'] != 'data') {
+ # v podatkih imamo nastavitve na prvem mestum zato ne rišemo spejsrja
+ echo '<li class="space">&nbsp;</li>';
+ }
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="dsp_link" title="' . $lang['srv_dsp_link_title'] . '">' . $lang['srv_dsp_link'] . '</span>'."\n";
+ echo '</li>';
+
+ }
+ }
+
+ /** prikažemo dropdown z izbranim profilom in link do nastavitev profila
+ *
+ *
+ */
+ static function DisplayLinkDropdown() {
+ $profiles = self :: getProfiles();
+ $izbranProfil = self :: getCurentProfileId();
+ echo '<select id="dsp_dropdown" name="dsp_dropdown" onchange="dataSettingProfileAction(\'change_profile\'); return false;" >'."\n";
+ if (count($profiles) > 0){
+ foreach ($profiles as $key => $value) {
+ echo '<option' . ($izbranProfil == $value['id'] ? ' selected="selected"' : '') . ' value="' . $value['id'] . '">' . $value['name'] . '</option>'."\n";
+ }
+ }
+ echo '</select>'."\n";
+
+ }
+
+ /** Funkcija prikaze izbor datuma
+ *
+ */
+ static function displayProfiles($current_pid = null) {
+ global $lang;
+ $_all_profiles = self::getProfiles();
+
+ echo '<h2>'.$lang['srv_analiza_settings'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="dataSettingProfileAction(\'cancel\'); return false;">✕</a></div>';
+
+ if ($current_pid == null) {
+ $current_pid = self::getCurentProfileId();
+ }
+ $currentFilterProfile = $_all_profiles[$current_pid];
+ if ( self::$currentProfileId != SDS_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+ echo '<div id="dsp_profiles_left">';
+ echo '<span id="dsp_profiles_holder">';
+ # zlistamo vse profile
+ echo '<span id="dsp_profiles" class="select">';
+ if (count($_all_profiles)) {
+ foreach ($_all_profiles as $id=>$profile) {
+
+ echo '<div class="option' . ($current_pid == $id ? ' active' : '') . '" id="dataSetting_profile_' . $id . '" value="'.$id.'">';
+
+ echo $profile['name'];
+
+ if($current_pid == $id){
+ # sistemskega ne moremo izbrisati
+ if ($current_pid != 0) {
+ echo ' <a href="#" onclick="dataSettingProfileAction(\'show_delete\'); return false;" value="'.$lang['srv_delete_profile'].'"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'."\n";
+ }
+ # sistemskega in seje ne moremo preimenovati
+ if ($current_pid > 0) {
+ echo ' <a href="#" onclick="dataSettingProfileAction(\'show_rename\'); return false;" value="'.$lang['srv_rename_profile'].'"><span class="faicon edit floatRight spaceRight"></span></a>'."\n";
+ }
+ }
+
+ echo '</div>';
+ }
+ }
+ echo '</span>'; # dataSetting_profile
+ echo '</span>'; # dsp_profiles_holder
+
+ echo '</div>'; # dsp_profiles_left
+
+ echo '<div id="dsp_profiles_right">'."\n";
+ if ($current_pid == 0) {
+ echo '<div id="dsp_note">';
+ echo $lang['srv_change_default_profile'];
+ echo '</div>'; // dataSetting_profile_note
+ echo '<br class="clr" />'."\n";
+ }
+
+ echo '<div id="dsp_content">';
+ self::DisplayProfileData($current_pid);
+ echo '</div>'; // dataSetting_profile_content
+
+ echo '</div>'; // dataSetting_profile_right
+
+
+ echo '<div id="dsp_button_holder">'."\n";
+ if ((int)$current_pid <= 0 ) {
+ if ((int)$current_pid == 0) {
+ echo '<span class="floatRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="dataSettingProfileAction(\'run_profile\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ } else {
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="dataSettingProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ }
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'show_create\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ } else {
+ echo '<span class="floatRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="dataSettingProfileAction(\'run_profile\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'show_create\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ }
+ echo '</div>'."\n"; // dsp_button_holder
+
+
+ // cover Div
+ echo '<div id="dsp_cover_div"></div>'."\n";
+
+ // div za kreacijo novega
+ echo '<div id="newProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="newProfileName" name="newProfileName" type="text" value="" size="45" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="dataSettingProfileAction(\'do_create\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'cancel_create\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . $currentFilterProfile['name'] . '" size="45" />'."\n";
+ echo '<input id="renameProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="dataSettingProfileAction(\'do_rename\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'cancel_rename\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . $currentFilterProfile['name'] . '</b>?'."\n";
+ echo '<input id="deleteProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="dataSettingProfileAction(\'do_delete\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="dataSettingProfileAction(\'cancel_delete\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+ }
+
+ /** Funkcija prikaze osnovnih informacije profila
+ *
+ */
+ static function DisplayProfileData($current_pid=null) {
+ global $lang;
+
+ # podatki profila
+ if ($current_pid == null) {
+ $current_pid = self::$currentProfileId;
+ }
+ $cp = self::$profiles[$current_pid];
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_results_filter_settings'].'</legend>';
+
+ echo '<label><input id="showCategories" name="showCategories" type="checkbox" ' .
+ (($cp['showCategories']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_analiza_kategorialneSpremenljivke'];
+ echo '</label>';
+
+ echo '<label><input id="showOther" name="showOther" type="checkbox" ' .
+ (($cp['showOther']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ #(($cp['showCategories']) ? '' : ' disabled="disabled" ')
+ echo $lang['srv_analiza_ShowOthersText'] ;
+ echo '</label>';
+
+ echo '<label><input id="showNumbers" name="showNumbers" type="checkbox" ' .
+ (($cp['showNumbers']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_analiza_numericneSpremenljivke'];
+ echo '</label>';
+
+ echo '<label><input id="showText" name="showText" type="checkbox" ' .
+ (($cp['showText']) ? ' checked="checked" ' : ' ') . ' autocomplete="off"/>';
+ echo '</label>';
+
+ echo $lang['srv_analiza_textovneSpremenljivke'];
+
+ echo '<br />'.$lang['srv_analiza_link'].': ';
+ echo '<select id="analysisGoTo">';
+ echo '<option value="0"'.((int)$cp['analysisGoTo'] == 0 ? ' selected="selected"' : '').'>'.$lang['srv_analiza_charts'].'</option>';
+ echo '<option value="1"'.((int)$cp['analysisGoTo'] == 1 ? ' selected="selected"' : '').'>'.$lang['srv_sumarnik'].'</option>';
+ echo '</select>';
+
+ echo '<br/>';
+
+ echo '<label>';
+ echo '<input id="analiza_legenda" name="analiza_legenda" type="checkbox" ' .(($cp['analiza_legenda'] == '1') ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_analiza_showLegend'];
+ echo '</label>';
+
+ echo '<br/>';
+
+ echo '<label>';
+ echo '<input id="hideEmpty" name="hideEmpty" type="checkbox" ' .
+ (($cp['hideEmpty']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_analiza_hideEmpty'] ;
+ echo '</label>';
+
+ echo '<br/>';
+
+ echo '<label>';
+ echo '<input id="hideAllSystem" name="hideAllSystem" type="checkbox" ' .
+ (($cp['hideAllSystem']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_analiza_hideAllEmpty'] ;
+ echo '</label>';
+
+ echo '<br/>';
+
+ echo '<label>';
+ echo $lang['srv_analiza_defAnsCnt'].": ";
+ echo '<select id="numOpenAnswers" name="numOpenAnswers" autocomplete="off">';
+ $lastElement = end(self::$textAnswersMore);
+
+ foreach (self::$textAnswersMore AS $key => $values) {
+ echo '<option'.((int)$cp['numOpenAnswers'] == $values ? ' selected="selected"' : '').' value="'.$values.'">';
+ if ($values != $lastElement) {
+ echo $values;
+ } else {
+ echo $lang['srv_all'];
+ }
+ echo '</option>';
+ }
+ echo '</select>';
+ echo '</label>';
+
+ echo '</fieldset>';
+
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_results_base_settings'].'</legend>';
+ echo '<span class="dsp_sett_label">'.$lang['srv_results_num_digits'].'</span>';
+ echo '&nbsp;&nbsp;<span clsss="dsp_sett_label">'.$lang['srv_results_for_percents'].':&nbsp;</span><input type="text" id="dsp_ndp" name="dsp_ndp" value="'.$cp['dsp_ndp'].'" size="2" autocomplete="off">';
+ echo '&nbsp;&nbsp;<span class="dsp_sett_label">'.$lang['srv_results_for_average'].':&nbsp;</span><input type="text" id="dsp_nda" name="dsp_nda" value="'.$cp['dsp_nda'].'" size="2" autocomplete="off">';
+ echo '&nbsp;&nbsp;<span class="dsp_sett_label">'.$lang['srv_results_for_deviation'].':&nbsp;</span><input type="text" id="dsp_ndd" name="dsp_ndd" value="'.$cp['dsp_ndd'].'" size="2" autocomplete="off">';
+
+ echo '<br/>'.$lang['srv_results_decimal_sign'].': ';
+ foreach (self::$seperators AS $skey => $seperators) {
+ echo '<label>';
+ echo '<input type="radio" id="radio_dsp_sep_'.$skey.'" name="radio_dsp_sep" value="'.$skey.'"'.($cp['dsp_sep'] == $skey ? ' checked="checked"' : '').' autocomplete="off">';
+ echo self::formatNumber('1234.56',2,$seperators);
+ echo '</label>';
+ }
+ echo '</fieldset>';
+
+
+ // Nastavitve za crosstabe - prikazemo samo v crosstabih
+ echo '<fieldset '.(isset($_POST['podstran']) && $_POST['podstran'] == 'crosstabs' ? '' : ' style="display:none;"').'>';
+ echo '<legend>'.$lang['srv_results_crostabs_settings'].'</legend>';
+ echo '<span class="dsp_sett_label">'.$lang['srv_results_num_digits'].'</span>';
+ echo '&nbsp;&nbsp;<span clsss="dsp_sett_label">'.$lang['srv_results_for_residual'].':&nbsp;</span><input type="text" id="dsp_res" name="dsp_res" value="'.$cp['dsp_res'].'" size="2" autocomplete="off">';
+
+ echo '<div class="crossCheckHolder">' ;
+ echo '<div class="crossCheckHolder">' ;
+// echo '<input id="crossCheck0" name="crossCheck0" type="checkbox" ' . ($cp['crossChk0'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span name="spn_residual" class="ctbChck_sp0">' . $lang['srv_analiza_crosstab_frekvence'] . '</span><br />';
+ echo '<label>';
+ echo '<input id="crossCheck1" name="crossCheck1" type="checkbox" ' . ($cp['crossChk1'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_sp1" class="ctbChck_sp1">' . $lang['srv_analiza_crosstab_odstotek_vrstice'] . '</span><br />';
+ echo '</label>';
+ echo '<label>';
+ echo '<input id="crossCheck2" name="crossCheck2" type="checkbox" ' . ($cp['crossChk2'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_sp2" class="ctbChck_sp2">' . $lang['srv_analiza_crosstab_odstotek_stolpci'] . '</span><br />';
+ echo '</label>';
+ echo '<label>';
+ echo '<input id="crossCheck3" name="crossCheck3" type="checkbox" ' . ($cp['crossChk3'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_sp3" class="ctbChck_sp3">' . $lang['srv_analiza_crosstab_odstotek_skupni'] . '</span><br />';
+ echo '</label>';
+ echo '</div>';
+
+ echo '<div class="crossCheckHolder">' ;
+ echo '<label>';
+ echo '<input id="crossCheckEC" name="crossCheckEC" type="checkbox" ' . ($cp['crossChkEC'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_EC" class="crossCheck_EC">' . $lang['srv_analiza_crosstab_expected_count'] . '</span><br />';
+ echo '</label>';
+ echo '<label>';
+ echo '<input id="crossCheckRE" name="crossCheckRE" type="checkbox" ' . ($cp['crossChkRE'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_RE" class="crossCheck_RE">' . $lang['srv_analiza_crosstab_residual'] . '</span><br />';
+ echo '</label>';
+ echo '<label>';
+ echo '<input id="crossCheckSR" name="crossCheckSR" type="checkbox" ' . ($cp['crossChkSR'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_SR" class="crossCheck_SR">' . $lang['srv_analiza_crosstab_stnd_residual'] . '</span><br />';
+ echo '</label>';
+ echo '<label>';
+ echo '<input id="crossCheckAR" name="crossCheckAR" type="checkbox" ' . ($cp['crossChkAR'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span id="spn_residual_AR" class="crossCheck_AR">' . $lang['srv_analiza_crosstab_adjs_residual'] . '</span><br />';
+ echo '</label>';
+ echo '</div>';
+
+ echo '<div class="crossCheckHolder">' ;
+ echo '<label>';
+ echo '<input id="crossCheckColor" name="crossCheckColor" type="checkbox" ' . ($cp['doColor'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span class="crossCheckColor">' . $lang['srv_analiza_crosstab_color_residual1'] . '</span><br />';
+ echo '</label>';
+ echo '<label>';
+ echo '<input id="crossCheckValues" name="crossCheckValues" type="checkbox" ' . ($cp['doValues'] == true ? ' checked="checked" ' : '') . ' autocomplete="off"/><span class="crossCheckValues">' . $lang['srv_analiza_crosstab_doValues'] . '</span>';
+ echo '</label>';
+ /*
+ echo '<table id="tbl_color_ersidual" class="residual">';
+ echo '<tr><td>'.$lang['srv_analiza_crosstab_value'].'</td><th>+</th><th>-</th></tr>';
+ echo '<tr><td>1.1 - 2.0</td><td class="rsdl_bck1">&nbsp;</td><td class="rsdl_bck4">&nbsp;</td></tr>';
+ echo '<tr><td>2.1 - 3.0</td><td class="rsdl_bck2">&nbsp;</td><td class="rsdl_bck5">&nbsp;</td></tr>';
+ echo '<tr><td>3.1 '.$lang['srv_analiza_crosstab_and_more'].'</td><td class="rsdl_bck3">&nbsp;</td><td class="rsdl_bck6">&nbsp;</td></tr>';
+ echo '</table>';
+*/
+ echo '</div>';
+ echo '</div>';
+ echo '</fieldset>';
+
+
+ // Nastavitve za grafe
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_results_charts_settings'].'</legend>';
+
+ // default poravnava tabel
+ echo $lang['srv_chart_table_defAlign'].': ';
+ echo '<label>';
+ echo '<input type="radio" id="chartTableAlign_0" name="chartTableAlign" value="0"'.($cp['chartTableAlign'] == 0 ? ' checked="checked"' : '').' autocomplete="off">'.$lang['srv_chart_table_defAlign_0'];
+ echo '</label>';
+ echo '<label>';
+ echo '<input type="radio" id="chartTableAlign_1" name="chartTableAlign" value="1"'.($cp['chartTableAlign'] == 1 ? ' checked="checked"' : '').' autocomplete="off">'.$lang['srv_chart_table_defAlign_1'];
+ echo '</label>';
+ // velikost pisave v grafih
+ echo '<br /><label>' . $lang['srv_export_font'] . ': </label>';
+ echo '<select name="chartFontSize" id="chartFontSize" >';
+ echo ' <option value="8"'.((int)$cp['chartFontSize'] == 8 ? ' selected="selected"' : '').'>8</option>';
+ echo ' <option value="9"'.((int)$cp['chartFontSize'] == 9 ? ' selected="selected"' : '').'>9</option>';
+ echo ' <option value="10"'.((int)$cp['chartFontSize'] == 10 ? ' selected="selected"' : '').'>10</option>';
+ echo ' <option value="11"'.((int)$cp['chartFontSize'] == 11 ? ' selected="selected"' : '').'>11</option>';
+ echo ' <option value="12"'.((int)$cp['chartFontSize'] == 12 ? ' selected="selected"' : '').'>12</option>';
+ echo '</select>';
+
+ // prikaz texta ob numerusu
+ echo '<br /><label>' . $lang['srv_chart_numerusText'] . ': </label>';
+ echo '<select name="chartNumerusText" id="chartNumerusText" >';
+ echo ' <option value="0"'.((int)$cp['chartNumerusText'] == 0 ? ' selected="selected"' : '').'>' . $lang['srv_chart_numerusText_0'] . '</option>';
+ echo ' <option value="1"'.((int)$cp['chartNumerusText'] == 1 ? ' selected="selected"' : '').'>' . $lang['srv_chart_numerusText_1'] . '</option>';
+ echo ' <option value="2"'.((int)$cp['chartNumerusText'] == 2 ? ' selected="selected"' : '').'>' . $lang['srv_chart_numerusText_2'] . '</option>';
+ echo ' <option value="3"'.((int)$cp['chartNumerusText'] == 3 ? ' selected="selected"' : '').'>' . $lang['srv_chart_numerusText_3'] . '</option>';
+ echo ' <option value="4"'.((int)$cp['chartNumerusText'] == 4 ? ' selected="selected"' : '').'>' . $lang['without'] . '</option>';
+ echo '</select>';
+
+ // prikaz povprecja
+ echo '<br /><label>' . $lang['srv_chart_showAvg_long'] . ': </label>';
+ echo '<select name="chartAvgText" id="chartAvgText" >';
+ echo ' <option value="1"'.((int)$cp['chartAvgText'] == 1 ? ' selected="selected"' : '').'>' . $lang['yes'] . '</option>';
+ echo ' <option value="0"'.((int)$cp['chartAvgText'] == 0 ? ' selected="selected"' : '').'>' . $lang['no'] . '</option>';
+ echo '</select>';
+
+ // stevilcenje vprasanj
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="chartNumbering" name="chartNumbering" type="checkbox" ' .
+ (($cp['chartNumbering']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_nastavitveStevilcenje'];
+ echo '</label>';
+ // uvodna stran v izvozu
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="chartFP" name="chartFP" type="checkbox" ' .
+ (($cp['chartFP']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_chart_frontpage'] ;
+ echo '</label>';
+ // prikaz textovnih odgovorov (vec)
+ /*echo '<br />';
+ echo '<label>';
+ echo '<input id="chartTableMore" name="chartTableMore" type="checkbox" ' .
+ (($cp['chartTableMore']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_chart_table_more'] ;
+ echo '</label>';*/
+ // prikaz nicelnih vrednosti v kroznih grafih
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="chartPieZeros" name="chartPieZeros" type="checkbox" ' .
+ (($cp['chartPieZeros']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_chart_pieZeros'] ;
+ echo '</label>';
+ echo '</fieldset>';
+
+# echo '<label>'.$lang['srv_displaydata_showIcon'].'</label>';
+# echo '&nbsp;<input id="dataShowIcons0" name="dataShowIcons" type="radio" value="0"' .
+# (($cp['dataShowIcons'] != 1) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+# echo '<label for="dataShowIcons0">'.$lang['no'].'</label>';
+#
+# echo '&nbsp;<input id="dataShowIcons1" name="dataShowIcons" type="radio" value="1"' .
+# (($cp['dataShowIcons'] == 1) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+# echo '<label for="dataShowIcons1">'.$lang['yes'].'</label>';
+# echo '<br/>';
+
+
+ #Nastavitve za izvoz podatkov - PRESTAVLJENO V SPLOSNE NASTAVITVE ANKETE
+ /*echo '<fieldset style="width: 43%; float: left;">';
+ echo '<legend>'.$lang['srv_export_results_settings'].'</legend>';
+
+ echo '<label>' . $lang['srv_displaydata_type'] . ': </label>';
+ echo '<select name="dataPdfType" id="dataPdfType" >';
+ echo ' <option value="0"'.((int)$cp['dataPdfType'] == 0 ? ' selected="selected"' : '').'>' . $lang['srv_displaydata_type0'] . '</option>';
+ echo ' <option value="1"'.((int)$cp['dataPdfType'] == 1 ? ' selected="selected"' : '').'>' . $lang['srv_displaydata_type1'] . '</option>';
+ echo ' <option value="2"'.((int)$cp['dataPdfType'] == 2 ? ' selected="selected"' : '').'>' . $lang['srv_displaydata_type2'] . '</option>';
+ echo '</select>';
+ echo Help :: display('displaydata_pdftype');
+
+ // ostevilcevanje vprasanj pri izvozih
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataNumbering" name="exportDataNumbering" type="checkbox" ' .
+ (($cp['exportDataNumbering']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_nastavitveStevilcenje'];
+ echo '</label>';
+ // prikaz recnumov respondentov pri izvozih
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataShowRecnum" name="exportDataShowRecnum" type="checkbox" ' .
+ (($cp['exportDataShowRecnum']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_show_recnum'];
+ echo '</label>';
+ // page break med posameznimi respondenti
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataPB" name="exportDataPB" type="checkbox" ' .
+ (($cp['exportDataPB']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_pagebreak'];
+ echo '</label>';
+ // izpusti vprasanja brez odgovora
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataSkipEmpty" name="exportDataSkipEmpty" type="checkbox" ' .
+ (($cp['exportDataSkipEmpty']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_skip_empty'];
+ echo '</label>';
+ // izpusti podvprasanja brez odgovora
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataSkipEmptySub" name="exportDataSkipEmptySub" type="checkbox" ' .
+ (($cp['exportDataSkipEmptySub']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_skip_empty_sub'];
+ echo '</label>';
+ // landscape postavitev izvoza - V DELU
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataLandscape" name="exportDataLandscape" type="checkbox" ' .
+ (($cp['exportDataLandscape']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_landscape'];
+ echo '</label>';
+ // prikaz pogojev pri izvozih
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportDataShowIf" name="exportDataShowIf" type="checkbox" ' .
+ (($cp['exportDataShowIf']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_if'];
+ echo '</label>';
+ // velikost pisave v izvozih
+ echo '<br /><label>' . $lang['srv_export_font'] . ': </label>';
+ echo '<select name="exportDataFontSize" id="exportDataFontSize" >';
+ echo ' <option value="8"'.((int)$cp['exportDataFontSize'] == 8 ? ' selected="selected"' : '').'>8</option>';
+ echo ' <option value="10"'.((int)$cp['exportDataFontSize'] == 10 ? ' selected="selected"' : '').'>10</option>';
+ echo ' <option value="12"'.((int)$cp['exportDataFontSize'] == 12 ? ' selected="selected"' : '').'>12</option>';
+ echo '</select>';
+
+ echo '</fieldset>';
+
+
+ #Nastavitve za izvoz vprasalnika - PRESTAVLJENO V SPLOSNE NASTAVITVE ANKETE
+ echo '<fieldset style="width: 43%; float: right; margin-bottom: 40px;">';
+ echo '<legend>'.$lang['srv_export_survey_settings'].'</legend>';
+
+ // ostevilcevanje vprasanj pri izvozih
+ echo '<label>';
+ echo '<input id="exportNumbering" name="exportNumbering" type="checkbox" ' .
+ (($cp['exportNumbering']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_nastavitveStevilcenje'];
+ echo '</label>';
+ // prikaz pogojev pri izvozih
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportShowIf" name="exportShowIf" type="checkbox" ' .
+ (($cp['exportShowIf']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_if'];
+ echo '</label>';
+ // velikost pisave v izvozih
+ echo '<br /><label>' . $lang['srv_export_font'] . ': </label>';
+ echo '<select name="exportFontSize" id="exportFontSize" >';
+ echo ' <option value="8"'.((int)$cp['exportFontSize'] == 8 ? ' selected="selected"' : '').'>8</option>';
+ echo ' <option value="10"'.((int)$cp['exportFontSize'] == 10 ? ' selected="selected"' : '').'>10</option>';
+ echo ' <option value="12"'.((int)$cp['exportFontSize'] == 12 ? ' selected="selected"' : '').'>12</option>';
+ echo '</select>';
+
+ // prikaz uvoda pri izvozih
+ echo '<br />';
+ echo '<label>';
+ echo '<input id="exportShowIntro" name="exportShowIntro" type="checkbox" ' .
+ (($cp['exportShowIntro']) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_export_intro'];
+ echo '</label>';
+ echo '</fieldset>';*/
+
+ //echo '<span class="clr"></span>';
+ }
+
+ public static function ajax() {
+ switch ($_GET['a']) {
+ case 'showProfile':
+ self::displayProfiles($_POST['pid']);
+ break;
+ case 'createProfile':
+ self::createNewProfile();
+ break;
+ case 'changeProfile':
+ self::SetDefaultProfile($_POST['pid']);
+ # odstranimo sejo za procent po odstotkih če je nastavljena
+ if (isset($_SESSION['crossChk1'])) {
+ unset($_SESSION['crossChk1']);
+ }
+
+ break;
+ case 'renameProfile':
+ self::RenameProfile($_POST['pid'], $_POST['name']);
+ break;
+ case 'deleteProfile':
+ self::DeleteProfile($_POST['pid']);
+ break;
+ case 'saveProfile':
+ self::SaveProfile($_POST['pid']);
+ break;
+ case 'saveSingleProfileSetting':
+ self::SaveSingleProfileSetting();
+ break;
+ case 'saveResidualProfileSetting':
+ self::saveResidualProfileSetting();
+ break;
+ case 'refreshDropdown':
+ self::DisplayLinkDropdown();
+ break;
+/*
+ case 'show_inspectListSpr':
+ self::showInspectListSpr();
+ break;
+ case 'saveInspectListVars':
+ self::saveInspectListVars();
+ break;
+ case 'displayInspectVars':
+ self::displayInspectVars();
+ break;
+*/
+ case 'removeKategoriesProfile':
+ self::removeKategoriesProfile();
+ break;
+ case 'changeDataIcons':
+ self::changeDataIcons();
+ break;
+ case 'changeDataIconsSettings':
+ self::changeDataIconsSettings();
+ break;
+ case 'changeUsabilityIconsSettings':
+ self::changeUsabilityIconsSettings();
+ break;
+ case 'changeParaAnalysisGraphSettings':
+ self::changeParaAnalysisGraphSettings();
+ break;
+ default:
+ print_r("<pre>");
+ print_r($_POST);
+ print_r($_GET);
+ break;
+ }
+ }
+
+ /** Kreira nov profil
+ *
+ */
+ public static function createNewProfile() {
+ global $lang;
+
+ if ($_POST['profileName'] == null || trim($_POST['profileName']) == '' ) {
+ $_POST['profileName'] = $lang['srv_new_profile'];
+ }
+
+ $new_name = $_POST['profileName'];
+ $dsp_ndp = NUM_DIGIT_PERCENT;
+ $dsp_nda = NUM_DIGIT_AVERAGE;
+ $dsp_ndd = NUM_DIGIT_DEVIATION;
+ $dsp_res = NUM_DIGIT_RESIDUAL;
+
+ $dsp_sep = self::$defaultSeperator;
+
+ $crossChk0 = '1';
+ $crossChk1 = '1';
+ $crossChk2 = '0';
+ $crossChk3 = '0';
+ $crossChkEC = '0';
+ $crossChkRE = '0';
+ $crossChkSR = '0';
+ $crossChkAR = '0';
+ $doColor = '1';
+ $doValues = '1';
+ $showCategories = '1';
+ $showOther = '1';
+ $showNumbers = '1';
+ $showText = '1';
+ $chartNumbering = '0';
+ $chartFontSize = '8';
+ $chartFP = '0';
+ $chartTableAlign = '0';
+ $chartTableMore = '0';
+ $chartNumerusText = '0';
+ $chartAvgText = '1';
+ $chartPieZeros = '0';
+ $hideEmpty = '1';
+ $hideAllSystem = '0';
+ $numOpenAnswers = self::$textAnswersMore['10'];
+# $enableInspect = '0';
+ $dataPdfType = '0';
+ $exportDataNumbering = '1';
+ $exportDataShowIf = '1';
+ $exportDataFontSize = '10';
+ $exportDataShowRecnum = '1';
+ $exportDataPB = '0';
+ $exportDataSkipEmpty = '0';
+ $exportDataSkipEmptySub = '0';
+ $exportDataLandscape = '0';
+ $exportNumbering = '1';
+ $exportShowIf = '1';
+ $exportFontSize = '10';
+ $exportShowIntro = '0';
+ $dataShowIcons = '1';
+ $analysisGoTo = '1';
+ $analiza_legenda = '1';
+
+ # skreiramo profil z imenom in privzetimi nastavitvami
+ $iStr = "INSERT INTO srv_datasetting_profile (id,uid,name,dsp_ndp,dsp_nda,dsp_ndd,dsp_res,dsp_sep,
+ crossChk0,crossChk1,crossChk2,crossChk3,crossChkEC,crossChkRE,crossChkSR,crossChkAR,doColor,doValues,showCategories,showOther,showNumbers,showText,chartNumbering,chartFontSize,chartFP,chartTableAlign,chartTableMore,chartNumerusText,chartAvgText,chartPieZeros,hideEmpty,hideAllSystem,numOpenAnswers,dataPdfType,exportDataNumbering,exportDataShowIf,exportDataFontSize,exportDataShowRecnum,exportDataPB,exportDataSkipEmpty,exportDataSkipEmptySub,exportDataLandscape,exportNumbering,exportShowIf,exportFontSize,exportShowIntro,dataShowIcons,analysisGoTo,analiza_legenda)" # enableInspect,
+ ."VALUES (NULL, '".self::getGlobalUserId()."', '".$new_name."', '".$dsp_ndp."', '".$dsp_nda."', '".$dsp_ndd."', '".$dsp_res."', '".$dsp_sep
+ ."', '".$crossChk0."', '".$crossChk1."', '".$crossChk2."', '".$crossChk3."', '".$crossChkEC."', '".$crossChkRE."', '".$crossChkSR."', '".$crossChkAR."', '".$doColor."', '".$doValues."'"
+ .", '".$showCategories."', '".$showOther."', '".$showNumbers."', '".$showText."', '".$chartNumbering."', '".$chartFontSize."', '".$chartFP."', '".$chartTableAlign."', '".$chartTableMore."', '".$chartNumerusText."', '".$chartAvgText."', '".$chartPieZeros."', '".$hideEmpty."', '".$hideAllSystem."', '".$numOpenAnswers."', '".$dataPdfType."', '".$exportDataNumbering."', '".$exportDataShowIf."', '".$exportDataFontSize."', '".$exportDataShowRecnum."', '".$exportDataPB."', '".$exportDataSkipEmpty."', '".$exportDataSkipEmptySub."', '".$exportDataLandscape."'"
+ .", '".$exportNumbering."', '".$exportShowIf."', '".$exportFontSize."', '".$exportShowIntro."', '".$dataShowIcons."', '".$analysisGoTo."', '".$analiza_legenda."')"; #
+ $ins = sisplet_query($iStr);
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query('COMMIT');
+ if ($id > 0) {
+ self :: SetDefaultProfile($id);
+ } else {
+ $id = 0;
+ echo $iStr;
+ self :: SetDefaultProfile(0);
+ }
+ echo $id;
+ return $id;
+ }
+
+ static function formatNumber ($value, $digit = 0, $form=null) {
+
+ if (is_array($form) && isset($form['decimal_point'])&& isset($form['thousands'])) {
+ $decimal_point = $form['decimal_point'];
+ $thousands = $form['thousands'];
+ } else {
+ $decimal_point = self::$seperators[0]['decimal_point'];
+ $thousands = self::$seperators[0]['thousands'];
+ }
+
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ $result = number_format($result, $digit, $decimal_point, $thousands);
+
+ return $result;
+ }
+
+ static function getVariableTypeNote() {
+
+ if (SurveyDataSettingProfiles :: getSetting('showCategories') == 0
+ || SurveyDataSettingProfiles :: getSetting('showNumbers') == 0
+ || SurveyDataSettingProfiles :: getSetting('showOther') == 0
+ || SurveyDataSettingProfiles :: getSetting('showText') == 0) {
+
+ echo '<div id="variableTypeNote">Spremenljivke tipa: <strong>';
+ if (self :: getSetting('showCategories') == 0) {
+ echo $prefix.'kategorije';
+ $prefix=', ';
+ }
+ if (self :: getSetting('showNumbers') == 0) {
+ echo $prefix.'števila';
+ $prefix=', ';
+ }
+ if (self :: getSetting('showOther') == 0) {
+ echo $prefix.'drugo';
+ $prefix=', ';
+ }
+ if (self :: getSetting('showText') == 0) {
+ echo $prefix.'besedilo';
+ $prefix=', ';
+ }
+ echo '</strong> niso prikazane. ';
+ echo '<span id="link_variableType_profile_setup" class="as_link">Nastavi</span>';
+ echo '&nbsp;<span id="link_variableType_profile_remove" class="as_link">Odstrani</span>';
+ echo '</div>';
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ function removeKategoriesProfile() {
+
+ #$pid = $_POST['pid'];
+ $pid = self::$currentProfileId;
+ $p_data =self::GetProfileData($pid);
+
+ if ($pid == 0 ) {
+ # imamo privzet profil
+ } else if ($pid > 0) {
+ # shranimo v bazo
+ $updateString = "UPDATE srv_datasetting_profile SET showCategories = '1', showOther = '1', showNumbers = '1', showText = '1' WHERE id = '".$pid."'";
+ $updatequery = sisplet_query($updateString);
+ sisplet_query('COMMIT');
+ } else {
+ # shranjujenmo v sejo
+ $_SESSION['dataSetting_profile'][self::$surveyId] = array('id'=>'-1',
+ 'showCategories' => 1,
+ 'showOther' => 1,
+ 'showNumbers' => 1,
+ 'showText' => 1,
+ );
+ }
+ }
+
+ static function changeDataIcons() {
+ session_start();
+ if (isset($_POST['dataIcons_quick_view']) && $_POST['dataIcons_quick_view'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_quick_view'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_quick_view'] = false;
+ }
+ if (isset($_POST['dataIcons_write']) && $_POST['dataIcons_write'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_write'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_write'] = false;
+ }
+ if (isset($_POST['dataIcons_edit']) && $_POST['dataIcons_edit'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_edit'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_edit'] = false;
+ }
+ if (isset($_POST['dataIcons_labels']) && $_POST['dataIcons_labels'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_labels'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_labels'] = false;
+ }
+ if (isset($_POST['dataIcons_multiple']) && $_POST['dataIcons_multiple'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_multiple'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_multiple'] = false;
+ }
+ }
+
+ // TODO!!! Spodnje funkcije bi bilo smoterno združit
+ static function changeDataIconsSettings(){
+ session_start();
+
+ if (isset($_POST['dataIcons_settings'])){
+ if($_POST['dataIcons_settings'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_settings'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['dataIcons_settings'] = false;
+ }
+ session_commit();
+ }
+ }
+
+ static function changeUsabilityIconsSettings(){
+ session_start();
+
+ if (isset($_POST['usabilityIcons_settings'])){
+ if($_POST['usabilityIcons_settings'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['usabilityIcons_settings'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['usabilityIcons_settings'] = false;
+ }
+ session_commit();
+ }
+ }
+
+ static function changeParaAnalysisGraphSettings(){
+ session_start();
+
+ if (isset($_POST['paraAnalysisGraph_settings'])){
+ if($_POST['paraAnalysisGraph_settings'] == '1') {
+ $_SESSION['sid_'.self::$surveyId]['paraAnalysisGraph_settings'] = true;
+ } else {
+ $_SESSION['sid_'.self::$surveyId]['paraAnalysisGraph_settings'] = false;
+ }
+ session_commit();
+
+ }
+ }
+
+ // Shranimo stevilo odprtih odgovorov (izven profilov)
+ static function saveSingleProfileSetting() {
+ global $lang;
+
+ $pid = (isset($_POST['pid'])) ? $_POST['pid'] : -1;
+
+ if(isset($_POST['what']))
+ $what = $_POST['what'];
+
+ if(isset($_POST['value']))
+ $value = $_POST['value'];
+
+ # shranimo v bazo
+ if ((int)$pid > 0) {
+ $updateString = "UPDATE srv_datasetting_profile SET ".$what."='".$value."' WHERE id='".$pid."'";
+ $updatequery = sisplet_query($updateString);
+ if (!$updatequery) echo mysqli_error($GLOBALS['connect_db']);
+
+ sisplet_query('COMMIT');
+
+ # nastavimo privzet profil na trenutnega
+ self :: SetDefaultProfile($pid);
+ }
+ # shranjujenmo v sejo
+ else {
+ // Nastavimo vrednosti default profila, ker drugace default vrednosti niso ok
+ $_SESSION['dataSetting_profile'][self::$surveyId] = self::$profiles['0'];
+ $_SESSION['dataSetting_profile'][self::$surveyId]['id'] = '-1';
+ $_SESSION['dataSetting_profile'][self::$surveyId]['name'] = $lang['srv_temp_profile'];
+
+ // Nastavimo se spremenjeno nastavitev
+ $_SESSION['dataSetting_profile'][self::$surveyId][$what] = $value;
+
+ self :: SetDefaultProfile(-1);
+ }
+
+ return $updatequery;
+ }
+
+ // Shranimo residuale za crosstabe
+ static function saveResidualProfileSetting() {
+ global $lang;
+
+ $pid = (isset($_POST['pid'])) ? $_POST['pid'] : -1;
+
+ if(isset($_POST['value'])){
+ $crossCheckEC = $_POST['value'];
+ $crossCheckRE = $_POST['value'];
+ $crossCheckSR = $_POST['value'];
+ $crossCheckAR = $_POST['value'];
+ }
+
+ # shranimo v bazo
+ if ((int)$pid > 0) {
+ $updateString = "UPDATE srv_datasetting_profile SET crossChkEC='".$crossCheckEC."', crossChkRE='".$crossCheckRE."', crossChkSR='".$crossCheckSR."', crossChkAR='".$crossCheckAR."' WHERE id='".$pid."'";
+ $updatequery = sisplet_query($updateString);
+ if (!$updatequery) echo mysqli_error($GLOBALS['connect_db']);
+
+ sisplet_query('COMMIT');
+
+ # nastavimo privzet profil na trenutnega
+ self :: SetDefaultProfile($pid);
+ }
+ # shranjujenmo v sejo
+ else {
+ // Nastavimo vrednosti default profila, ker drugace default vrednosti niso ok
+ $_SESSION['dataSetting_profile'][self::$surveyId] = self::$profiles['0'];
+ $_SESSION['dataSetting_profile'][self::$surveyId]['id'] = '-1';
+ $_SESSION['dataSetting_profile'][self::$surveyId]['name'] = $lang['srv_temp_profile'];
+
+ // Nastavimo se spremenjeno nastavitev
+ $_SESSION['dataSetting_profile'][self::$surveyId]['crossChkEC'] = $crossCheckEC;
+ $_SESSION['dataSetting_profile'][self::$surveyId]['crossChkRE'] = $crossCheckRE;
+ $_SESSION['dataSetting_profile'][self::$surveyId]['crossChkSR'] = $crossCheckSR;
+ $_SESSION['dataSetting_profile'][self::$surveyId]['crossChkAR'] = $crossCheckAR;
+
+ self :: SetDefaultProfile(-1);
+ }
+
+ return $updatequery;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyDiagnostics.php b/admin/survey/classes/class.SurveyDiagnostics.php
new file mode 100644
index 0000000..9a8b01a
--- /dev/null
+++ b/admin/survey/classes/class.SurveyDiagnostics.php
@@ -0,0 +1,1044 @@
+<?php
+/** Class ki skrbi za diagnostiko ankete
+ * September 2011
+ *
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+if(session_id() == '') {session_start();}
+
+define("SPR_ON_PAGE_LIMIT", 8); # priporočeno število spremenljivk na stran
+define("SPR_IN_BLOCK_LIMIT", 15); # priporočeno število spremenljivk na blok
+define("SUB_Q_IN_GRID_LIMIT", 8); # priporočeno število podvprašanj na grid
+define("SPR_UNAPROPRIATE_START_LIMIT", 30); # koliko % spremenljivk preverjamo na pravilen začetek
+define("SPR_REMINDER_ON_MGRID_LIMIT", 10); # koliko % spremenljivk preverjamo na pravilen začetek
+define("TIME_SOFT_LIMIT", 120); # čas izpolnjevanja 2 minuti priporočilo
+define("TIME_HARD_LIMIT", 900); # čas izpolnjevanja 15 minut opozorilo
+
+
+
+define("DIAG_SPR_ON_PAGE", "DIAG_SPR_ON_PAGE"); # Zaznali smo preveč spremenljivk na stran
+define("DIAG_SPR_IN_BLOCK", "DIAG_SPR_IN_BLOCK"); # Zaznali smo preveč spremenljivk na blok
+define("DIAG_SUB_Q_IN_GRID", "DIAG_SUB_Q_IN_GRID"); # Zaznali smo preveč podvprašanj v gridu
+define("DIAG_REMINDER_ON_IF", "DIAG_REMINDER_ON_IF"); # Manjka reminder na spremenljvko na katero se sklicuje if
+define("DIAG_REMINDER_ON_MGRID", "DIAG_REMINDER_ON_MGRID"); # Reminder na spremenljvko z veliko podvprašanji
+define("DIAG_UNAPROPRIATE_START", "DIAG_UNAPROPRIATE_START"); # ali imamo na začetku ankete neprimerna vprašanja
+define("DIAG_INVALID_CONDITIONS", "DIAG_INVALID_CONDITIONS"); # Ali so napake v ifih
+define("DIAG_INVALID_VARIABLENAMES", "DIAG_INVALID_VARIABLENAMES"); # Ali so varable podvojene
+define("DIAG_INVALID_VALIDATIONS", "DIAG_INVALID_VALIDATIONS"); # Ali so napacne validacije na spremenljivkah
+define("DIAG_TIME_SOFT_LIMIT", "DIAG_TIME_SOFT_LIMIT"); # predolga anketa 1
+define("DIAG_TIME_HARD_LIMIT", "DIAG_TIME_HARD_LIMIT"); # predolga anketa 2
+
+class SurveyDiagnostics
+{
+ private $sid;
+ private $surveyInfo;
+
+ private $struktura = array(); # drevesna struktura vprašalnika
+ private $spremenljivke = array(); # array z spremenljivkami
+
+ private $struktura_spremenljivk = array(); # spremenljivke po vrsti
+ private $pages = array(); # vprašanja po straneh
+ private $blocks = array(); # vprašanja po blokih
+ private $conditions = array(); # ifi - pogoji
+
+ private $cnt_spremenljivka = 0; # število spremenljivk
+ private $cnt_hidden = 0; # število skritih spremenljivk
+ private $cnt_pages = 1; # število strani
+ private $cnt_blocks = 0; # število blokov
+ private $cnt_conditions = 0; # število ifov
+
+ private $time = array(); # predviden čas array('sekund', 'formatiran => min:sekund')
+ private $comments = array(); # komentarji array('vsi', 'nerazrešeni')
+
+ private $diagnostic_note = array ();
+
+
+ function __construct($sid) {
+ $this->sid = $sid;
+
+ SurveyInfo::SurveyInit($this->sid);
+ $this->surveyInfo = SurveyInfo::getSurveyRow();
+
+ # polovimo vsa vprašanja
+ $this->init();
+ }
+
+ function init() {
+
+ # naenkrat preberemo vse spremenljivke, da ne delamo queryja vsakic posebej
+ $this->spremenljivke = Cache::cache_all_srv_spremenljivka($this->sid, true);
+ # enako za srv_branching
+ Cache::cache_all_srv_branching($this->sid, true);
+ # cachiramo tudi srv_if
+ Cache::cache_all_srv_if($this->sid);
+
+ $this->createStructure();
+ $this->countHidden();
+ }
+
+ function getDiagnostic() {
+ return $this->diagnostic_note;
+ }
+
+ function ajax() {
+ if (isset($_REQUEST['a']) && trim($_REQUEST['a']) != '') {
+ $this->action($_REQUEST['a']);
+ } else {
+ echo 'Ajax error!';
+ return 'Ajax error!';
+ }
+ }
+
+ function action($action) {
+ switch ($action) {
+ default:
+ $this->showDiagnostics();
+ break;
+ }
+ }
+
+ function doDiagnostics() {
+ $this->testUnapropriateStart();
+ $this->testHardRremindersAndSubQ();
+ $this->testTooManyQuestions();
+ $this->testTime();
+ $this->testComments();
+ $this->testConditions();
+
+ }
+
+ function displayDiagnostic() {
+ global $lang;
+ global $site_url;
+
+ echo '<div id="srv_diagnostic">';
+
+ # damo obvestilo o diagnostiki
+ #print_r($this->diagnostic_note);
+
+ # opozorila:
+ # DIAG_SPR_ON_PAGE
+ # DIAG_SPR_IN_BLOCK
+ # DIAG_SUB_Q_IN_GRID
+ # DIAG_UNAPROPRIATE_START
+ $_opozorila = false;
+ if (in_array(DIAG_SPR_ON_PAGE, $this->diagnostic_note)
+ || in_array(DIAG_SPR_IN_BLOCK, $this->diagnostic_note)
+ || in_array(DIAG_SUB_Q_IN_GRID, $this->diagnostic_note)
+ || in_array(DIAG_UNAPROPRIATE_START, $this->diagnostic_note)
+ || in_array(DIAG_TIME_HARD_LIMIT, $this->diagnostic_note)) {
+ $_opozorila = true;
+ }
+
+ # priporočila:
+ # DIAG_REMINDER_ON_IF
+ # DIAG_REMINDER_ON_MGRID
+ $_pripombe = false;
+ if (in_array(DIAG_REMINDER_ON_IF, $this->diagnostic_note)
+ || in_array(DIAG_REMINDER_ON_MGRID, $this->diagnostic_note)
+ || in_array(DIAG_TIME_SOFT_LIMIT, $this->diagnostic_note)) {
+ $_pripombe = true;
+ }
+
+
+ echo '<span class="srv_diagnostic_note">';
+ echo $this->printNote();
+ #
+ echo '</span>';
+
+
+ SurveySetting::getInstance()->Init($this->anketa);
+ $preview_disableif = SurveySetting::getInstance()->getSurveyMiscSetting('preview_disableif');
+ $preview_disablealert = SurveySetting::getInstance()->getSurveyMiscSetting('preview_disablealert');
+ $preview_displayifs = SurveySetting::getInstance()->getSurveyMiscSetting('preview_displayifs');
+ $preview_displayvariables = SurveySetting::getInstance()->getSurveyMiscSetting('preview_displayvariables');
+ $preview_hidecomment = SurveySetting::getInstance()->getSurveyMiscSetting('preview_hidecomment');
+ $preview_options = ''.($preview_disableif==1?'&disableif=1':'').($preview_disablealert==1?'&disablealert=1':'').($preview_displayifs==1?'&displayifs=1':'').($preview_displayvariables==1?'&displayvariables=1':'').($preview_hidecomment==1?'&hidecomment=1':'').'';
+
+ echo '<br><div style="display:inline-block; margin: 0 0 10px 20px">';
+
+ echo '<span class="tooltip">';
+ echo '<a href="'.SurveyInfo::getSurveyLink().'&preview=on&testdata=on'.$preview_options.'" target="_blank" style="font-size:15px"><span class="faicon edit_square"></span> '.$lang['srv_survey_testdata'].'</a>';
+ echo ' ('.SurveyInfo::getSurveyLink().'&preview=on&testdata=on'.$preview_options.') ';
+ echo '<span class="expanded-tooltip bottom light" style="left: -40px;">';
+ echo '<b>' . $lang['srv_survey_testdata2'] . ':</b> '.$lang['srv_testdata_text'].'';
+ echo '<p>'.$lang['srv_preview_testdata_longtext'].'</p>';
+ echo '<span class="arrow"></span>';
+ echo '</span>'; // expanded-tooltip bottom
+ echo '</span>'; // tooltip
+
+ echo ' - <a href="#" id="popup-open" onclick="javascript:testiranje_preview_settings(); return false;" title="'.$lang['settings'].'"><span class="sprites settings"></span> '.$lang['srv_uredniske_nastavitve'].'</a>';
+ echo '</div>';
+
+ if ( isset($_GET['popup']) && $_GET['popup'] == 'open' ) {
+ ?><script> $(function() { $('#popup-open').click(); }); </script><?php
+ }
+
+ echo '<br/>';
+ # predviden čas ankete
+ list($total,$skupni_cas) = $this->time;
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations?from1ka=1" target="_blank">%s</a>';
+
+ list($commentsAll,$commentsUnresolved,$commentsQuestionAll,$commentsQuestionUnresolved,$commentsUser,$commentsUserFinished,$commentsUserSurveyAll,$commentsUserSurveyUnresolved) = $this->comments;
+
+ if ($total < 120) { # 2min
+ $time = $lang['srv_diagnostic_time_1'];
+ } else if ($total < 300) { # 5min
+ $time = $lang['srv_diagnostic_time_2'];
+ } else if ($total < 900) { # 15 min
+ $time = $lang['srv_diagnostic_time_3'];
+ } else if ($total < 1800) { # 30 min
+ $time = $lang['srv_diagnostic_time_4'];
+ } else { #> 30 min
+ $time = $lang['srv_diagnostic_time_5'];
+ }
+
+ # Kompleksnost
+ if ((int)($this->cnt_blocks + $this->cnt_conditions) == 0) {
+ $kompleksnost = $lang['srv_diagnostic_complexity_1'];
+ } else if ((int)($this->cnt_blocks + $this->cnt_conditions) == 1) {
+ $kompleksnost = $lang['srv_diagnostic_complexity_2'];
+ } else if ((int)($this->cnt_blocks + $this->cnt_conditions) < 10) {
+ $kompleksnost = $lang['srv_diagnostic_complexity_3'];
+ } else if ((int)($this->cnt_blocks + $this->cnt_conditions) < 50) {
+ $kompleksnost = $lang['srv_diagnostic_complexity_4'];
+ } else {
+ $kompleksnost = $lang['srv_diagnostic_complexity_5'];
+ }
+
+ #OPOZORILA
+ echo '<div class="floatLeft">';
+ echo '<div id="srv_diagnostic_results" >';
+ echo '<table class="srv_diagnostic_results">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_diagnostika_table_title1'].'</th>';
+ echo '<th>'.$lang['srv_diagnostika_table_title'].'</th>';
+ echo '</tr>';
+ #Preveč ali premalo opomnikov (reminder).
+
+ #Napake - v IFih, Zankah
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_5_element_1'].'</td>';
+ echo '<td>';
+
+ if (in_array(DIAG_INVALID_CONDITIONS,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-odkriti-logicne-tehnicne-napake-vprasalniku?from1ka=1" target="_blank">'.$lang['srv_diagnostic_neustreza1'].'</a>';
+ else
+ echo '<a href="https://www.1ka.si/d/en/help/faq/how-do-i-detect-logical-and-technical-errors-the-questionnaire?from1ka=1" target="_blank">'.$lang['srv_diagnostic_neustreza1'].'</a>';
+ echo '</span>';
+ }
+ else {
+ echo '<span class="green">';
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-odkriti-logicne-tehnicne-napake-vprasalniku?from1ka=1" target="_blank">'.$lang['srv_diagnostic_ustreza'].'</a>';
+ else
+ echo '<a href="https://www.1ka.si/d/en/help/faq/how-do-i-detect-logical-and-technical-errors-the-questionnaire?from1ka=1" target="_blank">'.$lang['srv_diagnostic_ustreza'].'</a>';
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ #Napake - v validacijah
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_5_element_3'].'</td>';
+ echo '<td>';
+
+ if (in_array(DIAG_INVALID_VALIDATIONS, $this->diagnostic_note)) {
+ echo '<span class="red">';
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-odkriti-logicne-tehnicne-napake-vprasalniku?from1ka=1" target="_blank">'.$lang['srv_diagnostic_neustreza1'].'</a>';
+ else
+ echo '<a href="https://www.1ka.si/d/en/help/faq/how-do-i-detect-logical-and-technical-errors-the-questionnaire?from1ka=1" target="_blank">'.$lang['srv_diagnostic_neustreza1'].'</a>';
+ echo '</span>';
+ }
+ else {
+ echo '<span class="green">';
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-odkriti-logicne-tehnicne-napake-vprasalniku?from1ka=1" target="_blank">'.$lang['srv_diagnostic_ustreza'].'</a>';
+ else
+ echo '<a href="https://www.1ka.si/d/en/help/faq/how-do-i-detect-logical-and-technical-errors-the-questionnaire?from1ka=1" target="_blank">'.$lang['srv_diagnostic_ustreza'].'</a>';
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ #napake - Podovojenost imen varianel
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_5_element_2'].'</td>';
+ echo '<td>';
+ if (in_array(DIAG_INVALID_VARIABLENAMES,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-odkriti-logicne-tehnicne-napake-vprasalniku?from1ka=1" target="_blank">'.$lang['srv_diagnostic_neustreza1'].'</a>';
+ else
+ echo '<a href="https://www.1ka.si/d/en/help/faq/how-do-i-detect-logical-and-technical-errors-the-questionnaire?from1ka=1" target="_blank">'.$lang['srv_diagnostic_neustreza1'].'</a>';
+ echo '</span>';
+ echo '<span>&nbsp;';
+ echo '<a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&checkDuplicate=1" title="'.$lang['srv_check_pogoji'].'"><span class="faicon bug"></span></a> '."\n";
+ echo '</span>';
+ }
+ else {
+ echo '<span class="green">';
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/pomoc/pogosta-vprasanja/kako-odkriti-logicne-tehnicne-napake-vprasalniku?from1ka=1" target="_blank">'.$lang['srv_diagnostic_ustreza'].'</a>';
+ else
+ echo '<a href="https://www.1ka.si/d/en/help/faq/how-do-i-detect-logical-and-technical-errors-the-questionnaire?from1ka=1" target="_blank">'.$lang['srv_diagnostic_ustreza'].'</a>';
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ echo '</table>';
+ echo '</div>';
+
+ echo '<br/><br/>';
+
+ echo '<div id="srv_diagnostic_results" >';
+ echo '<table class="srv_diagnostic_results">';
+# echo '<COLGROUP><COL width="50%"><COL><COL><COLGROUP>';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_diagnostika_table_title2'].'</th>';
+ echo '<th>'.$lang['srv_diagnostika_table_title'].'</th>';
+ echo '</tr>';
+
+ # Preveč podvprašanj na eni strani.
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_1_element_1'].'</td>';
+ echo '<td>';
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/prevec-podvprasanj-bloku-prevec-vprasanj-na-eni-strani?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/too-many-subquestions-block-and-too-many-questions-on-one-page?from1ka=1" target="_blank">%s</a>';
+
+ if (in_array(DIAG_SPR_ON_PAGE,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ printf($link,$lang['srv_diagnostic_neustreza2']);
+ echo '</span>';
+ }
+ else {
+ echo '<span class="green">';
+ printf($link,$lang['srv_diagnostic_ustreza']);
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ # Preveč vprašanj v bloku.
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_1_element_2'].'</td>';
+ echo '<td>';
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/premajhna-strukturiranost-vprasalnika?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/insufficiently-structured-questionnaire?from1ka=1" target="_blank">%s</a>';
+
+ if (in_array(DIAG_SPR_IN_BLOCK,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ printf($link,$lang['srv_diagnostic_neustreza2']);
+ echo '</span>';
+ } else {
+ echo '<span class="green">';
+ printf($link,$lang['srv_diagnostic_ustreza']);
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ # Preveč podpvprašanj v multigridu
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_1_element_3'].'</td>';
+ echo '<td>';
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/prevec-podvprasanj-bloku-prevec-vprasanj-na-eni-strani?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/too-many-subquestions-block-and-too-many-questions-on-one-page?from1ka=1" target="_blank">%s</a>';
+
+ if (in_array(DIAG_SUB_Q_IN_GRID,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ printf($link,$lang['srv_diagnostic_neustreza2']);
+ echo '</span>';
+ } else {
+ echo '<span class="green">';
+ printf($link,$lang['srv_diagnostic_ustreza']);
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ #Začetek ankete z neprimernimi vprašanji.
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_2_element_1'].'</td>';
+ echo '<td>';
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/zacetek-ankete-z-neprimernimi-vprasanji?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/beginning-the-survey-with-inappropriate-questions?from1ka=1" target="_blank">%s</a>';
+
+ if (in_array(DIAG_UNAPROPRIATE_START,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ printf($link,$lang['srv_diagnostic_neustreza2']);
+ echo '</span>';
+ } else {
+ echo '<span class="green">';
+ printf($link,$lang['srv_diagnostic_ustreza']);
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ # predolga anketa - opozorilo
+ if (in_array(DIAG_TIME_HARD_LIMIT,$this->diagnostic_note)) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_2_element_2'].'</td>';
+ echo '<td>';
+ echo '<span class="red">';
+
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/kako-dolga-naj-bo-moja-anketa?from1ka=1" target="_blank">';
+ else
+ echo '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/how-long-should-my-survey-be?from1ka=1" target="_blank">';
+
+ echo $lang['srv_diagnostic_neustreza'];
+ echo '</a>';
+ echo '</span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '</div>';
+
+ # PRIPOROČILA
+ echo '<br/><br/>';
+ echo '<div id="srv_diagnostic_results" >';
+ echo '<table class="srv_diagnostic_results">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_diagnostika_table_title3'].'</th>';
+ echo '<th>'.$lang['srv_diagnostika_table_title'].'</th>';
+ echo '</tr>';
+ #Preveč ali premalo opomnikov (reminder).
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_3_element_1'].'</td>';
+ echo '<td>';
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/prevec-ali-premalo-opomnikov?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/too-many-or-too-few-reminders?from1ka=1" target="_blank">%s</a>';
+
+ if (in_array(DIAG_REMINDER_ON_IF,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ printf($link,$lang['srv_diagnostic_neustreza']);
+ echo '</span>';
+ } else {
+ echo '<span class="green">';
+ printf($link,$lang['srv_diagnostic_ustreza']);
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_3_element_2'].'</td>';
+ echo '<td>';
+
+ if($lang['id'] == '1')
+ $link = '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/prevec-ali-premalo-opomnikov?from1ka=1" target="_blank">%s</a>';
+ else
+ $link = '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/too-many-or-too-few-reminders?from1ka=1" target="_blank">%s</a>';
+
+ if (in_array(DIAG_REMINDER_ON_MGRID,$this->diagnostic_note)) {
+ echo '<span class="red">';
+ printf($link,$lang['srv_diagnostic_neustreza']);
+ echo '</span>';
+ } else {
+ echo '<span class="green">';
+ printf($link,$lang['srv_diagnostic_ustreza']);
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ # predolga naketa - priporočilo
+ if (in_array(DIAG_TIME_SOFT_LIMIT,$this->diagnostic_note)) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_2_element_2'].'</td>';
+ echo '<td>';
+ echo '<span class="red">';
+
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/kako-dolga-naj-bo-moja-anketa?from1ka=1" target="_blank">';
+ else
+ echo '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/how-long-should-my-survey-be?from1ka=1" target="_blank">';
+
+ echo $lang['srv_diagnostic_neustreza'];
+ echo '</a>';
+ echo '</span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '</div>';
+ echo '</div>';
+
+
+ # Trajanje - linki
+ echo '<div id="srv_diagnostic_results_right">';
+ echo '<table class="srv_diagnostic_results">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_info_duration'].'</th>';
+ echo '<th></th>';
+ echo '<th></th>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_testiranje_predvidenicas'].'</td>';
+ echo '<td>'.$skupni_cas.'</td>';
+ echo '<td><a href="index.php?anketa=' . $this->sid . '&amp;a='.A_TESTIRANJE.'&amp;m=predvidenicas" title="'.$lang['srv_testiranje_predvidenicas'].'">'.$lang['details'].'</a></td>';
+ echo '</tr>';
+ $sas = new SurveyAdminSettings();
+ $dejanski_cas = ($sas->testiranje_cas(1) == null) ? '-' : $sas->testiranje_cas(1);
+ echo '<tr>';
+ echo '<td>'.$lang['srv_testiranje_cas'].'</td>';
+ echo '<td>'.$dejanski_cas.'</td>';
+ echo '<td><a href="index.php?anketa=' . $this->sid . '&amp;a='.A_TESTIRANJE.'&amp;m='.M_TESTIRANJE_CAS.'" title="'.$lang['srv_testiranje_cas'].'">'.$lang['details'].'</a></td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</div>';
+ echo '<br /><br />';
+
+
+ echo '<div id="srv_diagnostic_results_right">';
+ echo '<table class="srv_diagnostic_results">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_diagnostika_table_title4'].'</th>';
+ echo '<th colspan="2">'.$lang['srv_diagnostika_table_title'].'</th>';
+ echo '</tr>';
+ /*echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_1_element_0'].'</td>';
+ echo '<td colspan="2">'.$skupni_cas.'</td>';
+ echo '</tr>';*/
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_1_element_5'].'</td>';
+
+ echo '<td colspan="2">';
+
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/kako-dolga-naj-bo-moja-anketa?from1ka=1" target="_blank">';
+ else
+ echo '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/how-long-should-my-survey-be?from1ka=1" target="_blank">';
+
+ echo $time;
+ echo '</a>';
+# echo Help::display('srv_diag_time').'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_9'].'</td>';
+ echo '<td colspan="2">'.(int)SurveyInfo::getSurveyGroupCount().'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_5'].'</td>';
+ echo '<td colspan="2">'.(int)$this->cnt_spremenljivka.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_5a'].'</td>';
+ echo '<td colspan="2">'.(int)$this->cnt_hidden.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_8'].'</td>';
+ echo '<td colspan="2">'.(int)SurveyInfo::getSurveyVariableCount().'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_2'].'</td>';
+ echo '<td colspan="2">'.(int)$this->cnt_conditions.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_3'].'</td>';
+ echo '<td colspan="2">'.(int)$this->cnt_blocks.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_4'].'</td>';
+ echo '<td colspan="2">'.(int)$this->globina.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_1_element_4'].'</td>';
+ echo '<td colspan="2">';
+
+ if($lang['id'] == '1')
+ echo '<a href="https://www.1ka.si/d/sl/spletne-ankete/osnovna-priporocila/kaj-pomeni-kompleksnost-ankete?from1ka=1" target="_blank">';
+ else
+ echo '<a href="https://www.1ka.si/d/en/web-surveys/basic-recommendations/what-does-survey-complexity-mean?from1ka=1" target="_blank">';
+
+ echo $kompleksnost;
+ echo '</a>';
+ #echo Help::display('srv_diag_complexity').'</td>';
+ echo '</tr>';
+
+ echo '</table>';
+ echo '</div>';
+ echo '<br /><br />';
+
+
+ # nerazrešeni komentarji uporabnikov $commentsUser,$commentsUserFinished
+ $commentsUserUnresolved = $commentsUser - $commentsUserFinished;
+ if (( (int)$commentsAll
+ +(int)$commentsUnresolved
+ +(int)$commentsQuestionAll
+ +(int)$commentsQuestionUnresolved
+ +(int)$commentsUser
+ +(int)$commentsUserFinished
+ ) > 0 ) {
+ echo '<div id="srv_diagnostic_results_right">';
+ echo '<table class="srv_diagnostic_results">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_diagnostic_4_element_0'].'</th>';
+ echo '<th>'.$lang['srv_diagnostic_unresolved'].'</th>';
+ echo '<th>'.$lang['srv_diagnostic_all'].'</th>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_1'].'</td>';
+ echo '<td>'.(int)$commentsUnresolved.'</td>';
+ echo '<td>'.(int)$commentsAll.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_1a'].'</td>';
+ echo '<td>'.(int)$commentsUserSurveyUnresolved.'</td>';
+ echo '<td>'.(int)$commentsUserSurveyAll.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_6'].'</td>';
+ echo '<td>'.(int)$commentsQuestionUnresolved.'</td>';
+ echo '<td>'.(int)$commentsQuestionAll.'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_diagnostic_4_element_7'].'</td>';
+ echo '<td>'.(int)$commentsUserUnresolved.'</td>';
+ echo '<td>'.(int)$commentsUser.'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</div>';
+ }
+
+
+ echo '<br /><br />';
+ echo '</div>'; # id="srv_diagnostic"
+ }
+
+ /* Začetek ankete z neprimernimi vprašanji.
+ * Ni najbolje začeti z demografijo (razen v primeru specifičnih anket ali ko te podatke potrebujemo zaradi vejitev).
+ * Še slabše je začeti z občutljivim ali težkimi vprašanji.
+ * Prvo vprašanje mora namreč biti (a) enostavno, (b) prijazno in (c) zanimivo.
+ * Demografija (spol, starost, izobrazba ipd.) je običajno na koncu.
+ * Pri tem je treba posebej dobro razmisliti ali vsa ta vprašanja res potrebujemo.
+ * Pogosto sprašujemo npr. po regiji, čeprav je regija za naš problem irelevantna in na tej osnovi kasneje ne izvedemo nobene analize.
+ * Nepotrebno je tudi preveč podrobno spraševanje (npr. po starosti), če vemo, da nas v pogledu starosti zanima
+ * kvečjemu analiza treh večjih starostnih skupin (npr. do 30, 30-50, 50+) - v takem primeru zato tako tudi vprašamo.
+ * S tem se izognemo dodatnemu rekodiranju, hkrati pa seveda respondentom olajšamo odgovarjanje.
+ */
+ function testUnapropriateStart() {
+ global $lang;
+ #Preverimo ali se v prvh 30% vprašanj pojavi beseda spol, starost, izobrazba
+
+
+ $cnt = 0;
+ $_30_percent = $this->cnt_spremenljivka / (100 / SPR_UNAPROPRIATE_START_LIMIT);
+
+ $_bad_words = $lang['srv_diagnostic_bad_start_words'];# = array('spol', 'starost', 'rojstva', 'izobrazba', 'šola');
+
+ foreach ( $this->struktura_spremenljivk AS $key => $spr_id ) {
+ if ( !in_array(DIAG_UNAPROPRIATE_START,$this->diagnostic_note)
+ && $cnt < $_30_percent
+ && $cnt < 5) {
+ # preverimo ali se kje pojavijo demografska vprašanja
+ $naslov = trim($this->spremenljivke[$spr_id]['naslov']);
+ foreach ($_bad_words AS $bad_word) {
+ if( !in_array(DIAG_UNAPROPRIATE_START,$this->diagnostic_note)
+ && stristr($naslov, $bad_word) !== FALSE ) {
+ $this->diagnostic_note[] = DIAG_UNAPROPRIATE_START;
+ }
+ }
+
+ }
+ $cnt++;
+ }
+ }
+
+ /* Za pomembna vprašanja, npr. vprašanja na osnovi katerih temeljijo vejitve ali vprašanja,
+ * ki so bistvena za našo analizo, je smiselno nastaviti opozorilo, ki respondenta opozori na pomembnost odgovora.
+ * Le v zelo nujnih primerih pa respondentu tudi preprečimo nadaljevanje, če ne odgovori.
+ * Druga skrajnost so trdi opomniki za čisto vsako vprašanje, ki pa lahko odvrnejo respondenta od celotne ankete.
+ */
+ # Hkrati potestiramo še za preveč podvprašanj v gridu
+ /*Znano je, da respondenti zapuščajo anketo predvsem pri blokih vprašanj,
+ * kjer se npr. zahteva strinjanje z več trditvami. V enem bloku naj bo zato
+ * praviloma do največ 8-10 vprašanj, nakar se naredi nov blok z novim (krajšim)
+ * nagovorom.
+ */
+
+ function testHardRremindersAndSubQ() {
+ $_spr_reminders_checked = array();
+ # najprej preverimo ali imamo opomnike na vprašanja na katere se sklicujejo if-i
+ if ($this->cnt_conditions > 0) {
+ # zloopamo skozi pogoje
+ foreach ($this->conditions AS $iid => $condition) {
+
+ # zloopamo skozi posamezen pogoj
+ if ( !in_array(DIAG_REMINDER_ON_IF,$this->diagnostic_note)
+ && $condition > 0) {
+ $sql_condition_spr = Cache::srv_condition($condition);
+ while($row_condition_spr = mysqli_fetch_array($sql_condition_spr)) {
+ # za vako posamezno spremenljivko preverimo ali imamo kakšen reminder
+ # vsako spremenljivko preverimo samo 1x :)
+ if ( !in_array(DIAG_REMINDER_ON_IF,$this->diagnostic_note)
+ && !isset($_spr_reminders[$row_condition_spr['spr_id']])) {
+ if ((int)$this->spremenljivke[$row_condition_spr['spr_id']]['reminder'] == 0) {
+ $this->diagnostic_note[] = DIAG_REMINDER_ON_IF;
+ }
+
+ # zakeširamo spremenljivko, da ne gledamo večkrat
+ $_spr_reminders[$row_condition_spr['spr_id']] = true;
+ }
+ }
+ }
+ }
+ }
+
+ # preverimo še da nimamo remindejrev na vprašanja z ogromno odgovori. (multigrid > 10)
+ if ($this->cnt_spremenljivka > 0) {
+ foreach ($this->spremenljivke as $skey => $spremenljivka) {
+ # checkbox
+ if ( $spremenljivka['tip'] == 6 # m-radio
+ || $spremenljivka['tip'] == 16 # m-check
+ || $spremenljivka['tip'] == 19 # m-text
+ || $spremenljivka['tip'] == 20 # m-number
+ ) {
+ # Preštejemo variable
+ $sql_string = "SELECT count(*) AS cnt FROM srv_vrednost WHERE spr_id = '".$spremenljivka['id']."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ if ($spremenljivka['reminder'] == 2 && $sql_row['cnt'] >= SPR_REMINDER_ON_MGRID_LIMIT) {
+ # če še ni nastavljeno
+ if (!in_array(DIAG_REMINDER_ON_MGRID,$this->diagnostic_note)) {
+ $this->diagnostic_note[] = DIAG_REMINDER_ON_MGRID;
+ }
+ }
+ if ($sql_row['cnt'] > SUB_Q_IN_GRID_LIMIT) {
+ $this->diagnostic_note[] = DIAG_SUB_Q_IN_GRID;
+ }
+ }
+ }
+ }
+ }
+
+
+ /* Večinoma - razen redkih primerov - je tudi smiselno, da je na eni spletni
+ * strani v grobem toliko vprašanj, kolikor jih je možno videti na običajnem ekranu pri običajni
+ * ločljivosti. V tem smislu tudi sicer dajemo na eno stran toliko vprašanj, kot jih gre na ekran,
+ * vključno s prvo stranjo, kjer poskrbimo, da je gumb "NAPREJ" viden brez uporabe drsnika.
+ * Le izjemoma in z dobrimi razlogi se odločimo, da dajemo na eno stran več al celo vsa vprašanja,
+ * kar seveda zahteva od uporabnika da se z miško premika po strani. Podobno velja tudi za tudi vprašanja,
+ * ki se prikažejo šele ob pogoju - običajno jh postavimo na novo stran, le v primeru manjših podvprašanj
+ * sprožimo prikaz na isti strani.
+ */
+ function testTooManyQuestions() {
+ # preštejemo vprašanja na posamezni strani
+ foreach ($this->pages AS $pid => $page) {
+ if (count($page) > SPR_ON_PAGE_LIMIT) {
+ $this->diagnostic_note[] = DIAG_SPR_ON_PAGE;
+ }
+ }
+
+ # preštejemo vprašanja v posamezem bloku
+ foreach ($this->blocks AS $bid => $block) {
+ if (count($block) > SPR_IN_BLOCK_LIMIT) {
+ $this->diagnostic_note[] = DIAG_SPR_IN_BLOCK;
+ }
+ }
+ }
+
+ function testTime() {
+ $sas = new SurveyAdminSettings();
+ $total = $sas->testiranje_predvidenicas(2);
+ $this->time = array( $total,
+ (bcdiv($total, 60, 0)>0?bcdiv($total, 60, 0).'min ':'').''.round(bcmod($total, 60), 0).'s'
+ );
+
+ if ($total >= TIME_SOFT_LIMIT) {
+ if ($total <= TIME_HARD_LIMIT) {
+ $this->diagnostic_note[] = DIAG_TIME_SOFT_LIMIT;
+ } else {
+ $this->diagnostic_note[] = DIAG_TIME_HARD_LIMIT;
+ }
+ }
+ }
+
+ function testComments() {
+ $spr_id=array();
+ $threads=array();
+ if ( is_array($this->spremenljivke) && count($this->spremenljivke) > 0 ) {
+ foreach ($this->spremenljivke as $id=>$value) {
+ $spr_id[] = $id;
+ if ((int)$value['thread'] > 0) {
+ $threads[] = $value['thread'];
+ }
+ }
+ }
+ if (count($spr_id) > 0) {
+
+ $db_table = ($this->surveyInfo['db_table'] == 1) ? '_active' : '';
+
+ #preštejemo komentarje uporabnikov na vprašanja
+ # srv_data_text where spr_id = 0 AND vre_id IN (id-ji spremenljivk)
+ $strqr = "SELECT count(*) FROM srv_data_text".$db_table." WHERE spr_id=0 AND vre_id IN (".implode(',',$spr_id).")";
+ $sqlqr = sisplet_query($strqr);
+ list($rowqr) = mysqli_fetch_row($sqlqr);
+
+ #končani komentarji respondentov
+ #text2 = 2 => končan
+ #text2 = 3 => nerelevantno
+ $strqrf = "SELECT count(*) FROM srv_data_text".$db_table." WHERE spr_id=0 AND vre_id IN (".implode(',',$spr_id).") AND text2 IN (2,3)";
+ $sqlqrf = sisplet_query($strqrf);
+ list($rowqrf) = mysqli_fetch_row($sqlqrf);
+
+ # vsi komentarji na anketo
+ $strta = "SELECT count(*) FROM post WHERE tid='".$this->surveyInfo['thread']."' AND parent > 0";
+ $sqlta = sisplet_query($strta);
+ list($rowta) = mysqli_fetch_row($sqlta);
+
+ # nerešeni komentarji: only_unresolved => ocena <= 1
+ $strtu = "SELECT count(*) FROM post WHERE tid='".$this->surveyInfo['thread']."' AND parent > 0 AND ocena <= 1 ";
+ $sqltu = sisplet_query($strtu);
+ list($rowtu) = mysqli_fetch_row($sqltu);
+
+ # vsi komentarji na anketo respondentov
+ $strtar = "SELECT count(*) FROM srv_comment_resp WHERE ank_id='".$this->sid."'";
+ $sqltar = sisplet_query($strtar);
+ list($rowtar) = mysqli_fetch_row($sqltar);
+
+ # nerešeni komentarji respondentov na anketo: only_unresolved => ocena <= 1
+ $strtur = "SELECT count(*) FROM srv_comment_resp WHERE ank_id='".$this->sid."' AND ocena <= 1 ";
+ $sqltur = sisplet_query($strtur);
+ list($rowtur) = mysqli_fetch_row($sqltur);
+
+ $rowtqa = 0;
+ $rowtqu = 0;
+ # preštejemo
+ if (count($threads) > 0) {
+ # vsi komentarji na anketo
+ $strta = "SELECT count(*) FROM post WHERE tid IN (".implode(',',$threads).") AND parent > 0";
+ $sqlta = sisplet_query($strta);
+ list($rowtqa) = mysqli_fetch_row($sqlta);
+
+ # nerešeni komentarji: only_unresolved => ocena <= 1
+ $strtu = "SELECT count(*) FROM post WHERE tid IN (".implode(',',$threads).") AND parent > 0 AND ocena <= 1 ";
+ $sqltu = sisplet_query($strtu);
+ list($rowtqu) = mysqli_fetch_row($sqltu);
+
+ }
+ }
+ $this->comments = array($rowta,$rowtu,$rowtqa,$rowtqu,$rowqr,$rowqrf,$rowtar,$rowtur);
+ return $this->comments;
+ }
+
+ function testConditions() {
+ global $lang;
+ $code = true;
+
+ $b = new Branching($this->sid);
+ $code1 = $b->check_pogoji();
+
+ // ce je vse ok, preverimo se loope
+ $code2 = $b->check_loops();
+
+ if (($code1===true && $code2 === true ) !== true) {
+ $this->diagnostic_note[] = DIAG_INVALID_CONDITIONS;
+ }
+
+ $code4 = $b->check_validation();
+ if ($code4 !== true) {
+ $this->diagnostic_note[] = DIAG_INVALID_VALIDATIONS;
+ }
+
+ // preverimo podvojensot imen variabel
+ $code3 = $b->check_variable();
+ if ( $code3 !== true ) {
+ $this->diagnostic_note[] = DIAG_INVALID_VARIABLENAMES;
+ }
+ }
+
+
+ /** Skreiramo "postavitev" ankete
+ *
+ */
+ function createStructure() {
+ $parent = '0';
+ $this->struktura = $this->getInlineBranching($parent);
+
+ $this->spremenljivk = count($this->struktura_spremenljivk);
+
+ $this->globina = ArrayDepth($this->struktura)-1;
+
+ }
+
+ function countHidden() {
+ if (count($this->spremenljivke) > 0) {
+ foreach ($this->spremenljivke as $spremenljivka) {
+ if ((int)$spremenljivka['visible'] == 0) {
+ $this->cnt_hidden++;
+ }
+ }
+ }
+ }
+
+ function getInlineBranching($parent) {
+
+ $_elements_in_block = Cache::srv_branching_parent($this->sid, $parent);
+ $result = array();
+ foreach ($_elements_in_block AS $key => $_element) {
+ if ($_element['element_if'] > 0) {
+ # če je if in je tip 1 imamo nov blok
+ $_if = Cache::srv_if($_element['element_if']);
+ if ($_if['tip'] == 1) {
+ # če je tip = 1 imamo blok
+ $this->cnt_blocks++;
+
+ } else {
+ # preštejemo navane ife
+ $this->conditions[$this->cnt_conditions] = $_element['element_if'];
+ $this->cnt_conditions++;
+
+ }
+
+ array_push($result, $this->getInlineBranching($_element['element_if']));
+ } else {
+ array_push($result, $_element['element_spr']);
+
+ # dodamo vrstni red spremenljivk
+ $this->struktura_spremenljivk[$this->cnt_spremenljivka] = $_element['element_spr'];
+ $this->cnt_spremenljivka++;
+
+ # ločimo spremenljivke po straneh
+ $this->pages[$this->cnt_pages][] = $_element['element_spr'];
+ if ($_element['pagebreak'] == 1) {
+ $this->cnt_pages++;
+ }
+
+ # ločimo spremenljivke po blokih, nov blok je označen kot if - z posebnim tipom
+ $this->blocks[$this->cnt_blocks][] = $_element['element_spr'];
+ }
+
+ }
+ return $result;
+ }
+
+ function printNote($show_link = false) {
+ global $lang;
+
+ # napake
+ $_napake = (int)in_array(DIAG_INVALID_CONDITIONS, $this->diagnostic_note);
+ $_napake += (int)in_array(DIAG_INVALID_VARIABLENAMES, $this->diagnostic_note);
+
+ # priporočila:
+ # DIAG_SPR_ON_PAGE
+ # DIAG_SPR_IN_BLOCK
+ # DIAG_SUB_Q_IN_GRID
+ # DIAG_UNAPROPRIATE_START
+ $_opozorila = (int)in_array(DIAG_SPR_ON_PAGE, $this->diagnostic_note)
+ +(int)in_array(DIAG_SPR_IN_BLOCK, $this->diagnostic_note)
+ +(int)in_array(DIAG_SUB_Q_IN_GRID, $this->diagnostic_note)
+ +(int)in_array(DIAG_UNAPROPRIATE_START, $this->diagnostic_note)
+ +(int)in_array(DIAG_TIME_HARD_LIMIT, $this->diagnostic_note);
+
+ # opozorila:
+ # DIAG_REMINDER_ON_IF
+ # DIAG_REMINDER_ON_MGRID
+ $_priporocila = (int)in_array(DIAG_REMINDER_ON_IF, $this->diagnostic_note)
+ +(int)in_array(DIAG_REMINDER_ON_MGRID, $this->diagnostic_note)
+ +(int)in_array(DIAG_TIME_SOFT_LIMIT, $this->diagnostic_note);
+
+ #print_r($this->diagnostic_note);
+ #echo $lang['srv_diagnostic_note'].' '.$lang['srv_diagnostic_note_1'].' ';
+ echo $lang['srv_diagnostic_note_1'].' ';
+
+ //$_comments = ($this->comments[1] + $this->comments[3] + $this->comments[4] - $this->comments[5]);
+ $_comments_survey = ($this->comments[1] + $this->comments[7]);
+ $_comments_question = ($this->comments[3] + $this->comments[4] - $this->comments[5]);
+
+ if((int)$_napake > 0) echo '<a href="index.php?anketa='.$this->sid.'&a=testiranje">';
+ echo $this->string_format((int)$_napake,'srv_cnt_napake');
+ if((int)$_napake > 0) echo '</a>';
+
+ echo ', ';
+
+ if((int)$_opozorila > 0) echo '<a href="index.php?anketa='.$this->sid.'&a=testiranje">';
+ echo $this->string_format((int)$_opozorila,'srv_cnt_opozorila');
+ if((int)$_opozorila > 0) echo '</a>';
+
+ echo ', ';
+
+ if((int)$_priporocila > 0) echo '<a href="index.php?anketa='.$this->sid.'&a=testiranje">';
+ echo $this->string_format((int)$_priporocila,'srv_cnt_priporocila');
+ if((int)$_priporocila > 0) echo '</a>';
+
+ /*echo '</a> '.$lang['srv_and'].' <a href="index.php?anketa='.$this->sid.'&a=komentarji">';
+ echo $this->string_format((int)$_comments, 'srv_cnt_komentarji');
+ echo '</a>.';*/
+
+ echo ', ';
+
+ if((int)$_comments_survey > 0) echo '<a href="index.php?anketa='.$this->sid.'&a=komentarji_anketa">';
+ echo $this->string_format((int)$_comments_survey, 'srv_cnt_komentarji_survey');
+ if((int)$_comments_survey > 0) echo '</a>';
+
+ echo ' '.$lang['srv_and'].' ';
+
+ if((int)$_comments_question > 0) echo ' <a href="index.php?anketa='.$this->sid.'&a=komentarji">';
+ echo $this->string_format((int)$_comments_question, 'srv_cnt_komentarji_question');
+ if((int)$_comments_question > 0) echo '</a>';
+
+ echo '.';
+ }
+
+ function string_format($cnt,$lang_root) {
+ global $lang;
+
+ $txt = '';
+ if ($cnt > 0) $txt .= '<span class="red">';
+
+ if (isset($lang[$lang_root.'_'.$cnt])) {
+ $txt .= $cnt.' '.$lang[$lang_root.'_'.$cnt];
+ } else {
+ $txt .= $cnt.' '.$lang[$lang_root.'_more'];
+ }
+
+ if ($cnt > 0) $txt .= '</span>';
+
+ return $txt;
+ }
+}
+
+function ArrayDepth($Array,$DepthCount=-1) {
+// Find maximum depth of an array
+// Usage: int ArrayDepth( array $array )
+// returns integer with max depth
+// if Array is a string or an empty array it will return 0
+ $DepthArray=array(0);
+ $DepthCount++;
+
+ if (is_array($Array))
+ foreach ($Array as $Key => $Value) {
+ $DepthArray[]=ArrayDepth($Value,$DepthCount);
+ }
+ else
+ return $DepthCount;
+ return max($DepthCount,max($DepthArray));
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyExport.php b/admin/survey/classes/class.SurveyExport.php
new file mode 100644
index 0000000..89133dc
--- /dev/null
+++ b/admin/survey/classes/class.SurveyExport.php
@@ -0,0 +1,1465 @@
+<?php
+/**
+ * Created on Jun.2010
+ *
+ * @author: Gorazd Vesleič
+ *
+ * @desc: za izvoze
+ *
+ * funkcije:
+ * - Init() - inicializacija
+ *
+ */
+
+DEFINE (NEW_LINE, "\n");
+DEFINE (TMP_EXT, '.tmp');
+DEFINE (STR_DLMT, '|');
+DEFINE (DAT_EXT, '.dat');
+
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+
+class SurveyExport
+{
+ private $sid = null; // id ankete
+ private $folder = ''; # pot do folderja
+
+ private $inited = false; # ali smo razred inicializirali
+ private $SMV = false; # manjkajoče vrednosti
+
+ private $survey = null; # podatki ankete
+ private $db_table = ''; # ali se uporablja aktivna tabela
+
+ private $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ public $_FILTRED_VARIABLES = array(); # filter po spremenljivkah
+
+ # ali obstaja datoteka z podatki in ali je zadnja verzija
+ private $_fileStatus = FILE_STATUS_NO_DATA; # (FILE_STATUS_OK,FILE_STATUS_OLD,FILE_STATUS_NO_FILE,FILE_STATUS_NO_DATA)
+ private $_dataFileName = null; # ime obstoječe datoteke na FS.
+ private $_headFileName = null; # ime obstoječe datoteke na FS.
+
+ private $exportSettings = array();
+ private $_EXPORT_FULL_META = false; # ali izvažamo polne meta podatke
+ private $_EXPORT_HIDDEN_SYSTEM = false; # ali izvažamo sistemske podatke (email, telefon)
+ private $_EXPORT_ONLY_DATA = false; # ali izvažamo samo podatke brez parapodatkov
+
+ private $_EXPORT_SPSS_DATA = false; # ali izvažamo podatke za spsss
+ private $_EXPORT_SPSS_HEAD = true; # ali izvažamo header za spss
+ private $_EXPORT_EXCEL_HEAD = true; # ali izvažamo header za excel
+ private $_EXPORT_EXCEL_REPLACE = array(); # ali izvažamo zamenjave za excel
+
+ private $_SPECIAL_EXPORT = false; # samo za posebne primere kadar "moramo" izpisovati skrite sistemske variable (preko get se pošlje special_export=true
+
+ private $_HEADERS = array(); # array z header podatki
+
+ private $_FIELDS_ARRAY = array(); # array kamor shranimo polja katera za katera pobiramo podatke
+
+ private $_QUOTE = '"'; # Kateri zanko uporabimo za nize " ali '
+
+ private $_VARIABLE_FILTER = ''; # sed string array z prikazanimi variablami z upoštevanjem filtrov
+
+ private $_SVP_PV = array(); # array z prikazanimi variablami z upoštevanjem filtrov
+
+ /** Inicializacija
+ *
+ * @param $sid
+ */
+ public function Init($sid = null) {
+ global $admin_type, $lang, $site_path, $global_user_id;
+
+ if ($sid == null) {
+ die('Error! Missing survey Id');
+ }
+
+ $this->folder = $site_path . EXPORT_FOLDER.'/';
+
+ # nastavimo id ankete
+ $this->sid = $sid;
+
+ if (IS_WINDOWS) {
+ $this->_QUOTE = '"';
+ } else {
+ $this->_QUOTE = '\'';
+ }
+
+ # informacije ankete
+ SurveyInfo::getInstance()->SurveyInit($this->sid);
+ $this->survey = SurveyInfo::getInstance()->resetSurveyData();
+ $this->survey = SurveyInfo::getInstance()->getSurveyRow();
+
+ # aktivne tabele
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ // Preverimo ce ima user dostop
+ $d = new Dostop();
+ if(!$d->checkDostop($this->sid)){
+ die('Error! Access to survey '.$this->sid.' denied.');
+ }
+
+ # vsilimo podstran zaradi profila statusov
+ $_POST['podstran'] = A_COLLECT_DATA_EXPORT;
+
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+ # za profile statusov
+ SurveyStatusProfiles :: Init($this->sid);
+
+ # za profile variabel
+ SurveyVariablesProfiles :: Init($this->sid, $global_user_id);
+
+ # za profil ifov
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+
+ # za profil časov
+ SurveyTimeProfiles :: Init($this->sid, $global_user_id);
+
+
+ $result = sisplet_query ("SELECT value FROM misc WHERE what='SurveyExport'");
+ list ($SurveyExport) = mysqli_fetch_row ($result);
+ $adminTypes = array(0=>$lang['forum_admin'],1=>$lang['forum_manager'],2=>$lang['forum_clan'],3=>$lang['forum_registered'] );
+
+ if ($SurveyExport<$admin_type) {
+ die ($lang['srv_export_no_access'].$adminTypes[$admin_type]);
+ }
+ # manjkajoče vrednosti
+ $this->SMV = new SurveyMissingValues($this->sid);
+
+ #preverimo datoteke
+ self::checkFile();
+
+ self::setUpFilter();
+
+ self::getHeaderData(); # header podatke rabimo vedno
+ }
+
+ /** Naredimo izvoz
+ *
+ */
+ public function DoExport() {
+ # v odvisnosti kaj eksportiramo
+
+ switch ($_GET['m']) {
+ case 'sav':
+ self::exportSav();
+ break;
+ case 'spss':
+ self::exportSpss();
+ break;
+ case 'excel':
+ self::exportExcel();
+ break;
+ case 'excel_xls':
+ self::exportExcelXls();
+ break;
+ case 'txt':
+ self::exportText();
+ break;
+ }
+ }
+
+ /** Nastavimo filtre
+ *
+ */
+ private function setUpFilter() {
+
+ if ($this->_fileStatus >= 0) {
+
+ $this->_HEADERS = unserialize(file_get_contents($this->_headFileName));
+
+ $this->exportSettings = array();
+ foreach ($_SESSION AS $pkey => $pvalue)
+ {
+ // if starts with export
+ if (!strncmp($pkey, "export", strlen("export")))
+ {
+ #ali iz seje ali preko requesta
+ $this->exportSettings[ltrim($pkey, "{export}")] = $pvalue
+ || $_REQUEST[lcfirst($pvalue)];
+ }
+ }
+
+ $this->_EXPORT_HIDDEN_SYSTEM = ($this->exportSettings['HiddenSystem']) ? true : false;
+ $this->_EXPORT_HIDDEN_SYSTEM = ((int)$_REQUEST['hiddenSystem'] == 1 || $_REQUEST['hiddenSystem'] == 'true') ? true : $this->_EXPORT_HIDDEN_SYSTEM;
+
+ $this->_EXPORT_FULL_META = ($this->exportSettings['FullMeta'] || !$this->_EXPORT_HIDDEN_SYSTEM) ? true : false;
+ $this->_EXPORT_ONLY_DATA = ($this->exportSettings['OnlyData'] || !$this->_EXPORT_HIDDEN_SYSTEM) ? true : false;
+
+ $this->_SPECIAL_EXPORT = ($_REQUEST['special_export'] == 'true') ? true : false;
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # ali imamo filter na testne podatke
+ if (isset($this->_HEADERS['testdata']['grids'][0]['variables'][0]['sequence']) && (int)$this->_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'] > 0) {
+ $test_data_sequence = $this->_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'];
+ $filter_testdata = SurveyStatusProfiles :: getStatusTestAsAWKString($test_data_sequence);
+ }
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # ali imamo filter na uporabnost
+ if (isset($this->_HEADERS['usability']['variables'][0]['sequence']) && (int)$this->_HEADERS['usability']['variables'][0]['sequence'] > 0) {
+ $usability_data_sequence = $this->_HEADERS['usability']['variables'][0]['sequence'];
+ $filter_usability = SurveyStatusProfiles :: getStatusUsableAsAWKString($usability_data_sequence);
+ }
+
+ # dodamo še ife
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ || ($_time_profile_awk != "" && $_time_profile_awk != null)
+ || ($filter_testdata != null)
+ || ($filter_usability != null)) {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ $this->_CURRENT_STATUS_FILTER .= '&&'.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ $this->_CURRENT_STATUS_FILTER .= '&&'.$_time_profile_awk;
+ }
+ if ($filter_testdata != null ) {
+ $this->_CURRENT_STATUS_FILTER .= '&&('.$filter_testdata.')';
+ }
+ if ($filter_usability != null ) {
+ $this->_CURRENT_STATUS_FILTER .= '&&('.$filter_usability.')';
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+
+
+ # FILTRI VARIABEL - Katere variable ne izpisujemo
+ $svp_pv = array();
+ # ne prikazujemo user-idja
+ $not_svp_pv['uid'] = 'uid';
+
+ # ne prikazujemo recnumberja
+ //$not_svp_pv['recnum'] = 'recnum';
+
+ # ne prikazujemo meta podatkov
+ if ($this->_EXPORT_FULL_META == false) {
+ $not_svp_pv['meta'] = 'meta';
+ $not_svp_pv['recnum'] = 'recnum';
+ }
+
+ # filtriranje po spremenljivkah
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $this->_FILTRED_VARIABLES = SurveyVariablesProfiles :: getProfileVariables(SurveyVariablesProfiles :: checkDefaultProfile($dvp));
+
+ # skreiramo filter variabel za podatke
+ if (count($this->_HEADERS) > 0) {
+ // zloopamo skozi spremenljivke in sestavimo filter po stolpcih
+ $_tmp_filter = array();
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ # privzeto spremenljivke ne prikazujemo
+ $_can_show = false;
+ $tip = $spremenljivka['tip'];
+ # če spremenljivka ni v neprikazanih jo prikažemo
+ if (!in_array($spid, $not_svp_pv)) {
+ # če imamo sistemski email ali telefon, ime, priimek (v header je nastavljno "hide_system" = 1)
+ # potem v odvisnosti od nastavitve prikazujemo samo navadne podatke ali pa samo te sistemske, zaradizaščite podatkov
+ if ($this->_EXPORT_HIDDEN_SYSTEM == true && $spremenljivka['hide_system'] == '1' || $this->_SPECIAL_EXPORT == true) {
+ # prikazujemo sistemske, in spremenljivka je sistemska
+ $_can_show = true;
+ } else
+ if ( $this->_EXPORT_HIDDEN_SYSTEM == false && $spremenljivka['hide_system'] !== '1' ) {
+ # prikazujemo nesistemske, in spremenljivka ni sistemska
+ $_can_show = true;
+ }
+ }
+
+ if ($_can_show == true) {
+ # če mamo filter po variablah ga upoštevamo
+ if ( ( $tip == 'm' || $tip == 'sm' )
+ || ( count($this->_FILTRED_VARIABLES) == 0 || (count($this->_FILTRED_VARIABLES) > 0 && isset($this->_FILTRED_VARIABLES[$spid])) )
+ || ( $this->_EXPORT_HIDDEN_SYSTEM == true )
+ ){
+
+ $svp_pv[$spid] = $spid;
+ if (count($spremenljivka['grids']) > 0 ) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if (($tip !== 'sm' && $tip !== 'm') || $this->exportSettings['FullMeta'] > 0) {
+ $_tmp_filter[]= $variable['sequence'];
+ }
+ }
+ }
+ }
+ }
+
+ $spr_cont++;
+ }
+ }
+ }
+ }
+
+
+ # prilagodimo array profilov variabel
+ $this->_SVP_PV = $svp_pv;
+
+ if (count($_tmp_filter) > 0) {
+ $this->_VARIABLE_FILTER = implode(',',$_tmp_filter);
+ }
+
+ }
+
+ }
+
+ /** polovimo array z header podatki
+ *
+ */
+ function getHeaderData() {
+ if ($this->_headFileName != null && $this->_headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($this->_headFileName));
+ } else {
+ echo 'Error! Empty file name!';
+ }
+ }
+
+ /** naredimo izvoz za excel - xls
+ *
+ */
+ function exportExcelXls() {
+ global $site_path;
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ($this->_fileStatus >= 0 && $this->_dataFileName !== null && $this->_dataFileName !== '' && $this->_headFileName !== null && $this->_headFileName !== '') {
+
+ #zapišemo v temp file
+
+ $file_handler = fopen($this->_dataFileName.'.xls',"w");
+
+ $output1 = '';
+ $output2 = '';
+
+ # naredimo header row
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ if (isset($this->_SVP_PV[$spid])) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+ $output1 .= '<td>'.strip_tags($variable['variable']).'</td>';
+ $output2 .= '<td>'.strip_tags($variable['naslov']).'</td>';
+ }
+ }
+ }
+ }
+ }
+ fwrite($file_handler,$output1."\r\n");
+ fwrite($file_handler,$output2."\r\n");
+ fclose($file_handler);
+
+ # sfiltriramo podatke
+ exec ('awk -F'.$this->_QUOTE.STR_DLMT.$this->_QUOTE.' '.$this->_QUOTE.$this->_CURRENT_STATUS_FILTER.' {print $0}'.$this->_QUOTE.' '.$this->_dataFileName.' > '.$this->_dataFileName .'_data1'.TMP_EXT);
+ if (IS_WINDOWS) {
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d "|" -f '.$this->_VARIABLE_FILTER.' '.$this->_dataFileName .'_data1'.TMP_EXT.' > '.$this->_dataFileName .'_data1_1'.TMP_EXT;
+ } else {
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d \'|\' -f '.$this->_VARIABLE_FILTER.' '.$this->_dataFileName .'_data1'.TMP_EXT.' > '.$this->_dataFileName .'_data1_1'.TMP_EXT;
+ }
+ $out1_1 = shell_exec($cmdLn1_1);
+
+ # zamenjamo | z </td><td>
+ exec('sed '.$this->_QUOTE.'s/|/<\/td><td align="center">/g'.$this->_QUOTE.' '.$this->_dataFileName .'_data1_1'.TMP_EXT.' >> '.$this->_dataFileName.'.xls');
+
+ $convertType = 1; // kateri tip konvertiranja uporabimo
+ $convertTypes[1] = array('charSet' => "windows-1250",
+ 'delimit' => ";",
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+
+ # izvedemo download
+ if ($fd = fopen ($this->_dataFileName.'.xls', "r")) {
+ // clean the output buffer
+ ob_clean();
+
+ $fsize = filesize($this->_dataFileName.'.xls');
+ $path_parts = pathinfo($this->_dataFileName.'.xls');
+ $ext = strtolower($path_parts["extension"]);
+ header('Content-type: application/vnd.ms-excel; charset='.$convertTypes[$convertType]['charSet']);
+ header('Content-Disposition: attachment; filename="anketa'.$this->sid.'-'.date('Y-m-d').'.xls"');
+ # header('Content-length: '.$fsize);
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+ header('Content-Transfer-Encoding:­ binary');
+ ob_flush();
+
+ # dodami boomchar za utf-8
+ echo $convertTypes[$convertType]['BOMchar'];
+
+ // Izpisemo celo tabelo
+ echo '<table border="1">'."\r\n";
+ $cnt=0;
+ while ($line = fgets ($fd)) {
+
+ if($cnt > 1) echo '<tr><td align="center">';
+ else print('</tr>');
+
+ $line = str_replace(array("\r","\n"), array("",""), $line);
+ print($line);
+
+ if($cnt > 1) print('</td></tr>');
+ else print('</tr>');
+
+ print("\r\n");
+
+ $cnt++;
+ }
+ echo '</table>';
+ }
+ else {
+ echo "Napaka";
+ }
+
+ fclose ($fd);
+
+ #pobrišemo vse tmp datoteke
+ foreach (glob($folder . 'export_data_'.$this->sid.'_*'.TMP_EXT) as $fileToDelete) {
+ unlink($fileToDelete);
+ }
+ unlink ($this->_dataFileName.'.xls');
+
+ } else {
+ echo '';
+ }
+
+ exit;
+ }
+
+ /** naredimo izvoz za excel
+ *
+ */
+ function exportExcel() {
+ global $site_path;
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ session_start();
+
+ if ($this->_fileStatus >= 0 && $this->_dataFileName !== null && $this->_headFileName !== null) {
+
+ if ($_POST['export_delimit'] == 0) {
+ $field_delimit = ';';
+ $replace_what = $_POST['replace_what0'];
+ $replace_with = $_POST['replace_with0'];
+ } else {
+ $field_delimit = ',';
+ $replace_what = $_POST['replace_what1'];
+ $replace_with = $_POST['replace_with1'];
+ }
+
+ #zapišemo v temp file
+ $file_handler = fopen($this->_dataFileName.'.csv',"w");
+
+ $output1 = '';
+ $output2 = '';
+
+
+ fclose($file_handler);
+
+
+ # sfiltriramo podatke
+ exec ('awk -F'.$this->_QUOTE.STR_DLMT.$this->_QUOTE.' '.$this->_QUOTE.$this->_CURRENT_STATUS_FILTER.' {print $0}'.$this->_QUOTE.' '.$this->_dataFileName.' > '.$this->_dataFileName .'_data1'.TMP_EXT);
+
+ if (IS_WINDOWS) {
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d "|" -f '.$this->_VARIABLE_FILTER.' '.$this->_dataFileName .'_data1'.TMP_EXT.' > '.$this->_dataFileName .'_data1_1'.TMP_EXT;
+ } else {
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d \'|\' -f '.$this->_VARIABLE_FILTER.' '.$this->_dataFileName .'_data1'.TMP_EXT.' > '.$this->_dataFileName .'_data1_1'.TMP_EXT;
+ }
+ $out1_1 = shell_exec($cmdLn1_1);
+
+ # zamenjamo uporabniške znake
+ if (is_array($replace_what) && count($replace_what) > 0 && is_array($replace_with) && count($replace_with) > 0) {
+ $_new_filename = '_data1_1';
+ $cnt_replace = min(count($replace_what),count($replace_with));
+ for ($i = 0; $i < $cnt_replace; $i++) {
+ exec('sed '.$this->_QUOTE .'s/'.$replace_what[$i].'/'.$replace_with[$i].'/g'.$this->_QUOTE .' '.$this->_dataFileName .'_data1_'.($i+1).TMP_EXT.' > '.$this->_dataFileName .'_data1_'.($i+2).TMP_EXT);
+ $_new_filename = '_data1_'.($i+2);
+ }
+
+ } else {
+ $_new_filename = '_data1_1';
+ }
+
+ # zamenjamo | z ;
+ exec('sed '.$this->_QUOTE.'s/|/\x22'.$field_delimit.'=\x22/g'.$this->_QUOTE.' '.$this->_dataFileName .$_new_filename.TMP_EXT.' >> '.$this->_dataFileName.'.csv');
+
+ $convertType = 1; // kateri tip konvertiranja uporabimo
+ $convertTypes[1] = array('charSet' => 'windows-1250',
+ 'delimit' => ';',
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+
+
+ # izvedemo download
+ if ($fd = fopen ($this->_dataFileName.'.csv', "r")) {
+ $fsize = filesize($this->_dataFileName.'.csv');
+ $path_parts = pathinfo($this->_dataFileName.'.csv');
+ $ext = strtolower($path_parts["extension"]);
+ #ob_clean();
+ #header('Content-type: application/vnd.ms-excel; charset='.$convertTypes[$convertType]['charSet']);
+ header('Content-type: text/csv; charset='.$convertTypes[$convertType]['charSet']);
+ header('Content-Disposition: attachment; filename="anketa'.$this->sid.'-'.date('Y-m-d').'.csv"');
+ # ker iz zacasne datoteke preberemo samo podatke brez headerja (header izpisujemo posebej)
+ # ne moremo podati content-lenght. Razen če bi predhodno vsae zapisali v tmp datoteko in potem prebrali dolžino
+ # header('Content-length: '.$fsize);
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+ header('Content-Transfer-Encoding:­ binary');
+ #ob_flush();
+ # dodami boomchar za utf-8
+ echo $convertTypes[$convertType]['BOMchar'];
+ # naredimo header row
+
+ if ((int)$_POST['export_labels'] == 1) {
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ if (isset($this->_SVP_PV[$spid])) {
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+ $output1 .= str_replace($replace_what, $replace_with, strip_tags($variable['variable'])) . $field_delimit;
+ $output2 .= str_replace($replace_what, $replace_with, strip_tags($variable['naslov'])) . $field_delimit;
+ }
+ }
+ }
+ }
+ }
+ }
+ echo $output1."\r\n";
+ echo $output2."\r\n";
+ }
+
+ while ($line= fgets ($fd)) {
+ echo '="';
+ $line = str_replace(array("\r","\n"), array("",""), $line);
+ print ($line);
+ print ('"');
+ print ("\r\n");
+ }
+ }
+ else {
+ echo 'x1:Napaka';
+ }
+ fclose ($fd);
+
+ #pobrišemo vse tmp datoteke
+ foreach (glob($folder . 'export_data_'.$this->sid.'*dat_data*'.TMP_EXT) as $fileToDelete) {
+ unlink($fileToDelete);
+ }
+ unlink ($this->_dataFileName.'.csv');
+ }
+ else {
+ echo 'x2:Napaka!';
+ }
+
+ exit;
+ }
+
+ /** naredimo izvoz za txt
+ *
+ */
+ function exportText() {
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ($this->_fileStatus >= 0 && $this->_dataFileName !== null && $this->_dataFileName !== '' && $this->_headFileName !== null && $this->_headFileName !== '') {
+
+ #zapišemo v temp file
+
+ $file_handler = fopen($this->_dataFileName.'.txt',"w");
+
+ $output1 = '';
+ $output2 = '';
+
+ // array za labele (ce jih izpisujemo)
+ $display_labels = true;
+ $labels = array();
+
+ # naredimo header row
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ if (isset($this->_SVP_PV[$spid])) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+ $output1 .= strip_tags($variable['variable']).';';
+ $output2 .= strip_tags($variable['naslov']).';';
+ }
+ }
+ }
+ }
+
+ // Ce izpisujemo tudi labele
+ if($display_labels && isset($spremenljivka['spr_id'])){
+ if(in_array($spremenljivka['tip'], array('1','3','6','16'))){
+
+ $sequences = array();
+ $sequences = explode('_', $spremenljivka['sequences']);
+ $vars = $this->getVariableLabels($spremenljivka['spr_id']);
+
+ foreach($sequences as $sequence){
+ $labels[$sequence] = $vars;
+ }
+ }
+ }
+ }
+ fwrite($file_handler,$output1."\n");
+ fwrite($file_handler,$output2."\n");
+ fclose($file_handler);
+
+
+ # sfiltriramo podatke
+ exec ('awk -F'.$this->_QUOTE.STR_DLMT.$this->_QUOTE.' '.$this->_QUOTE.$this->_CURRENT_STATUS_FILTER.' {print $0}'.$this->_QUOTE.' '.$this->_dataFileName.' > '.$this->_dataFileName .'_data1'.TMP_EXT);
+ if (IS_WINDOWS) {
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d "|" -f '.$this->_VARIABLE_FILTER.' '.$this->_dataFileName .'_data1'.TMP_EXT.' > '.$this->_dataFileName .'_data1_1'.TMP_EXT;
+ } else {
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d \'|\' -f '.$this->_VARIABLE_FILTER.' '.$this->_dataFileName .'_data1'.TMP_EXT.' > '.$this->_dataFileName .'_data1_1'.TMP_EXT;
+ }
+ $out1_1 = shell_exec($cmdLn1_1);
+
+ # zamenjamo | z ;
+ exec('sed '.$this->_QUOTE.'s/|/;/g'.$this->_QUOTE.' '.$this->_dataFileName .'_data1_1'.TMP_EXT.' >> '.$this->_dataFileName.'.txt');
+
+ $convertType = 1; // kateri tip konvertiranja uporabimo
+ $convertTypes[1] = array('charSet' => "windows-1250",
+ 'delimit' => ";",
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+
+ # izvedemo download
+ if ($fd = fopen ($this->_dataFileName.'.txt', "r")) {
+ // clean the output buffer
+ ob_clean();
+
+ $fsize = filesize($this->_dataFileName.'.txt');
+ $path_parts = pathinfo($this->_dataFileName.'.txt');
+ $ext = strtolower($path_parts["extension"]);
+ header('Content-type: text/plain; charset='.$convertTypes[$convertType]['charSet']);
+ header('Content-Disposition: attachment; filename="anketa'.$this->sid.'-'.date('Y-m-d').'.txt"');
+ # header('Content-length: '.$fsize);
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+ header('Content-Transfer-Encoding:­ binary');
+ ob_flush();
+
+
+ # dodami boomchar za utf-8
+ echo $convertTypes[$convertType]['BOMchar'];
+
+ /*while(!feof($fd)) {
+ $buffer = fread($fd, 2048);
+ echo $buffer.'';
+ }*/
+ $i=0;
+ // Loop po vrsticah
+ while(($line = fgets($fd)) !== false) {
+
+ // Samo naslovni vrstici z metapodatki oz. vse vrstice ce nimamo label
+ if($i < 2 || !$display_labels){
+ echo $line;
+ }
+ // Izpisujemo labele v podatkovnih vrsticah
+ else{
+ // Vrstico s podatki razbijemo, dodamo labele in jo nazaj sestavimo
+ $line_array = explode(';', $line);
+ if(count($line_array) > 0){
+ foreach($line_array as $seq => $val){
+
+ // Izpisemo vrednost
+ echo $val;
+
+ // Izpisemo labelo
+ $seq += 3;
+ if(isset($labels[$seq][0]['values'][$val])){
+ echo ' ("'.$labels[$seq][0]['values'][$val].'")';
+ }
+
+ // Vsem razen zadnjemu dodamo se separator
+ if($seq < count($line_array)+2)
+ echo ';';
+ }
+ }
+ }
+
+ $i++;
+ }
+ }
+ else {
+ echo "Napaka";
+ }
+ fclose ($fd);
+
+ #pobrišemo vse tmp datoteke
+ foreach (glob($folder . 'export_data_'.$this->sid.'_*'.TMP_EXT) as $fileToDelete) {
+ unlink($fileToDelete);
+ }
+ unlink ($this->_dataFileName.'.txt');
+
+ }
+ else {
+ echo '';
+ }
+
+ exit;
+ }
+
+ // shranim SPS in A00, potem pokličem spss in je.
+ private function exportSav () {
+
+ // izbriši staro
+ // pač... RM dela :-)
+ @unlink ($this->folder .'tmp_spss2sav' .$this->sid .'.a00');
+ @unlink ($this->folder .'tmp_spss2sav' .$this->sid .'.sps');
+
+ // spss + a00
+ $this->exportSpss("save", true, true);
+ $this->exportSpss("save", false, true);
+
+ // convert
+ //echo "Diagnostics for developers (link is below): <br>";
+ passthru ('pspp ' .$this->folder .'tmp_spss2sav' .$this->sid .'.sps');
+
+ //echo '<br><br><strong><a href="SurveyData/' .'tmp_spss2sav' .$this->sid .'.SAV">Link</a></strong>';
+
+ // Tole ne dela ker kessira star file
+ //header ('location: SurveyData/' .'tmp_spss2sav' .$this->sid .'.SAV');
+
+ $file_url = 'SurveyData/' .'tmp_spss2sav' .$this->sid .'.SAV';
+
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+ header('Content-Transfer-Encoding:­ binary');
+
+ header('Content-Type: application/octet-stream');
+ header("Content-Transfer-Encoding: Binary");
+ header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
+
+ readfile($file_url);
+ }
+
+
+ /**
+ * mode download - klasično, pač skrani SAV + A00
+ * mode save - shrani fajla
+ *
+ * pa porinem si noter še data_par (true - a00, false - sps).
+ */
+ private function exportSpss($mode = "download", $data_param = false, $pspp=false) {
+ global $site_path, $lang;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ $tmp_files = $this->folder.'tmp_spss_'.$this->sid.'.php';
+ #polovimo max št znakov za posamezne sekvence
+ if (IS_WINDOWS) {
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '
+ .'{if (MaxFields < NF) MaxFields = NF; for (i=1; i<=NF; i++) { Field[NR, i] = $i; l = length($i); if (l < 1) l = 1; if (Length[i] < l) Length[i] = l; };} '
+ .'END {print\"\x3C\x3Fphp\"; for (i=1; i<=MaxFields; i++) { print \"$spss_length[\",i,\"]\",\"=\",Length[i],\";\"}; print\"\x3F\x3E\"}" '
+ .$this->_dataFileName. ' > '.$tmp_files ;
+ } else {
+ $command = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"} {FS="\x7C"} {SUBSEP="\x7C"}} '
+ .'{if (MaxFields < NF) MaxFields = NF; for (i=1; i<=NF; i++) { Field[NR, i] = $i; l = length($i); if (l < 1) l = 1; if (Length[i] < l) Length[i] = l; };} '
+ .'END {print"\x3C\x3Fphp"; for (i=1; i<=MaxFields; i++) { print "$spss_length[",i,"]","=",Length[i],";"}; print"\x3F\x3E"}\' '
+ .$this->_dataFileName. ' > '.$this->folder.'tmp_spss_'.$this->sid.'.php';
+ }
+ $out = shell_exec($command);
+
+ include($tmp_files );
+
+ # pobrišemo inkludan fajl, ker jih več ne rabimo
+ if (file_exists($tmp_files )) {
+ unlink($tmp_files );
+ }
+
+ if ($this->_fileStatus >= 0 && $this->_dataFileName !== null && $this->_dataFileName !== '' && $this->_headFileName !== null && $this->_headFileName !== '') {
+
+ #ali lovimo datoteko s strukturo ali datoteko z podatki
+ $data = false;
+ if ((isset($_REQUEST['exportData']) && (int)$_REQUEST['exportData'] == 1) || $data_param == true) {
+ $data = true;
+ }
+
+ # delamo datoteko s strukturo
+ if ( $data == false ) {
+
+ # TODO - odstranit šumnike iz header datoteke
+ #$str = preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $str);
+
+ $_value_labels_numbers = ''; # temp variabla kamor shranimo imena variabel numeričnih odgovorov
+ $_value_labels_text = ''; # temp variabla kamor shranimo imena variabel tekstovnih odgovorov
+
+ #preberemo HEADERS iz datoteke
+ $this->_HEADERS = unserialize(file_get_contents($this->_headFileName));
+
+ # poiščemo maximalno število znakov pri missing vrednostih za tekstovne in number odgovore
+ $_all_missing_values = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_max_text_missing_chars = 0;
+ $_max_number_missing_chars = 0;
+
+ # polovimo maximalne dolžine znakov
+ foreach ($_all_missing_values AS $mkey => $missing) {
+ $_max_text_missing_chars = max($_max_text_missing_chars, strlen($mkey . ': '. $missing));
+ $_max_number_missing_chars = max($_max_number_missing_chars, strlen($mkey));
+ }
+ $maxLengthForSpr = self::create_array_SPSS(max($_max_text_missing_chars,$_max_number_missing_chars));
+ //$resultString .= .NEW_LINE;
+ $resultString = $lang['srv_spss_export_base_instructions'];
+ $resultString .= NEW_LINE.'.'.NEW_LINE.NEW_LINE;
+
+ $resultString .= 'PRESERVE.'.NEW_LINE;
+ // TOLE NE DELA OK ZA DECIMALKE V NOVIH SPSSih
+ /*if ($pspp == false) {
+ $resultString .= 'SET UNICODE ON.'.NEW_LINE;
+ }
+ else {
+ $resultString .= "SET LOCALE='UTF-8'.".NEW_LINE;
+ }*/
+ $resultString .= "SET LOCALE='en_US'.".NEW_LINE;
+ $resultString .= 'SET UNICODE ON.'.NEW_LINE;
+
+ $resultString .= 'SET DECIMAL DOT.'.NEW_LINE.NEW_LINE;
+
+ # seznam spremenljivk in opis formata
+ $resultString .= 'GET DATA'.NEW_LINE;
+ $resultString .= ' /TYPE = TXT'.NEW_LINE;
+
+
+ if ($mode == "download") {
+ $resultString .= ' /FILE = \'C:\anketa'.$this->sid.'-'.date('Y-m-d').'_podatki.txt\''.NEW_LINE;
+ }
+ else {
+ $resultString .= ' /FILE = \'' .$this->folder .'tmp_spss2sav' .$this->sid .'.a00\''.NEW_LINE;
+ }
+
+ //.$lang['srv_spss_export_file_instructions'].NEW_LINE;
+ $resultString .= ' /ARRANGEMENT = DELIMITED'.NEW_LINE;
+ $resultString .= ' /FIRSTCASE = 1'.NEW_LINE;
+ $resultString .= ' /IMPORTCASE = ALL'.NEW_LINE;
+ $resultString .= ' /DELIMITERS = " "'.NEW_LINE;
+ $resultString .= ' /QUALIFIER = "\'"'.NEW_LINE;
+ $resultString .= ' /VARIABLES = '.NEW_LINE;
+
+ # dodamo seznam variabel z tipi podatkov
+ if (count($this->_HEADERS) > 0) {
+
+ $cnt = 1;
+
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ if (isset($this->_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $seq=$variable['sequence'];
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+
+ # vsako v svojo vrstico
+ if (substr($variable['spss'],0,1) == 'F') {
+ # pri številih
+ $_number = explode('.',substr($variable['spss'],1));
+ $_cela = isset($_number[0]) && $_number[0] > 0 ? $_number[0] : 0;
+ $_decimalna = isset($_number[1]) && $_number[1] > 0 ? $_number[1] : 0;
+ $_spss_chars = 'F'.max($_max_number_missing_chars,$_cela,1).'.'.$_decimalna;
+ } else if ($variable['spss'] == 'DATETIMEw') {
+ # pri tekstovnih odgovorih
+ #$_spss_chars = 'A'.$_max_text_missing_chars;
+
+ #polovimo po novi metodi
+
+ $_spss_chars = 'A'.$spss_length[$seq];
+ } else {
+ # pri tekstovnih odgovorih
+ #$_spss_chars = substr($variable['spss'],0,1) . max($maxLengthForSpr[$spid],$_max_text_missing_chars,substr($variable['spss'],1),1);
+
+ #polovimo po novi metodi
+ $_spss_chars = 'A'.$spss_length[$seq];
+ }
+
+ // Language meta moramo preimenovati za spss, ker drugace je podvojen z language spremenljivko
+ if($variable['variable'] == 'Language')
+ $resultString .= ' Language_meta '.$_spss_chars.NEW_LINE;
+ else
+ $resultString .= ' ' . preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable['variable']) . ' '.$_spss_chars.NEW_LINE;
+
+ # polovimo imena variable za missing vrednosti Nagovora ne dodajmo
+ if (isset($spremenljivka['tip']) && $spremenljivka['tip'] != 'm' && $spremenljivka['tip'] != 'sm' && $spremenljivka['tip'] != 5) {
+ if (substr($variable['spss'],0,1) == 'F') {
+ $_value_labels_numbers .= $variable['variable'].' ';
+
+ // Dodamo prelom vsakih 10 variabel zaradi max dolzine vrstice
+ if($cnt > 10){
+ $_value_labels_numbers .= NEW_LINE;
+ $cnt = 0;
+ }
+
+ $cnt++;
+ }
+ else if (substr($variable['spss'],0,1) == 'A') {
+ $_value_labels_text .= $variable['variable'].' ';
+
+ // Dodamo prelom vsakih 10 variabel zaradi max dolzine vrstice
+ if($cnt > 10){
+ $_value_labels_text .= NEW_LINE;
+ $cnt = 0;
+ }
+
+ $cnt++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ $resultString .= ' .'.NEW_LINE.NEW_LINE;
+
+ #ime ankete brez presledkov
+ // pspp ne mara _
+ if ($pspp == false)
+ $resultString .= 'DATASET NAME ' . preg_replace("/[^a-zA-Z0-9_]/",'_',$this->survey['naslov']) . ' WINDOW=FRONT.' . NEW_LINE.NEW_LINE;
+ else
+ $resultString .= 'DATASET NAME ' . preg_replace("/[^a-zA-Z0-9_]/",'',$this->survey['naslov']) . ' WINDOW=FRONT.' . NEW_LINE.NEW_LINE;
+
+ #labele vprasanj ==> VARIABLE LABELS
+ # seznam spremenljivk in opis formata (pika na koncu vsake labele)
+ if (count($this->_HEADERS) > 0) {
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ if (isset($this->_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+
+ switch ($spremenljivka['tip']) {
+ case '2':
+ case '6':
+
+ $variable_label = substr($spremenljivka['naslov'],0,30).': '.$variable['naslov'];
+ $_variable = preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable['variable']);
+ break;
+ case '7':
+ if (isset($spremenljivka['enota'])) {
+ $variable_label= substr($spremenljivka['naslov'],0,30) .' ('.$variable['naslov'].')';
+ } else {
+ $variable_label= substr($spremenljivka['naslov'],0,30) ;
+ }
+ $_variable = preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable['variable']);
+ break;
+ case '16':
+ case '19':
+ case '20':
+ $variable_label= substr($spremenljivka['naslov'],0,15) .': '.$grid['naslov'].': '.$variable['naslov'];
+ $_variable = preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable['variable']);
+ break;
+ case '21':
+
+ $variable_label= substr($spremenljivka['naslov'],0,30) .' ('.$variable['naslov'].')';
+ $_variable = preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable['variable']);
+ break;
+ default:
+ $variable_label = $variable['naslov'];
+ $_variable = preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable['variable']);
+ break;
+ }
+ if($variable['other'] == 1 && $variable['text'] == 1) {
+ $variable_label .= ' '.$lang['srv_sppss_text_other'];
+ }
+
+ $variable_label = $this->getCleanString($variable_label);
+
+ // Language meta moramo preimenovati za spss, ker drugace je podvojen z language spremenljivko
+ if($variable['variable'] == 'Language')
+ $resultString .= 'VARIABLE LABELS Language_meta \''.$variable_label.'\' .'.NEW_LINE;
+ else
+ $resultString .= 'VARIABLE LABELS '.$_variable.' \''.$variable_label.'\' .'.NEW_LINE;
+ }
+ }
+ }
+ }
+ }
+ }
+ $resultString .=NEW_LINE;
+ }
+
+
+ # labele vrednosti ==> VALUE LABELS
+ # seznam label vrednosti spremenljivk (pika na koncu vsakega sklopa)
+ if (count($this->_HEADERS) > 0) {
+ foreach ($this->_HEADERS AS $spid => $spremenljivka) {
+ if (isset($this->_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+ if (isset($spremenljivka['options'])) {
+ $resultString .= 'VALUE LABELS';
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+
+ if ($variable['other'] != 1) {
+ $variable = $this->getCleanString($variable['variable']);
+ $resultString .= ' '.preg_replace ("/[^a-zA-Z0-9_\/]/", "_", $variable);
+ }
+ }
+ }
+ }
+ }
+
+ // pspp ne mara newline, hoče presledek vmes.
+ if ($pspp == false) $resultString .= NEW_LINE;
+ else $resultString .= ' ';
+
+ if (count($spremenljivka['options']) > 0) {
+ foreach ($spremenljivka['options'] AS $okey =>$option) {
+
+ if(($spremenljivka['tip'] !== 'sm' && $spremenljivka['tip'] !== 'm') || $this->exportSettings['FullMeta'] > 0){
+
+ if ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16) {
+ # pri čekboxu prevedemo
+ if ($pspp == false){
+ $resultString .= $okey. ' \''.$lang['srv_sppss_checkbox_value_'.$option].'\''.NEW_LINE;
+ }
+ else {
+ $resultString .= $okey. ' \''.$lang['srv_sppss_checkbox_value_'.$option].'\''.' ';
+ }
+ }
+ else {
+ $option = $this->getCleanString($option);
+ if ($pspp ==false) $resultString .= $okey. ' \''.$option.'\''.NEW_LINE;
+ else {
+ if (strpos ($option, "&#39;")===false) {
+ $resultString .= $okey. ' \''.$option.'\''.' ';
+ }
+ else {
+ $resultString .= $okey. ' \"'.str_replace ("&#39;", "'", $option) .'\"'.' ';
+ }
+ }
+ }
+ }
+ }
+ }
+ $resultString .='.'.NEW_LINE.NEW_LINE;
+ }
+ }
+ }
+ }
+
+ # missing vrednosti ==> MISSING VALUES
+ # seznam - razpon mising vrednosti ( pika na koncu ukaza)
+ /*
+ * Manjkajoče vrednosti se definirajo samo za številske (format F) spremenljivke, saj določanje intervala za
+ * tekstovne (format A) ni podprto. Interval manjkajočih vrednosti označi uporabnik v vmesniku za izvoz, privzeto
+ * je od -999 do -1. Uporabnik lahko izbere tudi, da ne želi definirati manjkajočih vrednosti – v tem primeru se
+ * spodnja koda ne vključi v sintakso.
+ * MISSING VALUES Q1 Q2 (...) Qn (a thru b).
+ * Q1, Q2, ..., Qn: imena številskih spremenljivk.
+ */
+ $_unset = SurveyMissingValues::GetUnsetValuesForSurvey();
+ $_missings = SurveyMissingValues::GetMissingValuesForSurvey();
+
+ #poiščemo razpon missingov, najmanjči in največji
+ $_min = null;
+ $_max = null;
+ if (count($_unset) > 0) {
+ foreach ( $_unset AS $key => $_mising_value) {
+ $_min = ($_min == null) ? $key : min($_min,$key);
+ $_max = ($_max == null) ? $key : max($_max,$key);
+ }
+ }
+ if (count($_missings) > 0) {
+ foreach ( $_missings AS $key => $_mising_value) {
+ $_min = ($_min == null) ? $key : min($_min,$key);
+ $_max = ($_max == null) ? $key : max($_max,$key);
+ }
+ }
+
+ if ($_min == null) $_min = -99; # privzeto
+ if ($_max == null) $_max = -1; # privzeto
+
+ if (count($this->_HEADERS) > 0 && $_value_labels_numbers != '') {
+ $resultString .='MISSING VALUES ';
+ $resultString .= $_value_labels_numbers . ' ('.$_min.' thru '.$_max.')';
+ $resultString .='.'.NEW_LINE.NEW_LINE;
+ }
+
+ # missing labele ==> ADD VALUE LABELS
+ # seznam label za missinge ( pika na koncu seznama) Naredimo dvakrat, 1x za števila in 1x za texte
+ /** Labele za manjkajoče vrednosti se definirajo za številska in besedilna vprašanja in sicer ločeno.
+ * Labele se dobijo iz sistemskih nastavitev manjkajočih vrednosti v 1KA (npr. neodgovor itd.)
+ */
+ # za number odgovore
+ if ( (count($_missings)+count($_unset)) > 0 && $_value_labels_numbers != '') {
+ if ($pspp == false)
+ $resultString .='ADD VALUE LABELS ' . $_value_labels_numbers.NEW_LINE;
+ else
+ $resultString .='VALUE LABELS ' . $_value_labels_numbers.' ';
+
+ if (count($_missings) > 0) {
+ foreach ( $_missings AS $mkey => $missing_value) {
+ if ($pspp == false)
+ $resultString .= $mkey . ' \'' . $this->getCleanString($missing_value).'\''.NEW_LINE;
+ else {
+ if (strpos ($this->getCleanString($unset_value), "&#39;")===false) {
+ $resultString .= $mkey . ' "' . $this->getCleanString($missing_value).'"'.' ';
+ }
+ else {
+ $resultString .= $mkey . ' "' . str_replace ("&#39;", "'", $this->getCleanString($missing_value)) .'"'.' ';
+ }
+ }
+ }
+ }
+ if (count($_unset) > 0) {
+ foreach ( $_unset AS $ukey => $unset_value) {
+ if ($pspp == false) $resultString .= $ukey . ' \'' . $this->getCleanString($unset_value).'\''.NEW_LINE;
+ else {
+ if (strpos ($this->getCleanString($unset_value), "&#39;")===false) {
+ $resultString .= $ukey . ' \'' . $this->getCleanString($unset_value).'\''.' ';
+ }
+ else {
+ $resultString .= $ukey . ' "' . str_replace ("&#39;", "'", $this->getCleanString($unset_value)).'"'.' ';
+ }
+ }
+ }
+ }
+
+ $resultString .='.'.NEW_LINE.NEW_LINE;
+ }
+
+ # za tekstovne odgovore prekodiramo missinge
+ // ne smeš, ker prideš preko dovoljene dolžine. V A5 pač ne gre 20 znakov...
+ // SPSS ima sicer komando "alter" za spremeniti string, ampak ker pspp ne podpira, delam labele!
+
+ if ( (count($_missings)+count($_unset)) > 0 && $_value_labels_text != '') {
+
+ $cnt = 1;
+ $resultString .= 'VALUE LABELS ' .$_value_labels_text .' '.NEW_LINE;
+
+ if (count($_missings) > 0) {
+ foreach ( $_missings AS $mkey => $missing_value) {
+ $resultString .= '\'' .$mkey . '\' \'' .$mkey . ': '. $this->getCleanString($missing_value).'\' ';
+
+ $resultString .= NEW_LINE;
+ }
+ }
+
+ if (count($_unset) > 0) {
+ foreach ( $_unset AS $ukey => $unset_value) {
+ if ($pspp == false){
+ $resultString .= '\'' . $ukey . '\' \'' . $ukey . ': '. $this->getCleanString($unset_value).'\' ';
+
+ $resultString .= NEW_LINE;
+ }
+ }
+ }
+
+ $resultString .= '.' . NEW_LINE.NEW_LINE;
+ }
+
+ if ($mode != "download") {
+ $resultString .= 'SAVE /OUTFILE \'' .$this->folder .'tmp_spss2sav' .$this->sid .'.SAV\'.' .NEW_LINE;
+ }
+
+ # povrnemo narejene spremembe v spssu
+ $resultString .='EXECUTE.'.NEW_LINE;
+ $resultString .='RESTORE.';
+
+ $convertType = 1; // kateri tip konvertiranja uporabimo
+ $convertTypes[1] = array('charSet' => "windows-1250",
+ 'delimit' => ";",
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+
+ // downloadaj
+ if ($mode == "download") {
+ ob_clean();
+
+ header('Content-type: text/plain; charset='.$convertTypes[$convertType]['charSet']);
+ header('Content-Disposition: attachment; filename="anketa'.$this->sid.'-'.date('Y-m-d').'.sps"');
+ # header("Content-length: $fsize");
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+ header('Content-Transfer-Encoding:­ binary');
+ ob_flush();
+
+ #$resultString = iconv("UTF-8", "CP1250", $resultString);
+ # dodami boomchar za utf-8
+
+ echo $convertTypes[$convertType]['BOMchar'];
+ echo $resultString;
+ }
+
+ // shrani nekam na disk če imaš "save" namesto "download"
+ else {
+ $fh = fopen($this->folder .'tmp_spss2sav' .$this->sid.'.sps', 'w');
+ fwrite($fh, $resultString);
+ fclose($fh);
+ }
+ // end if data = false
+ }
+ else {
+ #lovimo podatke
+
+ // | -> \x7C
+ // ` -> \x60
+ // ' -> \x27
+ // " -> \x22
+ $tmp_files = array( 'original' => $this->_dataFileName,
+ 'first' => $this->_dataFileName.'_first',
+ 'first1' => $this->_dataFileName.'_first_1',
+ 'second' => $this->_dataFileName.'_second',
+ 'third' => $this->_dataFileName.'_third',
+ 'fourth' => $this->_dataFileName.'_fourth');
+
+ if (IS_WINDOWS) {
+
+ # polovimo vrstice z statusom
+ $cmdLn1 = 'awk -F"'.STR_DLMT.'" "'.$this->_CURRENT_STATUS_FILTER.' {print $0}" '.$tmp_files['original'].' > '.$tmp_files['first'];
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d "|" -f '.$this->_VARIABLE_FILTER.' '.$tmp_files['first'].' > '.$tmp_files['first1'];
+ #zamenjamo ' => `
+ $cmdLn2 = 'sed "s/\x27/\x60/g" '.$tmp_files['first1'].' > '.$tmp_files['second'];
+ # zamenjamo | z ' '
+ $cmdLn3 = 'sed "s/'.STR_DLMT.'/\x27 \x27/g" '.$tmp_files['second'].' > '.$tmp_files['third'];
+ # dodamo ' na začetek in konec
+ $cmdLn4 = 'awk '.$this->_QUOTE.'{print \"\'\"$0\"\'\"}'.$this->_QUOTE.' '.$tmp_files['third'].' > '.$tmp_files['fourth'];
+ } else {
+ # polovimo vrstice z statusom
+ $cmdLn1 = "awk -F'\x7C' '".$this->_CURRENT_STATUS_FILTER." {print $0}' ".$tmp_files['original'].' > '.$tmp_files['first'];
+ #filtri spremenljivk
+ $cmdLn1_1 = 'cut -d \'|\' -f '.$this->_VARIABLE_FILTER.' '.$tmp_files['first'].' > '.$tmp_files['first1'];
+ #zamenjamo ' => `
+ $cmdLn2 = 'sed \'s/\x27/\x60/g\' '.$tmp_files['first1'].' > '.$tmp_files['second'];
+ # zamenjamo | z ' '
+ $cmdLn3 = 'sed \'s/'.STR_DLMT.'/\x27 \x27/g\' '.$tmp_files['second'].' > '.$tmp_files['third'];
+ # dodamo ' na začetek in konec
+ $this->_QUOTE = '\'';
+ $cmdLn4 = 'awk \'{print "\x27"$0"\x27"}\' '.$tmp_files['third'].' > '.$tmp_files['fourth'];
+ }
+
+ $out1 = shell_exec($cmdLn1);
+ $out1_1 = shell_exec($cmdLn1_1);
+ $out2 = shell_exec($cmdLn2);
+ $out3 = shell_exec($cmdLn3);
+ $out4 = shell_exec($cmdLn4);
+
+ if ($_GET['debug'] == 1) {
+ print_r('<br>'.$cmdLn1);
+ print_r('<br>'.$cmdLn2);
+ print_r('<br>'.$cmdLn3);
+ print_r('<br>'.$cmdLn4);
+ }
+
+ # nardimo output
+ $convertType = 1; // kateri tip konvertiranja uporabimo
+ $convertTypes[1] = array('charSet' => "windows-1250",
+ 'delimit' => ";",
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+ if ($mode == "download") {
+ # izvedemo download
+ if ($fd = fopen ($tmp_files['fourth'], "r")) {
+
+ ob_clean();
+
+ $fsize = filesize($tmp_files['fourth']);
+ $path_parts = pathinfo($tmp_files['fourth']);
+ $ext = strtolower($path_parts["extension"]);
+
+ header('Content-type: text/plain; charset='.$convertTypes[$convertType]['charSet']);
+ header('Content-Disposition: attachment; filename="anketa'.$this->sid.'-'.date('Y-m-d').'_podatki.txt"');
+ #header("Content-length: $fsize");
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+ header('Content-Transfer-Encoding:­ binary');
+ ob_flush();
+
+ # dodami boomchar za utf-8
+ echo $convertTypes[$convertType]['BOMchar'];
+
+ while(!feof($fd)) {
+ $buffer = fread($fd, 2048);
+ echo $buffer;
+ }
+
+ }
+ else {
+ echo "Napaka";
+ }
+
+ fclose ($fd);
+ }
+
+ // priprava za SAV
+ else {
+ copy ($tmp_files['fourth'], $this->folder .'tmp_spss2sav' .$this->sid.'.a00');
+ }
+
+ #pobrišemo vse tmp datoteke
+ if (file_exists($tmp_files['first'])) { unlink($tmp_files['first']); }
+ if (file_exists($tmp_files['first1'])) { unlink($tmp_files['first1']); }
+ if (file_exists($tmp_files['second'])) { unlink($tmp_files['second']); }
+ if (file_exists($tmp_files['third'])) { unlink($tmp_files['third']); }
+ if (file_exists($tmp_files['fourth'])) { unlink($tmp_files['fourth']); }
+
+ } // end if data = true
+ }
+ else {
+
+ }
+
+ if ($mode == "download") {
+ ob_flush();
+ exit;
+ }
+ else {
+ return;
+ }
+ }
+
+
+ /** Preveri ali obstajata datoteki z podatki in headerji in ali sta zadnji ažurni
+ *
+ */
+ public function checkFile() {
+
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->sid);
+
+ $this->_headFileName = $SDF->getHeaderFileName();
+ $this->_dataFileName = $SDF->getDataFileName();
+ $this->_fileStatus = $SDF->getStatus();
+
+ return $this->_fileStatus;
+ }
+
+ private function create_array_SPSS($max_missing) {
+ $array_SPSS = array();
+
+ $db_table = ($this->survey['db_table'] == 1) ? '_active' : '';
+
+ # poberemo max dolžine iz srv_data_text max(text1,text2)
+ $str_query = 'SELECT dt.spr_id, MAX(LENGTH(dt.text)) AS length, MAX(LENGTH(dt.text2)) AS length2 FROM srv_data_text'.$db_table.' dt, srv_grupa g, srv_spremenljivka s WHERE dt.spr_id = s.id AND s.gru_id=g.id AND g.ank_id='.$this->sid.' GROUP BY dt.spr_id';
+ $_qry_SPSS = sisplet_query($str_query);
+ while (list($spr_id,$text,$text2) = mysqli_fetch_row($_qry_SPSS)) {
+ $array_SPSS[$spr_id] = max((int)$text,(int)$text2,$max_missing);
+ }
+ $str_query = 'SELECT dt.spr_id, MAX(LENGTH(dt.text)) AS length FROM srv_data_textgrid'.$db_table.' AS dt, srv_grupa g, srv_spremenljivka s WHERE dt.spr_id = s.id AND s.gru_id=g.id AND g.ank_id='.$this->sid.' GROUP BY dt.spr_id';
+ $_qry_SPSS = sisplet_query($str_query);
+ while (list($spr_id,$text) = mysqli_fetch_row($_qry_SPSS)) {
+ #$this->_array_SPSS[$spr_id]['text2'] = ((int)$text < $this->MISSING_MAX_LENGTH ? $this->MISSING_MAX_LENGTH :$text);
+ $array_SPSS[$spr_id] = max((int)$text,$array_SPSS[$spr_id],$max_missing);
+ }
+ return $array_SPSS;
+ }
+
+
+ public function ajax() {
+ if ($_GET['a'] == 'doexport') {
+ self :: DoExport();
+ }
+ }
+
+ function getCleanString($string) {
+
+ // Replace quotov
+ $string = preg_replace ("/'/", "`", $string);
+
+ // Max dolžina stringa je 240 znakov
+ $string = $this->splitStringIntoLines($string);
+
+ return $string;
+ }
+
+ // Max dolžina stringa je 200 znakov - razbijemo v chunke za spss
+ private function splitStringIntoLines($string){
+
+ if(strlen($string) <= 200)
+ return $string;
+
+ $new_string = chunk_split($string, 200, '\'+'.NEW_LINE.'\'');
+ $new_string = substr($new_string, 0, -4);
+
+ return $new_string;
+ }
+
+ private function getVariableLabels($spr_id){
+ global $lang;
+
+ $s = sisplet_query("SELECT tip FROM srv_spremenljivka WHERE id = '$spr_id'");
+ $r = mysqli_fetch_array($s);
+
+ if ( in_array($r['tip'], array(1, 3)) ) {
+
+ $output = array();
+
+ $output['spr'] = $spr_id;
+ $output['tip'] = $r['tip'];
+
+ $output['values'] = array();
+
+ $sql = sisplet_query("SELECT naslov, variable FROM srv_vrednost WHERE spr_id='$spr_id' ORDER BY vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+ $output['values'][$row['variable']] = strip_tags( $row['naslov'] );
+ }
+
+ $output['values']['-1'] = $lang['srv_bottom_data_legend_note_li1a'];
+ $output['values']['-2'] = $lang['srv_bottom_data_legend_note_li2a'];
+ $output['values']['-3'] = $lang['srv_bottom_data_legend_note_li3a'];
+ $output['values']['-4'] = $lang['srv_bottom_data_legend_note_li4a'];
+ $output['values']['-5'] = $lang['srv_bottom_data_legend_note_li5a'];
+
+ $response[] = $output;
+
+ } elseif ( in_array($r['tip'], array(6, 16)) ) {
+
+ $output = array();
+
+ $output['spr'] = $spr_id;
+ $output['tip'] = $r['tip'];
+
+ $output['values'] = array();
+
+ $sql = sisplet_query("SELECT naslov, variable FROM srv_grid WHERE spr_id='$spr_id' ORDER BY vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+ $output['values'][$row['variable']] = strip_tags( $row['naslov'] );
+ }
+
+ $output['values']['-1'] = $lang['srv_bottom_data_legend_note_li1a'];
+ $output['values']['-2'] = $lang['srv_bottom_data_legend_note_li2a'];
+ $output['values']['-3'] = $lang['srv_bottom_data_legend_note_li3a'];
+ $output['values']['-4'] = $lang['srv_bottom_data_legend_note_li4a'];
+ $output['values']['-5'] = $lang['srv_bottom_data_legend_note_li5a'];
+
+ $response[] = $output;
+ }
+
+ return $response;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyExportProfiles.php b/admin/survey/classes/class.SurveyExportProfiles.php
new file mode 100644
index 0000000..f34e7b0
--- /dev/null
+++ b/admin/survey/classes/class.SurveyExportProfiles.php
@@ -0,0 +1,291 @@
+<?php
+/**
+ * Created on 6.4.2010
+ *
+ * @author: Gorazd Veselič
+ *
+ * @desc: za shranjevanje in nalaganje profilov izvozov
+ *
+ * funkcije:
+ *
+ *
+ */
+session_start();
+class SurveyExportProfiles
+{
+ static private $instance; // instanca razreda (razred kreiramo samo enkrat)
+ static private $userId = null; // user id
+ static private $surveyId = null; // id ankete
+
+ static private $availableProfiles = array(); // array kamor shranimo vse doseglijive profile
+ static private $profilesData = array(); // array kamor shranimo podatke o trenutnem profilu
+
+ protected function __construct() {}
+
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveyVariablesProfiles();
+ }
+ return self::$instance;
+ }
+
+ /** Inicializacija
+ *
+ */
+ static function Init($sid, $uid, $doRefresh=true) {
+ session_start();
+ self::setSurveyId($sid);
+ self::setUserId($uid);
+ self::checkBaseProfileExisit();
+ if ($doRefresh==true) {
+ //poiščemo vse dosegljive profile
+ self::refreshAvailableProfiles();
+ }
+ }
+
+
+ static function getSurveyId() { return self::$surveyId; }
+ static function setSurveyId($sid) { self::$surveyId = $sid; }
+ static function getUserId() { return self::$userId; }
+ static function setUserId($uid) { self::$userId = $uid; }
+
+ static function getAvailableProfiles() { return self::$availableProfiles; }
+
+ static function checkBaseProfileExisit() {
+ global $lang;
+
+ $selectCheckProfile = "SELECT id FROM srv_variable_profiles WHERE id='1' AND sid = '" . self::getSurveyId() . "' AND uid = '" . self::getUserId() . "'";
+ $sqlCheckProfile = sisplet_query($selectCheckProfile);
+
+ // če ne obstaja noben profil, kreiramo novega sistemskega - Vse spremenljivke.
+ if (!mysqli_num_rows($sqlCheckProfile)) {
+ $stringInsert = "INSERT INTO srv_variable_profiles (id, sid, uid, name, system) " .
+ "VALUES ('1', '" . self::getSurveyID() . "', '" . self::getUserID() . "','".$lang['srv_variable_profile_new_all']."', '1')";
+ sisplet_query($stringInsert) or die(mysqli_error($GLOBALS['connect_db']));
+ }
+
+ return 1;
+ }
+
+ static function refreshAvailableProfiles() {
+ // počistimo
+ self::$availableProfiles = array();
+ // dodamo profil iz seje če obstaja
+ $sid = self::getSurveyId();
+ if ( isset($_SESSION['variables_profile'][$sid])) {
+ self::$availableProfiles[0] = array( 'id' => $_SESSION['variables_profile'][$sid]['id'],
+ 'name' => $_SESSION['variables_profile'][$sid]['name'],
+ 'system'=> $_SESSION['variables_profile'][$sid]['system'],
+ 'variables'=> $_SESSION['variables_profile'][$sid]['variables']);
+ }
+
+ $selectSqlProfile = "SELECT * FROM srv_variable_profiles WHERE sid = '" . self::getSurveyId() . "' AND uid = '" . self::getUserId() . "' ORDER BY id";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+ while ($rowProfileSetting = mysqli_fetch_assoc($sqlProfileSetting)) {
+ self::$availableProfiles[$rowProfileSetting['id']] = $rowProfileSetting;
+ }
+ }
+
+
+ static function getProfileData($pid) {
+ // preverimo ali smo v razredu že lovili podatke za ta profil, potem jih preberemo čene jih osvežimo
+ if ( isset( self::$profilesData[$pid] ) ) {
+ return self::$profilesData[$pid];
+ } else {
+ $result = self::refreshProfileData($pid);
+ // rezultat si zapomnimo
+ self::$profilesData[$pid] = $result;
+ return self::$profilesData[$pid];
+ }
+ }
+
+
+ static function refreshProfileData($pid) {
+ // preberemo iz seje če obstaja zapis, čene preberemo privzet zapis (id=1)
+ if ($pid == 0) { // če je seja vrnemo sejo
+ // preberemo iz seje če obstaja zapis, čene preberemo privzet zapis (id=1)
+ if ( isset($_SESSION['variables_profile'][self::getSurveyId()]) ) {
+ return $_SESSION['variables_profile'][self::getSurveyId()];
+ } else
+ $pid = 1;
+ }
+
+ // polovimo podatke iz baze
+ // prvo polovimo nastavitve profila (id,name, system, variables)
+ $selectSqlProfile = "SELECT * FROM srv_variable_profiles WHERE id = '".$pid."' AND sid = '". self::getSurveyID()."' AND uid='". self::getUserID()."'";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+ $rowProfileSetting = mysqli_fetch_assoc($sqlProfileSetting);
+ $result = array( 'id' => $rowProfileSetting['id'],
+ 'name' => $rowProfileSetting['name'],
+ 'system' => $rowProfileSetting['system'],
+ 'variables'=> array());
+ // variable vrnemo kot array $key == $value;
+ foreach (explode(',',$rowProfileSetting['variables']) as $vriabla ){
+
+ if ($vriabla)
+ $result['variables'][$vriabla] = $vriabla;
+ }
+ // string iz baze za variables razbijemo v array
+ return $result;
+ }
+
+ static function getProfileVariables($pid) {
+
+ $_pd = self::getProfileData($pid);
+ return $_pd['variables'];
+ }
+ static function setProfileVariables($pid, $variables) {
+ if ($pid == 0) {
+ $sid = self::getSurveyId();
+ // nastavimo kot sejo
+ if ( !isset($_SESSION['variables_profile'][$sid]) ) {
+ global $lang;
+ //kreiramo začasin profil
+ $_SESSION['variables_profile'][$sid]['id'] = '0';
+ $_SESSION['variables_profile'][$sid]['name'] = $lang['srv_missing_profile_temp'];
+ $_SESSION['variables_profile'][$sid]['system'] = '0';
+ }
+ // počistimo stare vrednosti
+ $_SESSION['variables_profile'][$sid]['variables'] = array();
+ foreach (explode(',',$variables) as $vriabla ){
+ if ($vriabla)
+ $_SESSION['variables_profile'][$sid]['variables'][$vriabla] = $vriabla;
+ }
+ // dodoamo še v class
+ self::$availableProfiles[0] = array( 'id' => $_SESSION['variables_profile'][$sid]['id'],
+ 'name' => $_SESSION['variables_profile'][$sid]['name'],
+ 'system'=> $_SESSION['variables_profile'][$sid]['system'],
+ 'variables'=> $_SESSION['variables_profile'][$sid]['variables']);
+ } else {
+
+ $updateString = "UPDATE srv_variable_profiles SET variables = '" . $variables . "' WHERE id = '" . $pid . "' AND sid = '". self::getSurveyID()."' AND uid='". self::getUserID()."'";
+
+ $sqlupdate = sisplet_query($updateString) or die(mysqli_error($GLOBALS['connect_db']));
+ self::$availableProfiles[$pid]['variables'] = array();
+ foreach (explode(',',$variables) as $vriabla ){
+ if ($vriabla)
+ self::$availableProfiles[$pid]['variables'][$vriabla] = $vriabla;
+ }
+ }
+ }
+
+ function getAvailableVariables ($assArray = false) {
+ $variablesFilter = array ();
+ $sqlSpremenljivkeAnkete = sisplet_query("SELECT s.tip, s.naslov, s.variable, s.id, s.textfield, s.textfield_label FROM srv_grupa g, srv_spremenljivka s WHERE g.ank_id='".self::getSurveyID()."' AND g.id=s.gru_id ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ while ($rowSpremenljivkeAnkete = mysqli_fetch_assoc($sqlSpremenljivkeAnkete)) {
+ $value = $rowSpremenljivkeAnkete['id'];
+ $text = strip_tags("(" . $rowSpremenljivkeAnkete['variable'] . ") - " . $rowSpremenljivkeAnkete['naslov']);
+ if ($assArray)
+ $variablesFilter[] = $value;
+ else
+ $variablesFilter[] = array (
+ 'value' => $value,
+ 'text' => $text
+ );
+ }
+ return $variablesFilter;
+ }
+
+ static function checkDefaultProfile($dvp) {
+ // preverimo ali izbran privzet profil obstaja
+ if ($dvp == 0) { //preverimo sejo
+ if ( isset($_SESSION['variables_profile'][self::getSurveyId()]) ) {
+ return $_SESSION['variables_profile'][self::getSurveyId()]['id'];
+ } else { // morali bi imeti sejo pa je ni, zato nastavimo na privzetega (1)
+ $dvp = 1;
+ }
+ }
+
+ if ($dvp > 0 ) {
+ $stringSelect = "SELECT id FROM srv_variable_profiles WHERE id = '" . $dvp . "'";
+ $sqlSelect = sisplet_query($stringSelect);
+
+ if (mysqli_num_rows($sqlSelect) > 0) {// profil obstaja
+ $rowSelect = mysqli_fetch_assoc($sqlSelect);
+ return $rowSelect['id'];
+ }
+ }
+
+ // če ne izberemo osnovni profil
+ return self::checkBaseProfileExisit();
+ }
+
+ static function newProfileVariables($profileName=null, $data) {
+ global $global_user_id, $lang;
+ $profileId = -1;
+ $numrows = -1;
+
+ // ime profila preverima ali obstaja
+ if (!$profileName || $profileName == null || $profileName == "")
+ $profileName = $lang['srv_new_profile_name'];
+
+ do { // preverimo ali ime že obstaja
+ $selectSqlProfile = "SELECT * FROM srv_variable_profiles WHERE name = '" . $profileName . "' AND sid = '" . self::getSurveyID() . "' AND uid = '" . self::getUserID() . "'";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+ $numrows = mysqli_num_rows($sqlProfileSetting);
+ if ($numrows != 0) { // ime že obstaja zgeneriramo novo
+ srand(time());
+ $profileName .= rand(0, 9);
+ }
+ } while ($numrows != 0);
+
+ // poiščemo zadnji id
+ $selectProfileId = "SELECT max(id) as last_id FROM srv_variable_profiles WHERE sid = '" . self::getSurveyID() . "' AND uid = '" . self::getUserID() . "'";
+ $sqlProfileId = sisplet_query($selectProfileId);
+ $rowProfileId = mysqli_fetch_assoc($sqlProfileId);
+ $profileId = $rowProfileId['last_id']+1;
+ $stringInsert = "INSERT INTO srv_variable_profiles (id, sid, uid, name, system, variables) " .
+ "VALUES ('".$profileId."', '" . self::getSurveyID() . "', '" . self::getUserID() . "', '" . $profileName . "', '0', '".$data."')";
+ sisplet_query($stringInsert);
+ $insertId = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($insertId > 1) {
+ $profileId = $insertId;
+ }
+ return $profileId;
+
+ }
+
+ function deleteVariableProfile($profileId) {
+ if ($profileId == 0 ) { // seja -
+ unset($_SESSION['variables_profile'][self::getSurveyId()]);
+ } else {
+ $deleteString = "DELETE FROM srv_variable_profiles WHERE id = '" . $profileId . "' AND `system` != '1'";
+ $sqlDelete = sisplet_query($deleteString);
+ }
+
+ return self::checkBaseProfileExisit();
+ }
+ function renameVariableProfile($profileId, $newProfileName) {
+ global $lang;
+ $sqlInsert = -1;
+ if ( $profileId != null && $profileId != "" && $profileId > 1) {
+ if ( $newProfileName == null || $newProfileName == "" ) {
+ $newProfileName = $lang['srv_new_profile_name'];
+ }
+
+ $numrows = -1;
+ do { // preverimo ali ime že obstaja
+ $selectSqlProfile = "SELECT * FROM srv_variable_profiles WHERE name = '" . $newProfileName . "' AND sid = '" . self::getSurveyID() . "' AND uid = '" . self::getUserID() . "'";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+
+ $numrows = mysqli_num_rows($sqlProfileSetting);
+ if ($numrows != 0) { // ime že obstaja zgeneriramo novo
+ srand(time());
+ $newProfileName .= rand(0, 9);
+ }
+ } while ($numrows != 0);
+
+ $updateString = "UPDATE srv_variable_profiles SET name = '" . $newProfileName . "' WHERE id = '" . $profileId . "'";
+ $sqlInsert = sisplet_query($updateString);
+ }
+ return $sqlInsert;
+ }
+}
+?>
diff --git a/admin/survey/classes/class.SurveyGetHeatMapRadij.php b/admin/survey/classes/class.SurveyGetHeatMapRadij.php
new file mode 100644
index 0000000..7898075
--- /dev/null
+++ b/admin/survey/classes/class.SurveyGetHeatMapRadij.php
@@ -0,0 +1,29 @@
+<?php
+/**
+ * November 2016
+ *
+ * Pridobi podatke o radiju za heatmap
+ *
+ * @author Patrik Pucer
+ */
+class SurveyGetHeatMapRadij
+{
+
+ function __construct() {
+ }
+
+ function ajax() {
+
+ if(isset($_POST['sprid'])) {
+ $anketa = $_POST['anketa'];
+ $sprid = $_POST['sprid'];
+ $heatmapId = 'heatmap'.$sprid;
+
+ SurveyUserSession::Init($anketa);
+ // Shranimo spremenjene nastavitve radija v bazo
+ $radij = SurveyUserSession::getData($heatmapId);
+ echo $radij;
+ }
+ exit();
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyHeatMap.php b/admin/survey/classes/class.SurveyHeatMap.php
new file mode 100644
index 0000000..0fa4af3
--- /dev/null
+++ b/admin/survey/classes/class.SurveyHeatMap.php
@@ -0,0 +1,76 @@
+<?php
+/**
+ * November 2016
+ *
+ * Pridobi podatke o klikanih tockah na slikah, za njihov prikaz v heatmap
+ *
+ * @author Patrik Pucer
+ */
+
+include_once('../survey/definition.php');
+
+class SurveyHeatMap
+{
+ function __construct() {
+ }
+
+
+ function ajax() {
+ if(isset($_POST['heatmap_data'])) {
+ $heatmap_data = $_POST['heatmap_data'];
+
+ $dataPointValue = array();
+ $data = array();
+
+ #nov del - za pobiranje podatkov iz baze
+ $str_query = "SELECT sdm.lat, sdm.lng, sdm.usr_id "
+ . "FROM srv_data_heatmap AS sdm JOIN srv_user AS u ON sdm.usr_id = u.id WHERE u.deleted = '0' AND sdm.spr_id = ". $heatmap_data['spr_id'];
+
+ if($heatmap_data['usr_id'] != '-1'){
+ $str_query.=" AND usr_id = ". $heatmap_data['usr_id'];
+ }
+
+ if($heatmap_data['loop_id'] != '0' && $heatmap_data['loop_id'] != '-1'){
+ $str_query.=" AND loop_id = ". $heatmap_data['loop_id'];
+ }
+
+
+ $heatmap_data2 = array();
+ $data = sisplet_query($str_query);
+
+ while ($row1 = mysqli_fetch_array($data)) {
+ $heatmap_data2[] = $row1;
+ }
+
+ //error_log(json_encode($heatmap_data));
+ //error_log(json_encode($heatmap_data2));
+
+ #nov del - za pobiranje podatkov iz baze - konec
+
+
+ //************* pridobitev stevila podatkov v object-u
+ $i = 0;
+ foreach($heatmap_data2 as $key => $value) {
+ $i++;
+ }
+ $heatmap_data_size = $i - 3;
+ //error_log("heatmap_data_size ".$heatmap_data_size);
+ //************* pridobitev stevila podatkov v object-u - konec
+
+
+ for ($i = 0; $i<$heatmap_data_size; $i++){
+ //error_log('| '.$i.'. lat: '.$heatmap_data2[$i]['lat'].' lng: '.$heatmap_data2[$i]['lng'].' ');
+ $lat = $heatmap_data2[$i]['lat'];
+ $lng = $heatmap_data2[$i]['lng'];
+ $data = sisplet_query("SELECT COUNT(lat) as pointValue from srv_data_heatmap WHERE lat = $lat AND lng = $lng ");
+ $rowPointValue = mysqli_fetch_assoc($data);
+ $dataPointValue[$i] = $rowPointValue['pointValue'];
+ //error_log( '|'.$i.'. stevilo tock s temi koordinatami: '.$dataPointValue[$i]);
+ $heatmap_data2[$i]['text'] = $dataPointValue[$i];
+ }
+ echo json_encode($heatmap_data2);
+
+ }
+ exit();
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyHeatMapBackground.php b/admin/survey/classes/class.SurveyHeatMapBackground.php
new file mode 100644
index 0000000..0b37a7e
--- /dev/null
+++ b/admin/survey/classes/class.SurveyHeatMapBackground.php
@@ -0,0 +1,137 @@
+<?php
+/**
+ * November 2016
+ *
+ * Pridobi podatke o klikanih tockah na slikah, za njihov prikaz v heatmap
+ *
+ * @author Patrik Pucer
+ */
+include_once('../survey/definition.php');
+
+class SurveyHeatMapBackground
+{
+ function __construct() {
+ }
+
+ function ajax() {
+ if(isset($_POST['heatmapBackground_data'])) {
+ $spr_id = $_POST['heatmapBackground_data'];
+ //echo $spr_id;
+ $data = sisplet_query("SELECT params from srv_spremenljivka WHERE id = $spr_id");
+ $rowImageHtml = mysqli_fetch_assoc($data);
+ $spremenljivkaParams = new enkaParameters($rowImageHtml['params']);
+
+ //kopiranje slike iz spleta, ce ta ni na lokalnem strezniku
+ //$this->getImagename('hotspot', $spr_id, 'hotspot_image=');
+ $text=$spremenljivkaParams->get('hotspot_image');
+ $this->changeHeatmapImage($text, $spr_id);
+ //kopiranje slike iz spleta, ce ta ni na lokalnem strezniku - konec
+
+
+ echo $spremenljivkaParams->get('hotspot_image');
+ }
+ exit();
+ }
+
+
+ //function getImagename($text, $sprId, $findme){
+ function changeHeatmapImage($text, $sprId){
+ global $site_path;
+ $imageName = $text;
+ //echo "imageName ".$imageName."</br>";
+ $findme = 'editor/';
+
+ $pos = strpos($imageName, $findme); //najdi pozicijo teksta 'editor/'
+ //echo "editor je tu ".$pos."</br>";
+
+ if($pos){ //ce je slika na strezniku
+ $slikaNaStrezniku = 1;
+ }else{//ce slike ni na strezniku
+ $slikaNaStrezniku = 0;
+ }
+
+ if($slikaNaStrezniku==0){ //ce slika ni na strezniku
+ $this->getOnlineImageName($imageName, $slikaNaStrezniku, $sprId); //pridobi njen URL
+ }
+ //$imageName = substr($imageName, 0, $pos-4); //pokazi le del params od zacetka besedila do '"'-4character manj ".png"/".jpg"*/
+
+ //echo "imagename pred return: ".$imageName."</br>";
+ //return $imageName;
+ }
+
+ function getEndPosition($imageName){
+ $findme = '"';
+ $pos = strpos($imageName, $findme); //najdi pozicijo teksta '"'
+ return $pos;
+ }
+
+ function getOnlineImageName($imageName, $slikaNaStrezniku, $sprId){
+ global $site_path;
+ global $site_url;
+ //$imageName = "jo je potrebno pobrati online";
+ //$row = Cache::srv_spremenljivka(self::$spremenljivka);
+ $row = Cache::srv_spremenljivka($sprId);
+ //echo "sprem: ".self::$spremenljivka."</br>";
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ //echo "params: ".$spremenljivkaParams->get('hotspot_image');
+ $imageName = $spremenljivkaParams->get('hotspot_image');
+
+ $findHttp = 'http';
+ $posHttp = strpos($imageName, $findHttp);
+ $imageName = substr($imageName,$posHttp); //besedilo do zacetka http
+
+ $pos = $this->getEndPosition($imageName); //najdi pozicijo konca URL slike
+ $imageName = substr($imageName, 0, $pos); //pokazi le del params od zacetka besedila do '"' oz. konca URL slike
+ $imageExtension = substr($imageName, $pos-3, 3); //pridobi koncnico slike
+
+ if($imageExtension!='jpg'&&$imageExtension!='png'&&$imageExtension!='gif'){ //ce ni veljavnen extension, spremeni ga v png
+ $imageExtension='png';
+ }
+
+ $imgFilename = $sprId.'tmpImage.'.$imageExtension; //tmp ime slike, ki je sestavljeno iz id spremenljivke+tmpImage+extension
+ $pathDir = $site_path.'uploadi/editor/'; //pot za novo mapo, kjer se bodo shranjevale slike za trenutno anketo
+ $path = $pathDir.$imgFilename; //pot do datoteke z imenom datoteke
+
+ # ukaz za pretakanje slike
+ if(IS_WINDOWS){
+ //za windows sisteme //powershell -command "& { iwr URL -OutFile 'PATH' }"
+ $command = 'powershell -command "& { iwr \''.$imageName.'\' -OutFile \''.$path.'\' }"';
+ }elseif(IS_LINUX){
+ //za linux sisteme //exec('wget URL -P PATH ');
+ //$command = 'wget \''.$imageName.'\' -P '.$path.' ';
+ $command = 'wget -O '.$path.' \''.$imageName.'\' ';
+ }
+ //echo $command;
+ exec($command); //pretoci sliko
+
+ //$path = $pathDir.$imgFilename; //pot do datoteke z imenom datoteke
+ if($imageExtension == 'gif' || $imageExtension == 'jpg'){ //ce je slika gif, jo je potrebno pretvoriti v png, saj latex ne podpira gif
+ //$this->convertGifToPng($path, $slikaNaStrezniku);
+ $this->convertGifToPng($path, $slikaNaStrezniku, $imageExtension);
+ }
+
+ }
+
+ function convertGifToPng($path, $slikaNaStrezniku, $imageExtension){
+ //echo "path: ".$path."</br>";
+ if($imageExtension == 'gif'){
+ $image = imagecreatefromgif($path); //pripravi sliko iz gif za pretvorbo
+ }elseif($imageExtension == 'jpg'){
+ $image = imagecreatefromjpeg($path); //pripravi sliko iz jpeg za pretvorbo
+ }
+ $imageName = substr($path, 0, -3); //ime slike brez extension-a
+ //echo $imageName."</br>";
+ $imageNamePNG = $imageName.'png'; //ime slike z ustreznim extension
+ imagepng($image, $imageNamePNG); //pretvori pripravljeno gif sliko v png
+
+ if($slikaNaStrezniku==0){ //ce slika je iz URL in ni na strezniku,
+ if($imageExtension == 'gif'){
+ unlink($imageName.'gif'); //izbrisi gif sliko
+ }elseif($imageExtension == 'jpg'){
+ unlink($imageName.'jpg'); //izbrisi jpg sliko
+ }
+ }
+ }
+
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyHeatMapExportIcons.php b/admin/survey/classes/class.SurveyHeatMapExportIcons.php
new file mode 100644
index 0000000..06e0b6a
--- /dev/null
+++ b/admin/survey/classes/class.SurveyHeatMapExportIcons.php
@@ -0,0 +1,24 @@
+<?php
+/**
+ * December 2016
+ *
+ * Pridobi kodo za prikazovanje gumbov za izvoz
+ *
+ * @author Patrik Pucer
+ */
+class SurveyHeatMapExportIcons
+{
+
+ function SurveyHeatMapExportIcons() {
+ }
+
+ function ajax() {
+ //if(isset($_POST['getheatmapexporticons'])) {
+ $anketa = $_POST['anketa'];
+ $sprid = $_POST['sprid'];
+
+ echo SurveyAnalysis::displayExportIcons4Heatmap($sprid, $anketa);
+ //}
+ exit();
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyHeatMapRadij.php b/admin/survey/classes/class.SurveyHeatMapRadij.php
new file mode 100644
index 0000000..c3e3c89
--- /dev/null
+++ b/admin/survey/classes/class.SurveyHeatMapRadij.php
@@ -0,0 +1,31 @@
+<?php
+/**
+ * November 2016
+ *
+ * Pridobi podatke o klikanih tockah na slikah, za njihov prikaz v heatmap
+ *
+ * @author Patrik Pucer
+ */
+class SurveyHeatMapRadij
+{
+
+ function __construct() {
+ }
+
+ function ajax() {
+ if(isset($_POST['heatmapRadij'])) {
+ $radij = $_POST['heatmapRadij'];
+ $anketa = $_POST['anketa'];
+ $sprid = $_POST['sprid'];
+ $heatmapId = 'heatmap'.$sprid;
+ //$heatmapData = ['radij'=>$radij, 'sprid'=>$sprid];
+
+ SurveyUserSession::Init($anketa);
+ // Shranimo spremenjene nastavitve radija v bazo
+ SurveyUserSession::saveData($radij, $heatmapId);
+ //SurveyUserSession::saveData($heatmapData, 'heatmap');
+
+ }
+ exit();
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyHeatMapSaveImage.php b/admin/survey/classes/class.SurveyHeatMapSaveImage.php
new file mode 100644
index 0000000..9556880
--- /dev/null
+++ b/admin/survey/classes/class.SurveyHeatMapSaveImage.php
@@ -0,0 +1,36 @@
+<?php
+/**
+ * Januar 2017
+ *
+ * Shrani heatmap porocilo v obliki slike
+ *
+ * @author Patrik Pucer
+ */
+class SurveyHeatMapImageSave
+{
+
+ function __construct() {
+ }
+
+ function ajax() {
+
+ global $site_url;
+ global $site_path;
+
+ if(isset($_POST['sprid'])) {
+ $sprid = $_POST['sprid'];
+ $heatmapId = 'heatmap'.$sprid;
+ $img = $_POST['image'];
+
+ define('UPLOAD_DIR', $site_path.'main/survey/uploads/');
+
+ $img = str_replace('data:image/png;base64,', '', $img);
+ $img = str_replace(' ', '+', $img);
+ $data = base64_decode($img);
+ $file = UPLOAD_DIR . $heatmapId . '.png';
+ $success = file_put_contents($file, $data);
+ print $success ? $file : 'Unable to save the file.';
+ }
+ //exit();
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyInfo.php b/admin/survey/classes/class.SurveyInfo.php
new file mode 100644
index 0000000..5e24766
--- /dev/null
+++ b/admin/survey/classes/class.SurveyInfo.php
@@ -0,0 +1,851 @@
+<?php
+/**
+ * Created on 6.4.2009
+ *
+ * @author: GOrazd Vesleič
+ */
+class SurveyInfo
+{
+ static private $instance;
+ static private $inited;
+
+ static private $surveyId = null;
+
+ static private $cntUsers = null;
+ static private $cntAnswers = null;
+ static private $cntApropriateAnswers = null; // ustrezni odgovori (status = 4,5)
+ static private $cntValidSurveys = null; // hrani stevilo ustrezno izpolnjenih vprasalnikov (status = 6)
+ static private $cntPartiallyValidSurveys = null; // hrani stevilo delno izpolnjenih vprasalnikov (status = 5)
+ static private $cntInvalidSurveys = null; // hrani stevilo neustrezno izpolnjenih vprasalnikov (status = 3 ali 4)
+ static private $cntGroups = null;
+ static private $cntQuestions = null;
+ static private $cntVarables = null;
+
+ static private $access_users = null;
+
+ static private $rowSurveyInit = null;
+ static private $rowUserInsertInfo = null;
+ static private $rowUserEditInfo = null;
+ static private $rowVsiUpo = null;
+ static private $rowFirstLast = null;
+
+ static private $surveyModules = null;
+
+ static public $dateTimeSeperator = ', ';
+
+ static private $enkaVersion = null;
+
+ protected function __construct() {}
+
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveyInfo();
+ }
+ return self::$instance;
+ }
+
+ /**
+ * ob inicializaciji samo nastavimo survey ID, podatke bomo polovili, ko jih bomo rabili
+ *
+ * @param mixed $_surveyId
+ */
+ static function SurveyInit($_surveyId)
+ {
+ self::$surveyId = $_surveyId;
+
+ self::$cntUsers = null;
+ self::$cntAnswers = null;
+ self::$cntApropriateAnswers = null;
+ self::$cntValidSurveys = null;
+ self::$cntPartiallyValidSurveys = null;
+ self::$cntInvalidSurveys = null;
+ self::$cntGroups = null;
+ self::$cntQuestions = null;
+ self::$cntVarables = null;
+ self::$access_users = null;
+ self::$rowSurveyInit = null;
+ self::$rowUserInsertInfo = null;
+ self::$rowUserEditInfo = null;
+ self::$rowVsiUpo = null;
+ self::$rowFirstLast = null;
+ self::$dateTimeSeperator = ', ';
+ self::$surveyModules = null;
+
+ self::$enkaVersion = null;
+
+ self::$inited = true;
+
+ return true;
+ }
+
+ /**
+ * Vsilimo ponovno branje podatkov iz baze. (Uporabljamo po updejtih srv_anketa)
+ */
+ static function resetSurveyData() {
+ self::$rowSurveyInit = null;
+ }
+
+ /**
+ * vrne stolpec ($key) iz tabele srv_anketa za inicializirano anketo
+ *
+ * @param mixed $key stolpec v tabeli srv_anketa
+ * @return vrednost v stolpcu $key
+ */
+ static function getSurveyColumn ($key) {
+ $row = self::getSurveyRow();
+ return $row[$key];
+ }
+
+ static function getSurveyRow () {
+ if (!self::$rowSurveyInit) {
+ $querySurveyInit = sisplet_query("SELECT * FROM srv_anketa WHERE id = '".self::$surveyId."'");
+ self::$rowSurveyInit = mysqli_fetch_assoc($querySurveyInit);
+ }
+
+ return self::$rowSurveyInit;
+ }
+
+ static function getUserInsertInfo ($key) {
+ if (!self::$rowUserInsertInfo) {
+ $sqlUserInsertInfo = sisplet_query("SELECT name, surname, id, email FROM users WHERE id='".self::getSurveyInsertUid()."'");
+ self::$rowUserInsertInfo = mysqli_fetch_assoc($sqlUserInsertInfo);
+ }
+
+ return self::$rowUserInsertInfo[$key];
+ }
+
+ static function getUserEditInfo ($key) {
+ if (!self::$rowUserEditInfo) {
+ $sqlUserEditInfo = sisplet_query("SELECT name, surname, id, email FROM users WHERE id='".self::getSurveyEditUid()."'");
+ self::$rowUserEditInfo = mysqli_fetch_assoc($sqlUserEditInfo);
+ }
+
+ return self::$rowUserEditInfo[$key];
+ }
+
+ static function getEnkaVersion($key) {
+ if (!self::$enkaVersion) {
+ $sqlEnkaVersion = sisplet_query("SELECT value FROM misc WHERE what='version' ");
+ self::$enkaVersion = mysqli_fetch_assoc($sqlEnkaVersion);
+ }
+
+ return self::$enkaVersion[$key];
+ }
+
+
+/*
+ static function getVsiUpo () {
+ if (!self::$rowVsiUpo) {
+ $sqlVsiUpo = sisplet_query("SELECT id AS usr_id FROM srv_user WHERE ank_id = '".self::$surveyId."' AND preview = '0'");
+ self::$rowVsiUpo = mysqli_fetch_assoc($sqlVsiUpo);
+ }
+ return self::$rowVsiUpo;
+ }
+ */
+ static function getFirstLast ($key) {
+ if (!self::$rowFirstLast) {
+ $sqlFirstLast = sisplet_query("SELECT min( time_insert ) as frst, max( time_insert ) as lst FROM srv_user WHERE ank_id = '".self::$surveyId."' AND preview ='0' AND deleted='0'");
+ self::$rowFirstLast = mysqli_fetch_assoc($sqlFirstLast);
+ }
+ return self::$rowFirstLast[$key];
+ }
+
+ // te funkcije ohranimo, da se obdrzi kompatibilnost za nazaj. Za naprej se lahko uporabi kar direktno getSurveyColumn (v primerih kjer se lahko)
+ static function getSurveyId() { return self::$surveyId; }
+ static function getSurveyTitle() { return strip_tags(self::getSurveyColumn('naslov')); }
+ static function getSurveyAkronim() { return strip_tags(self::getSurveyColumn('akronim')); }
+ static function getSurveyActive() { return self::getSurveyColumn('active'); }
+ static function getSurveyFolder() { return self::getSurveyColumn('folder'); }
+ static function getSurveyInfo() { return self::getSurveyColumn('intro_opomba'); }
+ static function getSurveyType() { return self::getSurveyColumn('survey_type'); }
+
+ static function getSurveyShowIntro() { return self::getSurveyColumn('show_intro'); }
+ static function getSurveyShowConcl() { return self::getSurveyColumn('show_concl'); }
+ static function getSurveyIntro() { return strip_tags(self::getSurveyColumn('introduction')); }
+ static function getSurveyConcl() { return strip_tags(self::getSurveyColumn('conclusion')); }
+ static function getSurveyCountType() { return self::getSurveyColumn('countType'); }
+ static function getSurveyInsertUid() { return self::getSurveyColumn('insert_uid'); }
+ static function getSurveyInsertName() {
+ if (trim(self::getUserInsertInfo('name')) || trim(self::getUserInsertInfo('surname'))) {
+ return self::getUserInsertInfo('name').(trim(self::getUserInsertInfo('name')) || trim(self::getUserInsertInfo('surname')) ? ' ' : '').self::getUserInsertInfo('surname');
+ } else {
+ global $lang;
+ return $lang['srv_anonymous'];
+ }
+ }
+
+ static function getSurveyInsertNameShort(){
+ return substr(self::getUserInsertInfo('name'),0,1).substr(self::getUserInsertInfo('surname'),0,1);
+ }
+ static function getSurveyInsertEmail() {
+ if (trim(self::getUserInsertInfo('email'))) {
+ return self::getUserInsertInfo('email');
+ } else {
+ global $lang;
+ return $lang['srv_anonymous'];
+ }
+ }
+ static function getSurveyInsertDate() { $insertDateTime = explode(" ", self::getSurveyColumn('insert_time')); $tmpDate = explode('-',$insertDateTime[0]); return $tmpDate[2].".".$tmpDate[1].".".$tmpDate[0]; }
+ static function getSurveyInsertTime() { $insertDateTime = explode(" ", self::getSurveyColumn('insert_time')); return $insertDateTime[1]; }
+ static function getSurveyEditUid() { return self::getSurveyColumn('edit_uid'); }
+ static function getSurveyEditName() {
+ if (trim(self::getUserEditInfo('name')) || trim(self::getUserEditInfo('surname'))) {
+ return self::getUserEditInfo('name').(trim(self::getUserEditInfo('name')) || trim(self::getUserEditInfo('surname')) ? ' ' : '').self::getUserEditInfo('surname');
+ } else {
+ global $lang;
+ return $lang['srv_anonymous'];
+ }
+ }
+ static function getSurveyEditNameShort(){
+ return substr(self::getUserEditInfo('name'),0,1).substr(self::getUserEditInfo('surname'),0,1);
+ }
+ static function getSurveyEditEmail() {
+ if (trim(self::getUserEditInfo('email'))) {
+ return self::getUserEditInfo('email');
+ } else {
+ global $lang;
+ return $lang['srv_anonymous'];
+ }
+ }
+ static function getSurveyEditDate() { $editDateTime = explode(" ", self::getSurveyColumn('edit_time')); $tmpDate = explode('-',$editDateTime[0]); return $tmpDate[2].".".$tmpDate[1].".".$tmpDate[0]; }
+ static function getSurveyEditTime() { $editDateTime = explode(" ", self::getSurveyColumn('edit_time')); return $edit_time = $editDateTime[1]; }
+ static function getSurveyStartsDate() { $tmpDate = explode('-',self::getSurveyColumn('starts')); return $tmpDate[2].".".$tmpDate[1].".".$tmpDate[0]; }
+ static function getSurveyExpireDate() { $tmpDate = explode('-',self::getSurveyColumn('expire')); return $tmpDate[2].".".$tmpDate[1].".".$tmpDate[0]; }
+
+ static function getSurveyFirstEntryDate() {
+ if (self::getFirstLast('frst') == '0000-00-00 00:00:00' || self::getFirstLast('frst') == null)
+ return null;
+ $firstDateTime = explode(" ", self::getFirstLast('frst')); $tmpDate = explode('-',$firstDateTime[0]); return $tmpDate[2].".".$tmpDate[1].".".$tmpDate[0];
+ }
+ static function getSurveyLastEntryDate() {
+ if (self::getFirstLast('lst') == '0000-00-00 00:00:00' || self::getFirstLast('lst') == null)
+ return null;
+ $lastDateTime = explode(" ", self::getFirstLast('lst')); $tmpDate = explode('-',$lastDateTime[0]); return $tmpDate[2].".".$tmpDate[1].".".$tmpDate[0];
+ }
+
+ static function getSurveyFirstEntryTime() { $firstDateTime = explode(" ", self::getFirstLast('frst')); $tmpDate = explode(':',$firstDateTime[1]); return $tmpDate[0].":".$tmpDate[1].":".$tmpDate[2]; }
+ static function getSurveyLastEntryTime() { $lastDateTime = explode(" ", self::getFirstLast('lst')); $tmpDate = explode(':',$lastDateTime[1]); return $tmpDate[0].":".$tmpDate[1].":".$tmpDate[2]; }
+
+ static function getSurveyGroupCount() {
+ if (!self::$cntGroups) {
+ $sqlg = sisplet_query("SELECT count(*) FROM srv_grupa WHERE ank_id='".self::$surveyId."'");
+ $rowg = mysqli_fetch_row($sqlg);
+ self::$cntGroups = $rowg[0];
+ }
+ return self::$cntGroups;
+ }
+ /*
+ static function getSurveyUsersId() { return self::getVsiUpo(); }
+ static function getSurveyUsersCount() { return count(self::getVsiUpo()); }
+ */
+ static function getSurveyAnswersCount() {
+
+ if (!self::$cntAnswers) {
+ # ročno preštrejemo odgovore
+ $str_qry_all_users = "SELECT count(u.id) AS user_count FROM srv_user AS u " . "WHERE u.ank_id = '".self::getSurveyId()."' AND u.preview = '0' AND u.deleted='0'";
+ $qry_all_users = sisplet_query($str_qry_all_users);
+ $row_all_users = mysqli_fetch_assoc($qry_all_users);
+ self::$cntAnswers = $row_all_users['user_count'];
+ }
+
+ return self::$cntAnswers;
+ }
+
+ static function getSurveyApropriateAnswersCount() {
+ //@Uroš je 31.8.2017 dodal v funkcijo refreshData() v classSurveyList.php izkljucevanje lurkerjev v stolpcu approp
+ //v DB tabeli srv_survey_list. Prej so bili v approp vkljuceni vsi userji s parametri "preview = '0' AND deleted='0' AND last_status IN (5,6)"
+ //zaenkrat se se naj uporablja ta funkcija, ker bi drugace prislo do razhajanja v stevilu ustreznih enot, ker se
+ //podatki za stare ankete ne bi posodobili (bi bili se vedno vkljuceni lurkerji)
+ //enkrat v prihodnosti, bi se lahko klicalo samo SELECT approp FROM srv_survey_list WHERE id='self::getSurveyId()'
+ //tocen datum, kdaj se bo yadeva updatala na produkcijo, glej datum prvega updata po tej spremembi
+
+ if (!self::$cntApropriateAnswers) {
+ # ročno preštrejemo veljavne odgovore
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . self::getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status IN (5,6) AND lurker = 0"; // samo veljavne statuse
+ $qry_AppAnsw = sisplet_query($sqlStringAll);
+ $row_AppAnsw = mysqli_fetch_assoc($qry_AppAnsw);
+ self::$cntApropriateAnswers = $row_AppAnsw['cnt'];
+ }
+
+ return self::$cntApropriateAnswers;
+ }
+
+
+ static function getValidSurveysCount() {
+
+ if (!self::$cntValidSurveys) {
+ # rocno prestejemo veljavno (ali delno) veljavne vprasalnike
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id='" . self::getSurveyId() . "' AND last_status = '6' AND lurker = '0' AND deleted='0' AND preview = '0' AND testdata='0'"; // samo Completed status ali Partially completed
+ $qry_ValidSurveys = sisplet_query($sqlStringAll);
+ $row_ValidSurveys = mysqli_fetch_assoc($qry_ValidSurveys);
+ self::$cntValidSurveys = $row_ValidSurveys['cnt'];
+ }
+
+ return self::$cntValidSurveys;
+ }
+
+ static function getPartiallyValidSurveysCount() {
+
+ if (!self::$cntPartiallyValidSurveys) {
+ # rocno prestejemo veljavno (ali delno) veljavne vprasalnike
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id='" . self::getSurveyId() . "' AND last_status = '5' AND lurker = '0' AND deleted='0' AND preview = '0' AND testdata='0'"; // samo Completed status ali Partially completed
+ $qry_PartiallyValidSurveys = sisplet_query($sqlStringAll);
+ $row_PartiallyValidSurveys = mysqli_fetch_assoc($qry_PartiallyValidSurveys);
+ self::$cntPartiallyValidSurveys = $row_PartiallyValidSurveys['cnt'];
+ }
+
+ return self::$cntPartiallyValidSurveys;
+ }
+
+ static function getInvalidSurveysCount() {
+
+ if (!self::$cntInvalidSurveys) {
+ # rocno prestejemo neveljavne vprasalnike
+ //$sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id='" . self::getSurveyId() . "' AND last_status IN (0,1,2,3,4,5l,6l) AND deleted='0' AND preview = '0' AND testdata='0'"; // samo invalid
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id='" . self::getSurveyId() . "' AND last_status IN (0,1,2,3,4,'5l', '6l') AND lurker = '1' AND deleted='0' AND preview = '0' AND testdata='0'"; // samo invalid
+ $qry_InvalidSurveys = sisplet_query($sqlStringAll);
+ $row_InvalidSurveys = mysqli_fetch_assoc($qry_InvalidSurveys);
+ self::$cntInvalidSurveys = $row_InvalidSurveys['cnt'];
+ }
+
+ return self::$cntInvalidSurveys;
+ }
+
+ static function getSurveyQuestionCount(){
+
+ if (!self::$cntQuestions) {
+ # zato ročno preštrejemo vprašanja
+ $str_qry_Questions = "SELECT s.id FROM srv_grupa g, srv_spremenljivka s WHERE g.ank_id='".self::getSurveyId()."' "." AND g.id=s.gru_id ";
+ $qry_Questions = sisplet_query($str_qry_Questions);
+ self::$cntQuestions = mysqli_num_rows($qry_Questions);
+ }
+
+ return self::$cntQuestions;
+ }
+
+ static function getSurveyVariableCount(){
+
+ if (!self::$cntVarables) {
+ #ročno preštrejemo variable
+ $str_qry_variables = "SELECT s.id, s.tip, s.size, s.enota FROM srv_grupa g, srv_spremenljivka s WHERE g.ank_id='".self::getSurveyId()."' "." AND g.id=s.gru_id ";
+ $qry_variables = sisplet_query($str_qry_variables);
+ self::$cntVarables = self::doVariablesCount($qry_variables);
+ }
+
+ return self::$cntVarables;
+ }
+
+ static function getDateTimeSeperator(){
+ return self::$dateTimeSeperator;
+ }
+
+ // preverimio še kdo ima dostop
+ static function getSurveyAccessUsers() {
+
+ if (!self::$access_users) {
+ self::$access_users= array();
+ $sqlDostop = sisplet_query("SELECT u.id, u.name, u.surname, u.email, dostop.alert_complete FROM users as u "
+ ." RIGHT JOIN (SELECT sd.uid, sd.alert_complete FROM srv_dostop as sd WHERE sd.ank_id='".self::$surveyId."') AS dostop ON u.id = dostop.uid WHERE u.id != '".self::getSurveyInsertUid()."'");
+ while ($rowDostop = mysqli_fetch_assoc($sqlDostop)) {
+ self::$access_users[] = $rowDostop;
+ }
+ }
+
+ return self::$access_users;
+ }
+
+ /** Polovimo vse datume aktivnosti ankete
+ *
+ * @return unknown_type
+ */
+ static function getSurveyActivity() {
+ $activity = array();
+ if ( self::getSurveyColumn('active') == 1 ) {
+ $_starts = self::getSurveyColumn('starts');
+ $_expire = self::getSurveyColumn('expire');
+
+ // izberemo samo unikatne zapise ki niso enaki trenutni aktivnosti
+ $str = "SELECT DISTINCT starts, expire FROM srv_activity WHERE not(starts = '".$_starts."' AND expire = '".$_expire."') AND sid = '".self::getSurveyId()."'";
+ $qry = sisplet_query($str);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $activity[] = array('starts'=>$row['starts'],'expire'=>$row['expire']);
+ }
+ // dodamo trenutno nastavljeno aktivnost
+ $activity[] = array('starts'=>$_starts,'expire'=>$_expire);
+
+ } else {
+ // anketa ni aktivna, preberemo samo iz tabele aktivnosti
+ $str = "SELECT DISTINCT starts, expire FROM srv_activity WHERE sid = '".self::getSurveyId()."'";
+ $qry = sisplet_query($str);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $activity[] = array('starts'=>$row['starts'],'expire'=>$row['expire']);
+ }
+
+ }
+ return $activity;
+ }
+
+
+ static function DisplayInfoBox($showIcons = false) {
+ global $lang;
+ global $site_url;
+ global $global_user_id;
+
+ // Ce smo v seznamu anket upostevamo splosni jezik in ne jezik ankete
+ if(isset($_GET['a']) && $_GET['a'] == 'surveyList_display_info'){
+
+ $lang_orig = $lang['id'];
+
+ $sql = sisplet_query("SELECT lang FROM users WHERE id = '$global_user_id'");
+ $row = mysqli_fetch_array($sql);
+ $lang_admin = $row['lang'];
+
+ // Naložimo jezikovno datoteko
+ if($lang_admin != $lang_orig){
+ $file = '../../lang/'.$lang_admin.'.php';
+ include($file);
+ }
+
+ echo '<div class="popup_close">';
+ echo ' <a style="position:absolute; right:10px; top:10px" href="#" title="'.$lang['srv_zapri'].'" onclick="$(\'#survey_list_info\').hide(); return false;">✕</a>';
+ echo '</div>';
+ }
+
+ echo '<span class="survey_info_title">'.$lang['srv_status_osnovni'].'</span><br /><br />';
+
+ // spremenljivk
+ echo '<span class="space">' . $lang['srv_info_name'] . ':</span>' . self::getSurveyTitle() . '<br/>';
+ echo '<span class="space">' . $lang['srv_info_type'] . ':</span>' . $lang['srv_vrsta_survey_type_'.self::getSurveyType()] . '<br/>';
+ echo '<span class="space">' . $lang['srv_info_questions']. ':</span>' .self::getSurveyQuestionCount().'<br/>';
+ echo '<span class="space">' . $lang['srv_info_variables']. ':</span>' .self::getSurveyVariableCount().'<br/>';
+ echo '<span class="space">' . $lang['srv_info_answers']. ':</span>' .self::getSurveyAnswersCount().'<br/>';
+ echo '<span class="space">' . $lang['srv_info_answers_valid']. ':</span>' .self::getSurveyApropriateAnswersCount().'<br/>';
+
+ # jezik izpolnjevanja
+ echo '<span class="space">' . $lang['srv_info_language']. ':</span>'.self::getRespondentLanguage().'<br/>';
+ echo '<span class="space">' . ($showIcons ? '<span class="sprites user" title="'.$lang['srv_info_author'].'"></span> ' : '' )
+ . $lang['srv_info_author']. ':</span>' .self::getSurveyInsertEmail();
+ if (self::getSurveyInsertDate() && self::getSurveyInsertDate() != "00.00.0000")
+ echo self::$dateTimeSeperator . self::getSurveyInsertDate();
+ if (self::getSurveyInsertTime() && self::getSurveyInsertTime() != "00:00:00")
+ echo self::$dateTimeSeperator . self::getSurveyInsertTime();
+ echo '<br/>';
+
+ echo '<span class="space">' . ($showIcons ? '<span class="sprites user_edit" title="'.$lang['srv_info_modify'].'"></span> ' : '' )
+ . $lang['srv_info_modify']. ':</span>' .self::getSurveyEditEmail();
+ if (self::getSurveyEditDate() && self::getSurveyEditDate() != "00.00.0000")
+ echo self::$dateTimeSeperator . self::getSurveyEditDate() ;
+ if (self::getSurveyEditTime() && self::getSurveyEditTime() != "00:00:00")
+ echo self::$dateTimeSeperator . self::getSurveyEditTime();
+ echo '<br/>';
+
+ $dostop = self::getSurveyAccessUsers();
+ // dostop, Kdo razen avtorja ima dostop
+ if ($dostop) {
+ $cnt=0;
+ foreach ( $dostop as $user) {
+ if ($cnt==0) {
+ echo '<span class="space">';
+ echo ($showIcons ? '<span class="sprites user_add" title="'.$lang['srv_info_access'].'"></span> ' : '');
+ echo $lang['srv_info_access']. ': </span>'.$user['name']." (".$user['email'].")<br/>";
+ }
+
+ else
+ echo '<span class="infoData">'.$user['name']." (".$user['email'].')</span><br/>';
+ $cnt++;
+ }
+ }
+
+ // aktivnost
+ echo '<span class="space">';
+ echo ($showIcons ? '<span class="sprites clock_play" title="'.$lang['srv_info_activity'].'"></span> ' : '');
+ echo $lang['srv_info_activity']. ': </span>';
+ $activity = self:: getSurveyActivity();
+ if ( count($activity) > 0 ) {
+ $prefix = '';
+ foreach ($activity as $active) {
+ $_starts = explode('-',$active['starts']);
+ $_expire = explode('-',$active['expire']);
+
+ echo $prefix.$_starts[2].'.'.$_starts[1].'.'.$_starts[0].'-'.$_expire[2].'.'.$_expire[1].'.'.$_expire[0];
+ $prefix = '; ';
+ }
+ } else {
+ echo $lang['srv_anketa_noactive2'].'!';
+ }
+ echo "<br />";
+
+ // prvi / zadnj vnos
+ if (trim(self::getSurveyFirstEntryDate()) != '') {
+ echo '<span class="space">';
+ echo ($showIcons ? '<span class="sprites date_previous" title="'.$lang['srv_info_first_entry'].'"></span> ' : '');
+ echo $lang['srv_info_first_entry']. ': </span>' . self::getSurveyFirstEntryDate() . self::$dateTimeSeperator .self::getSurveyFirstEntryTime() . '<br/>';
+ }
+ if (trim(self::getSurveyLastEntryDate()) != '') {
+ echo '<span class="space">';
+ echo ($showIcons ? '<span class="sprites date_next" title="'.$lang['srv_info_last_entry'].'"></span> ' : '');
+ echo $lang['srv_info_last_entry']. ': </span>' . self::getSurveyLastEntryDate() . self::$dateTimeSeperator . self::getSurveyLastEntryTime() . '<br/>';
+ }
+
+ echo '<br class="clr"/>';
+
+ $link = $site_url.'admin/survey/index.php?anketa=' . self::$surveyId.'&a=reporti';
+ echo '<span style="text-transform:capitalize; font-weight:600;"><a class="link" href="'.$link.'">'.$lang['srv_more'].' >></a></span>';
+
+ // Ce smo v seznamu anket upostevamo splosni jezik in ne jezik ankete
+ if(isset($_GET['a']) && $_GET['a'] == 'surveyList_display_info'){
+
+ // Naložimo originalno jezikovno datoteko
+ if($lang_admin != $lang_orig){
+ $file = '../../lang/'.$lang_orig.'.php';
+ include($file);
+ }
+ }
+ }
+
+ static function doVariablesCount($query) {
+ // zloopamo skozi vprašanja in za vsako vprašan je preberemo št variabel
+ $cnt= 0;
+
+ while ($rowVprasanje = mysqli_fetch_assoc($query)) {
+
+ $spr_id= $rowVprasanje['id'];
+ switch ( $rowVprasanje['tip'] ) { // v odvisnosti od tipa vprašanja pohandlamo podatke
+ case 1: // radio
+ case 3: // dropdown
+ $cnt++; // za sam header
+ $sqlSrvVred = self::select_sql_vrednost($rowVprasanje['id']);
+ while ( $rowSrvVred = mysqli_fetch_assoc($sqlSrvVred) ) {
+ if ($rowSrvVred['other'] == 1)
+ {
+ $cnt++; // za text polje
+ }
+ }
+ break;
+ case 2: // checkbox
+ case 6: // multigrid
+ case 18: // vsota
+ case 17: // ranking
+ case 21: // text*
+// $cnt++; // za sam header
+ $sqlSrvVred = self::select_sql_vrednost($rowVprasanje['id']);
+ while ( $rowSrvVred = mysqli_fetch_assoc($sqlSrvVred) ) {
+ $cnt++; // za vsako variablo
+ if ($rowSrvVred['other'] == 1) {
+ $cnt++; // za text polje (polj edrugo še ima tekstovni vnos
+ }
+ }
+ break;
+ case 4: // text
+ case 8: // datum
+ case 7: // number
+ case 22:// compute
+ case 25:// kvota
+ $cnt++;
+ if ( $rowVprasanje['tip'] == 7 && $rowVprasanje['size'] != 1 ) {
+ $cnt+=2;
+ }
+ break;
+ case 16: // multicheckbox
+ case 19: // multitext
+ case 20: // multinumber
+ $cnt++; // za sam header
+ $sqlSrvVred = self::select_sql_vrednost($spr_id);
+ //gridi s katerimi sestavljamo header (vrstica_grid)
+ while ( $rowSrvVred = mysqli_fetch_assoc($sqlSrvVred) ) {
+ //loop cez gride znotraj ene vrstice - ponovimo za vsako vrstico
+ $sqlSrvGrid = self::select_sql_grid($spr_id);
+ while ( $colSrvVred = mysqli_fetch_assoc($sqlSrvGrid) ) {
+ $cnt++;
+ }
+ if ($rowSrvVred['other'] == 1) {
+ $cnt++;
+ }
+ }
+ break;
+ case 26: // lokacija
+ if($rowVprasanje['enota'] == 3){
+ $sqlSrvVred = self::select_sql_vrednost($rowVprasanje['id']);
+ while ( $rowSrvVred = mysqli_fetch_assoc($sqlSrvVred) ) {
+ $cnt++; // za vsako variablo
+ }
+ }
+ else
+ $cnt++; // moja lokacija in multilokacija je 1
+ break;
+ case 27: // heatmap
+ $cnt++; // za koordinate
+ $sqlSrvVred = self::select_sql_vrednost($rowVprasanje['id']);
+ while ( $rowSrvVred = mysqli_fetch_assoc($sqlSrvVred) ) { //za morebitna obmocja
+ $cnt++; // za vsako variablo
+ if ($rowSrvVred['other'] == 1) {
+ $cnt++; // za text polje (polj edrugo še ima tekstovni vnos
+ }
+ }
+ break;
+ } // end switch
+
+ } // end while
+ return $cnt;
+ }
+
+ // pointerji do vrednosti zaradi hitrosti
+ /**
+ * @desc vrne sisplet_query za podan spr_id. v bistvu kesramo queryje, ker jih uporabljamo (zlo pogosto) v izpisu
+ */
+ //static private $otherCondition = ' AND other NOT IN (99,98,97,96)';
+ static private $otherCondition = '';
+ private static $_select_sql_vrednost = array();
+ static function select_sql_vrednost ($spr_id) {
+ if ( isset(self::$_select_sql_vrednost[$spr_id]) ) {
+ // resetiramo pointer in vrnemo ke�iran query
+ if (mysqli_num_rows(self::$_select_sql_vrednost[$spr_id]))
+ mysqli_data_seek(self::$_select_sql_vrednost[$spr_id], 0);
+ return self::$_select_sql_vrednost[$spr_id];
+ }
+ else {
+ self::$_select_sql_vrednost[$spr_id] = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id='".$spr_id."' AND vrstni_red > 0".self::$otherCondition." ORDER BY vrstni_red ASC");
+ return self::$_select_sql_vrednost[$spr_id];
+ }
+ }
+ /**
+ * @desc vrne sisplet_query za podan spr_id. v bistvu kesramo queryje, ker jih uporabljamo (zlo pogosto) v izpisu
+ */
+ private static $_select_sql_grid = array();
+ static function select_sql_grid ($spr_id) {
+ if ( isset(self::$_select_sql_grid[$spr_id]) ) {
+ // resetiramo pointer in vrnemo ke�iran query
+ if (mysqli_num_rows(self::$_select_sql_grid[$spr_id]))
+ mysqli_data_seek(self::$_select_sql_grid[$spr_id], 0);
+ return self::$_select_sql_grid[$spr_id];
+ }
+ else {
+ self::$_select_sql_grid[$spr_id] = sisplet_query("SELECT * FROM srv_grid WHERE spr_id='".$spr_id."' ORDER BY vrstni_red");
+ return self::$_select_sql_grid[$spr_id];
+ }
+ }
+
+ /**
+ * vrne URL naslov ankete (lahko je lep :) )
+ *
+ */
+ static private $surveyLink = array();
+ static function getSurveyLink ($anketa = false, $uporabnost = true) {
+ global $site_url;
+
+ if ($anketa == false)
+ $anketa = self::$surveyId;
+
+ // V get-u ni vec id ankete ampak string (zaradi zascite, da en more kdorkoli dostopati do vseh anket)
+ $anketa_string = Common::encryptAnketaID($anketa);
+
+ if ( ! isset( self::$surveyLink[$anketa_string] ) ) {
+
+ $sqll = sisplet_query("SELECT link FROM srv_nice_links WHERE ank_id = '".$anketa."' ORDER BY id ASC LIMIT 1");
+ if (mysqli_num_rows($sqll) > 0) {
+ $rowl = mysqli_fetch_array($sqll);
+
+ $link = $site_url . $rowl['link'] ;
+ }
+ else {
+ if (self::checkSurveyModule('uporabnost') && $uporabnost == true) // na redirectih pa v form action ne sme it na uporabnost (ker se odpira znotraj frama)
+ $link = $site_url.'main/survey/uporabnost.php?anketa=' . $anketa_string ;
+ else
+ $link = $site_url.'a/' . $anketa_string ;
+ }
+
+ self::$surveyLink[$anketa_string] = $link;
+ }
+
+ return self::$surveyLink[$anketa_string];
+ }
+
+ static function getRespondentLanguage() {
+ global $lang;
+ $lang_resp = SurveyInfo::getSurveyColumn('lang_resp');
+ if ($lang['id'] <> $lang_resp && $lang_resp > 0) {
+ $lang_old= $lang;
+
+ $file = dirname(__FILE__).'/../../../lang/'.$lang_resp.'.php';
+ if (file_exists($file)) {
+ include($file);
+ $_lang_name = $lang['language'];
+ $lang = $lang_old;
+ }
+ } else {
+ $_lang_name = $lang['language'];
+ }
+
+ $p = new Prevajanje(self::$surveyId);
+ $arr = $p->get_all_translation_langs();
+ $dodatni = '';
+ foreach ($arr AS $l) {
+ if ($dodatni != '') $dodatni .= ', ';
+ $dodatni .= $l;
+ }
+ if ($dodatni != '') $_lang_name .= ' ('.$dodatni.')';
+
+ return $_lang_name;
+ }
+
+ /**
+ * Polovimo vse module, ki so vklopljeni na anketi
+ */
+ public static function getSurveyModules($ime = null) {
+ global $global_user_id;
+
+ if (!self::$surveyModules) {
+
+ $modules = array();
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $sql = sisplet_query("SELECT modul, vrednost FROM srv_anketa_module WHERE ank_id='".self::getSurveyId()."'");
+ while($row = mysqli_fetch_array($sql)){
+
+ $module_availible = true;
+
+ // Preverimo, ce je modul omogocen v placljivem paketu
+ switch($row['modul']){
+
+ case 'uporabnost':
+ if(!$userAccess->checkUserAccess($what='uporabnost'))
+ $module_availible = false;
+ break;
+
+ case 'quiz':
+ if(!$userAccess->checkUserAccess($what='kviz'))
+ $module_availible = false;
+ break;
+
+ case 'voting':
+ if(!$userAccess->checkUserAccess($what='voting'))
+ $module_availible = false;
+ break;
+
+ case 'social_network':
+ if(!$userAccess->checkUserAccess($what='social_network'))
+ $module_availible = false;
+ break;
+
+ case 'slideshow':
+ if(!$userAccess->checkUserAccess($what='slideshow'))
+ $module_availible = false;
+ break;
+
+ case 'phone':
+ if(!$userAccess->checkUserAccess($what='telephone'))
+ $module_availible = false;
+ break;
+
+ case 'chat':
+ if(!$userAccess->checkUserAccess($what='chat'))
+ $module_availible = false;
+ break;
+
+ case 'panel':
+ if(!$userAccess->checkUserAccess($what='panel'))
+ $module_availible = false;
+ break;
+ }
+
+ // Ce je modul na voljo v paketu, ga dodamo v array
+ if($module_availible)
+ $modules[$row['modul']] = $row['vrednost'];
+ }
+
+ self::$surveyModules = $modules;
+ }
+
+ if(!is_null($ime) && isset(self::$surveyModules[$ime]))
+ return self::$surveyModules[$ime];
+ elseif(!is_null($ime) && sizeof(self::$surveyModules) == 0)
+ return 0;
+ else
+ return self::$surveyModules;
+ }
+
+ /**
+ * Preverimo, ce je specificen modul vklopljen na anketi
+ */
+ public static function checkSurveyModule($module, $anketa_id = null) {
+ global $global_user_id;
+
+ if(is_null($anketa_id))
+ $anketa_id = self::getSurveyId();
+
+ if($anketa_id > 0 && $module != ''){
+
+ // Preverimo, ce je modul omogocen v placljivem paketu
+ $userAccess = UserAccess::getInstance($global_user_id);
+ switch($module){
+
+ case 'uporabnost':
+ if(!$userAccess->checkUserAccess($what='uporabnost'))
+ return false;
+ break;
+
+ case 'quiz':
+ if(!$userAccess->checkUserAccess($what='kviz'))
+ return false;
+ break;
+
+ case 'voting':
+ if(!$userAccess->checkUserAccess($what='voting'))
+ return false;
+ break;
+
+ case 'social_network':
+ if(!$userAccess->checkUserAccess($what='social_network'))
+ return false;
+ break;
+
+ case 'slideshow':
+ if(!$userAccess->checkUserAccess($what='slideshow'))
+ return false;
+ break;
+
+ case 'phone':
+ if(!$userAccess->checkUserAccess($what='telephone'))
+ return false;
+ break;
+
+ case 'chat':
+ if(!$userAccess->checkUserAccess($what='chat'))
+ return false;
+ break;
+
+ case 'panel':
+ if(!$userAccess->checkUserAccess($what='panel'))
+ return false;
+ break;
+ }
+
+ if (!self::$surveyModules) {
+ $sql = sisplet_query("SELECT EXISTS (SELECT 1 FROM srv_anketa_module WHERE ank_id='".$anketa_id."' AND modul='".$module."')");
+ $row = mysqli_fetch_array($sql);
+
+ if($row[0] > 0)
+ return true;
+ else
+ return false;
+ }
+ else{
+ if(self::$surveyModules[$module] > 0)
+ return true;
+ else
+ return false;
+ }
+ }
+ else
+ return false;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyInpect.php b/admin/survey/classes/class.SurveyInpect.php
new file mode 100644
index 0000000..6bfac12
--- /dev/null
+++ b/admin/survey/classes/class.SurveyInpect.php
@@ -0,0 +1,757 @@
+<?php
+/**
+ * @author Gorazd Veselič
+ * @date November 2011
+ *
+ */
+
+define('SI_DEFAULT_PROFILE', false);
+define('SI_GOTO_ANALIZE', 0);
+define('SI_GOTO_VPOGLED', 1);
+define('SI_GOTO_PODATKI', 2);
+
+class SurveyInspect {
+
+ public $sid; # id ankete
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ function __construct($anketa) {
+
+ global $global_user_id;
+
+ $this->sid = $anketa;
+
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyUserSetting::getInstance()->Init($anketa, $global_user_id);
+
+ #inicializiramo class za datoteke
+ SurveyDataFile::get_instance();
+ SurveyDataFile::get_instance()->init($anketa);
+ $headFileName = SurveyDataFile::get_instance()->getHeaderFileName();
+ $dataFileStatus = SurveyDataFile::get_instance()->getStatus();
+
+
+ # polovimo header datoteko
+ if ($dataFileStatus == FILE_STATUS_NO_DATA
+ || $dataFileStatus == FILE_STATUS_NO_FILE
+ || $dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+ if ($headFileName !== null && $headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($headFileName));
+ }
+
+ session_start();
+ #nastavimo inspect
+ if (isset($_SESSION['enableInspect']) && $_SESSION['enableInspect'] == true) {
+ $this->enableInspect = true;
+ } else {
+ $this->enableInspect = false;
+ }
+
+ #nastavimo GOTO (analize,vpogled,podatki)
+ if (isset($_SESSION['inspect_goto'])) {
+ $this->inspect_goto = (int)$_SESSION['inspect_goto'];
+ } else {
+ $this->inspect_goto = 0;
+ }
+
+ }
+
+ public function isInspectEnabled() {
+ return $this->enableInspect;
+ }
+
+ public function whereToGo() {
+
+ $inspect_goto_array = array( SI_GOTO_ANALIZE => '&a=analysis&m=sumarnik',
+ SI_GOTO_VPOGLED => '&a=data&m=quick_edit',
+ SI_GOTO_PODATKI => '&a=data');
+
+ return ($inspect_goto_array[$this->inspect_goto]);
+ }
+
+ public function ajax() {
+
+ switch ($_GET['a']) {
+ case 'analizaPrepareInspect':
+ $this->PrepareInspectAnaliza();
+ break;
+ case 'changeSessionInspect':
+ $this->changeSessionInspect();
+ break;
+ case 'showInspectSettings':
+ $this->showInspectSettings();
+ break;
+ case 'show_inspectListSpr':
+ $this->showInspectListSpr();
+ break;
+ case 'saveInspectListVars':
+ $this->saveInspectListVars();
+ break;
+ case 'saveSettings':
+ $this->saveSettings();
+ break;
+ case 'displayInspectVars':
+ $this->displayInspectVars();
+ break;
+ case 'removeInspect':
+ $this->removeInspect();
+ break;
+ default:
+ print_r("<PRE>");
+ print_r($_POST);
+ print_r($_GET);
+ print_r("<PRE>");
+ break;
+ }
+ }
+
+ function PrepareInspectAnaliza() {
+ global $global_user_id, $lang;
+
+ # nastavimo filter variable
+ #izluščimo spr_id
+ $spr_data = explode('_',$_POST['spr_data']);
+ $spr = $spr_data[0];
+ $sequence = $spr_data[2];
+ $counter = $spr_data[3];
+ $_spr = $this->_HEADERS[$spr.'_0'];
+ # nastavimo v sejo od kod smo prišli v inspect:
+ session_start();
+ if ((isset($_POST['from_podstran']) && trim($_POST['from_podstran']) != '')) {
+ $_SESSION['inspectFromPodstran'][$this->sid] = $_POST['from_podstran'];
+ } else {
+ unset($_SESSION['inspectFromPodstran'][$this->sid]);
+ }
+ session_commit();
+ # naredimo inspect profil za variable
+ $variables = $spr.'_0';
+ $var_array[] = $variables;
+ if ($this->isInspectEnabled()) {
+ $_add_vars = $_SESSION['dataSetting_profile'][$this->sid]['InspectListVars'];
+ if (isset($_add_vars) && is_array($_add_vars) && count($_add_vars) > 0) {
+ foreach ($_add_vars AS $add_var) {
+ $variables .= ','.$add_var.'_0';
+ $var_array[] = $add_var.'_0';
+ }
+ }
+ }
+
+ $svp = new SurveyVariablesProfiles();
+ $svp -> Init($this->sid);
+ $svp-> setProfileInspect($var_array);
+
+ # if id za inspect shranimo v nastavitev ankete SurveyUserSetting -> inspect_if_id (če ne obstaja skreiramo novega)
+ # dodamo tudi kot profil pogojev (če ne obstaja skreiramo novega)
+
+ #preverimo ali obstaja zapis v SurveyUserSetting->inspect_if_id
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ # preverimo dejanski obstoj ifa (srv_if) če ne skreiramo novega
+ if ((int)$if_id > 0) {
+ $chks1 = "SELECT id FROM srv_if WHERE id='$if_id'";
+ $chkq1 = sisplet_query($chks1);
+ # dodamo še k profilu če ne obstaja
+ if (mysqli_num_rows($chkq1) == 0) {
+ $if_id = null;
+ SurveyUserSetting :: getInstance()->removeSettings('inspect_if_id');
+ }
+ }
+
+ if ( (int)$if_id == 0 || $if_id == null) {
+ # if še ne obstaja, skreiramo novga
+ $newIfString = "INSERT INTO srv_if (id) VALUES ('')";
+ $sql = sisplet_query($newIfString);
+ # if (!$sql) echo '<br> -1';
+
+ $if_id = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+ # shranimo pogoj kot privzet pogoj z ainspect
+ SurveyUserSetting :: getInstance()->saveSettings('inspect_if_id',(int)$if_id);
+ }
+ if ((int)$if_id > 0) {
+ # dodamo ifa za obe variabli
+ # ne brišemo starih pogojev, da omogočimo gnezdenje
+ #$delStr = "DELETE FROM srv_condition WHERE if_id = '$if_id'";
+ #sisplet_query($delStr);
+
+ # poiščemo vrednosti za oba vprašanja
+ $condition = $this->createSubCondition($_POST['vkey'],$if_id,$spr,$_spr,$sequence);
+ sisplet_query("COMMIT");
+
+ # pogoj dodamo še v srv_condition_profile vendar ga ne nastavimo kot privzetega
+ $chk_if_str = "SELECT id FROM srv_condition_profiles WHERE sid='".$this->sid."' AND uid = '".$global_user_id."' AND type='inspect'";
+ $chk_if_qry = sisplet_query($chk_if_str);
+ $_tmp_name = $lang['srv_inspect_temp_profile'];
+ if (mysqli_num_rows($chk_if_qry) > 0) {
+ # if že obstaja popravimo morebitne podatke
+ $str = "UPDATE srv_condition_profiles SET name = '$_tmp_name', if_id='$if_id'";
+ $sql = sisplet_query($str);
+ } else {
+ #vstavimo nov profil pogojev - inspect
+ $str = "INSERT INTO srv_condition_profiles (sid, uid, name, if_id, type ) VALUES ('".$this->sid."', '".$global_user_id."', '$_tmp_name', '$if_id', 'inspect')"
+ . " ON DUPLICATE KEY UPDATE name='$_tmp_name', if_id='$if_id'";
+ $sql = sisplet_query($str);
+ }
+ sisplet_query("COMMIT");
+ }
+ echo $this->whereToGo();
+ return $this->whereToGo();
+
+ }
+
+ function createSubCondition($vrednost,$if_id,$spr,$_spr,$sequence) {
+ $tip = $_spr['tip'];
+ # 1. Radio
+ # 3. Dropdown
+ # 2. Select - checkbox
+ if ($tip == '1' || $tip == '3' || $tip == '2')
+ {
+ #radio in dropdown
+ if ($tip == '1' || $tip == '3')
+ {
+ #s pomočjo k preberemo stni red
+ $sql_string = "SELECT id FROM srv_vrednost WHERE spr_id='$spr' AND variable = '".$vrednost."'";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) == 1 )
+ {
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ $vred_id = $sql_row['id'];
+ }
+ }
+ #select
+ if ($tip == '2' )
+ {
+ $vred_id=null;
+ # če je čekbox poiščemo vred_id za sekvenco k
+ foreach ($_spr['grids'] as $gkey=>$grid)
+ {
+ foreach ($grid['variables'] as $vkey=>$variable)
+ {
+ if ($variable['sequence'] == $sequence)
+ {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+ }
+
+ if ($vred_id != null && (int)$vred_id > 0) {
+ if ($tip == '2' && $vrednost == 0) {
+ $_operator_str = ', operator';
+ $_operator_val = ", '1'";
+ $_operator_repl = ", operator = '1'";
+ }
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red".$_operator_str.") VALUES ('$if_id', '$spr', '1'".$_operator_val.")"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1'".$_operator_repl;
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ if ((int)$vred_id > 0 || (int)$cond_id > 0) {
+ $istr = "INSERT INTO srv_condition_vre (cond_id, vre_id) VALUES ('$cond_id', '$vred_id')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+ return $cond_id;
+ }
+ }
+ # 6. multi radio
+ if ($tip == '6' ) {
+ # če je dvojni grid potem posebej polovimo vrednosti
+ list($enota) = mysqli_fetch_row(sisplet_query("SELECT enota FROM srv_spremenljivka WHERE id='$spr'"));
+ if($enota != 3) {
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ foreach ($_spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $sequence) {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+ $sql_string = "SELECT id FROM srv_grid WHERE spr_id='$spr' AND (variable = '".$vrednost."' OR other = '".$vrednost."')";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) == 1 ) {
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ $vrednost_id = $sql_row['id'];
+ }
+ } else {
+ $vred_id = $sequence;
+ # za dvojni grid moramo id polovit s pomočjo part
+ $_tmp = explode('_',$vrednost);
+ $vrednost = $_tmp[0];
+ $part = $_tmp[1];
+ $sql_string = "SELECT id FROM srv_grid WHERE spr_id='$spr' AND (variable = '".$vrednost."' OR other = '".$vrednost."') AND part = '$part'";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) == 1 ) {
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ $vrednost_id = $sql_row['id'];
+ }
+ }
+
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id) VALUES ('$if_id', '$spr', '1', '$vred_id')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1', vre_id='$vred_id'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ #dodamo še v srv_grid
+ if ($cond_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$vrednost_id."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } else {
+ echo '<br>-5 :: ';
+ }
+ return $cond_id;
+ }
+ }
+ # 7. Number
+ if ($tip == '7' ) {
+
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ foreach ($_spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $sequence) {
+ $grid_id = $vkey;
+ }
+ }
+ }
+
+ if ($grid_id !== null) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, grd_id, text) VALUES ('$if_id', '$spr', '1', '$grid_id', '$vrednost')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1', grd_id='$grid_id', text='$vrednost'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ return $cond_id;
+ }
+ }
+ # 16. multi checkbox
+ if ($tip == '16' ) {
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ foreach ($_spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $sequence) {
+ $vred_id = $variable['vr_id'];
+ $grid_id = $variable['gr_id'];
+ }
+ }
+ }
+ if ($vrednost == 0) {
+ $_operator_str = ', operator';
+ $_operator_val = ", '1'";
+ $_operator_repl = ", operator = '1'";
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id".$_operator_str.") VALUES ('$if_id', '$spr', '1', '$vred_id'".$_operator_val.")"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1', vre_id='$vred_id'".$_operator_repl;
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ #dodamo še v srv_grid
+ if ($cond_id > 0 && $grid_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$grid_id."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } else {
+ echo '<br>-5 :: ';
+ }
+ return $cond_id;
+ }
+ }
+ # 17. razvrščanje ranking
+ if ($tip == '17' ) {
+
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ foreach ($_spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $sequence) {
+ $vred_id = $variable['vr_id'];
+
+ }
+ }
+ }
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id) VALUES ('$if_id', '$spr', '1', '$vred_id')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1', vre_id='$vred_id'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ $grid_id = $_spr['options'][$vrednost];
+ #dodamo še v srv_grid
+ if ($cond_id > 0 && $grid_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$grid_id."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } else {
+ echo '<br>-5 :: ';
+ }
+ return $cond_id;
+ }
+ }
+ # 21. besedilo
+ # 18. vsota
+ if ($tip == '21' || $tip == '18') {
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+
+ foreach ($_spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $sequence) {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id, text) VALUES ('$if_id', '$spr', '1', '$vred_id', '$vrednost')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1', vre_id='$vred_id', text='$vrednost'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ return $cond_id;
+ }
+ }
+
+ # 19. multi text
+ # 20. multi number
+ if ($tip == '19' || $tip == '20') {
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ foreach ($_spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $sequence) {
+ $vred_id = $variable['vr_id'];
+ $grid_id = $variable['gr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0 && $grid_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id, grd_id, text) VALUES ('$if_id', '$spr', '1', '$vred_id', '$grid_id', '$vrednost')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr', vrstni_red = '1', grd_id='$grid_id', text='$vrednost'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ return $cond_id;
+ }
+ }
+
+ return null;
+ }
+ function changeSessionInspect() {
+ session_start();
+ #Zamenjamo sejo
+ if (isset($_SESSION['enableInspect']) && $_SESSION['enableInspect'] == true) {
+ unset($_SESSION['enableInspect']);
+ } else {
+ $_SESSION['enableInspect'] = true;
+ }
+ session_commit();
+
+ #nastavimo inspect
+ if (isset($_SESSION['enableInspect']) && $_SESSION['enableInspect'] == true) {
+ $this->enableInspect = true;
+ } else {
+ # če ne preberemo iz profila
+ $this->enableInspect = false;
+ }
+
+ $this->displaySessionInspectCheckbox((isset($_POST['isAnaliza']) && (int)$_POST['isAnaliza'] == 1) ? true : false);
+ }
+
+ function DisplayLink($hideAdvanced = true) {
+ global $lang;
+
+ $css = ($this->enableInspect == SI_DEFAULT_PROFILE ? ' gray' : '');
+ if ($hideAdvanced == false || $this->enableInspect != SI_DEFAULT_PROFILE) {
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="link_inspect" title="' . $lang['srv_inspect_setting'] . '" onClick="show_inspect_settings();">' . $lang['srv_inspect_setting'] . '</span>'."\n";
+ echo '</li>';
+
+ }
+ }
+ function displaySessionInspectCheckbox($isAnaliza=false) {
+ global $lang;
+ if ($isAnaliza == true) {
+ echo '<input type="checkbox" id="session_inspect" '.($this->enableInspect == true ? ' checked="checekd"' : '').' onClick="changeSessionInspectAnaliza();">'.$lang['srv_inspect_setting'];
+ } else {
+ echo '<input type="checkbox" id="session_inspect" '.($this->enableInspect == true ? ' checked="checekd"' : '').' onClick="changeSessionInspect();">'.$lang['srv_inspect_setting'];
+ }
+
+ echo Help :: display('srv_crosstab_inspect');
+ }
+
+ function showInspectSettings() {
+ global $lang;
+
+ echo '<div class="popup_close"><a href="#" onClick="inspectCloseSettings(); return false;">✕</a></div>';
+
+ // Naslov
+ echo '<h2>'.$lang['srv_inspect_setting'].'</h2>';
+
+ if ( $this->enableInspect != SI_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+ # Nastavitve za Inspect
+ echo '<p>'.$lang['srv_inspect_setting_link'].'</p>';
+ echo '<p>';
+ echo '<label>'.$lang['srv_inspect_setting_enabled'].'</label>';
+ echo '&nbsp;<input id="enableInspect0" name="enableInspect" type="radio" value="0"' .
+ (($this->enableInspect == false) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo '<label for="enableInspect0">'.$lang['no'].'</label>';
+
+ echo '&nbsp;<input id="enableInspect1" name="enableInspect" type="radio" value="1"' .
+ (($this->enableInspect == true) ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo '<label for="enableInspect1">'.$lang['yes'].'</label>';
+ echo Help :: display('srv_crosstab_inspect');
+ echo '</p>';
+ echo '<p>';
+ echo '<div>';
+ echo '<span class="floatLeft">'.$lang['srv_inspect_goto_note'].'</span>&nbsp;';
+ echo '<span class="floatLeft">';
+ echo '<label><input type="radio" name="inspectGoto" id="inspectGoto_'.SI_GOTO_ANALIZE.'" value="'.SI_GOTO_ANALIZE.'"'.($this->inspect_goto == SI_GOTO_ANALIZE ? ' checked="checked"' : '').' onchange="inspectRadioChange();return false;" autocomplete="off"/>'.$lang['srv_inspect_goto_'.SI_GOTO_ANALIZE].'</label><br/>';
+ echo '<label><input type="radio" name="inspectGoto" id="inspectGoto_'.SI_GOTO_VPOGLED.'" value="'.SI_GOTO_VPOGLED.'"'.($this->inspect_goto == SI_GOTO_VPOGLED ? ' checked="checked"' : '').' onchange="inspectRadioChange();return false;" autocomplete="off"/>'.$lang['srv_inspect_goto_'.SI_GOTO_VPOGLED].'</label> <br/>';
+ echo '<label><input type="radio" name="inspectGoto" id="inspectGoto_'.SI_GOTO_PODATKI.'" value="'.SI_GOTO_PODATKI.'"'.($this->inspect_goto == SI_GOTO_PODATKI ? ' checked="checked"' : '').' onchange="inspectRadioChange();return false;" autocomplete="off"/>'.$lang['srv_inspect_goto_'.SI_GOTO_PODATKI].'</label>';
+ echo '</span>';
+ echo '</div>';
+ echo'</p>';
+ echo'<br class="clr">';
+ echo '<p>';
+ echo '<div id="inspectListDiv" '.($this->inspect_goto != SI_GOTO_PODATKI ? ' class="displayNone"' : '').'>';
+ echo '<span>'.$lang['srv_inspect_setting_show_variables'].'</span>';
+ echo '<span id="inspectListSpr" class="as_link">';
+ $this->displayInspectVars();
+ echo '</span>';
+ echo '</div>';
+ echo '</p>';
+
+ echo '<span class="floatRight" title="'.$lang['srv_save_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inspectSaveSettings(); return false;"><span>'.$lang['srv_save_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inspectCloseSettings(); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+
+ // cover Div
+ echo '<div id="inspect_cover_div"></div>'."\n";
+
+ }
+
+ function displayInspectVars() {
+ global $lang;
+ $vars = $_SESSION['dataSetting_profile'][$this->sid]['InspectListVars'];
+
+ if (is_array($vars) && count($vars) > 0 ) {
+ $stringSelect = "SELECT variable FROM srv_spremenljivka WHERE id IN (".implode(',',$_SESSION['dataSetting_profile'][$this->sid]['InspectListVars']).") ORDER BY vrstni_red";
+
+ $querySelect = sisplet_query($stringSelect);
+ $prefix = '&nbsp;';
+ while ( list($variable) = mysqli_fetch_row($querySelect) ) {
+ echo $prefix.$variable;
+ $prefix = ', ';
+ }
+ } else {
+ echo $lang['srv_inspect_no_variables'];
+ }
+ }
+
+ function showInspectListSpr() {
+
+ global $lang, $site_url;
+ $all_spr = Cache::cache_all_srv_spremenljivka($this->sid);
+ $vars = $_SESSION['dataSetting_profile'][$this->sid]['InspectListVars'];
+ echo '<div id="dsp_inspect_cover">';
+ echo '<div id="dsp_inspect_spr_select">';
+
+ echo '<span>'.$lang['srv_inspect_choose'].'</span>';
+ foreach ($all_spr AS $id => $spremenljivka) {
+ echo '<div class="dsp_inspect_var">';
+ echo '<input name="dsp_inspect_vars" id="dsp_inspect_var_'.$spremenljivka['id'].'" value="'.$spremenljivka['id'].'" type="checkbox"'
+ .(is_array($vars) && in_array($spremenljivka['id'],$vars) ? ' checked' : '').'>';
+ echo '<label for="dsp_inspect_var_'.$spremenljivka['id'].'">'.$spremenljivka['variable'].' - '.strip_tags($spremenljivka['naslov']).'</label>';
+ echo '</div>';
+ }
+
+ echo '</div>';
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span id="dsp_inspect_cancel" class="floatLeft spaceLeft buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#"><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span id="dsp_inspect_save" class="floatRight spaceRight buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#"><span>'.$lang['srv_zapri'].'</span></a></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ #echo '</div>';
+ echo '</div>';
+ }
+
+ function saveInspectListVars() {
+ if (count($_POST['vars']) > 0 ) {
+ $_SESSION['dataSetting_profile'][$this->sid]['InspectListVars'] = $_POST['vars'];
+ } else {
+ unset($_SESSION['dataSetting_profile'][$this->sid]['InspectListVars']);
+ }
+ }
+
+ function saveSettings() {
+ if (isset($_POST['enableInspect']) && $_POST['enableInspect'] == 1 ) {
+ $this->enableInspect = true;
+ $_SESSION['enableInspect'] = true;
+ } else {
+ unset($_SESSION['enableInspect']);
+ $this->enableInspect = false;
+ }
+
+ $this->inspectGoto = (int)$_POST['inspectGoto'];
+ $_SESSION['inspect_goto'] = $this->inspectGoto;
+ }
+
+
+ function getConditionString() {
+ global $lang;
+ #preverimi ali imamo nastavljen pogoj za inspect
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ if ($if_id > 0) {
+ ob_start();
+ $b = new Branching($this->sid);
+
+ $b->display_if_label($if_id);
+ #$condition_label = mysqli_escape_string(ob_get_contents());
+ $condition_label = ob_get_contents();
+ ob_end_clean();
+
+ if ( $if_id > 0 && $condition_label != '') {
+
+ echo '<div id="conditionProfileNote">';
+ echo '<span class="floatLeft">'.$lang['srv_profile_data_is_filtred_zoom'].'</span>';
+ echo '<span class="floatLeft spaceLeft">'.$condition_label.'</span>';
+ // ali imamo napake v ifu
+ #TODO
+ # if ((int)self::$profiles[self :: $currentProfileId]['condition_error'] != 0) {
+ # echo '<br>';
+ # echo '<span style="border:1px solid #009D91; background-color: #34D0B6; padding:5px; width:auto;"><img src="img_0/error.png" /> ';
+ # echo '<span class="red strong">'.$lang['srv_profile_condition_has_error'].'</span>';
+ # echo '</span>';
+ # }
+ #
+ session_start();
+ global $site_url;
+ if (isset($_SESSION['inspectFromPodstran'][$this->sid])) {
+ $inspect_comeFrom = '\''.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a=analysis&m='.$_SESSION['inspectFromPodstran'][$this->sid].'\'';
+ unset($_SESSION['inspectFromPodstran'][$this->sid]);
+ } else {
+ $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
+ $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
+ $inspect_comeFrom = '\''.$pageURL.'\'';
+ }
+ echo '<span class="as_link spaceLeft" id="link_condition_edit">'.$lang['srv_profile_edit'].'</span>';
+ echo '<span class="as_link spaceLeft" onclick="window.location=\'index.php?anketa='.$this->sid.'&a=data&m=quick_edit&quick_view=1\'">'.$lang['srv_zoom_link_whoisthis'].'</span>';
+ echo '<span class="as_link spaceLeft" onclick="doZoomFromInspect();return false">Segmentiraj'.$lang[''].'</span>';
+ echo '<span class="as_link spaceLeft" onclick="inspectRemoveCondition('.$inspect_comeFrom.');">'.$lang['srv_profile_remove'].'</span>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function removeInspect() {
+ #preverimi ali imamo nastavljen pogoj za inspect
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ if ($if_id > 0) {
+ # odstranimo pogoj, srv_if
+ $delStr = "DELETE FROM srv_if WHERE if = '$if_id'";
+ sisplet_query($delStr);
+
+ # odstranimo condition profil: srv_condition profile
+ $delStr = "DELETE FROM srv_condition_profiles WHERE sid='".$this->sid."' AND type='inspect' AND if_id = '$if_id'";
+ sisplet_query($delStr);
+
+ #odstranimo zapis za inspect
+ SurveyUserSetting :: getInstance()->removeSettings('inspect_if_id');
+ }
+ }
+
+ function generateAwkCondition() {
+ global $global_user_id;
+
+ #preverimi ali imamo nastavljen pogoj za inspect
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ if ($if_id > 0) {
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+ return SurveyConditionProfiles:: generateAwkCondition($if_id);
+ } else {
+ return null;
+ }
+ }
+
+ public function getInspectVariables() {
+ global $global_user_id;
+ $vars = array();
+ #preverimi ali imamo nastavljen pogoj za inspect
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ if ($if_id > 0) {
+ $sql = sisplet_query("SELECT spr_id, vre_id FROM srv_condition WHERE if_id = '$if_id'");
+ while (list($spr_id, $vre_id) = mysqli_fetch_row($sql)) {
+ if ((int)$vre_id > 0) {
+ $vars[] = $spr_id.'_'.$vre_id;
+ } else {
+ $vars[] = $spr_id;
+ }
+ }
+ }
+ return $vars;
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyLanguageTechnology.php b/admin/survey/classes/class.SurveyLanguageTechnology.php
new file mode 100644
index 0000000..40fcea1
--- /dev/null
+++ b/admin/survey/classes/class.SurveyLanguageTechnology.php
@@ -0,0 +1,809 @@
+<?php
+ini_set('max_execution_time', 300); //300 seconds = 5 minutes
+#set_time_limit(20);
+ini_set('default_socket_timeout', 60); // 20 Seconds
+/**
+ * @author Gorazd Veselič
+ * @date July 2014
+ *
+ */
+class SurveyLanguageTechnology {
+
+ protected $anketa;
+
+ protected $response;
+
+ protected $settings = array(
+ 'lt_language' => 'Slo',
+ 'lt_min_FWD' => 5000,
+ 'lt_min_nNoM' => 9999,
+ 'lt_min_vNoM'=> 9999,
+ 'lt_special_setting'=> false
+ );
+
+ public function __construct($anketa) {
+ global $lang;
+ $this->anketa = $anketa;
+ $this->lang = $lang;
+ }
+
+ public function setup( array $settings) {
+ if (isset($settings['lt_language']) && is_string($settings['lt_language']) && in_array(strtolower($settings['lt_language']), array('slo','eng'))) {
+ $this->settings['lt_language'] = $settings['lt_language'];
+ }
+ if (isset($settings['lt_min_FWD']) && is_numeric($settings['lt_min_FWD'])) {
+ $this->settings['lt_min_FWD'] = $settings['lt_min_FWD'];
+ }
+ if (isset($settings['lt_min_nNoM']) && is_numeric($settings['lt_min_nNoM'])) {
+ $this->settings['lt_min_nNoM'] = $settings['lt_min_nNoM'];
+ }
+ if (isset($settings['lt_min_vNoM']) && is_numeric($settings['lt_min_vNoM'])) {
+ $this->settings['lt_min_vNoM'] = $settings['lt_min_vNoM'];
+ }
+ return $this->settings;
+ }
+
+ public function display() {
+ global $lang;
+ global $site_url;
+ global $admin_type;
+ global $global_user_id;
+
+ echo '<div id="placeholder" class="language_technology">';
+ $this->dispalySettings();
+#$r = $this->sendJson('Na kolokvij se prijavljam kot');
+#print_r("<pre>");
+#print_r($r);
+#print_r("</pre>");
+
+ echo '<div id="language_technology" class="branching_new expanded language_technology">';
+ ?><script> locked = true; </script><?php
+ $lang_admin = $lang;
+
+ $lang = $lang_admin;
+
+ $b = new Branching($this->anketa);
+ $b->displayKomentarji(false);
+ $b->branching = '';
+ $b->locked = true;
+
+ $sql = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ if (mysqli_num_rows($sql) > 0 ) {
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<li id="branching_'.$row['id'].'" class="spr">';
+ ob_start();
+ $b->vprasanje($row['id']);
+ $out1 = ob_get_contents();
+ ob_end_clean();
+ echo $out1;
+ echo '</li>';
+ echo '<div class="clr"></div>';
+# print_r("<pre>");
+# print_r(strip_tags($out1));
+# print_r("<pre>");
+ }
+ }
+ echo '</div>'; // branching
+ echo '<div id="vprasanje_float_editing" class="language_technology">';
+ $this->displayVprasanjeFloatEditing();
+ echo '</div>';
+ echo '</div>'; // placeholder
+
+ }
+ private function dispalySettings() {
+
+
+ #echo '<div id="language_technology_setting">';
+ echo '<div id="topSettingsHolder" class="language_technology" style="margin-bottom:10px;">';
+ echo '<div id="additional_navigation">';
+ echo '<table class="setting">';
+ echo '<tr><td class="lt_table_lang">' . $this->lang['srv_language_technology_language'] . '</td>';
+ echo '<td>' . $this->lang['srv_language_technology_flag_words'] . '</td>';
+ echo '<td rowspan="2"><button type="button" onclick="cleanLanguageTechnology();">' . $this->lang['srv_language_technology_clean'] . '</button></td>';
+ //echo '<td rowspan="2"><label id="lt_export_excel" onclick="lt_export_excel();"><span class="sprites xls_grey_16"></span>' . $this->lang['srv_language_technology_export_excel'] . '</label></td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td><select id="lt_language">';
+ if ($this->lang['id'] === '1') {
+ echo '<option value="Slo" selected>Slovenščina</option>';
+ echo '<option value="Eng">English</option>';
+ } else {
+ echo '<option value="Slo">Slovenščina</option>';
+ echo '<option value="Eng" selected>English</option>';
+ }
+ echo '</select></td>';
+
+ echo '<td>' . $this->lang['srv_language_technology_wf_under'] . '&nbsp;&nbsp;<input id="lt_min_FWD" type="text" value="5000"></td></tr>';
+ #echo '<tr>';
+ #echo '<td>' . $this->lang['srv_language_technology_verbs_above'] . 'Verbs </td><td><input id="lt_min_vNoM" type="text" value="3"></td></tr>';
+ echo '</table>';
+ echo '</div>';
+ echo '</div>';
+ }
+
+ private function getMustangResult($sentence, $wordType = null) {
+ if (empty($sentence) || trim($sentence) == "") {
+ return null;
+ }
+
+ //$d = '[{"language": "Eng","sentence": "Sometimes it work.","min_FWD": 5000,"min_nNoM": 1,"min_vNoM": 3}]';
+ //$d = '[{"language": "Slo","sentence": "S šumniki so težave","min_FWD": 5000,"min_nNoM": 1,"min_vNoM": 3}]';
+ #$d = '[{"language": "Slo","sentence": "Na kolokvij se prijavljam kot","min_FWD": 5000,"min_nNoM": 1,"min_vNoM": 3}]';
+ //$d = '[{"language": "Slo","sentence": "'.$sentence.'","min_FWD": 5000,"min_nNoM": 0,"min_vNoM": 3}]';
+ $d .= '"language": "' . $this->settings['lt_language'] . '",';
+ if ($wordType == null) {
+ $mustangWordSentance = 'sentence?json=';
+ $d .= '"sentence": "' . $sentence . '",';
+ } else {
+ $mustangWordSentance = 'word?json=';
+ $d .= '"word": "' . $sentence . '",';
+ $d .= '"Tag": "' . $wordType . '",';
+ }
+ $d .= '"min_FWD": ' . $this->settings['lt_min_FWD'] . ',';
+ $d .= '"min_nNoM": ' . $this->settings['lt_min_nNoM'] . ',';
+ $d .= '"min_vNoM": ' . $this->settings['lt_min_vNoM'] ;
+ $d = trim($d);
+
+ if (false) {
+ $d = '[{' . urlencode($d) . '}]';
+ } else {
+ $d = urlencode('[{' . $d . '}]');
+ }
+
+ $result = $this->makeMustangRequest($this->settings['lt_language'], $mustangWordSentance . $d);
+
+ return $result;
+ }
+
+ private function makeMustangRequest($language, $mustangString) {
+
+ if ( strtolower($language) == 'eng') {
+ $url = 'http://mustang.ijs.si:5111/synonym/' . $mustangString ;
+ } else {
+ $url = 'http://mustang.ijs.si:5112/synonym/' . $mustangString;
+ }
+
+ try {
+ //$r = $this->get_url_contents($url); // na testu ne deluje curl ???
+
+ $ctx = stream_context_create(array('http'=>
+ array(
+ 'timeout' => 20, // 20 Seconds
+ )
+ ));
+
+ $r = (file_get_contents($url, false, $ctx));
+ $r = str_replace(array("\r\n", "\n"), "", $r);
+ $r = json_decode($r, true);
+
+
+ if (is_array($r) && count($r) == 1) {
+ $r = $r[0];
+ }
+
+ } catch(Exception $e) {
+
+ $r = null;
+ }
+ return $r;
+ }
+
+ private function parseMustangResult($spremenljivka_mustang, $onlyProblematic = true) {
+ $result = array();
+
+ //$spremenljivka_mustang = $spremenljivka_mustang['sentence'];
+ if (is_array($spremenljivka_mustang) && count($spremenljivka_mustang) > 0) {
+
+ foreach ($spremenljivka_mustang['sentence'] AS $mustangWordArray) {
+ $mw = new MustangWord($mustangWordArray);
+ if (($onlyProblematic== true && $mw->isProblematic()) || $onlyProblematic == false)
+ {
+ $result[] = $mw->getJson();
+ }
+ }
+ }
+ return $result;
+ }
+
+ public function parseSpremenljivka($spremenljivka) {
+ // polovimo tekste vprašanja
+
+ $spremenljivka_naslov = $this->sanityze($this->getNaslovSpremenljivka($spremenljivka));
+ $spremenljivka_mustang = $this->getMustangResult($spremenljivka_naslov);
+ $spremenljivkaResult = $this->parseMustangResult($spremenljivka_mustang);
+ return array('data' => $spremenljivkaResult );
+ /*
+ $this->response['mustang']['naslov'] = $spremenljivka_mustang;
+
+ //$this->addWords($spremenljivka_naslov);
+ $vrednosti = ($this->getVrednostiSpremenljivka($spremenljivka));
+ foreach ($vrednosti AS $vrednost) {
+ $this->response['mustang']['vrednosti'][] = $this->sendJson($spremenljivka_naslov);
+ //$this->response['vrednosti'][] = $this->sanityze($vrednost);
+ //$this->addWords($this->sanityze($vrednost));
+ }
+
+ //echo strip_tags($spremenljivka_naslov);
+ #echo 'ank:'.$this->anketa;
+ #echo 'spr:'.$spremenljivka;
+
+ return $this->response['mustang']['naslov'][0];
+ */
+ }
+
+ /** funkcija počisti string neveljavnih zankov
+ *
+ * @param unknown_type $string
+ */
+ private function sanityze($string) {
+ // odstranimo html tage
+ $string = strip_tags($string);
+
+ // odstanimo dvojne narekovaje
+ $string = str_replace(array('"', "\n\r", "\n", "/", "-", "\\"), " ", $string);
+ $string = preg_replace('!\s+!', ' ', $string);
+
+ // odstranimo nepotrebne spejse
+ $string = trim($string);
+ return $string;
+ }
+
+ private function addWords($sentance) {
+ $words = explode(" ", $sentance);
+ if (!empty($words)) {
+ foreach ($words AS $word) {
+ $word = str_replace(array('"', "\n\r", "\n", "."), "", $word);
+ $this->response['words'][$word] = $word;
+ }
+ }
+ }
+
+ protected function getNaslovSpremenljivka($spremenljivka) {
+ $result = Cache::srv_spremenljivka($spremenljivka,'naslov');
+ return $result;
+ }
+
+ protected function getVrednostiSpremenljivka($spremenljivka) {
+ $result = array();
+ $sql1 = sisplet_query("SELECT naslov FROM srv_vrednost WHERE spr_id='$spremenljivka'");
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+ $result[] = $row1['naslov'];
+ }
+ return $result;
+ }
+
+ private function get_url_contents($url) {
+ $curl = curl_init();
+ $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
+
+ //The contents of the "User-Agent: " header to be used in a HTTP request.
+ curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
+ curl_setopt($curl, CURLOPT_URL, $url);
+ //To fail silently if the HTTP code returned is greater than or equal to 400.
+ curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
+ // Removes the headers from the output
+ curl_setopt($curl, CURLOPT_HEADER, 0);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+ // Return the output instead of displaying it directly
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
+ //To follow any "Location: " header that the server sends as part of the HTTP header.
+ curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
+ //To automatically set the Referer: field in requests where it follows a Location: redirect.
+ curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
+ //The maximum number of seconds to allow cURL functions to execute.
+ curl_setopt($curl, CURLOPT_TIMEOUT, 10);
+
+ $ret = curl_exec($curl);
+ curl_close($curl);
+ return $ret;
+ }
+
+ public function exportLanguageTechnology($lt_data, $language) {
+ require_once("./excel/PHPExcel.php");
+ require_once("./excel/PHPExcel/IOFactory.php");
+
+ $data = $this->prepareExcelData($lt_data, $language);
+
+ $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
+ PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
+
+ // Create new PHPExcel object
+ $objPHPExcel = new PHPExcel();
+ // Create a first sheet, representing sales data
+ $objPHPExcel->setActiveSheetIndex(0);
+ $aSheet = $objPHPExcel->getActiveSheet();
+ // Rename sheet
+ $aSheet->setTitle('Relevant meaning');
+ $aSheet->getColumnDimension('A')->setWidth(8);
+ $aSheet->getColumnDimension('B')->setWidth(20);
+ $aSheet->getColumnDimension('C')->setWidth(12);
+ $aSheet->getColumnDimension('D')->setWidth(12);
+ // first lines
+ $aSheet->setCellValue('A1', 'Question');
+ $aSheet->setCellValue('B1', 'Original word');
+ $aSheet->setCellValue('C1', 'WF');
+ $aSheet->setCellValue('D1', 'NoM');
+
+ $line = 2;
+ //$response = unserialize(file_get_contents('mustangData.dat'));
+ // loop po spremenljivkah
+
+ foreach ($data['words'] as $spr_id => $words) {
+ $spremenljivkaId = $spr_id;
+ $spremenljivkaVariable = Cache::srv_spremenljivka($spremenljivkaId, 'variable');
+ $naslov = Cache::srv_spremenljivka($spremenljivkaId, 'naslov');
+
+
+ $sc = 0;
+ foreach ($words as $w_idx => $bData) {
+ $word = $data['spremenljivkeData'][$spr_id][$w_idx]['word'];
+ $tag = $data['spremenljivkeData'][$spr_id][$w_idx]['Tag'];
+ $fwd = $data['spremenljivkeData'][$spr_id][$w_idx]['FWD'];
+ $nom = $data['spremenljivkeData'][$spr_id][$w_idx]['NoM'];
+ if ($sc == 0) {
+ $aSheet->setCellValue('A'.$line, $spremenljivkaVariable . ' - ' . strip_tags ($naslov));
+ }
+ $sc ++;
+ $aSheet->setCellValue('B'.$line, $word);
+ $aSheet->setCellValue('C'.$line, $fwd);
+ $aSheet->setCellValue('D'.$line, $nom);
+ $line++;
+ }
+ }
+
+ #SYNONYMS
+ $objPHPExcel->createSheet();
+ $objPHPExcel->setActiveSheetIndex(1);
+ $aSheet = $objPHPExcel->getActiveSheet();
+ $aSheet->setTitle('Synonyms');
+
+ $aSheet->getColumnDimension('A')->setWidth(8);
+ $aSheet->getColumnDimension('B')->setWidth(20);
+ $aSheet->getColumnDimension('C')->setWidth(20);
+ $aSheet->getColumnDimension('D')->setWidth(12);
+ $aSheet->getColumnDimension('E')->setWidth(12);
+
+ $aSheet->setCellValue('A1', 'Question');
+ $aSheet->setCellValue('B1', 'Original wording');
+ $aSheet->setCellValue('C1', 'Alternative wording');
+ $aSheet->setCellValue('D1', 'WF');
+ $aSheet->setCellValue('E1', 'NoM');
+
+ $line = 2;
+ if (count($data['synsets'])) {
+ foreach ($data['synsets'] as $spr_id => $wordData) {
+ $spremenljivkaId = $spr_id;
+ $spremenljivkaVariable = Cache::srv_spremenljivka($spremenljivkaId, 'variable');
+ $naslov = Cache::srv_spremenljivka($spremenljivkaId, 'naslov');
+
+ $sc = 0;
+ foreach ($wordData AS $w_idx => $synsetsData) {
+ $wc = 0;
+ $word = $data['spremenljivkeData'][$spr_id][$w_idx]['word'];
+ foreach ($synsetsData AS $syns_word => $syns_data) {
+ if ($sc == 0) {
+ $aSheet->setCellValue('A'.$line, $spr_id);
+ $aSheet->setCellValue('A'.$line, $spremenljivkaVariable . ' - ' . strip_tags ($naslov));
+ }
+ $sc++;
+ if ($wc == 0) {
+ $aSheet->setCellValue('B'.$line, $word);
+ }
+ $wc++;
+ $aSheet->setCellValue('C'.$line, $syns_word);
+ $aSheet->setCellValue('D'.$line, $syns_data['freq']);
+ $aSheet->setCellValue('E'.$line, $syns_data['nom']);
+ $line++;
+ }
+ }
+ }
+ }
+
+ # HYPERNYMS
+ $objPHPExcel->createSheet();
+ $objPHPExcel->setActiveSheetIndex(2);
+ $aSheet = $objPHPExcel->getActiveSheet();
+ // Rename 2nd sheet
+ $aSheet->setTitle('Hypernyms');
+
+ $aSheet->getColumnDimension('A')->setWidth(8);
+ $aSheet->getColumnDimension('B')->setWidth(20);
+ $aSheet->getColumnDimension('C')->setWidth(20);
+
+ $aSheet->setCellValue('A1', 'Question');
+ $aSheet->setCellValue('B1', 'Original wording');
+ $aSheet->setCellValue('C1', 'Hypernym');
+
+ $line = 2;
+ if (count($data['hypernyms'])) {
+ foreach ($data['hypernyms'] as $spr_id => $wordData) {
+ $spremenljivkaId = $spr_id;
+ $spremenljivkaVariable = Cache::srv_spremenljivka($spremenljivkaId, 'variable');
+ $naslov = Cache::srv_spremenljivka($spremenljivkaId, 'naslov');
+
+ $sc = 0;
+ foreach ($wordData AS $w_idx => $hypersData) {
+ $wc = 0;
+ $word = $data['spremenljivkeData'][$spr_id][$w_idx]['word'];
+ foreach ($hypersData AS $syns_word => $hyper_data) {
+ if ($sc == 0) {
+ $aSheet->setCellValue('A'.$line, $spr_id);
+ $aSheet->setCellValue('A'.$line, $spremenljivkaVariable . ' - ' . strip_tags ($naslov));
+ }
+ $sc++;
+ if ($wc == 0) {
+ $aSheet->setCellValue('B'.$line, $word);
+ }
+ $wc++;
+ $aSheet->setCellValue('C'.$line, $hyper_data);
+ $line++;
+ }
+ }
+ }
+ }
+ # HYPONYMS
+ $objPHPExcel->createSheet();
+ $objPHPExcel->setActiveSheetIndex(3);
+ $aSheet = $objPHPExcel->getActiveSheet();
+ // Rename 2nd sheet
+ $aSheet->setTitle('Hyponyms');
+
+ $aSheet->getColumnDimension('A')->setWidth(8);
+ $aSheet->getColumnDimension('B')->setWidth(20);
+ $aSheet->getColumnDimension('C')->setWidth(20);
+
+ $aSheet->setCellValue('A1', 'Question');
+ $aSheet->setCellValue('B1', 'Original wording');
+ $aSheet->setCellValue('C1', 'Hyponym');
+
+ $line = 2;
+ if (count($data['hyponyms'])) {
+ foreach ($data['hyponyms'] as $spr_id => $wordData) {
+ $sc = 0;
+ foreach ($wordData AS $w_idx => $hypersData) {
+ $wc = 0;
+ $word = $data['spremenljivkeData'][$spr_id][$w_idx]['word'];
+ foreach ($hypersData AS $syns_word => $hyper_data) {
+ if ($sc == 0) {
+ $aSheet->setCellValue('A'.$line, $spr_id);
+ }
+ $sc++;
+ if ($wc == 0) {
+ $aSheet->setCellValue('B'.$line, $word);
+ }
+ $wc++;
+ $aSheet->setCellValue('C'.$line, $hyper_data);
+ $line++;
+ }
+ }
+ }
+ }
+
+ global $site_path;
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ // izberemo random hash, ki se ni v bazi (to more bit, ker je index na fieldu cookie)
+ $filename = null;
+ $rand = null;
+ $x = 0;
+ do {
+ $rand = md5(mt_rand(1, mt_getrandmax()).'@'.$_SERVER['REMOTE_ADDR']);
+ $filename = $folder . "lt_" . $rand . '.xlsx';
+ $x++;
+ } while (file_exists($filename) === true && $x < 99999); // backup loop
+
+ if ($filename != null) {
+ $objPHPExcel->setActiveSheetIndex(0);
+ $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
+ $objWriter->save($filename);
+ return $rand;
+ } else {
+ throw new Exception("Can't create excel report!");
+ }
+ }
+
+
+ public function parseWord($word, $wordType) {
+ $spremenljivkaResult = array();
+
+ if (in_array($wordType, array('a', 'n', 'v', 'adv', 'e'))) {
+ $spremenljivka_mustang = $this->getMustangResult($word, $wordType);
+
+
+ $data = array('language'=>$spremenljivka_mustang['language']);
+ unset($spremenljivka_mustang['language']);
+ $data['sentence'][] = $spremenljivka_mustang;
+ // ker delamo posamezne besede ni pomembno da je onlyProblematic
+ $spremenljivkaResult = $this->parseMustangResult($data, false);
+ }
+ return $spremenljivkaResult ;
+
+ }
+
+ public function getHypoHypernym($synsets) {
+ if (!is_array($synsets) || empty($synsets)) {
+ return null;
+ }
+ $hypernyms = array();
+ $hyponyms = array();
+
+ $_synsets = array();
+
+ foreach ($synsets AS $synset) {
+ $synset = $synset['synonyms'];
+
+ // http://mustang.ijs.si:5111/synonym/hypohypernym?json=
+ // [{ "language": "Eng", "": "1. spouse,partner,married person,mate,better half|n|a person's partner in marriage|"}]
+
+ $mustangWordSentance = 'hypohypernym?json=';
+ $d = '';
+ $d .= '"language": "' . $this->settings['lt_language'] . '", ';
+ $d .= '"synset": "' . ( $synset) . '"';
+ $d = trim($d);
+
+ if (false) {
+ $d = '[{' . urlencode($d) . '}]';
+ } else {
+ $d = urlencode('[{' . $d . '}]');
+ }
+
+ $result = $this->makeMustangRequest($this->settings['lt_language'], $mustangWordSentance . $d);
+
+ // nima vsaka beseda hypernymov in hyponimpov takrat mustang vrne specifičen string:
+ if (isset($result['hypernym'][0]['hypernym'])
+ && ($result['hypernym'][0]['hypernym']== 'blamaža, kiks, zagata'
+ || $result['hypernym'][0]['hypernym']== 'blamaža, kiks, zagata'
+ || $result['hypernym'][0]['hypernym']== 'happening, occurrence, occurrent, natural event'))
+ {
+ // beseda nima hypernymov in hyponymov
+ $result['hypernym'] = array();
+ $result['hyponym'] = array();
+ }
+
+ if (isset($result['hypernym']) && is_array($result['hypernym']) && count($result['hypernym']) > 0) {
+ foreach ($result['hypernym'] AS $_hypernyms) {
+ if (isset($_hypernyms['hypernym'])) {
+ $__hypernyms = array_map('trim',explode(',', $_hypernyms['hypernym']));
+ $hypernyms = array_merge($hypernyms, $__hypernyms);
+
+ }
+ }
+ }
+ if (isset($result['hyponym']) && is_array($result['hyponym']) && count($result['hyponym']) > 0) {
+ foreach ($result['hyponym'] AS $_hyponyms) {
+ $_hyponyms = array_map('trim',explode(',', $_hyponyms));
+ $hyponyms = array_merge($hyponyms, $_hyponyms);
+ }
+ }
+ }
+ $hypernyms = array_unique($hypernyms);
+ $hyponyms = array_unique($hyponyms);
+ natsort($hypernyms);
+ natsort($hyponyms);
+ if(($key = array_search('NO HYPERNYMS', $hypernyms)) !== false) {
+ unset($hypernyms[$key]);
+ }
+ if(($key = array_search('NO HYPONYMS', $hyponyms)) !== false) {
+ unset($hyponyms[$key]);
+ }
+ return array('data' => array('hypernyms' => $hypernyms, 'hyponyms' => $hyponyms), 'synsets' => $_synsets);
+ }
+
+ private function displayVprasanjeFloatEditing() {
+ echo '<p><label>Frekvenca besede je pod: <input type="text" id="lt_min_FWD_spr" value=""></label>';
+ echo '</p><p>';
+ echo '<label>Nastavi le tej spremenljivki <input type="checkbox" id="lt_special_setting" value=""></label>';
+ echo '</p><p>';
+ echo '<label><button type="button" onclick="saveLanguageTechnologySetting();">' . $this->lang[''] . 'Nastavi</button>';
+ echo '</p><p>';
+ echo '<button type="button" onclick="runLanguageTechnology();">' . $this->lang['srv_language_technology_run'] . '</button>';
+ echo '</p>';
+ echo '</p><p>';
+ echo '<label id="lt_export_excel" onclick="lt_export_excel();"><span class="sprites xls_grey_16"></span>' . $this->lang['srv_language_technology_export_excel'] . '</label>';
+ echo '</p>';
+
+
+ }
+
+ private function prepareExcelData($lt_data, $language) {
+
+ $result = array();
+
+ if (!isset($lt_data['response'])) {
+ return $result;
+ }
+ $spremenljivkeData = $lt_data['response'];
+ $result['spremenljivkeData'] = $spremenljivkeData;
+ unset($lt_data['response']);
+
+ $spremenljivkaWords = array();
+ if (isset($lt_data['wordsSynonyms'])) {
+ foreach ($lt_data['wordsSynonyms'] as $spr_id => $wordSynData) {
+ foreach ($wordSynData as $wordIdx => $synData) {
+ foreach ($synData AS $synIdx => $star) {
+ if (isset($spremenljivkeData[$spr_id][$wordIdx]['Synset'][$synIdx])) {
+ $wordSynsets = $this->parseExcelSynsets($spremenljivkeData[$spr_id][$wordIdx]['Synset'][$synIdx], $language);
+ foreach($wordSynsets AS $word => $wordData) {
+ if (!isset($result['words'][$spr_id][$wordIdx])) {
+ $result['words'][$spr_id][$wordIdx] = true;
+ }
+ if (!isset($result['synsets'][$spr_id][$wordIdx][$word])) {
+ $result['synsets'][$spr_id][$wordIdx][$word] = $wordData;
+ }
+ }
+ }
+
+ }
+ }
+
+ }
+ }
+
+ if (isset($lt_data['wordsHypernyms'])) {
+ foreach ($lt_data['wordsHypernyms'] as $spr_id => $wordHyperData) {
+ foreach ($wordHyperData as $wordIdx => $synData) {
+ foreach ($synData AS $synIdx => $star) {
+ if (isset($spremenljivkeData[$spr_id][$wordIdx]['cleanhypernyms'][$synIdx])) {
+ if (!isset($result['words'][$spr_id][$wordIdx])) {
+ $result['words'][$spr_id][$wordIdx] = true;
+ }
+
+ if (!isset($result['hypernyms'][$spr_id][$wordIdx][$synIdx])) {
+ $result['hypernyms'][$spr_id][$wordIdx][$synIdx] = $spremenljivkeData[$spr_id][$wordIdx]['cleanhypernyms'][$synIdx];
+ }
+ }
+
+ }
+ }
+
+ }
+ }
+
+ if (isset($lt_data['wordsHyponyms'])) {
+ foreach ($lt_data['wordsHyponyms'] as $spr_id => $wordHypoData) {
+ foreach ($wordHypoData as $wordIdx => $synData) {
+ foreach ($synData AS $synIdx => $star) {
+ if (isset($spremenljivkeData[$spr_id][$wordIdx]['cleanhyponyms'][$synIdx])) {
+ if (!isset($result['words'][$spr_id][$wordIdx])) {
+ $result['words'][$spr_id][$wordIdx] = true;
+ }
+
+ if (!isset($result['hyponyms'][$spr_id][$wordIdx][$synIdx])) {
+ $result['hyponyms'][$spr_id][$wordIdx][$synIdx] = $spremenljivkeData[$spr_id][$wordIdx]['cleanhyponyms'][$synIdx];
+ }
+ }
+
+ }
+ }
+
+ }
+ }
+
+ return $result;
+ }
+
+ private function parseExcelSynsets($stringWordSynsets, $language) {
+ $result = array();
+ $synonyms = $stringWordSynsets['FWDNoM'];
+
+ if (strtolower($language) == 'eng') {
+ // besede so ločene z vejico
+ $words = explode(';', $synonyms);
+ foreach ($words AS $word) {
+ if ($word == null || trim($word) == "") {
+ continue;
+ }
+ $tmp = explode(':', $word);
+ $tmpWord = trim($tmp[0]);
+ $tmp = explode(',', $tmp[1]);
+ $freq = trim(str_replace(array("FW","=", " "), "", trim($tmp[0])));
+ $nom = trim(str_replace(array("NoM","=", " "), "", trim($tmp[1])));
+ if (!isset($result[$tmpWord])) {
+ $result[$tmpWord] = array('freq'=>$freq, 'nom'=> $nom);
+ }
+ }
+
+ } else {
+ // besede so ločene z vejico
+ $words = explode(';', $synonyms);
+ foreach ($words AS $word) {
+ if ($word == null || trim($word) == "") {
+ continue;
+ }
+ $tmp = explode(':', $word);
+ $tmpWord = trim($tmp[0]);
+ $tmp = explode(',', $tmp[1]);
+ $freq = trim(str_replace(array("FW","=", " "), "", trim($tmp[0])));
+ $nom = trim(str_replace(array("NoM","=", " "), "", trim($tmp[1])));
+ if (!isset($result[$tmpWord])) {
+ $result[$tmpWord] = array('freq'=>$freq, 'nom'=> $nom);
+ }
+ }
+ }
+ return $result;
+ }
+}
+
+class MustangWord {
+
+
+ public $word = "";
+ private $Tag = ""; // {Do, n, v, adv,
+ private $FWD = 0;
+ private $NoM = 0;
+ private $minFWD = false;
+ private $min_nNoM = false;
+ private $min_vNoM = false;
+ private $Synset = array();
+
+ public $problematic;
+ private $json;
+
+ /**
+ *
+{
+ "word": "kot",
+ "Tag": "Vd",
+ "FWD": 467459,
+ "NoM": 0,
+ "Flag": {
+ "minFWD": false,
+ "min_nNoM": false,
+ "min_vNoM": false
+ },
+ "Synset": [{
+ "synonyms": "enako, kakor, ko, kot, medtem ko, prav tako, tako kot",
+ "FWDNoM": "enako NoM: 2 Frek: 14288, kakor NoM: 1 Frek: 37364, ko NoM: 1 Frek: 297690, kot NoM: 6 Frek: 467459, medtem ko NoM: 1 Frek: neznana, prav tako NoM: 1 Frek: neznana, tako kot NoM: 1 Frek: neznana"
+ },
+ {
+ "synonyms": "kot, vogal",
+ "FWDNoM": "kot NoM: 6 Frek: 467459, vogal NoM: 5 Frek: 2507"
+ },
+ {
+ "synonyms": "kot, vogal",
+ "FWDNoM": "kot NoM: 6 Frek: 467459, vogal NoM: 5 Frek: 2507"
+ },
+ {
+ "synonyms": "kot",
+ "FWDNoM": "kot NoM: 6 Frek: 467459"
+ },
+ {
+ "synonyms": "kot, vogal, vogel",
+ "FWDNoM": "kot NoM: 6 Frek: 467459, vogal NoM: 5 Frek: 2507, vogel NoM: 2 Frek: 269"
+ },
+ {
+ "synonyms": "kot",
+ "FWDNoM": "kot NoM: 6 Frek: 467459"
+ }]
+}
+ */
+ public function __construct($mustangWordArray) {
+ $this->json = $mustangWordArray;
+
+ $this->word = $mustangWordArray['word'];
+ $this->Tag = $mustangWordArray['Tag'];
+ $this->FWD = $mustangWordArray['FWD'];
+ $this->NoM = $mustangWordArray['NoM'];
+
+ $this->minFWD = $mustangWordArray['Flag']['minFWD'];
+ $this->min_nNoM = $mustangWordArray['Flag']['min_nNoM'];
+ $this->min_vNoM = $mustangWordArray['Flag']['min_vNoM'];
+
+ $this->problematic = $this->minFWD || $this->min_nNoM || $this->min_vNoM;
+
+
+ }
+
+ public function isProblematic() {
+
+ return $this->problematic;
+ }
+
+ public function getJson() {
+ return $this->json;
+ }
+
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyList.php b/admin/survey/classes/class.SurveyList.php
new file mode 100644
index 0000000..a9377e1
--- /dev/null
+++ b/admin/survey/classes/class.SurveyList.php
@@ -0,0 +1,3241 @@
+<?php
+/** Klass ki vodi seznam anket za prikaz na prvi stranu.
+ * se posodablja sproti za ankete ki jih uporabnik trenutno preglejuje
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+
+define('SRV_LIST_ORDER_BY', 16); # privzeto: sortiranje po stolpcu 1
+define('SRV_LIST_ORDER_TYPE', 1); # privzeto: sortiranje padajoče
+define('SRV_LIST_REC_PER_PAGE', 25); # privzeto: koliko zapisov na stran prikažemo
+define('SRV_LIST_GET_AS_LIST', true); # privzeto: ali lovimo kot seznam ali kot drevo folderjev
+define('SRV_LIST_GET_SUB_FOLDERS', true); # privzeto: ali poizvedujemo po poddirektorijih
+define('SRV_LIST_CHECK_DOSTOP', true); # ali preverja dostop na nivoju ankete
+define('SRV_LIST_GROUP_PAGINATE', 5); # po kolko strani grupira pri paginaciji
+define('SRV_LIST_UPDATE_TIME_LIMIT', 900); # na koliko minut updejtamo: 15min = 60s*15
+
+if(session_id() == '') {session_start();}
+
+
+class SurveyList {
+
+ private $surveys_ids = array(); # array z id-ji anket
+ private $settingsArray = array(); # array z nastavitvami
+
+ private $parentFolder; # osnovni direktorij
+ private $currentFolder; # trenutni direktorij
+ private $folders = array(); # array z direktoriji
+
+ private $user_id = null; # ali filtriramo po userju
+ private $g_uid = null; # globalna nastavitev user_id
+ private $g_adminType = null; # globalna nastavitev adminType
+
+
+ private $onlyPhone = false; # Ali prikazujemo samo telefonske ankete
+
+ private $lang_id = 0; # nastavitev languageType
+
+ private $gdpr = 0; # nastavitev gdpr filter za ankete
+
+ private $dostopCondition = null; # shranimo omejitve dostopa (glede na tip uporabnika in uporabniški uid)
+ private $folderCondition = null; # shranimo omejevanja folderjev
+
+ private $libraryCondition = null; # shranimo novo omejevanje folderjev (moja knjiznica)
+ private $currentLibrary; # trenutni direktorij moje knjiznice
+
+ private $filter = null; # filter za ime ankete
+
+ private $show_folders = 0; # ali prikazujemo mape ali ne (default zaenkrat da)
+
+
+ private $isSearch = 0; # ali izvajamo search po anektah
+ private $searchString = ''; # geslo po katerem iscemo po anketah
+ private $searchStringProcessed = array(); # geslo po katerem iscemo po anketah, obdelano (skrajsano da isce tudi po drugih sklanjatvah)
+ private $searchSettings = array(); # nastavitve searcha
+
+
+ # privzete nastavitve
+ private $pageno = 1; # na kateri strani navigacije smo
+ private $max_pages = 1; # koliko strani imamo
+ private $sortby = SRV_LIST_ORDER_BY; # id polja po katerem sortiramo
+ private $sorttype = SRV_LIST_ORDER_TYPE; # tip sortiranja 1= deac, 0 = asc
+ private $rec_per_page = SRV_LIST_REC_PER_PAGE; # število zapisov na stran
+ private $orderByText = false; # ali sortiramo po tekstovnem polju (takrat uporabimo upper)
+
+ # privzete možnosti
+ private $sort_types_options = array(1=>'DESC',2=>'ASC'); # možni načini sortiranja
+ private $appropriateStatus = '5,6'; # statusi ki veljajo kot ustrezni
+
+ # možni načini sortiranja
+ private $order_by_options = array(
+ 1=>'naslov',
+ 2=>'active',
+ 3=>'lib_glb',
+ 4=>'lib_usr',
+ 5=>'answers',
+ 6=>'variables',
+ 7=>'i_name',
+ 8=>'i_surname',
+ 9=>'i_email',
+ 10=>'insert_time',
+ 11=>'e_name',
+ 12=>'e_surname',
+ 13=>'e_email',
+ 14=>'edit_time',
+ 15=>'a_first',
+ 16=>'a_last',
+ 17=>'starts',
+ 18=>'expire',
+ 19=>'survey_type',
+ #20=>'del',
+ 20=>'naslov', # po ikoni za brisanje ne moremo sortirat
+ 21=>'approp',
+ );
+
+ # polja za prikaz
+ private $dataFields = array(
+ 1=>array('id'=>1,'visible'=>1,'order_by'=>'naslov','header_field'=>'sl_naslov','alsoResize'=>'.sl_naslov','minWidth'=>100,'data_field'=>'naslov','data_type'=>'naslov', 'data_css'=>'sl_naslov_padding', 'order_text'=>true),
+ 2=>array('id'=>2,'visible'=>1,'order_by'=>'active','header_field'=>'sl_active','lang_label'=>'sl_active_1','alsoResize'=>'.sl_active','minWidth'=>20,'maxWidth'=>30,'data_field'=>'active','data_type'=>'active','data_css'=>'anl_ac'),
+ 3=>array('id'=>3,'visible'=>0,'order_by'=>'lib_glb','header_field'=>'sl_lib_glb','lang_label'=>'sl_lib_glb_1','alsoResize'=>'.sl_lib_glb','minWidth'=>20,'maxWidth'=>30,'data_field'=>'lib_glb','data_type'=>'lib_glb','data_css'=>'anl_ac'),
+ 4=>array('id'=>4,'visible'=>1,'order_by'=>'lib_usr','header_field'=>'sl_lib_usr','lang_label'=>'sl_lib_usr_1','alsoResize'=>'.sl_lib_usr','minWidth'=>20,'maxWidth'=>100,'data_field'=>'lib_usr','data_type'=>'lib_usr','data_css'=>'anl_ac'),
+ 5=>array('id'=>5,'visible'=>1,'order_by'=>'answers','header_field'=>'sl_answers','lang_label'=>'sl_answers_1','alsoResize'=>'.sl_answers','minWidth'=>25,'maxWidth'=>100,'data_field'=>'answers','data_css'=>'anl_ac'),
+ 6=>array('id'=>6,'visible'=>1,'order_by'=>'variables','header_field'=>'sl_variables','lang_label'=>'sl_variables_1','alsoResize'=>'.sl_variables','minWidth'=>25,'maxWidth'=>100,'data_field'=>'variables','data_css'=>'anl_ac'),
+ 7=>array('id'=>7,'visible'=>0,'order_by'=>'i_name','header_field'=>'sl_i_name','header_grupa'=>'h_sl_avtor','alsoResize'=>'#h_sl_avtor_holder,#h_sl_avtor_title,#h_sl_avtor,.sl_i_name','minWidth'=>30,'data_field'=>'i_name','data_type'=>'iuid','order_text'=>true),
+ 8=>array('id'=>8,'visible'=>0,'order_by'=>'i_surname','header_field'=>'sl_i_surname','header_grupa'=>'h_sl_avtor','alsoResize'=>'#h_sl_avtor_holder,#h_sl_avtor_title,#h_sl_avtor,.sl_i_surname','minWidth'=>30,'data_field'=>'i_surname','data_type'=>'iuid','order_text'=>true),
+ 9=>array('id'=>9,'visible'=>0,'order_by'=>'i_email','header_field'=>'sl_i_email','header_grupa'=>'h_sl_avtor','alsoResize'=>'#h_sl_avtor_holder,#h_sl_avtor_title,#h_sl_avtor,.sl_i_email','minWidth'=>30,'data_field'=>'i_email','data_type'=>'iuid','order_text'=>true),
+ 10=>array('id'=>10,'visible'=>1,'order_by'=>'insert_time','header_field'=>'sl_i_time','header_grupa'=>'h_sl_avtor','alsoResize'=>'#h_sl_avtor_holder,#h_sl_avtor_title,#h_sl_avtor,.sl_i_time','minWidth'=>50,'data_field'=>'i_time'),
+ 11=>array('id'=>11,'visible'=>1,'order_by'=>'e_name','header_field'=>'sl_e_name','header_grupa'=>'h_sl_spreminjal','alsoResize'=>'#h_sl_spreminjal_holder,#h_sl_spreminjal_title,#h_sl_spreminjal,.sl_e_name','minWidth'=>30,'data_field'=>'e_name','data_type'=>'euid','order_text'=>true),
+ 12=>array('id'=>12,'visible'=>0,'order_by'=>'e_surname','header_field'=>'sl_e_surname','header_grupa'=>'h_sl_spreminjal','alsoResize'=>'#h_sl_spreminjal_holder,#h_sl_spreminjal_title,#h_sl_spreminjal,.sl_e_surname','minWidth'=>30,'data_field'=>'e_surname','data_type'=>'euid','order_text'=>true),
+ 13=>array('id'=>13,'visible'=>0,'order_by'=>'e_email','header_field'=>'sl_e_email','header_grupa'=>'h_sl_spreminjal','alsoResize'=>'#h_sl_spreminjal_holder,#h_sl_spreminjal_title,#h_sl_spreminjal,.sl_e_email','minWidth'=>30,'data_field'=>'e_email','data_type'=>'euid','order_text'=>true),
+ 14=>array('id'=>14,'visible'=>1,'order_by'=>'edit_time','header_field'=>'sl_e_time','header_grupa'=>'h_sl_spreminjal','alsoResize'=>'#h_sl_spreminjal_holder,#h_sl_spreminjal_title,#h_sl_spreminjal,.sl_e_time','minWidth'=>50,'data_field'=>'e_time'),
+ 15=>array('id'=>15,'visible'=>0,'order_by'=>'vnos_time_first','header_field'=>'sl_vnos_time_first','alsoResize'=>'.sl_vnos_time_first','minWidth'=>30,'data_field'=>'v_time_first'),
+ 16=>array('id'=>16,'visible'=>1,'order_by'=>'vnos_time_last','header_field'=>'sl_vnos_time_last','alsoResize'=>'.sl_vnos_time_last','minWidth'=>30,'data_field'=>'v_time_last'),
+ 17=>array('id'=>17,'visible'=>1,'order_by'=>'trajanjeod','header_field'=>'sl_trajanjeod','header_grupa'=>'h_sl_trajanje','alsoResize'=>'#h_sl_trajanje_holder,#h_sl_trajanje_title,#h_sl_trajanje,.sl_trajanjeod','minWidth'=>30,'data_field'=>'trajanjeod'),
+ 18=>array('id'=>18,'visible'=>1,'order_by'=>'trajanjedo','header_field'=>'sl_trajanjedo','header_grupa'=>'h_sl_trajanje','alsoResize'=>'#h_sl_trajanje_holder,#h_sl_trajanje_title,#h_sl_trajanje,.sl_trajanjedo','minWidth'=>30,'data_field'=>'trajanjedo'),
+ 19=>array('id'=>19,'visible'=>0,'order_by'=>'survey_type','header_field'=>'sl_survey_type','lang_label'=>'sl_survey_type_1','alsoResize'=>'.sl_survey_type','minWidth'=>30,'data_field'=>'survey_type','data_type'=>'survey_type','order_text'=>true),
+ 20=>array('id'=>20,'visible'=>1,'order_by'=>'delete','header_field'=>'sl_delete','lang_label'=>'sl_delete_1','alsoResize'=>'.sl_delete','minWidth'=>20,'maxWidth'=>30,'data_field'=>'del','data_type'=>'delete','data_css'=>'anl_ac'),
+ 21=>array('id'=>21,'visible'=>0,'order_by'=>'approp','header_field'=>'sl_approp','lang_label'=>'sl_approp_1','alsoResize'=>'.sl_approp','minWidth'=>25,'maxWidth'=>100,'data_field'=>'approp','data_css'=>'anl_ac'),
+ );
+
+
+ public function __construct() {
+
+ global $admin_type, $global_user_id, $site_path;
+
+ $this->lang_id = 0;
+ $this->g_uid = $global_user_id;
+ $this->g_adminType = $admin_type;
+
+ $this->onlyPhone = false;
+ if ( (isset($_REQUEST['onlyPhone']) && $_REQUEST['onlyPhone'] == 'true')
+ || (isset($_REQUEST['a']) && $_REQUEST['a'] == 'phoneSurveys')) {
+ $this->onlyPhone = true;
+ }
+
+ # Anketam ki so potekle popravimo aktivnost
+ $this->checkSurveyExpire();
+
+ # vsilimo refresh podatkov
+ SurveyInfo :: getInstance()->resetSurveyData();
+
+ #Inicializiramo (preberemo potrebne nastavitve iz baze, in pogledamo katero stran prikazujemo)
+ $this -> init();
+
+ # posodobimo podatke prikazanih anket
+ $this -> refreshData();
+ }
+
+ private function init($parentFolder = 0) {
+ global $global_user_id;
+
+ # pogledamo ali imamo shranjeno nastavitev po katerem polj u sortiramo
+ UserSetting::getInstance()->Init($global_user_id);
+
+ $userSettins = UserSetting::getInstance()->getUserSetting('survey_list_order_by');
+ if ( isset($userSettins) && $userSettins != null) {
+ $old_data = array_unique(explode(",",$userSettins));
+ if (isset($old_data[0]) && $old_data[0] > 0) {
+ $this->sortby = $old_data[0];
+ if (isset($old_data[1]) && $old_data[1] > 0) {
+ $this->sorttype = $old_data[1];
+ }
+ }
+ }
+ $this->setParentFolder($parentFolder);
+ $this->setCurrentFolder($parentFolder);
+
+ // Ali prikazujemo folderje ali ne
+ $userAccess = UserAccess::getInstance($global_user_id);
+ $detect = New Mobile_Detect();
+ if($userAccess->checkUserAccess('my_survey_folders') && !$detect->isMobile() && !$detect->isTablet())
+ $this->show_folders = UserSetting::getInstance()->getUserSetting('survey_list_folders');
+
+ # koliko zapisov prikazujemo na stran
+ $survey_list_rows_per_page = UserSetting::getInstance()->getUserSetting('survey_list_rows_per_page');
+ if (isset($survey_list_rows_per_page) && $survey_list_rows_per_page != "" && (int)$survey_list_rows_per_page > 0) {
+ $this->rec_per_page = (int)$survey_list_rows_per_page;
+ }
+ #session_start();
+ # preverimo ali imamo filter po userju
+ if ($_GET['a'] == 'surveyList_user' && (int)$_POST['uid'] > 0 && ($_POST['list_user_type'] == 'i' || $_POST['list_user_type'] == 'e' || $_POST['list_user_type'] == 'clr')) {
+ $this->setUserId();
+ } else if (isset($_SESSION['sl_uid']) && (int)$_SESSION['sl_uid'] > 0 && isset($_SESSION['sl_typ']) && ($_SESSION['sl_typ'] == 'e' || $_SESSION['sl_typ'] == 'i')) {
+ $this->user_id = (int)$_SESSION['sl_uid'];
+ }
+ # nastavimo sort po jezikih
+ if (isset($_SESSION['sl_lang_id']) && (int)$_SESSION['sl_lang_id'] > 0 ) {
+ $this->lang_id= (int)$_SESSION['sl_lang_id'];
+ }
+
+ # nastavimo sort po gdpr
+ if (isset($_SESSION['sl_gdpr']) && (int)$_SESSION['sl_gdpr'] > 0 ) {
+ $this->gdpr = (int)$_SESSION['sl_gdpr'];
+ }
+
+ # nastavimo filter po folderju moje knjiznice
+ if (isset($_SESSION['currentLibrary']) && (int)$_SESSION['currentLibrary'] > 0 ) {
+ $this->currentLibrary = (int)$_SESSION['currentLibrary'];
+ }
+
+ // Preverimo ce gre za search po anketah
+ if(isset($_GET['search']) && $_GET['search'] != ''){
+ $this->isSearch = 1;
+ $this->searchString = str_replace("\\", "", trim($_GET['search']));
+
+ // Iscemo po naslovu ali avtorju
+ $this->searchSettings['stype'] = (isset($_GET['stype'])) ? $_GET['stype'] : '0';
+
+ // Aktivnost ankete
+ $this->searchSettings['sstatus'] = (isset($_GET['sstatus'])) ? $_GET['sstatus'] : '0';
+
+ // Datum ustvarjanja ankete
+ $this->searchSettings['sidatefrom'] = (isset($_GET['sidatefrom'])) ? $_GET['sidatefrom'] : '';
+ $this->searchSettings['sidateto'] = (isset($_GET['sidateto'])) ? $_GET['sidateto'] : '';
+
+ // Datum zadnjega urejanja ankete
+ $this->searchSettings['sedatefrom'] = (isset($_GET['sedatefrom'])) ? $_GET['sedatefrom'] : '';
+ $this->searchSettings['sedateto'] = (isset($_GET['sedateto'])) ? $_GET['sedateto'] : '';
+
+ // Dodaten filter po avtorju (samo metaadmini)
+ $this->searchSettings['onlyAuthor'] = (isset($_GET['onlyAuthor'])) ? str_replace("\\", "", trim($_GET['onlyAuthor'])) : '';
+ }
+
+ $this->reloadSurveys();
+
+ return count($this->surveys_ids);
+ }
+
+
+ /**
+ * @desc prikaze zgornjo navigacijo
+ */
+ function display_sub_tabs () {
+ global $lang, $global_user_id, $admin_type, $site_domain, $aai_instalacija;
+
+ $SLCount = $this->countSurveys();
+
+ // *** druga vrstica navigacije ***//
+ echo '<div id="secondNavigation" class="library clr">';
+
+ if ($_GET['a']=='diagnostics') {
+
+ if ($_GET['t'] == 'uporabniki') {
+
+ // Admini imajo pregled nad vsemi zavihki uporabnikov
+ if ($admin_type == 0) {
+ echo '<ul class="secondNavigation">';
+
+ #zavihek osnovni pregled uporabnikov
+ echo '<li>';
+ echo '<a class="no-img single '.((!isset($_GET['m']) || $_GET['m'] == 'my') ? 'active' : '').'"'
+ .' href="index.php?a=diagnostics&t=uporabniki" title="'.$lang['n_users_list_all'].'">';
+ echo $lang['n_users_list'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ #zavihek seznam vseh uporabnikov
+ echo '<li>';
+ echo '<a class="no-img single '.($_GET['m'] == 'all' ? 'active' : '').'"'
+ .' href="index.php?a=diagnostics&t=uporabniki&m=all" title="'.$lang['n_users_list_all'].'">';
+ echo $lang['n_users_list_all'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ #zavihek izbrisani uporabniki
+ echo '<li>';
+ echo '<a class="no-img single '.(!empty($_GET['m']) && $_GET['m'] == 'izbrisani' ? 'active' : '').'"'
+ .' href="index.php?a=diagnostics&t=uporabniki&m=izbrisani" title="'.$lang['n_deleted_users'].'">';
+ echo $lang['n_deleted_users'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ #zavihek odjavljeni uporabniki
+ echo '<li>';
+ echo '<a class="no-img single '.(!empty($_GET['m']) && $_GET['m'] == 'nepotrjeni' ? 'active' : '').'"'
+ .' href="index.php?a=diagnostics&t=uporabniki&m=nepotrjeni" title="'.$lang['n_unconfirmed_users'].'">';
+ echo $lang['n_unconfirmed_users'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ #zavihek nepotrjenih uporabnikov
+ echo '<li>';
+ echo '<a class="no-img single '.(!empty($_GET['m']) && $_GET['m'] == 'odjavljeni' ? 'active' : '').'"'
+ .' href="index.php?a=diagnostics&t=uporabniki&m=odjavljeni" title="'.$lang['n_unsigned_users'].'">';
+ echo $lang['n_unsigned_users'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ #zavihek sa modul
+ echo '<li>';
+ echo '<a class="no-img single '.(!empty($_GET['m']) && $_GET['m'] == 'sa-modul' ? 'active' : '').'"'
+ .' href="index.php?a=diagnostics&t=uporabniki&m=sa-modul" title="'.$lang['srv_hierarchy_users_access'].'">';
+ echo $lang['srv_hierarchy_users_access'].'</a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+
+ // Menegerji imajo samo osnovni pregled svojih uporabnikov
+ if ($admin_type == 1) {
+
+ echo '<ul class="secondNavigation">';
+
+ #zavihek osnovni pregled uporabnikov
+ echo '<li>';
+ echo '<a class="no-img single active" href="index.php?a=diagnostics&t=uporabniki" title="'.$lang['n_users_list_all'].'">';
+ echo $lang['n_users_list'].'</a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+ }
+ else {
+
+ if ($admin_type == 0) {
+ echo '<ul class="secondNavigation">';
+ #zavihek ankete
+ echo '<li>';
+ echo '<a class="no-img side-left'.(($_GET['t']=='ankete'||$_GET['a']=='diagnostics')&& !isset($_GET['t']) ? ' active' : '').'"'
+ .' href="index.php?a=diagnostics" title="'.$lang['srv_ankete'].'">';
+ echo $lang['srv_ankete'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img'.(($_GET['t']=='time_span_daily') ? ' active' : '').'"'
+ .' href="index.php?a=diagnostics&t=time_span_daily" title="'.$lang['srv_weekly_diagnostics'].'">';
+ echo $lang['srv_weekly_diagnostics'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img'.(($_GET['t']=='time_span_monthly') ? ' active' : '').'"'
+ .' href="index.php?a=diagnostics&t=time_span_monthly" title="'.$lang['srv_monthly_diagnostics'].'">';
+ echo $lang['srv_monthly_diagnostics'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img'.(($_GET['t']=='time_span_yearly') ? ' active' : '').'"'
+ .' href="index.php?a=diagnostics&t=time_span_yearly" title="'.$lang['srv_yearly_diagnostics'].'">';
+ echo $lang['srv_yearly_diagnostics'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img side-right'.(($_GET['t']=='time_span') ? ' active' : '').'"'
+ .' href="index.php?a=diagnostics&t=time_span&uvoz=0&ustrezni=1&delnoustrezni=1&neustrezni=0" title="'.$lang['srv_all_diagnostics'].'">';
+ echo $lang['srv_all_diagnostics'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img side-right'.(($_GET['t']=='paradata') ? ' active' : '').'"'
+ .' href="index.php?a=diagnostics&t=paradata" title="'.$lang['srv_metapodatki'].'">';
+ echo $lang['srv_metapodatki'].'</a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+
+ }
+ }
+ #podnavigacija za knjižnico
+ if( $_GET['a']=='knjiznica' ) {
+
+ echo '<ul class="secondNavigation">';
+
+ #zavihek javna knjižnica
+ echo '<li>';
+ echo '<a class="no-img side-left'.(($_GET['t']=='javne_ankete'||$_GET['a']=='knjiznica')&& !isset($_GET['t']) ? ' active' : '').'"'
+ .' href="index.php?a=knjiznica" title="'.$lang['srv_javna_knjiznica'].'">';
+ echo $lang['srv_javna_knjiznica'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+
+ # Zavihek moja knjižnica
+ echo '<li>';
+ echo '<a class="no-img side-right'.($_GET['t'] == 'moje_ankete' ? ' active' : '').'"'
+ .' href="index.php?a=knjiznica&t=moje_ankete" title="'.$lang['srv_moja_knjiznica'].'">';
+ echo $lang['srv_moja_knjiznica'].'</a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+ #podnavigacija za nastavitve
+ if(($_GET['a']=='nastavitve')) {
+
+ $tab = $_GET['m'];
+
+ echo '<ul class="secondNavigation">';
+
+ if ($admin_type == '0') {
+ #zavihek sistemske
+ echo '<li>';
+ echo '<a class="no-img side-left'.($tab=='system' || $tab == '' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=system" title="'.$lang['srv_settingsSystem'].'">';
+ echo $lang['srv_settingsSystem'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+ # Zavihek ocenjevanje trajanja
+ echo '<li>';
+ echo '<a class="no-img'.($tab=='predvidenicasi' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=predvidenicasi" title="'.$lang['srv_testiranje_predvidenicas'].'">';
+ echo $lang['srv_testiranje_predvidenicas'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+ # Zavihek mape
+ echo '<li>';
+ echo '<a class="no-img'.($tab=='collectData' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=collectData" title="'.$lang['srv_collectData'].'">';
+ echo $lang['srv_collectData'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+ # Zavihek lep url
+ echo '<li>';
+ echo '<a class="no-img'.($tab=='nice_links' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=nice_links" title="'.$lang['srv_nice_url'].'">';
+ echo $lang['srv_nice_url'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+ # ankete z administrativnim dostopom
+ echo '<li>';
+ echo '<a class="no-img'.($tab=='anketa_admin' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=anketa_admin" title="'.$lang['srv_anketa_admin'].'">';
+ echo $lang['srv_anketa_admin'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+ # zbrisane ankete
+ echo '<li>';
+ echo '<a class="no-img'.($tab=='anketa_deleted' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=anketa_deleted" title="'.$lang['srv_anketa_deleted'].'">';
+ echo $lang['srv_anketa_deleted'].'</a>';
+ echo '</li>';
+ echo '<li class="space"></li>';
+ # Zbrisani podatki
+ echo '<li>';
+ echo '<a class="no-img'.($tab=='data_deleted' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=data_deleted" title="'.$lang['srv_data_deleted'].'">';
+ echo $lang['srv_data_deleted'].'</a>';
+ echo '</li>';
+ }
+
+ // nastavitve uporabnika
+ if($admin_type == 0)
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img side-right'.($tab=='global_user_settings' ? ' active' : '').'"'
+ .' href="index.php?a=nastavitve&amp;m=global_user_settings" title="'.$lang['srv_user_settings'].'">';
+ echo $lang['srv_user_settings'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ // Moj profil
+ echo '<li>';
+ echo '<a class="no-img side-right' . ($tab == 'global_user_myProfile' ? ' active' : '') . '"' . ' href="index.php?a=nastavitve&amp;m=global_user_myProfile" title="' . $lang['edit_data'] . '">';
+ echo $lang['edit_data'] . '</a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+ #podnavigacija za obvestila
+ if(($_GET['a']=='obvestila')) {
+
+ echo '<ul class="secondNavigation">';
+
+ # prejeta obvestila
+ echo '<li>';
+ echo '<a class="no-img side-right'.(!isset($_GET['t']) ? ' active' : '').'"'
+ .' href="index.php?a=obvestila" title="'.$lang['srv_notifications_recieved'].'">';
+ echo $lang['srv_notifications_recieved'].'</a>';
+ echo '</li>';
+
+ if ($admin_type == '0') {
+
+ echo '<li class="space"></li>';
+
+ # poslana obvestila
+ echo '<li>';
+ echo '<a class="no-img side-left'.($_GET['t']=='sent' ? ' active' : '').'"'
+ .' href="index.php?a=obvestila&amp;t=sent" title="'.$lang['srv_notifications_sent'].'">';
+ echo $lang['srv_notifications_sent'].'</a>';
+ echo '</li>';
+ }
+
+ echo '</ul>';
+ }
+ #podnavigacija za narocila
+ if(($_GET['a']=='narocila')) {
+
+ echo '<ul class="secondNavigation">';
+
+ # moja narocila
+ echo '<li>';
+ echo '<a class="no-img side-right'.(!isset($_GET['m']) ? ' active' : '').'"'
+ .' href="index.php?a=narocila" title="'.$lang['srv_narocila_my'].'">';
+ echo $lang['srv_narocila_my'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ # placila - samo admini
+ if ($admin_type == '0') {
+ echo '<li>';
+ echo '<a class="no-img side-right'.((isset($_GET['m']) && $_GET['m'] == 'placila') ? ' active' : '').'"'
+ .' href="index.php?a=narocila&m=placila" title="'.$lang['srv_placila'].'">';
+ echo $lang['srv_placila'].'</a>';
+ echo '</li>';
+ }
+
+ echo '</ul>';
+ }
+ # podnavigacija za gdpr
+ if($_GET['a']=='gdpr'){
+
+ echo '<ul class="secondNavigation">';
+
+ // Nastavitve uporabnika
+ echo '<li>';
+ echo '<a class="no-img side-right'.(!isset($_GET['m']) || $_GET['m']=='gdpr_user' ? ' active' : '').'"'
+ .' href="index.php?a=gdpr&amp;m=gdpr_user" title="'.$lang['srv_gdpr_user_settings'].'">';
+ echo $lang['srv_gdpr_user_settings'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ // Seznam anket
+ echo '<li>';
+ echo '<a class="no-img side-right'.($_GET['m']=='gdpr_survey_list' ? ' active' : '').'"'
+ .' href="index.php?a=gdpr&amp;m=gdpr_survey_list" title="'.$lang['srv_gdpr_survey_list'].'">';
+ echo $lang['srv_gdpr_survey_list'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ // DPA
+ echo '<li>';
+ echo '<a class="no-img side-right'.($_GET['m']=='gdpr_dpa' ? ' active' : '').'"'
+ .' href="index.php?a=gdpr&amp;m=gdpr_dpa" title="'.$lang['srv_gdpr_dpa'].'">';
+ echo $lang['srv_gdpr_dpa'].'</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ // Zahteve za izbris
+ echo '<li>';
+ $request_counter = GDPR::countUserUnfinishedRequests();
+ $request_counter_text = ($request_counter > 0) ? ' <sup class="red" style="vertical-align: top;">('.$request_counter.')</sup>' : '';
+ echo '<a class="no-img side-right'.($_GET['m']=='gdpr_requests' ? ' active' : '').'"'
+ .' href="index.php?a=gdpr&amp;m=gdpr_requests" title="'.$lang['srv_gdpr_requests'].'">';
+ echo $lang['srv_gdpr_requests'].$request_counter_text.'</a>';
+ echo '</li>';
+
+ // Vse zahteve za izbris - samo ADMINI
+ if($admin_type == '0'){
+
+ echo '<li class="space"></li>';
+
+ echo '<li>';
+ echo '<a class="no-img side-right'.($_GET['m']=='gdpr_requests_all' ? ' active' : '').'"'
+ .' href="index.php?a=gdpr&amp;m=gdpr_requests_all" title="'.$lang['srv_gdpr_requests_all'].'">';
+ echo $lang['srv_gdpr_requests_all'].'</a>';
+ echo '</li>';
+ }
+ }
+ #podnavigacija za UL evalvacijo
+ if($_GET['a']=='ul_evalvation') {
+
+ echo '<ul class="secondNavigation">';
+
+ # Izvozi za ul evalvacijo
+ echo '<li>';
+ echo '<a class="no-img side-right'.((!isset($_GET['t']) || $_GET['t'] == 'export') ? ' active' : '').'"'
+ .' href="index.php?a=ul_evalvation" title="Izvozi">';
+ echo 'Izvozi</a>';
+ echo '</li>';
+
+
+ if ($admin_type == 0) {
+ echo '<li class="space"></li>';
+
+ # Uvozi - samo admini
+ echo '<li>';
+ echo '<a class="no-img side-left'.($_GET['t']=='import' ? ' active' : '').'"'
+ .' href="index.php?a=ul_evalvation&amp;t=import" title="Uvozi">';
+ echo 'Uvozi</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ # Testiranje - samo admini
+ echo '<li>';
+ echo '<a class="no-img side-left'.($_GET['t']=='test' ? ' active' : '').'" href="index.php?a=ul_evalvation&amp;t=test" title="Testiranje">';
+ echo 'Testiranje</a>';
+ echo '</li>';
+
+ echo '<li class="space"></li>';
+
+ # GC - samo admini
+ echo '<li>';
+ echo '<a class="no-img side-left'.($_GET['t']=='gc' ? ' active' : '').'" href="index.php?a=ul_evalvation&amp;t=gc" title="GC">';
+ echo 'GC</a>';
+ echo '</li>';
+ }
+
+ echo '</ul>';
+ }
+
+ echo '<div id="secondNavigation_links"></div>'; # id="secondNavigation_links"
+ echo '</div>'; #<div class="secondNavigation" >
+
+ $this->language_change();
+ }
+
+ /**
+ * @desc prikaze zgornjo navigacijo
+ */
+ function display_tabs () {
+ global $lang, $global_user_id, $admin_type, $mysql_database_name;
+
+ $css_1 = 'on';
+ $css_2 = 'off';
+ $css_3 = 'off';
+ $css_4 = 'off';
+ $css_5 = 'off';
+ $css_6 = 'off';
+ $css_7 = 'off';
+ $css_8 = 'off';
+ $css_9 = 'off';
+ $css_10 = 'off';
+
+ if ($_GET['a'] == 'diagnostics') {
+
+ if ($_GET['t'] == 'uporabniki') {
+ #uporabniki
+ $css_1 = 'off';
+ $css_5 = 'on';
+ }
+ else {
+ #aktivnosti
+ $css_1 = 'off';
+ $css_2 = 'on';
+ }
+ }
+ if ($_GET['a'] == 'knjiznica') {
+ $css_1 = 'off';
+ $css_3 = 'on';
+ }
+ if ($_GET['a'] == 'nastavitve') {
+ $css_1 = 'off';
+ $css_4 = 'on';
+ }
+ if ($_GET['a'] == 'nastavitve') {
+ $css_1 = 'off';
+ $css_4 = 'on';
+ }
+ if ($_GET['a'] == 'phoneSurveys') {
+ $css_1 = 'off';
+ $css_6 = 'on';
+ }
+ if ($_GET['a'] == 'obvestila') {
+ $css_1 = 'off';
+ $css_7 = 'on';
+ }
+ if ($_GET['a'] == 'ul_evalvation') {
+ $css_1 = 'off';
+ $css_8 = 'on';
+ }
+ if ($_GET['a'] == 'gdpr') {
+ $css_1 = 'off';
+ $css_9 = 'on';
+ }
+ if ($_GET['a'] == 'narocila') {
+ $css_1 = 'off';
+ $css_10 = 'on';
+ }
+
+ echo '<div id="firstNavigation" class="frontpage">';
+
+
+ echo '<ol class="smaller left-side left-1ka">';
+ echo '<li class="moja1ka">';
+ echo '<a href="index.php?a=pregledovanje" title="' . $lang['srv_pregledovanje'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_1.'">'. $lang['srv_pregledovanje'] . '</div>';
+ echo '</a>';
+ echo '</li>';
+
+ $SLCountPhoneSurvey = $this->countPhoneSurveys();
+ if ($SLCountPhoneSurvey > 0 && $admin_type != '0') {
+ #echo '<li class="spaceLarge">&nbsp;</li>';
+ echo '<li class="spaceBig">&nbsp;</li>';
+ echo '<li>';
+ echo '<a href="index.php?a=phoneSurveys" title="' . $lang['srv_telephone_surveys'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_6.'">' . $lang['srv_telephone_surveys'] . '</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+
+
+ $SLCount = $this->countSurveys();
+ if ($SLCount > 0 && $admin_type <= 1) {
+ #echo '<li class="spaceLarge">&nbsp;</li>';
+ echo '<li class="spaceBig">&nbsp;</li>';
+ echo '<li>';
+ echo '<a href="index.php?a=diagnostics" title="' . $lang['srv_diagnostics'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_2.'">'. $lang['srv_diagnostics'] . '</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+
+ # uporabniki
+ if ($admin_type <= 1 /*or true*/) {
+ # ni smiselno da ostali uporabniki vidijo zavihek, ker so tako prikazane samo njihove ankete
+ echo '<li class="spaceBig">&nbsp;</li>';
+ echo '<li>';
+ echo '<a href="index.php?a=diagnostics&t=uporabniki" title="' . $lang['hour_users'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_5.'">'. $lang['hour_users'] . '</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+ echo '<li class="spaceBig">&nbsp;</li>';
+ echo '<li>';
+ echo '<a href="index.php?a=knjiznica" title="' . $lang['srv_library'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_3.'">'. $lang['srv_library'] . '</div>';
+ echo '</a>';
+ echo '</li>';
+
+ # Nastavitve
+ //if ($admin_type == 0) {
+ echo '<li class="spaceBig">&nbsp;</li>';
+
+ echo '<li>';
+ echo '<a href="index.php?a=nastavitve'.($admin_type != 0 ? '&m=global_user_settings' : '').'" title="' . $lang['settings'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_4.'">' . $lang['settings'] . '</div>';
+ echo '</a>';
+ echo '</li>';
+ //}
+
+ # Streznik
+ if ($admin_type == 0 && false) {
+ echo '<li class="spaceBig">&nbsp;</li>';
+
+ echo '<li>';
+ echo '<a href="http://www.1ka.si/SAR/" title="'.$lang['srv_sar'].'" target="_blank">';
+ echo '<div class="smaller-singlebutton-off">'/*<span class="sprites streznik_off"></span>'*/.$lang['srv_sar'].'</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+
+ # Obvestila - zaenkrat samo admin
+ if ($admin_type == 0) {
+ echo '<li class="spaceBig">&nbsp;</li>';
+
+ echo '<li>';
+ echo '<a href="index.php?a=obvestila'.($admin_type == 0 ? '&t=sent' : '').'" title="' . $lang['srv_notifications'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_7.'">'.$lang['srv_notifications'].'</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+
+ # Narocila - samo ce imamo vklopljene pakete
+ global $app_settings;
+ if($app_settings['commercial_packages']){
+ echo '<li class="spaceBig">&nbsp;</li>';
+
+ echo '<li>';
+ echo '<a href="index.php?a=narocila" title="' . $lang['srv_narocila'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_10.'">'.$lang['srv_narocila'].'</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+
+ # GDPR
+ echo '<li class="spaceBig">&nbsp;</li>';
+
+ echo '<li>';
+ $request_counter = GDPR::countUserUnfinishedRequests();
+ $request_counter_text = (true) ? ' <sup class="red" style="vertical-align: baseline; position: relative; top: -0.4em;">('.$request_counter.')</sup>' : '';
+ echo '<a href="index.php?a=gdpr'.($request_counter > 0 ? '&m=gdpr_requests' : '').'" title="' . $lang['srv_gdpr_settings'] . '">';
+ echo '<div class="smaller-singlebutton-'.$css_9.'" style="margin-top: -1px">'.$lang['srv_gdpr_settings'].$request_counter_text.'</div>';
+ echo '</a>';
+ echo '</li>';
+
+ # UL evalvacija razne nastavitve, uvozi, izvozi - samo na anketa.uni-lj.si/student (zaenkrat samo admin)
+ if (Common::checkModule('evalvacija') == '1' && $admin_type == 0) {
+ echo '<li class="spaceBig">&nbsp;</li>';
+
+ echo '<li>';
+ echo '<a href="index.php?a=ul_evalvation" title="UL evalvacije">';
+ echo '<div class="smaller-singlebutton-'.$css_8.'">UL evalvacije</div>';
+ echo '</a>';
+ echo '</li>';
+ }
+
+ echo '</ol>';
+
+ // genialno, rewrite se nismo ucili...
+ if ($lang['id'] == "1") $subdomain = "www";
+ else $subdomain = "english";
+
+
+ switch ($_GET['a']) {
+ case 'pregledovanje':
+ $help_url = 'http://' .$subdomain .'.1ka.si/c/790/Moja_anketa/?preid=795&from1ka=1';
+ break;
+ case 'diagnostics':
+ if ($_GET['t'] == 'uporabniki') {
+ $help_url = 'http://' .$subdomain .'.1ka.si/c/904/Uporabniki/?preid=795&from1ka=1';
+ } else {
+ $help_url = 'http://' .$subdomain .'.1ka.si/c/795/Aktivnost/?preid=790&from1ka=1';
+ }
+ break;
+ case 'knjiznica':
+ $help_url = 'http://' .$subdomain .'.1ka.si/c/796/Knjiznica/?preid=795&from1ka=1';
+ break;
+ case 'nastavitve':
+ $help_url = 'http://' .$subdomain .'.1ka.si/c/797/Nastavitve/?preid=796&from1ka=1';
+ break;
+ default:
+ $help_url = 'http://' .$subdomain .'.1ka.si/c/790/Moja_anketa/?preid=795&from1ka=1';
+ break;
+ }
+
+ echo '<ol class="smaller left-side help-1ka" >';
+ echo ' <li>';
+ echo ' <a href="'.$help_url.'" title="'.$lang['srv_settings_help'].'" target="_blank" >';
+ echo ' <div class="smaller-singlebutton-off">'.$lang['srv_settings_help'].'</div>';
+ echo ' </a>';
+ echo ' </li>';
+ echo '</ol>';
+
+ echo '</div>';
+ }
+
+ /**
+ * prikaze izbiro jezika zgoraj desno
+ *
+ */
+ function language_change() {
+ global $lang;
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT lang FROM users WHERE id = '$global_user_id'");
+ $row = mysqli_fetch_array($sql);
+ $lang_admin = $row['lang'];
+
+ echo '<div id="language_select">';
+
+ if($lang_admin == 1){
+ echo '<a href="#" onClick="language_change(2); return false;"><div class="flag eng"></div> <span>English</span></a>';
+ }
+ else{
+ echo '<a href="#" onClick="language_change(1); return false;"><div class="flag slo"></div> <span>Slovenščina</span></a>';
+ }
+
+ echo '</div>';
+ }
+
+
+
+ /** Seznam vseh anket ki so na voljo posameznemu uporabniku
+ *
+ */
+ function reloadSurveys() {
+
+ # polovimo seznam uporabnikovih anket
+ $this->dostopCondition = null;
+ $this->surveys_ids = array();
+
+ $stringSurveyList = "SELECT id, backup, active, folder, dostop FROM srv_anketa sa WHERE sa.backup='0' AND sa.id > 0 AND sa.active >= 0 AND sa.invisible = '0' ".$this->getFolderCondition().$this->getDostopAnketa();
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ while ( $rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+ $this->surveys_ids[$rowSurveyList['id']] = $rowSurveyList['id'];
+ }
+ }
+
+ function setUserId() {
+ # nastavimo filter po userju
+ if ($_GET['a'] == 'surveyList_user' && (int)$_POST['uid'] > 0 && ($_POST['list_user_type'] == 'i' || $_POST['list_user_type'] == 'e')) {
+ $_SESSION['sl_uid'] = (int)$_POST['uid'];
+ $_SESSION['sl_typ'] = $_POST['list_user_type'];
+ $this->user_id = (int)$_POST['uid'];
+ } else {
+ unset($_SESSION['sl_uid']);
+ unset($_SESSION['sl_typ']);
+ $this->user_id = null;
+ }
+ $this->reloadSurveys();
+ # posodobimo podatke prikazanih anket
+ $this -> refreshData();
+
+ }
+ function setUserLanguage() {
+ # nastavimo filter po userju
+ if ( isset($_POST['lang_id']) && (int)$_POST['lang_id']) {
+ $_SESSION['sl_lang_id'] = (int)$_POST['lang_id'];
+ $this->lang_id = (int)$_POST['lang_id'];
+ } else {
+ unset($_SESSION['sl_lang_id']);
+ $this->lang_id = 0;
+ }
+ $this->reloadSurveys();
+ # posodobimo podatke prikazanih anket
+ $this -> refreshData();
+
+ }
+ function setUserGDPR() {
+ # nastavimo filter po GDPR anketah
+ if ( isset($_POST['gdpr']) && (int)$_POST['gdpr']) {
+ $_SESSION['sl_gdpr'] = (int)$_POST['gdpr'];
+ $this->gdpr = (int)$_POST['gdpr'];
+ } else {
+ unset($_SESSION['sl_gdpr']);
+ $this->gdpr = 0;
+ }
+ $this->reloadSurveys();
+ # posodobimo podatke prikazanih anket
+ $this -> refreshData();
+
+ }
+ function setUserLibrary() {
+ # nastavimo filter po folderju knjiznice
+ if ( isset($_POST['currentLibrary']) && (int)$_POST['currentLibrary']) {
+ $_SESSION['currentLibrary'] = (int)$_POST['currentLibrary'];
+ $this->currentLibrary = (int)$_POST['currentLibrary'];
+ } else {
+ unset($_SESSION['currentLibrary']);
+ $this->currentLibrary = 0;
+ }
+ $this->reloadSurveys();
+ # posodobimo podatke prikazanih anket
+ $this -> refreshData();
+ }
+
+
+ /** Polovimo podatke anket in jih izrišemo
+ *
+ */
+ public function getSurveys() {
+ global $global_user_id;
+ global $lang;
+
+ // ali imamo star napreden vmesnik za moje ankete
+ $advancedMySurveys = UserSetting::getInstance()->getUserSetting('advancedMySurveys');
+
+ // Nastavitve zgoraj - nekatere niso prikazane pri searchu
+ if($this->isSearch != 1){
+
+ // Gumb za ustvarjanje ankete
+ echo '<div id="anketa_new_float">';
+ $this->new_anketa_div();
+ echo '</div>';
+
+ // Paginacija
+ echo '<div id="pagination">';
+ $this->displayPagiantion();
+ echo '</div>';
+ }
+
+ // Sort gumb - samo v novem vmesniku
+ if($advancedMySurveys != 1 && $this->onlyPhone == false){
+ echo '<div id="sortButton">';
+ $this->displaySortButton();
+ echo '</div>';
+ }
+
+ // Gumb za filtriranje - samo v novem vmesniku
+ //if($this->g_adminType <= 1){
+ if($advancedMySurveys != 1 && $this->onlyPhone == false){
+ //echo '<div id="filterButton">';
+ $this->displayFilterButton();
+ //echo '</div>';
+ }
+
+ // Preklop na pogled s folderji (samo ce imamo nov vmesnik)
+ if($this->isSearch != 1){
+ if($advancedMySurveys != 1 && $this->onlyPhone == false){
+ //echo '<div id="folderSwitch">';
+ $this->displayFolderSwitch();
+ //echo '</div>';
+ }
+ }
+
+ // Nastavitve zgoraj - nekatere niso prikazane pri searchu
+ if($this->isSearch != 1){
+ // Gumb z nastavitvami pogleda - za star vmesnik
+ if ($this->onlyPhone == false && $advancedMySurveys == 1){
+ $this->displaySettingsUrl();
+ }
+
+ // Okno za search po mojeih anketah
+ echo '<div id="searchMySurveys">';
+ $this->displaySearch();
+ echo '</div>';
+ }
+
+ // Izris seznama anket - star oz. nov design
+ if($advancedMySurveys == 1){
+ $this->displaySurveyList();
+ }
+ else{
+ if($this->show_folders == 1 && $this->isSearch != 1){
+
+ // Info box za posamezno anketo (hover)
+ echo '<div id="survey_list_info"></div>';
+
+ echo '<div class="clr"></div>';
+
+ // Loop po vseh folderjih prvega nivoja - samo na prvi strani
+ if($this->pageno == 1){
+ // Plus za dodajanje folderja
+ echo '<div style="margin: 15px 0 -15px 0"><a style="vertical-align:0px; line-height:18px;" href="#" title="'.$lang['srv_mySurvey_create_folder'].'" onClick="create_folder(\''.$folder['id'].'\'); return false;">';
+ echo '<span style="vertical-align:middle;" class="faicon add icon-blue-hover-orange pointer"></span> <span style="vertical-align:middle;" class="bold">'.$lang['srv_mySurvey_create_folder'].'</span>';
+ echo '</a></div>';
+
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE usr_id='$global_user_id' AND parent='0' ORDER BY naslov ASC");
+ if(mysqli_num_rows($sql) > 0) {
+ while($row = mysqli_fetch_array($sql)){
+ echo '<div id="folder_holder_'.$row['id'].'" class="folder_holder level1">';
+ $this->displayNewFolder($row);
+ echo '</div>';
+ }
+ }
+ }
+
+ // Na koncu se izpisemo ankete ki niso v nobenem folderju
+ $row = array('id'=>0, 'naslov'=>$lang['srv_mySurvey_unallocated']);
+ echo '<div id="folder_holder_0" class="folder_holder level1">';
+ $this->displayNewFolder($row);
+ echo '</div>';
+
+ echo '<script type="text/javascript">surveyList_folder_init();</script>';
+ }
+ // Ce ne prikazujemo map je vse po starem
+ else{
+ // Info box za posamezno anketo (hover)
+ echo '<div id="survey_list_info"></div>';
+
+ echo '<div id="div_sl_new_-1" class="div_sl_new">';
+ $this->displayNewSurveyList($folder=-1);
+ echo '</div>';
+ }
+
+ // Paginacija - se na dnu - ni prikazana pri searchu
+ if($this->isSearch != 1){
+ echo '<div id="pagination" class="bottom">';
+ $this->displayPagiantion();
+ echo '</div><br /><br />';
+ }
+ }
+ }
+
+ function displaySurveyList() {
+ global $lang;
+
+ if ($this->onlyPhone == true) {
+ $this->settingsArray = array();
+ # prikažemo samo naslov
+ $this->settingsArray['naslov'] = $this->dataFields[1];;
+ echo '<input type="hidden" id="onlyPhone" name="onlyPhone" value="1">';
+ }
+
+ echo '<div id="div_sl">';
+ if ( SRV_LIST_GET_AS_LIST == true) {
+ echo '<br class="clr" />';
+ // labelo za aktivno, in knji?nico popravimo kar ro?no - nardimo slikice
+ $lang['srv_h_sl_active_1'] = '<span class="faicon star_on" title="'.$lang['srv_anketa_active'].'"></span>';
+ $lang['srv_h_sl_delete_1'] = '';
+ $lang['srv_h_sl_lib_glb_1'] = '<span class="sprites library_admin_on" title="'.$lang['srv_ank_lib_on'].'"></span>';
+ $lang['srv_h_sl_lib_usr_1'] = '<span class="sprites library_on" title="'.$lang['srv_ank_mylib_on'].'"></span>';
+
+ $ankete = $this->getSurveysAsList();
+
+ echo '<input type="hidden" id="sortby" value="'.(isset($_POST['sortby']) ? $_POST['sortby'] : null).'">';
+ echo '<input type="hidden" id="sorttype" value="'.(isset($_POST['sorttype']) ? $_POST['sorttype'] : null).'">';
+
+ echo '<ul id="surveyList" >';
+ // izpi?emo header celice
+ echo '<li class="sl_header">';
+ $grupaName = "";
+ $groupWidths = array();
+
+ if (count($this->settingsArray) > 0 ){
+ foreach ( $this->settingsArray as $opcija ) {
+ if ($opcija['visible'] == 1) {
+ // preverimo ali smo zaklju?ili prej?njo grupo
+ if ((!isset($opcija['header_grupa']) && $grupaName != "") || // nismo ve? v grupi stara ?e obstaja
+ ( isset($opcija['header_grupa']) && $grupaName != "" && $opcija['header_grupa'] != $grupaName)) { // smo v grupi ampak ime ni enako prej?njemu
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '</div>';
+ $grupaName = "";
+ }
+ // preverimo ali naredimo novo grupo (Vnesel / urejal)
+ if (isset($opcija['header_grupa']) && $grupaName == "") { // smo v grupi polj pod in imamo podpolja: ime priimek, email, datum
+ // imamo za?etek grupe nari?emo ?tartne dive
+ echo '<div id="'.$opcija['header_grupa'].'_holder" class="floatLeft" style="padding:0px; margin:0px; border:none; height:100%;">';
+ echo '<div id="'.$opcija['header_grupa'].'_title" style="height:26px; /*border-bottom: 1px solid #C2D2C9;*/ padding:0px; margin:0px; /*border-right:1px solid #C2D2C9;*/">';
+ echo '<div id="'.$opcija['header_grupa'].'" class="floatLeft anl_ac" style="border:none;">'.$lang['srv_'.$opcija['header_grupa']].'</div>';
+ // nastavimo sirino grupe na 0
+ $groupWidths[$opcija['header_grupa']] = 0;
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '<div style="height:26px;padding:0px; margin:0px; border:none;">';
+ $grupaName = $opcija['header_grupa'];
+ }
+ echo '<div id="h_'.$opcija['header_field'].'" class="floatLeft sl_header_field '.$opcija['header_field'].' anl_ac" baseCss="'.$opcija['header_field'].'">'
+ . $this->createOrderUrl( $opcija['id'], (isset($opcija['lang_label']) ? $lang['srv_h_'.$opcija['lang_label']] : $lang['srv_h_'.$opcija['header_field']] ) )
+ . '</div>';
+ }
+ flush(); @ob_flush();
+ }
+ }
+ // na koncu ?e preverimo ali imamo kon?ano grupo ?ene nardimo zaklju?na diva
+ if ($grupaName != "") {
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '</div>';
+ $grupaName = "";
+ }
+ echo '</li>';
+ $cnt = 1;
+ if (count($ankete)) {
+ foreach ( $ankete as $anketa ) {
+ $eavenOdd = $cnt&1;
+ $cnt++;
+ $anketa_answers_cnt = $anketa['answers'];
+ $anketa_is_active = $anketa['active'];
+ $anketa_is_copy = isset($anketa['insert_uid']) && $anketa['insert_uid'] == -1 ? true : false;
+ $anketa_i_uid= isset($anketa['insert_uid']) ? $anketa['insert_uid'] : null;
+ $anketa_e_uid= isset($anketa['edit_uid']) ? $anketa['edit_uid'] : null;
+ $anketa_canEdit= $anketa['canEdit'];
+ echo '<li id="anketa_list_'.$anketa['id'].'" class="sl_bck_'.$eavenOdd.'">';
+ // za vsako vidno polje za header izpi?emopodatek
+ foreach ( $this->settingsArray as $opcija ) {
+
+ if (isset($opcija['visible']) && $opcija['visible'] == 1) {
+ echo '<div class="floatLeft '.$opcija['header_field'].' '.(isset($opcija['data_css']) ? $opcija['data_css'] : null).' sl_bck_br_'.$eavenOdd.'" title="'.$anketa[$opcija['data_field']].'" >';
+ if (isset($opcija['data_type'])) {
+ $this->echoText($anketa[$opcija['data_field']], $opcija['data_type'], $anketa['id'], array('answers_cnt'=>$anketa_answers_cnt, 'is_active'=>$anketa_is_active, 'anketa_is_copy'=>$anketa_is_copy, 'anketa_i_uid'=>$anketa_i_uid, 'anketa_e_uid'=>$anketa_e_uid,'anketa_canEdit'=>$anketa_canEdit));
+ } else {
+ $this->echoText($anketa[$opcija['data_field']], 'text', $anketa['id'], array('answers_cnt'=>$anketa_answers_cnt, 'is_active'=>$anketa_is_active, 'anketa_is_copy'=>$anketa_is_copy, 'anketa_i_uid'=>$anketa_i_uid, 'anketa_e_uid'=>$anketa_e_uid,'anketa_canEdit'=>$anketa_canEdit));
+ }
+ echo '</div>';
+ }
+ }
+ echo '</li>';
+ }
+ }
+ echo '</ul>';
+ // izpi?emo javascript za resizable
+ echo '<script type="text/javascript">';
+ echo '$(document).ready(function() {';
+ // echo '$().ready(function() {';
+ foreach ( $this->settingsArray as $opcija ) {
+ if ($opcija['visible'] == 1) {
+ echo '$("#h_'.$opcija['header_field'].'").resizable({handles:"e", alsoResize: "'.$opcija['alsoResize'].'"'.
+ (isset($opcija['minWidth'])?', minWidth: '.$opcija['minWidth']:'').(isset($opcija['maxWidth'])?', maxWidth: '.$opcija['maxWidth']:'').
+ ', stop: function(event, ui) { save_surveyListCssSettings(event, ui); }'.'});';
+ }
+ }
+
+ // ponastavimo ?irine celic z JS
+ $css_data = $this->getCssSetings();
+ if (isset($css_data) && count($css_data)>0) {
+ foreach ($css_data as $css_key => $css) {
+ echo '$(".'.$css_key.'").width('.$css.');';
+ }
+ }
+
+ // prika?emo seznam
+ echo '$("#surveyList").show();';
+ // header title priredimo sirino
+
+ foreach ( $groupWidths as $grupa => $widths ) {
+ //echo '$("#'.$grupa.'").css( { "width": ($("#'.$grupa.'_holder").width()-5)+"px"});';
+ // chrome bux fix --mitja
+ echo '$("#'.$grupa.'").css( { "width": "100%"});';
+ }
+ echo '});';
+ echo '</script>';
+ }
+
+ echo '</div>'; // id="div_sl"
+
+ }
+
+
+ /** Kreacija nove ankete
+ */
+ function new_anketa_div(){
+ global $lang;
+ global $admin_type;
+ global $site_url;
+
+ echo '<span id="buttonCreate" class="floatLeft"><a href="' . $site_url . 'admin/survey/index.php?a=ustvari_anketo" title="' . $lang['srv_create_survey'] . '">';
+ echo $lang['srv_create_survey'];
+ echo '</a></span>';
+
+ // uporabniki z vklopljeno moznostjo imajo tudi hitro ustvarjanje ankete (brez vnosa imena in izbire skina)
+ $oneclickCreateMySurveys = UserSetting::getInstance()->getUserSetting('oneclickCreateMySurveys');
+ if ($oneclickCreateMySurveys == 1) {
+ echo '<span class="floatLeft" style="margin:10px 0 0 20px; font-weight:600;"><a style="vertical-align:0px; line-height:18px;" href="#" onclick="newAnketaBlank();" title="' . $lang['one_click_create'] . '"><span style="vertical-align:top;" class="faicon add icon-blue-hover-orange"></span> <span>'.$lang['one_click_create'].'</span></a>';
+ }
+ }
+
+ function displayNewSurveyList($folder=0) {
+ global $lang;
+ global $site_url;
+ global $global_user_id;
+
+ if (SRV_LIST_GET_AS_LIST == true) {
+
+ $ankete = $this->getSurveysAsListNew($folder);
+
+ // Ce searchamo izrisemo napredne nastavitve za search
+ if($this->isSearch == 1){
+ echo '<div id="searchSettings">';
+ $this->displaySearchSettings();
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+ }
+
+ echo '<input type="hidden" id="sortby" value="'.(isset($_POST['sortby']) ? $_POST['sortby'] : null).'">';
+ echo '<input type="hidden" id="sorttype" value="'.(isset($_POST['sorttype']) ? $_POST['sorttype'] : null).'">';
+
+ if ($count = count($ankete)) {
+
+ // Naslov za search
+ if($this->isSearch == 1){
+ if($count == 1)
+ $hits = $lang['s_hits_1'];
+ elseif($count == 2)
+ $hits = $lang['s_hits_2'];
+ elseif($count == 3 || $count == 4)
+ $hits = $lang['s_hits_34'];
+ else
+ $hits = $lang['s_hits'];
+
+ // Ce imamo vec kot 1000 zadetkov izpisemo samo 1000 in opozorilo
+ if($count < 1000)
+ $cnt_text = '<span class="italic">('.$count.' '.$hits.')</span>';
+ else
+ $cnt_text = '<span class="italic">('.$lang['s_hits_1000'].')</span>';
+
+ echo '<span class="search_title">'.$lang['s_search_mySurvey_title'].' '.$cnt_text.':</span>';
+ }
+
+ echo '<table id="surveyList_new">';
+
+
+ // HEADER VRSTICA
+ echo '<tr class="sl_header_new">';
+
+ // Info ikona
+ echo '<td class="col1">';
+ echo '</td>';
+
+ // Tip ankete (forma, navadna, glasovanje)
+ //echo '<td class="col2"></td>';
+ // Aktivnost ankete
+ echo '<td class="col2"></td>';
+
+ // Naslov
+ echo '<td class="col3">';
+ echo $this->createOrderUrlNew(1, $lang['title']);
+ echo '</td>';
+
+ // Trajanje - status
+ echo '<td class="col4">';
+ echo $this->createOrderUrlNew(18, 'Status');
+ echo '</td>';
+
+ // Tip + st. vprasanj
+ echo '<td class="col5">';
+ echo '';
+ echo $this->createOrderUrlNew(19, $lang['srv_tip']);
+ echo '</td>';
+
+ // Zadnji vnos
+ echo '<td class="col6">';
+ echo $this->createOrderUrlNew(16, $lang['srv_last_insrt']);
+ echo '</td>';
+
+ // Sprememba
+ echo '<td class="col7">';
+ echo $this->createOrderUrlNew(14, $lang['change']);
+ echo '</td>';
+
+ // Ikona1
+ echo '<td class="col8"></td>';
+
+ // Ikona2
+ echo '<td class="col9"></td>';
+
+ echo '</tr>';
+
+
+ // VRSTICE Z ANKETAMI
+ foreach ( $ankete as $anketa ) {
+
+ echo '<tr id="anketa_list_'.$anketa['id'].'" class="anketa_list '.($this->show_folders == 1 ? ' mySurvey_draggable' : '').'" anketa_id="'.$anketa['id'].'">';
+
+ // Info ikona
+ echo '<td class="col1">';
+ //var_dump($anketa);
+ echo '<span id="info_icon_'.$anketa['id'].'" anketa="'.$anketa['id'].'" class="faicon info icon-as_link pointer icon-center" title="'.$lang['srv_survey_info'].'" onClick="surveyList_info(\''.$anketa['id'].'\');"></span>';
+ echo '</td>';
+
+ // Aktivnost - neaktivna, aktivna, zakljucena
+ echo '<td class="col2">';
+ if ($anketa['active'] == 1) {
+ echo '<div class="dot blue" title="'.$lang['srv_anketa_active2'].'"></div>';
+ } else {
+ $sqlA = sisplet_query("SELECT sid FROM srv_activity WHERE sid='".$anketa['id']."'");
+ if (mysqli_num_rows($sqlA) > 0) {
+ # anketa je zaključena
+ echo '<div class="dot grey" title="'.$lang['srv_survey_non_active'].'"></div>';
+ } else {
+ # anketa je neaktivna
+ echo '<div class="dot grey" title="'.$lang['srv_survey_non_active_notActivated'].'"></div>';
+ }
+ }
+ echo '</td>';
+
+ // Naslov
+ echo '<td class="col3">';
+ if(strlen($anketa['naslov']) > 60)
+ $text = substr($anketa['naslov'],0,60);
+ else
+ $text = $anketa['naslov'];
+
+ // Ce gre za search moramo ustrezno pobarvati najden del besede
+ $text_searched = $text;
+ if($this->isSearch == 1 && $this->searchSettings['stype'] == '0'){
+ foreach($this->searchStringProcessed as $search_word){
+
+ // Pobarvamo najden niz v naslovu ankete
+ preg_match_all("/$search_word+/i", $text_searched, $matches);
+ if (is_array($matches[0]) && count($matches[0]) >= 1) {
+ foreach ($matches[0] as $match) {
+ $text_searched = str_replace($match, '<span class="red">'.$match.'</span>', $text_searched);
+ }
+ }
+ }
+ }
+
+ echo '<a href="'.$site_url.'admin/survey/index.php?anketa='.$anketa['id'].'&a='.A_REDIRECTLINK.'" title="'.$text.'">';
+ echo '<span class="title">'.$text_searched.'</span>';
+ echo '</a>';
+
+ $i_time = substr($anketa['i_time'], 0, 8);
+ $i_time = explode('.', $i_time);
+ echo '<br /><span class="small">';
+ if($anketa['mobile_created'] == '1')
+ echo '<span class="red spaceRight pointer" title="'.$lang['srv_mobile_survey'].'">M</span>';
+ // Ce gre za search moramo ustrezno pobarvati najden del besede
+ $name_searched = $anketa['i_name'];
+ $surname_searched = $anketa['i_surname'];
+ if($this->isSearch == 1 && $this->searchSettings['stype'] == '1'){
+ foreach($this->searchStringProcessed as $search_word){
+
+ // Pobarvamo najden niz v imenu
+ preg_match_all("/$search_word+/i", $name_searched, $matches);
+ if (is_array($matches[0]) && count($matches[0]) >= 1) {
+ foreach ($matches[0] as $match) {
+ $name_searched = str_replace($match, '<span class="red">'.$match.'</span>', $name_searched);
+ }
+ }
+
+ // Pobarvamo najden niz v priimku
+ preg_match_all("/$search_word+/i", $surname_searched, $matches);
+ if (is_array($matches[0]) && count($matches[0]) >= 1) {
+ foreach ($matches[0] as $match) {
+ $surname_searched = str_replace($match, '<span class="red">'.$match.'</span>', $surname_searched);
+ }
+ }
+ }
+ }
+ echo $lang['srv_h_sl_avtor'].': '.$name_searched.' '.$surname_searched.', '.$i_time[0].'.'.$i_time[1].'.20'.$i_time[2].'</span>';
+ echo '</td>';
+
+ // Trajanje - status
+ echo '<td class="col4">';
+ if ($anketa['active'] == 1) {
+ $now = time();
+ $do = explode('.', $anketa['trajanjedo']);
+ $do = strtotime($do[0].'.'.$do[1].'.20'.$do[2]);
+ $trajanje = $do - $now;
+ $trajanje = floor($trajanje/60/60/24) + 1;
+ if($trajanje >= 0){
+ // Ce je aktivna za vec kot 2000 dni je trajna
+ if($trajanje > 2000)
+ echo $lang['srv_trajna_anketa'];
+ else
+ echo $lang['more'].' '.$trajanje.' '.$lang['hour_days'];
+ }
+ else{
+ echo $lang['srv_trajna_anketa'];
+ }
+ }
+ else {
+ $sqlA = sisplet_query("SELECT sid FROM srv_activity WHERE sid='".$anketa['id']."'");
+ if (mysqli_num_rows($sqlA) > 0) {
+ # anketa je zaključena
+ echo $lang['srv_survey_list_closed'];
+ } else {
+ # anketa je neaktivna
+ echo $lang['srv_survey_list_inpreparation'];
+ }
+ }
+ echo '</td>';
+
+ // Tip + st. vprasanj
+ echo '<td class="col5">';
+ if($anketa['survey_type'] == 0)
+ echo $lang['srv_vrsta_survey_type_0'];
+ elseif($anketa['survey_type'] == 1)
+ echo $lang['srv_vrsta_survey_type_1'];
+ elseif(SurveyInfo::checkSurveyModule('hierarhija', $anketa['id']))
+ echo $lang['srv_vrsta_survey_type_10'];
+ else
+ echo $lang['srv_vrsta_survey_type_2'];
+
+ echo '<br /><span class="small">'.$lang['srv_h_sl_stvprasanj'].': '. $anketa['variables'].'</span>';
+ echo '</td>';
+
+ // Zadnji vnos
+ echo '<td class="col6">';
+ if($anketa['answers'] > 0){
+ $v_time = substr($anketa['v_time_last'], 0, 8);
+ $v_time = explode('.', $v_time);
+ echo $v_time[0].'.'.$v_time[1].'.20'.$v_time[2].'<br />';
+ }
+ else{
+ echo '/<br />';
+ }
+ echo '<span class="small">'.$lang['srv_info_answers'].': '.$anketa['answers'].'</span>';
+ echo '</td>';
+
+ // Sprememba
+ echo '<td class="col7">';
+ $e_time = substr($anketa['e_time'], 0, 8);
+ $e_time = explode('.', $e_time);
+ echo $e_time[0].'.'.$e_time[1].'.20'.$e_time[2].'<br />';
+
+ echo '<a href="#" onclick="surveyList_user(\'e\',\'#edit_user_'.$anketa['id'].'\');">';
+ echo '<span id="edit_user_'.$anketa['id'].'" euid="'.$anketa['edit_uid'].'" class="email">'.$anketa['e_email'].'</span>';
+ echo '</a>';
+ echo '</td>';
+
+ // Knjiznica - uporabnik
+ echo '<td class="col8">';
+ echo '<a href="#" title="'.($anketa['lib_usr'] == 1 ? $lang['srv_ank_mylib_off'] : $lang['srv_ank_mylib_on']).'" onclick="surveyList_myknjiznica_new(\''.$anketa['id'].'\'); return false;">';
+ echo '<span class="sprites '.($anketa['lib_usr'] == 1 ? ' sl_active_on': ' sl_active_off').'"></span>';
+ echo '</a>';
+ echo '</td>';
+
+ // Knjiznica - global (samo admin)
+ echo '<td class="col9">';
+ if ($this->g_adminType == 0){
+ echo '<a href="#" title="'.($anketa['lib_glb'] == 1 ? $lang['srv_ank_lib_off'] : $lang['srv_ank_lib_on']).'" onclick="surveyList_knjiznica_new(\''.$anketa['id'].'\'); return false;">';
+ echo '<span class="sprites '.($anketa['lib_glb'] == 1 ? ' sl_library_on': ' sl_library_off').'"></span>';
+ echo '</a>';
+ }
+ echo '</td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ else{
+ // Naslov za prazen search
+ if($this->isSearch == 1)
+ echo '<span class="search_title">'.$lang['s_search_mySurvey_nothing'].'.</span>';
+ }
+ }
+ }
+
+ function displayNewFolder($folder){
+ global $lang;
+ global $global_user_id;
+ global $admin_type;
+
+ // Izris nerazvrscenih anket
+ if($folder['id'] == 0){
+ echo '<div class="folder_title droppable" id="folder_0" folder_id="0">';
+
+ echo '<a href="#" onClick="toggle_folder(\''.$folder['id'].'\'); return false;"><span class="faicon minus icon-blue pointer"></span></a>';
+
+ echo ' <span class="spaceRight" style="vertical-align:0px;">'.$folder['naslov'].'</span>';
+
+ // Ikona za dodajanje folderja
+ echo '</div>';
+
+
+ echo '<div id="folder_content_0" class="folder_content '.(/*$this->pageno == 1*/false ? ' closed' : '').'">';
+ $this->displayNewSurveyList($folder=0);
+ echo '</div>';
+ }
+ else{
+ echo '<div class="folder_title mySurvey_draggable droppable" id="folder_'.$folder['id'].'" folder_id="'.$folder['id'].'">';
+ if($folder['open'] == 1)
+ echo '<a href="#" onClick="toggle_folder(\''.$folder['id'].'\'); return false;"><span class="faicon minus icon-blue pointer"></span></a>';
+ else
+ echo '<a href="#" onClick="toggle_folder(\''.$folder['id'].'\'); return false;"><span class="faicon plus icon-blue pointer"></span></a>';
+
+ // Naslov folderja
+ echo ' <span class="faicon folder icon-blue"></span> <span id="folder_title_text_'.$folder['id'].'" class="folder_title_text spaceRight" style="vertical-align:0px;"><a href="#" onClick="edit_title_folder(\''.$folder['id'].'\'); return false;">'.$folder['naslov'].'</a></span>';
+
+ // Ikona za dodajanje folderja
+ echo ' <a href="#" title="'.$lang['srv_mySurvey_create_subfolder'].'" onClick="create_folder(\''.$folder['id'].'\'); return false;"><span class="faicon add icon-blue pointer map_holder_control"></span></a>';
+
+ // Ikona za brisanje folderja
+ echo ' <a href="#" title="'.$lang['srv_mySurvey_delete_folder'].'" onClick="delete_folder(\''.$folder['id'].'\'); return false;"><span class="faicon remove icon-orange pointer map_holder_control"></span></a>';
+
+ // Ikona za kopiranje folderja - samo admini
+ if($admin_type == 0)
+ echo ' &nbsp;<a href="#" title="'.$lang['srv_mySurvey_copy_folder'].'" onClick="copy_folder(\''.$folder['id'].'\'); return false;"><span class="faicon copy icon-blue_soft pointer map_holder_control"></span></a>';
+
+ echo '</div>';
+
+
+ echo '<div id="folder_content_'.$folder['id'].'" class="folder_content '.($folder['open'] == 1 ? '' : ' closed').' '.($folder['parent'] != 0 ? ' subfolder' : '').'">';
+
+ $this->displayNewSurveyList($folder['id']);
+
+ // Izpisemo se vse folderje znotraj trenutnega folderja
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE usr_id='$global_user_id' AND parent='".$folder['id']."' ORDER BY id DESC");
+ if(mysqli_num_rows($sql) > 0) {
+ while($row = mysqli_fetch_array($sql)){
+ echo '<div id="folder_holder_'.$row['id'].'" class="folder_holder">';
+ $this->displayNewFolder($row);
+ echo '</div>';
+ }
+ }
+
+ echo '</div>';
+ }
+ }
+
+
+ /** Prikažemo navigacijo po straneh rezultatov
+ *
+ */
+ function displayPagiantion() {
+ global $site_url, $lang;
+
+ //$this->max_pages = 100;
+
+ # ali sploh izrisujemo paginacijo
+ if ($this->max_pages > 1) {
+ if ($this->onlyPhone == false) {
+ $baseUrl = $site_url."admin/survey/index.php?pageno=";
+ } else {
+ $baseUrl = $site_url."admin/survey/index.php?a=phoneSurveys&pageno=";
+ }
+
+ # povezava na prejšnjo stran
+ $prev_page = $this->pageno - 1;
+ if($prev_page >= 1) {
+ //echo('<div><a href="'.$baseUrl.$prev_page.'">'.$lang['previous_page_short'].'</a></div>');
+ echo('<div><a href="'.$baseUrl.$prev_page.'"><span class="faicon pagination_left icon-blue"></span></a></div>');
+ } else {
+ # brez href povezave
+ //echo('<div class="disabledPage">'.$lang['previous_page_short'].'</div>');
+ echo('<div class="disabledPage"><span class="faicon pagination_left icon-blue_soft"></span></div>');
+ }
+
+ # povezave za vmesne strani
+ $middle = $this->max_pages / 2;
+ $skipped = false;
+ for($a = 1; $a <= $this->max_pages; $a++) {
+ if ($this->max_pages < ((SRV_LIST_GROUP_PAGINATE+1) * 2) || $a <= SRV_LIST_GROUP_PAGINATE || $a > ($this->max_pages-SRV_LIST_GROUP_PAGINATE)
+
+ || ( abs($a-$this->pageno) < SRV_LIST_GROUP_PAGINATE)) {
+ if ($skipped == true) {
+ echo '<div class="spacePage">.&nbsp;.&nbsp;.</div>';
+ $skipped = false;
+ }
+ if($a == $this->pageno) {
+ # brez href povezave
+ echo('<div class="currentPage">'.$a.'</div>');
+ } else {
+ echo('<div><a href="'.$baseUrl.$a.'">'.$a.'</a></div>');
+ }
+ } else {
+ $skipped = true;
+ }
+ }
+ # povezava na naslednjo stran
+ $next_page = $this->pageno + 1;
+ if($next_page <= $this->max_pages) {
+ //echo('<div><a href="'.$baseUrl.$next_page.'">'.$lang['next_page_short'].'</a></div>');
+ echo('<div><a href="'.$baseUrl.$next_page.'"><span class="faicon pagination_right icon-blue"></span></a></div>');
+ } else {
+ # brez href povezave
+ //echo('<div class="disabledPage">'.$lang['next_page_short'].'</div>');
+ echo('<div class="disabledPage"><span class="faicon pagination_right icon-blue_soft"></span></div>');
+ }
+
+ }
+ }
+
+ // Prikazemo gumb za sortiranje seznama anket
+ private function displaySortButton(){
+ global $lang, $site_url;
+
+ echo $lang['orderby'];
+ //echo ' <img style="margin-left:5px; vertical-align:middle;" src="'.$site_url.'admin/survey/img_new/bullet_arrow_down.png">';
+
+
+ echo '<div id="sortSettings">';
+
+ echo '<ul>';
+
+ if($this->sorttype == 2){
+ $sort = 1;
+ $img_src = 'sort_ascending';
+ }
+ else{
+ $sort = 2;
+ $img_src = 'sort_descending';
+ }
+
+ echo '<a href="#" onClick="surveyList_goTo(\'1\',\''.($this->sortby != 1 ? '1' : $sort).'\')"><li '.($this->sortby == 1 ? ' class="active"' : '').'>'.$lang['sort_by_title'].' <span class="faicon '.($this->sortby != 1 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'6\',\''.($this->sortby != 6 ? '1' : $sort).'\')"><li '.($this->sortby == 6 ? ' class="active"' : '').'>'.$lang['sort_by_qcount'].' <span class="faicon '.($this->sortby != 6 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'5\',\''.($this->sortby != 5 ? '1' : $sort).'\')"><li '.($this->sortby == 5 ? ' class="active"' : '').'>'.$lang['sort_by_answercount'].' <span class="faicon '.($this->sortby != 5 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'16\',\''.($this->sortby != 16 ? '1' : $sort).'\')"><li '.($this->sortby == 16 ? ' class="active"' : '').'>'.$lang['sort_by_insert'].' <span class="faicon '.($this->sortby != 16 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'14\',\''.($this->sortby != 14 ? '1' : $sort).'\')"><li '.($this->sortby == 14 ? ' class="active"' : '').'>'.$lang['sort_by_edit'].' <span class="faicon '.($this->sortby != 14 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'18\',\''.($this->sortby != 18 ? '1' : $sort).'\')"><li '.($this->sortby == 18 ? ' class="active"' : '').'>Status <span class="faicon '.($this->sortby != 18 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'7\',\''.($this->sortby != 7 ? '1' : $sort).'\')"><li '.($this->sortby == 7 ? ' class="active"' : '').'>'.$lang['sort_by_author'].' <span class="faicon '.($this->sortby != 7 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+ echo '<a href="#" onClick="surveyList_goTo(\'11\',\''.($this->sortby != 11 ? '1' : $sort).'\')"><li '.($this->sortby == 11 ? ' class="active"' : '').' style="border:0;">'.$lang['sort_by_editor'].' <span class="faicon '.($this->sortby != 11 ? 'sort_unsorted' : $img_src).'"></span></li></a>';
+
+ echo '</ul>';
+
+ echo '</div>';
+ }
+
+ // Prikazemo gumb za filtriranje seznama anket
+ private function displayFilterButton(){
+ global $lang, $site_url, $admin_languages;
+
+ echo '<div id="filterButton" '.(($this->user_id || $this->lang_id != 0 || $this->gdpr != 0) ? 'class="active"' : '').'>';
+
+ echo $lang['srv_analiza_filter'];
+ //echo ' <img style="margin-left:5px; vertical-align:middle;" src="'.$site_url.'admin/survey/img_new/bullet_arrow_down.png">';
+
+
+ echo '<div id="filterSettings">';
+ echo '<ul>';
+
+
+ # filter po uporabniku
+ echo '<li>';
+
+ echo '<span class="filter_title">'.$lang['srv_list_author'].'</span><br />';
+
+ // Ce preklapljamo v searchu moramo refreshati celo stran (druga js funkcija)
+ $reload = ($this->isSearch == 1) ? '_reload' : '';
+
+ echo '<input type="radio" name="filter_mySurveys" id="filter_mySurveys_0" value="0" '.(!$this->user_id ? 'checked="checked"' : '').' onclick="surveyList_user'.$reload.'(\'clr\',\'0\');"> <label for="filter_mySurveys_0">'.$lang['srv_list_all_surveys'].'</label>';
+ echo '<br /><input type="radio" name="filter_mySurveys" id="filter_mySurveys_1" value="1" '.($this->user_id ? 'checked="checked"' : '').' onclick="surveyList_user'.$reload.'(\'uid\',\''.$this->g_uid.'\');"> <label for="filter_mySurveys_1">'.$lang['srv_list_my_surveys'].'</label>';
+
+ echo '</li>';
+
+
+ # filter po jeziku
+ echo '<li>';
+
+ echo '<span class="filter_title">'.$lang['srv_sl_set_language'].'</span><br />';
+
+ echo '<input type="radio" name="filter_language" id="filter_language_0" value="0" '.((int)$this->lang_id == 0 ? 'checked="checked"' : '').' onclick="surveyList_language'.$reload.'(\'0\');"> <label for="filter_language_0">'.$lang['srv_sl_set_language_all'].'</label>';
+ echo '<br /><input type="radio" name="filter_language" id="filter_language_1" value="1" '.((int)$this->lang_id == 1 ? 'checked="checked"' : '').' onclick="surveyList_language'.$reload.'(\'1\');"> <label for="filter_language_1">'.$admin_languages['1'].'</label>';
+ echo '<br /><input type="radio" name="filter_language" id="filter_language_2" value="2" '.((int)$this->lang_id == 2 ? 'checked="checked"' : '').' onclick="surveyList_language'.$reload.'(\'2\');"> <label for="filter_language_2">'.$admin_languages['2'].'</label>';
+
+ echo '</li>';
+
+
+ # filter po GDPR anketah
+ echo '<li>';
+
+ echo '<span class="filter_title">'.$lang['srv_gdpr'].'</span><br />';
+
+ echo '<input type="radio" name="filter_gdpr" id="filter_gdpr_0" value="0" '.((int)$this->gdpr == 0 ? 'checked="checked"' : '').' onclick="surveyList_gdpr'.$reload.'(\'0\');"> <label for="filter_gdpr_0">'.$lang['srv_list_all_surveys'].'</label>';
+ echo '<br /><input type="radio" name="filter_gdpr" id="filter_gdpr_1" value="1" '.((int)$this->gdpr == 1 ? 'checked="checked"' : '').' onclick="surveyList_gdpr'.$reload.'(\'1\');"> <label for="filter_gdpr_1">'.$lang['srv_list_gdpr_gdpr'].'</label>';
+ //echo '<br /><input type="radio" name="filter_gdpr" id="filter_gdpr_2" value="2" '.((int)$this->gdpr == 2 ? 'checked="checked"' : '').' onclick="surveyList_gdpr'.$reload.'(\'2\');"> <label for="filter_gdpr_2">'.$lang['srv_list_gdpr_no_gdpr'].'</label>';
+
+ echo '</li>';
+
+
+ echo '</ul>';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ // Prikazemo preklop med navadnim pogledom in pogledom s folderji
+ private function displayFolderSwitch(){
+ global $lang, $global_user_id;
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ // Ce ni na voljo
+ if(!$userAccess->checkUserAccess('my_survey_folders')){
+ echo '<div title="'.$lang['srv_mySurvey_show_folders_desc'].'" id="folderSwitch" class="user_access_locked" onClick="popupUserAccess(\'my_survey_folders\');">';
+ echo $lang['srv_mySurvey_show_folders'];
+ echo '</div>';
+ }
+ else{
+ echo '<div title="'.$lang['srv_mySurvey_show_folders_desc'].'" id="folderSwitch" '.($this->show_folders == 1 ? ' class="active"' : '').' onClick="switchFolder(\''.$this->show_folders.'\');">';
+ echo $lang['srv_mySurvey_show_folders'];
+ echo '</div>';
+ }
+ }
+
+ private function displaySettingsUrl() {
+ global $lang;
+
+ echo '<span class="sl_setting_link"><a href="#" onclick="show_surveyListSettings(); return false;"> '.$lang['settings'].'</a></span>';
+
+ echo '<div id="survey_ListQickInfo" class="displayNone"></div>';
+ }
+
+ // Prikazemo nastavitve za napredno iskanje ce iscemo po anketah
+ private function displaySearchSettings(){
+ global $lang;
+ global $site_url;
+
+ // Posebej imamo skrito polje s parametri da jih ohranimo pri ajax klicih
+ echo '<input type="hidden" id="searchParams" name="searchParams" value="'.$this->getSearchParams().'" />';
+
+ echo '<span class="title">'.$lang['s_search_settings_my'].'</span>';
+
+ echo '<form method="GET" id="1kasf2" action="'.$site_url.'admin/survey/index.php">';
+
+ // Iskano geslo
+ echo '<p>';
+ echo ' <span class="bold">'.$lang['s_search2'].':</span> <input type="text" name="search" id="searchMySurveyText" value="'.htmlentities($this->searchString).'" placeholder="' . $lang['s_search'] . '" />';
+ echo '</p>';
+
+ // Iskanje po naslovu ali avtorju ali besedilu
+ echo '<p>';
+ echo ' <span>'.$lang['s_thru'].': </span>';
+ echo ' <label for="stype_0"><input type="radio" name="stype" id="stype_0" value="0" '.($this->searchSettings['stype'] == '0' ? ' checked="checked"' : '').' />'.$lang['s_title'].'</label>';
+ echo ' <label for="stype_1"><input type="radio" name="stype" id="stype_1" value="1" '.($this->searchSettings['stype'] == '1' ? ' checked="checked"' : '').' />'.$lang['s_author'].'</label>';
+ echo ' <label for="stype_2"><input type="radio" name="stype" id="stype_2" value="2" '.($this->searchSettings['stype'] == '2' ? ' checked="checked"' : '').' />'.$lang['s_text'].'</label>';
+ echo '</p>';
+
+
+ // NAPREDNE NASTAVITVE ISKANJA
+ $show_advanced_search = false;
+ if($this->searchSettings['sstatus'] != '0'
+ || $this->searchSettings['sidatefrom'] != ''
+ || $this->searchSettings['sidateto'] != ''
+ || $this->searchSettings['sedatefrom'] != ''
+ || $this->searchSettings['sedateto'] != ''){
+
+ $show_advanced_search = true;
+ }
+
+ echo '<span class="advancedSearchButton clr bold spaceLeft">';
+ echo ' <a href="#" onClick="showAdvancedSearch(); return false;">';
+ echo '<span class="faicon '.($show_advanced_search ? ' minus': 'plus').'"></span> ' . $lang['s_advanced'];
+ echo ' </a>';
+ echo '</span>';
+
+ echo '<div id="advancedSearch" '.($show_advanced_search ? '' : ' style="display:none;"').'>';
+
+ // Metaadmin lahko dodatno omeji search po avtorju
+ if(Dostop::isMetaAdmin()){
+ echo '<p>';
+ echo ' <span class="bold">'.$lang['s_search_metaadmin'].':</span> <input type="text" name="onlyAuthor" id="onlyAuthor" value="'.htmlentities($this->searchSettings['onlyAuthor']).'" placeholder="' . $lang['s_search'] . '" />';
+ echo '</p>';
+ }
+
+ // Status ankete (aktivna, neaktivna, zakljucena)
+ echo '<p>';
+ echo ' <span>'.$lang['s_activity'].': </span>';
+ echo ' <label for="sstatus_0"><input type="radio" name="sstatus" id="sstatus_0" value="0" '.($this->searchSettings['sstatus'] == '0' ? ' checked="checked"' : '').' />'.$lang['s_all_surveys'].'</label>';
+ echo ' <label for="sstatus_1"><input type="radio" name="sstatus" id="sstatus_1" value="1" '.($this->searchSettings['sstatus'] == '1' ? ' checked="checked"' : '').' />'.$lang['s_active_surveys'].'</label>';
+ echo ' <label for="sstatus_2"><input type="radio" name="sstatus" id="sstatus_2" value="2" '.($this->searchSettings['sstatus'] == '2' ? ' checked="checked"' : '').' />'.$lang['s_nonactive_surveys'].'</label>';
+ echo '</p>';
+
+ // Datum ustvarjanja ankete
+ echo '<p>';
+ echo ' <span class="spaceRight">'.$lang['s_itime'].': </span>';
+ echo ' <span class="spaceRight">'.$lang['s_from2'].' <input type="text" id="sidatefrom" name="sidatefrom" value="'.$this->searchSettings['sidatefrom'].'" autocomplete="off" size="12" /></span>';
+ echo ' <span>'.$lang['s_to'].' <input type="text" id="sidateto" name="sidateto" value="'.$this->searchSettings['sidateto'].'" autocomplete="off" size="12" /></span>';
+ echo '</p>';
+
+ // Datum zadnjega urejanja ankete
+ echo '<p>';
+ echo ' <span class="spaceRight">'.$lang['s_etime'].': </span>';
+ echo ' <span class="spaceRight">'.$lang['s_from2'].' <input type="text" id="sedatefrom" name="sedatefrom" value="'.$this->searchSettings['sedatefrom'].'" autocomplete="off" size="12" /></span>';
+ echo ' <span>'.$lang['s_to'].' <input type="text" id="sedateto" name="sedateto" value="'.$this->searchSettings['sedateto'].'" autocomplete="off" size="12" /></span>';
+ echo '</p>';
+
+ echo '</div>';
+
+
+ // Gumba isci in zapri
+ echo '<span style="margin-top: 10px;" class="floatRight spaceRight">';
+ echo ' <div class="buttonwrapper floatLeft spaceRight">';
+ echo ' <a class="ovalbutton ovalbutton_gray" href="'.$site_url.'admin/survey/index.php"><span>'.$lang['s_search_mySurvey_back'].'</span></a>';
+ echo ' </div>';
+ echo ' <div class="buttonwrapper floatRight">';
+ echo ' <a class="ovalbutton ovalbutton_orange" href="#" onclick="$(\'#1kasf2\').submit(); return false;"><span>'.$lang['s_search'].'</span></a>';
+ echo ' </div>';
+ echo '</span>';
+
+ // Gumb nazaj na moje ankete
+ /*echo '<span style="margin:5px 20px 0 5px;" class="floatRight bold">';
+ echo ' <a href="'.$site_url.'admin/survey/index.php"><span>'.$lang['s_search_mySurvey_back'].'</span></a>';
+ echo '</span>';*/
+
+ // Link na isci po knjiznici
+ echo '<span class="link"><a href="'.$site_url.'admin/survey/index.php?a=knjiznica&search='.$this->searchString.'">'.$lang['s_search_Library'].'</a></span>';
+
+ echo '<input style="display: none;" value="Išči" type="submit">';
+
+ echo '</form>';
+
+
+ // JS za koledar
+ echo '<script type="text/javascript">
+ var srv_site_url = \''.$site_url.'\';
+ $(document).ready(function () {
+ $("#sidatefrom, #sidateto, #sedatefrom, #sedateto").datepicker({
+ showOtherMonths: true,
+ selectOtherMonths: true,
+ changeMonth: true,
+ changeYear: true,
+ dateFormat: "dd.mm.yy",
+ showAnim: "slideDown",
+ showOn: "button",
+ buttonText: ""
+ });
+ });
+ </script>';
+ }
+
+ // Prikazemo search okno za iskanje po anketah
+ public function displaySearch(){
+ global $lang;
+ global $site_url;
+
+ echo '<form method="GET" id="1kasmysurvey" action="'.$site_url.'admin/survey/index.php">';
+
+ //echo '<span class="sprites search"></span> ';
+ echo '<input id="searchMySurvey" type="text" value="" placeholder="' . $lang['s_search_mySurvey'] . '" name="search" />';
+
+ //echo '<input type="submit" value="' . $lang['s_search'] . '" />';
+ echo ' <div class="buttonwrapper floatRight">';
+ echo ' <a class="ovalbutton ovalbutton_orange" href="#" onclick="$(\'#1kasmysurvey\').submit(); return false;"><span>'.$lang['s_search2'].'</span></a>';
+ echo ' </div>';
+
+ echo '</form>';
+ }
+
+
+ /** polovimo nastavitve prikaza za posameznega uporabnika
+ *
+ */
+ private function getSettings($display_default = false) {
+
+ $defaultOrder = $this->dataFields;
+ $resultArray = array();
+ $izBaze = false;
+
+ if ($this->g_uid > 0) {
+ $saved_surveyList_string = UserSetting::getInstance()->getUserSetting('survey_list_order');
+ $saved_surveyList_visible_string = UserSetting::getInstance()->getUserSetting('survey_list_visible');
+ $saved_surveyList_visible = array_unique(explode(",",$saved_surveyList_visible_string));
+ if (isset($saved_surveyList_string) && $saved_surveyList_string != "" && !$display_default ) {
+ $saved_surveyList_order = array_unique(explode(",",$saved_surveyList_string));
+ $izBaze = true;
+ // uporabimo shranjene nastavitve
+ foreach ( $saved_surveyList_order as $order) {
+ if (in_array($order,$saved_surveyList_visible))
+ {
+ $defaultOrder[$order]['visible'] = 1;
+ } else {
+ $defaultOrder[$order]['visible'] = 0;
+ }
+ if (isset($defaultOrder[$order]['order_by']) && isset($defaultOrder[$order]))
+ {
+ $resultArray[$defaultOrder[$order]['order_by']] = $defaultOrder[$order];
+ if (isset($defaultOrder[$order]))
+ {
+ unset($defaultOrder[$order]);
+ }
+ }
+ }
+ }
+ }
+
+ // za vse ostalo uporabimo privzete nastavitve
+ foreach ( $defaultOrder as $order)
+ {
+ if ($izBaze)
+ {
+ $order['visible'] = 0; // ponastavimo vidnost ?e imamo iz baze
+ }
+ if (isset($order['order_by']))
+ {
+ $resultArray[$order['order_by']] = $order;
+ }
+ }
+ return $resultArray;
+ }
+
+ private function getSurveysAsList() {
+
+ $result = array();
+
+ // ce imas hkrati dostop do ankete (srv_dostop) in preko managerskega dostopa (srv_dostop_manage) se brez DISTINCT podvajajo ankete
+ $stringSurveyList = "SELECT DISTINCT sa.id, sa.folder, '1' as del, sa.naslov, sa.active, sa.edit_time, ";
+ $stringSurveyList .= ( $this->settingsArray['lib_glb']['visible'] == 1 ) ? 'sal.lib_glb AS lib_glb, ' :'';
+ $stringSurveyList .= ( $this->settingsArray['lib_usr']['visible'] == 1 ) ? 'sal.lib_usr AS lib_usr, ' : '';
+ $stringSurveyList .= ( $this->settingsArray['e_name']['visible'] == 1 || $this->settingsArray['e_surname']['visible'] == 1 || $this->settingsArray['e_email']['visible'] == 1 )
+ ? "sa.edit_uid, sal.e_name AS e_name, sal.e_surname AS e_surname, sal.e_email AS e_email, " : '';
+ $stringSurveyList .= ( $this->settingsArray['i_name']['visible'] == 1 || $this->settingsArray['i_surname']['visible'] == 1 || $this->settingsArray['i_email']['visible'] == 1 )
+ ? "sa.insert_uid, sal.i_name AS i_name, sal.i_surname AS i_surname, sal.i_email AS i_email, " : '';
+ $stringSurveyList .= ( $this->settingsArray['edit_time']['visible'] == 1 ) ? "date_format(edit_time, '%d.%m.%y %k:%i') AS e_time, " : '';
+ $stringSurveyList .= ( $this->settingsArray['insert_time']['visible'] == 1 ) ? "date_format(insert_time, '%d.%m.%y %k:%i') AS i_time, " : '';
+ $stringSurveyList .= ( $this->settingsArray['vnos_time_first']['visible'] == 1 || $this->settingsArray['vnos_time_last']['visible'] == 1)
+ ? "date_format(sal.a_first, '%d.%m.%y %k:%i') AS v_time_first, date_format(sal.a_last, '%d.%m.%y %k:%i') AS v_time_last, " : '';
+
+ $stringSurveyList .= "sal.answers as answers, "; // vedno prestejemo odgovore
+ $stringSurveyList .= ( $this->settingsArray['variables']['visible'] == 1 ) ? "sal.variables as variables, " : '';
+ $stringSurveyList .= ( $this->settingsArray['trajanjeod']['visible'] == 1 ) ? "date_format(sa.starts, '%d.%m.%y') as trajanjeod, " : '';
+ $stringSurveyList .= ( $this->settingsArray['trajanjedo']['visible'] == 1 ) ? "date_format(sa.expire, '%d.%m.%y') as trajanjedo, " : '';
+ $stringSurveyList .= ( $this->settingsArray['approp']['visible'] == 1 ) ? "approp, " : '';
+ $stringSurveyList .= "sd.canEdit, sa.survey_type "; // tega pustim tukaj, da ni problemov z vejico
+
+ $stringSurveyList .= "FROM srv_anketa sa ";
+ $stringSurveyList .= "LEFT OUTER JOIN srv_survey_list AS sal ON sal.id = sa.id " ;
+
+ # kdo lahko ureja anketo (briše)
+ // tega substringy se ne da dodatno razbit z prepareSubquery, ker selectamo 2 elementa...
+ $stringSurveyList .= "LEFT OUTER JOIN (SELECT 1 AS canEdit, ank_id FROM srv_dostop WHERE FIND_IN_SET('edit', dostop ) ='1' AND aktiven = '1' AND uid = '$this->g_uid' OR uid IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT user FROM srv_dostop_manage WHERE manager = '".$this->g_uid."'")).")) AS sd ON sd.ank_id = sa.id " ;
+ #$stringSurveyList .= "LEFT OUTER JOIN (SELECT ank_id, FIND_IN_SET('edit', dostop ) AS canEdit FROM srv_dostop WHERE aktiven = '1' AND uid = '$this->g_uid') AS sd ON sd.ank_id = sa.id " ;
+
+ $stringSurveyList .= "WHERE sa.backup='0' AND sa.id>0 AND active >= '0' AND invisible = '0' ";
+ //$stringSurveyList .= $this->getFolderCondition();
+
+ $stringSurveyList .= $this->getLanguageLimit();
+ $stringSurveyList .= $this->getDostopAnketa();
+ $stringSurveyList .= $this->getOrderString();
+ $stringSurveyList .= $this->getLimitString();
+
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ if (!$sqlSurveyList) {
+ print_r("ERROR in query:");
+ print_r($stringSurveyList);
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $ids = array();
+ while ($rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+ $result[] = $rowSurveyList;
+
+ }
+ return $result;
+ }
+
+ // Dobimo seznam anket za nov prikaz (starega se naceloma ne uporablja vec)
+ private function getSurveysAsListNew($folder=0) {
+
+ $result = array();
+
+ // ce imas hkrati dostop do ankete (srv_dostop) in preko managerskega dostopa (srv_dostop_manage) se brez DISTINCT podvajajo ankete
+ $stringSurveyList = "SELECT DISTINCT sa.id, sa.folder, '1' as del, sa.naslov, sa.active, sa.mobile_created, sa.edit_time, ";
+ $stringSurveyList .= 'sal.lib_glb AS lib_glb, ';
+ $stringSurveyList .= 'sal.lib_usr AS lib_usr, ';
+ $stringSurveyList .= "sa.edit_uid, sal.e_name AS e_name, sal.e_surname AS e_surname, sal.e_email AS e_email, ";
+ $stringSurveyList .= "sa.insert_uid, sal.i_name AS i_name, sal.i_surname AS i_surname, sal.i_email AS i_email, ";
+ $stringSurveyList .= "date_format(edit_time, '%d.%m.%y %k:%i') AS e_time, ";
+ $stringSurveyList .= "date_format(insert_time, '%d.%m.%y %k:%i') AS i_time, ";
+ $stringSurveyList .= "date_format(sal.a_first, '%d.%m.%y %k:%i') AS v_time_first, date_format(sal.a_last, '%d.%m.%y %k:%i') AS v_time_last, ";
+
+ $stringSurveyList .= "sal.answers as answers, "; // vedno prestejemo odgovore
+ $stringSurveyList .= "sal.variables as variables, ";
+ $stringSurveyList .= "date_format(sa.starts, '%d.%m.%y') as trajanjeod, ";
+ $stringSurveyList .= "date_format(sa.expire, '%d.%m.%y') as trajanjedo, ";
+ $stringSurveyList .= "approp, ";
+ $stringSurveyList .= "sd.canEdit, sa.survey_type "; // tega pustim tukaj, da ni problemov z vejico
+
+ if($folder > 0)
+ $stringSurveyList .= ", sf.folder as mysurvey_folder ";
+
+ // Ce searchamo po besedah dodamo se uvod, zakljucek, naslove vprasanj in vrednosti vprasanj
+ if($this->isSearch == 1 && $this->searchSettings['stype'] == '2'){
+ $stringSurveyList .= ", sa.introduction AS introduction, sa.conclusion AS conclusion ";
+
+ $stringSurveyList .= ", sg.id AS sg_id, sg.ank_id AS sg_ank_id ";
+ $stringSurveyList .= ", ss.id AS ss_id, ss.naslov AS ss_naslov, ss.gru_id AS ss_gru_id ";
+ $stringSurveyList .= ", sv.id AS sv_id, sv.naslov AS sv_naslov, sv.spr_id AS sv_spr_id ";
+ }
+
+
+ $stringSurveyList .= "FROM srv_anketa sa ";
+ $stringSurveyList .= "LEFT OUTER JOIN srv_survey_list AS sal ON sal.id = sa.id " ;
+ $stringSurveyList .= "LEFT OUTER JOIN srv_library_anketa AS sla ON sla.ank_id = sa.id " ;
+
+ # kdo lahko ureja anketo (briše)
+ // tega substringy se ne da dodatno razbit z prepareSubquery, ker selectamo 2 elementa...
+ $stringSurveyList .= "LEFT OUTER JOIN (SELECT 1 AS canEdit, ank_id FROM srv_dostop WHERE FIND_IN_SET('edit', dostop ) ='1' AND aktiven = '1' AND uid = '$this->g_uid' OR uid IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT user FROM srv_dostop_manage WHERE manager = '".$this->g_uid."'")).")) AS sd ON sd.ank_id = sa.id " ;
+ #$stringSurveyList .= "LEFT OUTER JOIN (SELECT ank_id, FIND_IN_SET('edit', dostop ) AS canEdit FROM srv_dostop WHERE aktiven = '1' AND uid = '$this->g_uid') AS sd ON sd.ank_id = sa.id " ;
+
+ if($folder > 0)
+ $stringSurveyList .= "LEFT OUTER JOIN srv_mysurvey_anketa AS sf ON sf.ank_id = sa.id ";
+
+ // Ce iscemo po kljucnih besedah moramo dodat se tabele srv_grupa, srv_spremenljivka in srv_vrednost
+ if($this->isSearch == 1 && $this->searchSettings['stype'] == '2'){
+ $stringSurveyList .= "LEFT OUTER JOIN srv_grupa AS sg ON sg.ank_id = sa.id ";
+ $stringSurveyList .= "LEFT OUTER JOIN srv_spremenljivka AS ss ON ss.gru_id = sg.id ";
+ $stringSurveyList .= "LEFT OUTER JOIN srv_vrednost AS sv ON sv.spr_id = ss.id ";
+ }
+
+ $stringSurveyList .= "WHERE sa.backup='0' AND sa.id>0 AND active >= '0' AND invisible = '0' ";
+
+ //$stringSurveyList .= $this->getFolderCondition();
+ //$stringSurveyList .= $this->getLibraryCondition(); // Tega ni vec ker imamo nove folderje v mojih anketah
+ if($folder > 0)
+ $stringSurveyList .= "AND sf.usr_id='$this->g_uid' AND sf.folder='$folder' ";
+ elseif($folder == 0)
+ $stringSurveyList .= "AND NOT EXISTS (SELECT * FROM srv_mysurvey_anketa sma WHERE sma.ank_id=sa.id AND sma.usr_id='$this->g_uid') ";
+
+
+ // GDPR filter
+ if($this->gdpr == 1)
+ $stringSurveyList .= "AND EXISTS (SELECT * FROM srv_gdpr_anketa sgdpr WHERE sgdpr.ank_id=sa.id) ";
+ elseif($this->gdpr == 2)
+ $stringSurveyList .= "AND NOT EXISTS (SELECT * FROM srv_gdpr_anketa sgdpr WHERE sgdpr.ank_id=sa.id) ";
+
+
+ // Ce izvajamo search po anketah
+ if($this->isSearch == 1){
+ // Filter glede na search
+ $stringSurveyList .= $this->getSearchString();
+
+ // Filter glede na jezik ankete
+ $stringSurveyList .= $this->getLanguageLimit();
+ // Filter glede na dostop do ankete
+ $stringSurveyList .= $this->getDostopAnketa();
+ // Vrstni red anket
+ $stringSurveyList .= $this->getOrderString();
+
+ // Ce iscemo po kljucnih besedah moramo na koncu grupirat po anketi
+ if($this->searchSettings['stype'] == '2'){
+ //$stringSurveyList .= " GROUP BY id";
+ //$stringSurveyList .= " LIMIT 1000";
+ }
+ else{
+ // Limit anket
+ //$stringSurveyList .= $this->getLimitString();
+ $stringSurveyList .= " LIMIT 1000";
+ }
+ }
+ else{
+ // Filter glede na jezik ankete
+ $stringSurveyList .= $this->getLanguageLimit();
+ // Filter glede na dostop do ankete
+ $stringSurveyList .= $this->getDostopAnketa();
+ // Vrstni red anket
+ $stringSurveyList .= $this->getOrderString();
+ // Limit anket
+ $stringSurveyList .= $this->getLimitString();
+ }
+
+
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ if (!$sqlSurveyList) {
+ print_r("ERROR in query:");
+ print_r($stringSurveyList);
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ while ($rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+ $result[$rowSurveyList['id']] = $rowSurveyList;
+ }
+
+ return $result;
+ }
+
+
+ // Enostaven seznam anket za mobilno aplikacijo
+ public function getSurveysSimple($ank_id = 0, $limit = '', $mobile_created = -1, $include_folders=false) {
+
+ $result = array();
+
+ // ce imas hkrati dostop do ankete (srv_dostop) in preko managerskega dostopa (srv_dostop_manage) se brez DISTINCT podvajajo ankete
+ $stringSurveyList = "SELECT DISTINCT sa.id, sa.folder, '1' as del, sa.naslov, sa.active, sa.mobile_created, sa.block_ip, ";
+ //$stringSurveyList .= 'sal.lib_glb AS lib_glb, ';
+ //$stringSurveyList .= 'sal.lib_usr AS lib_usr, ';
+ $stringSurveyList .= "sa.edit_uid, sal.e_name AS e_name, sal.e_surname AS e_surname, sal.e_email AS e_email, ";
+ $stringSurveyList .= "sa.insert_uid, sal.i_name AS i_name, sal.i_surname AS i_surname, sal.i_email AS i_email, ";
+ $stringSurveyList .= "date_format(edit_time, '%d.%m.%y %k:%i') AS e_time, ";
+ $stringSurveyList .= "date_format(insert_time, '%d.%m.%y %k:%i') AS i_time, ";
+ $stringSurveyList .= "date_format(sal.a_first, '%d.%m.%y %k:%i') AS v_time_first, date_format(sal.a_last, '%d.%m.%y %k:%i') AS v_time_last, ";
+
+ $stringSurveyList .= "sal.answers as answers, "; // vedno prestejemo odgovore
+ $stringSurveyList .= "sal.approp as approp, "; // vedno prestejemo odgovore
+ $stringSurveyList .= "sal.variables as variables, ";
+ $stringSurveyList .= "date_format(sa.starts, '%d.%m.%y') as trajanjeod, ";
+ $stringSurveyList .= "date_format(sa.expire, '%d.%m.%y') as trajanjedo, ";
+ $stringSurveyList .= "sa.survey_type "; // tega pustim tukaj, da ni problemov z vejico
+
+ $stringSurveyList .= "FROM srv_anketa sa ";
+ $stringSurveyList .= "LEFT OUTER JOIN srv_survey_list AS sal ON sal.id = sa.id " ;
+ $stringSurveyList .= "LEFT OUTER JOIN srv_library_anketa AS sla ON sla.ank_id = sa.id " ;
+
+ # kdo lahko ureja anketo (briše)
+ // tega substringy se ne da dodatno razbit z prepareSubquery, ker selectamo 2 elementa...
+ $stringSurveyList .= "LEFT OUTER JOIN (SELECT 1 AS canEdit, ank_id FROM srv_dostop WHERE FIND_IN_SET('edit', dostop ) ='1' AND aktiven = '1' AND uid = '$this->g_uid' OR uid IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT user FROM srv_dostop_manage WHERE manager = '".$this->g_uid."'")).")) AS sd ON sd.ank_id = sa.id " ;
+
+ $stringSurveyList .= "WHERE sa.backup='0' AND sa.id>0 AND active >= '0' AND invisible = '0' ";
+
+ if($mobile_created == 1)
+ $stringSurveyList .= "AND sa.mobile_created='".$mobile_created."' ";
+
+ if(!$include_folders)
+ $stringSurveyList .= "AND NOT EXISTS (SELECT * FROM srv_mysurvey_anketa sma WHERE sma.ank_id=sa.id AND sma.usr_id='$this->g_uid') ";
+
+ // Ce imamo podan ank_id vrnemo samo za 1 anketo
+ if($ank_id > 0)
+ $stringSurveyList .= "AND sa.id='".$_GET['ank_id']."' ";
+
+ //$stringSurveyList .= $this->getLanguageLimit();
+ $stringSurveyList .= $this->getDostopAnketa();
+ //$stringSurveyList .= $this->getOrderString();
+ //$stringSurveyList .= $this->getLimitString();
+
+ //$stringSurveyList .= 'ORDER BY upper(naslov) ASC';
+
+ //zacasno zaradi aplikacije
+ if($mobile_created == 1)
+ $stringSurveyList .= "ORDER BY edit_time DESC";
+ else
+ $stringSurveyList .= 'ORDER BY sal.a_last DESC';
+
+ //@Uros dodal, da vrne samo doloceno stevilo zadnjih anktivnih anket, ce je nastavljeno
+ if($limit != '' && $limit != 0)
+ $stringSurveyList .= ' limit '.$limit;
+
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ while ($rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+
+ // Pretvorimo vse v utf - drugace vcasih ne dela json_encode
+ foreach($rowSurveyList as $key => $val){
+ //$rowSurveyList[$key] = utf8_encode($val);
+ $rowSurveyList[$key] = mb_convert_encoding($val, 'HTML-ENTITIES', "UTF-8");
+ }
+
+ $result[] = $rowSurveyList;
+ }
+ return $result;
+ }
+
+ private function createOrderUrl($id=null, $txt) {
+
+ if (!isset($id) || $id == null || $id == "") {
+ $id=1;
+ }
+
+ if ($this->sortby != $id ) {
+ $img_src = 'sort_unsorted';
+ $result='<div onClick="surveyList_goTo(\''.$id.'\',\'1\')">'.$txt.'</div>';
+ } else {
+
+ if ($this->sorttype == 2) {
+ $img_src = 'sort_ascending';
+ $result='<div onClick="surveyList_goTo(\''.$id.'\',\'1\')" class="red">'.$txt.'<span class="faicon '.$img_src.'" title=""></span></div>';
+ } else {
+ $img_src = 'sort_descending';
+
+ $result='<div onClick="surveyList_goTo(\''.$id.'\',\'2\')" class="red">'.$txt.'<span class="faicon '.$img_src.'" title=""></span></div>';
+ }
+ }
+
+ return $result;
+ }
+
+ private function createOrderUrlNew($id=null, $txt) {
+ global $site_url;
+
+ if (!isset($id) || $id == null || $id == "") {
+ $id=1;
+ }
+
+ if ($this->sortby != $id ) {
+ $result='<div onClick="surveyList_goTo(\''.$id.'\',\'1\')">'.$txt.'</div>';
+ } else {
+
+ if ($this->sorttype == 2) {
+ $result='<div class="active" onClick="surveyList_goTo(\''.$id.'\',\'1\')">'.$txt.'<span class="active faicon after sort_up_arrow icon-orange"/></div>';
+ } else {
+ $result='<div class="active" onClick="surveyList_goTo(\''.$id.'\',\'2\')">'.$txt.'<span class="active faicon after sort_down_arrow icon-orange"/></div>';
+ }
+ }
+
+ return $result;
+ }
+
+ private function echoText($text, $type = 'text', $id = null,$options=array()) {
+ global $lang;
+ global $site_url;
+
+ if ( $type == 'text') {
+ $result = ( isset($text) && $text != null && $text != "") ? $text : "&nbsp;";
+ } elseif ($type == 'naslov') {
+ $result = '<strong><a href="'.$site_url.'admin/survey/index.php?anketa='.$id.'&a='.A_REDIRECTLINK.'" title="'.$text.'">'.$text.'</a></strong>';
+ } elseif ($type == 'active') {
+ $result = '<a href="/" onclick="anketa_active(\''.$id.'\',\''.(int)$text.'\',\'true\'); return false;">' .
+ '<span class="faicon '.((int)$text==1?'star_on':'star_off').'" alt="'.(int)$text.'" title="'.((int)$text==1?$lang['srv_anketa_active']:$lang['srv_anketa_noactive']).'"></span>'.
+ '</a>';
+ } elseif ($type == 'delete') {
+ if ((int)$options['anketa_canEdit'] > 0) {
+ $result = '<a href="/" onclick="anketa_delete_list(\''.$id.'\', \''.$lang['srv_anketadeleteconfirm'].'\'); return false;">' .
+ '<span class="faicon delete_circle icon-orange_link" title="'.$lang['srv_anketa_delete'].'"></span>'.
+ '</a>';
+ } else {
+ $result=' ';
+ }
+ } elseif ($type == 'lib_glb') {
+ if ($this->g_adminType == 0) {
+ // samo admin lahko dodaja in odstranjuje v sistemsko knjiznico
+ $result = '<a href="/" onclick="surveyList_knjiznica(\''.$id.'\'); return false;">'.
+ '<span class="sprites library_admin_'.((int)$text==1?'on':'off').'" title="'.((int)$text==1?$lang['srv_ank_lib_off']:$lang['srv_ank_lib_on']).'"></span>'.
+ '</a>';
+ } else {
+ $result = '<a href="/" onclick="surveyList_knjiznica_noaccess(\''.$lang['srv_list_library_no_access'].'\'); return false;">'.
+ '<span class="sprites library_admin_'.((int)$text==1?'on':'off').'" title="'.((int)$text==1?$lang['srv_ank_lib_off']:$lang['srv_ank_lib_on']).'"></span>'.
+ '</a>';
+ }
+ } elseif ($type == 'lib_usr') {
+ $result = '<a href="/" onclick="surveyList_myknjiznica(\''.$id.'\'); return false;">'.
+ '<span class="sprites '.((int)$text==1?'library_on':'library_off').'" title="'.((int)$text==1?$lang['srv_ank_mylib_off']:$lang['srv_ank_mylib_on']).'"></span>'.
+ '</a>';
+ } elseif ($type == 'survey_type') {
+ if ($text == '3') {
+ $text = '2';
+ }
+
+ $result = $lang['srv_vrsta_survey_type_'.$text];
+
+ } elseif ($type == 'euid' || $type == 'iuid') {
+ $text = iconv("iso-8859-2", "utf-8",$text);
+ if ($options['anketa_is_copy']) {
+ $result = $lang['srv_survey_is_copy'];
+ } else {
+ $result = ( isset($text) && $text != null && $text != "")
+ ? '<span class="as_link"'.($type == 'euid' ? ' onclick="surveyList_user(\'e\',this);" euid="'.$options['anketa_e_uid'].'"': ' onclick="surveyList_user(\'i\',this);" iuid="'.$options['anketa_i_uid'].'"').'>'.$text.'</span>' :
+ "&nbsp;";
+
+ // echoText($text, 'text', $id, $options );
+ }
+ } else {
+
+ $this->echoText($text, 'text', $id, $options );
+ }
+
+ echo (isset($result) && $result != "" && $result != null) ? $result : "&nbsp;";
+ }
+
+ /**
+ * polovimo shranjene ?irine za polja
+ */
+ private function getCssSetings() {
+ global $global_user_id;
+ $result_old_data = array();
+ if ($this->g_uid > 0) {
+ // najprej iz nastavitev preberemo obstoje?e shranjene ?irine
+ $saved_old_data_string = UserSetting::getInstance()->getUserSetting('survey_list_widths');
+
+ if (isset($saved_old_data_string) && $saved_old_data_string != null && $saved_old_data_string != "" ) {
+ $old_data = array_unique(explode(";",$saved_old_data_string));
+ foreach ( $old_data as $tmp_old_data ) {
+ $_tmp_old_data = array_unique(explode(",",$tmp_old_data));
+ $result_old_data[$_tmp_old_data[0]] = $_tmp_old_data[1];
+ }
+ }
+ }
+ return $result_old_data;
+ }
+
+ /** Izrišemo div z nastavitvami
+ *
+ * Enter description here ...
+ * @param unknown_type $display_default
+ */
+ public function displaySettings($display_default = false) {
+ global $site_url, $lang;
+
+ # izpisemo dive
+ $settingsArray = $this->getSettings();
+ echo '<div id="survey_list_inner">';
+ echo '<input type="hidden" id="sortby" value="'.$_POST['sortby'].'">';
+ echo '<input type="hidden" id="sorttype" value="'.$_POST['sorttype'].'">';
+ $grupaName = "";
+ $zastopaneGrupe = array();
+
+ echo '<div class="floatLeft" style="width:auto !important"><ul id="sortable" style="width:auto !important;">';
+ foreach ( $settingsArray as $opcija ) {
+ // preverimo ali je nova grupa
+ if ((!isset($opcija['header_grupa']) && $grupaName != "") || // nismo več v grupi stara še obstaja
+ ( isset($opcija['header_grupa']) && $grupaName != "" && $opcija['header_grupa'] != $grupaName)) { // smo v grupi ampak ime ni enako prejšnjemu
+ echo '</ul>';
+ echo '</div>';
+ echo '<div class="clr"></div>';
+ echo '</li>';
+ $grupaName = "";
+ }
+ // preverimo ali naredimo novo grupo (Vnesel / urejal)
+ if (isset($opcija['header_grupa']) && $grupaName == "") { // smo v grupi polj pod in imamo podpolja: ime priimek, email, datum
+ // imamo začtek grupe
+ echo '<li class="sortable_group">';
+ echo '<div style="width:20px; float:left;">';
+ echo '<img class="parent movable" src="'.$site_url.'admin/survey/icons/icons/move_updown.png" alt="move" vartical-align="middle" />';
+ echo '</div>';
+ echo '<div id="group_holder" style="float:left;">';
+ echo '<ul id="sortableGroup" name="'.$opcija['header_grupa'].'">';
+ $grupaName = $opcija['header_grupa'];
+ $zastopaneGrupe[] = $opcija['header_grupa'];
+ }
+ if (!isset($opcija['header_grupa'])) {
+ echo '<li id="'.$opcija['id'].'" class="sortable_noGroup"><span class="">';
+ echo '<img class="parent movable" src="'.$site_url.'admin/survey/icons/icons/move_updown.png" alt="move" vartical-align="middle" />';
+ // ?e je viden ali ?e je id = 1 (ime ankete) potem dodamo checkbox (imena ankete ne moremo izklju?it)
+ echo '<input name="sl_fields" id="sl_fields_'.$opcija['id'].'" value="'.$opcija['id'].'" type="checkbox" '.($opcija['visible'] == 1 || $opcija['id'] == 1 ? 'checked="checked"':'').' '.($opcija['id'] == 1 ? 'disabled="disabled"':'').'>';
+ echo $lang['srv_h_'.$opcija['header_field']];
+ echo '</span>';
+ echo '</li>';
+ } else {
+ echo '<li id="'.$opcija['id'].'" class="sortable_noGroup"><span class="">';
+ echo '<img class="sub_child movable" src="'.$site_url.'admin/survey/icons/icons/move_updown.png" alt="move" vartical-align="middle" />';
+ // ?e je viden ali ?e je id = 1 (ime ankete) potem dodamo checkbox (imena ankete ne moremo izklju?it)
+ echo '<input name="sl_fields" id="sl_fields_'.$opcija['id'].'" value="'.$opcija['id'].'" type="checkbox" '.($opcija['visible'] == 1 || $opcija['id'] == 1 ? 'checked="checked"':'').' '.($opcija['id'] == 1 ? 'disabled="disabled"':'').'>';
+ echo $lang['srv_'.$opcija['header_grupa']]. " - ";
+ echo $lang['srv_h_'.$opcija['header_field']];
+ echo '</span>';
+ echo '</li>';
+ }
+ }
+ // na koncu ?e preverimo ali imamo kon?ano grupo ?ene nardimo zaključna diva
+ if ($grupaName != "") {
+ echo '</ul>';
+ echo '</div>';
+ echo '<div class="clr"></div>';
+
+ echo '</li>';
+ $grupaName = "";
+ }
+
+ echo '</ul></div>';
+
+ echo '<div class="floatRight sl_div_error_holder" style="margin-right:10px; width:420px;">';
+ echo '<div id="div_error" class="red sl_div_error"><img src="icons/icons/error.png" alt="" vartical-align="middle" />'.$lang['srv_sl_error_msg'].'</div>';
+ echo '<div style="margin-top:20px;">'.$lang['srv_sl_setting_show'].'<input id="rows_per_page" value="'.$this->rec_per_page.'" type="text" />'.$lang['srv_sl_setting_records'];
+ echo '</div>';
+ echo '<div style="margin-top:20px;">';
+ echo ' <div class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="default_surveyListSettings(); return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/page_white_gear.png" alt="" vartical-align="middle" />'.$lang['srv_default'].'</span></a></div></div>';
+ echo ' <div class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="cancle_surveyListSettings(); return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/cog_back.png" alt="" vartical-align="middle" />'.$lang['srv_cancel'].'</span></a></div></div>';
+ echo ' <div class="floatLeft spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="save_surveyListSettings(); return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/cog_save.png" alt="" vartical-align="middle" />'.$lang['save'].'</span></a></div></div>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '<script type="text/javascript">';
+ // echo '$(function() {';
+ echo '$(document).ready(function() {';
+ echo '$("#sortable").sortable({ axis: "y", handle: "img.parent"}).stop();';
+ // echo '$("#sortable").disableSelection();';
+ foreach ( $zastopaneGrupe as $grupa ) {
+ echo '$("[name='.$grupa.']").sortable({ axis: "y", handle: "img.sub_child", zIndex: 5 }).stop();';
+ }
+ // $("#sortableGroup").sortable();
+ // $("#sortableGroup").disableSelection();
+
+ echo '})';
+ echo '</script>';
+ }
+
+ public function displayListQickInfo() {
+ # prikažemo hitri povzetek anket uporabnika
+
+ # preštejemo zadnje ankete v 12 urah
+ $ank1hour = "SELECT id FROM srv_anketa sa WHERE sa.backup='0' AND sa.id > 0 AND sa.active >= 0 AND invisible = '0' AND (sa.insert_time > (DATE_SUB(CURDATE(), INTERVAL 1 HOUR)) || sa.edit_time > (DATE_SUB(CURDATE(), INTERVAL 1 HOUR)) ) ".$this->getDostopAnketa();
+ $ank12hour = "SELECT id FROM srv_anketa sa WHERE sa.backup='0' AND sa.id > 0 AND sa.active >= 0 AND invisible = '0' AND (sa.insert_time > (DATE_SUB(CURDATE(), INTERVAL 12 HOUR)) || sa.edit_time > (DATE_SUB(CURDATE(), INTERVAL 12 HOUR)) ) ".$this->getDostopAnketa();
+ $ank24hour = "SELECT id FROM srv_anketa sa WHERE sa.backup='0' AND sa.id > 0 AND sa.active >= 0 AND invisible = '0' AND (sa.insert_time > (DATE_SUB(CURDATE(), INTERVAL 24 HOUR)) || sa.edit_time > (DATE_SUB(CURDATE(), INTERVAL 23 HOUR)) ) ".$this->getDostopAnketa();
+
+ $qry1hour = sisplet_query($ank1hour);
+ $qry12hour = sisplet_query($ank12hour);
+ $qry24hour = sisplet_query($ank24hour);
+
+ $cnt1hour = mysqli_num_rows($qry1hour);
+ $cnt12hour = mysqli_num_rows($qry12hour);
+ $cnt24hour = mysqli_num_rows($qry24hour);
+
+
+ }
+
+
+ // Vrne stevilo vseh anket
+ public function countSurveys() {
+ return count($this->surveys_ids);
+ }
+
+ // Vrne stevilo vseh anket v rootu (ce imamo folderje)
+ public function countRootSurveys() {
+ global $global_user_id;
+
+ // Poiscemo vse ankete v custom folderjih
+ $sql = sisplet_query("SELECT ank_id FROM srv_mysurvey_anketa WHERE usr_id='$global_user_id'");
+
+ // Vrnemo razliko v stevilu anket (odstejemo ankete v custom folderjih)
+ $survey_count = count($this->surveys_ids);
+ if(mysqli_num_rows($sql) > 0)
+ $survey_count -= mysqli_num_rows($sql);
+
+ return $survey_count;
+ }
+
+ /** Anketam ki so potekle popravimo aktivnost
+ *
+ */
+ public function checkSurveyExpire() {
+ //v primeru maza moramo sporociti vsem aplikacijam deaktivacijo ankete
+ if(Common::checkModule('maza')){
+ $maza = new MAZA();
+ $maza -> maza_check_expired_surveys();
+ }
+
+ # Anketam ki so potekle popravimo aktivnost
+ sisplet_query("UPDATE srv_anketa SET active = '0' WHERE active = '1' AND expire < CURDATE()");
+ // vsilimo refresh podatkov
+ SurveyInfo :: getInstance()->resetSurveyData();
+ }
+
+ /** GETERS && SETTERS **/
+ /* GETERS */
+ private function getParentFolder() { return $this->parentFolder; }
+ private function getCurrentFolder() { return $this->currentFolder; }
+ public function getDef_Rows_per_page() { return SRV_LIST_REC_PER_PAGE; }
+
+ /** vrne sql pogoj za folderje na podlagi trenutnega folderja */
+ private function getFolderCondition () {
+ if ($this->folderCondition == null) {
+ $resultString = " AND 0";
+ #$this->folders = array();
+ $folderArray = $this->getFolderTreeAsArray($this->getCurrentFolder());
+ if ( count( $folderArray ) > 0) {
+ $prefix="";
+ $resultString = " AND sa.folder IN (";
+ foreach ($folderArray as $fid => $fname) {
+ $resultString .= $prefix.$fid;
+ $prefix=",";
+ }
+ $resultString .=") ";
+ }
+ $this->folderCondition = $resultString;
+ }
+ return $this->folderCondition;
+ }
+
+ /** vrne array z folderjem in subfolderji (če je SRV_LIST_GET_SUB_FOLDERS = true) */
+ function getFolderTreeAsArray($parent) {
+ # če ni dodan parent ga dodamo
+ if (!isset($this->folders[$parent])) {
+ $parentSql = sisplet_query('SELECT id, naslov FROM srv_folder WHERE id="'.$parent.'";');
+ if (mysqli_num_rows($parentSql)>0) {
+ $rowParent = mysqli_fetch_assoc($parentSql);
+ $this->folders[$rowParent['id']] = $rowParent['naslov'];
+ }
+ }
+ if (SRV_LIST_GET_SUB_FOLDERS || $parent == 0) {
+ $result = sisplet_query('SELECT id, naslov FROM srv_folder WHERE parent="'.$parent.'";');
+ while ($row = mysqli_fetch_array($result)) {
+ $this->folders[$row['id']] = $row['naslov'];
+ $this->getFolderTreeAsArray($row['id']);
+ }
+ }
+ return $this->folders;
+ }
+
+ /** vrne sql pogoj za ankete v moji knjiznici na podlagi trenutnega folderja */
+ private function getLibraryCondition () {
+
+ if ($this->currentLibrary == null) {
+ $resultString = '';
+ }
+ else{
+ $children = array();
+ $children = $this->getLibraryChildren($this->currentLibrary, $children);
+
+ $childrenString = '';
+ if(!empty($children))
+ $childrenString = ','.implode(',', $children);
+
+ //$resultString = " AND sla.ank_id=sa.id AND sla.folder='".$this->currentLibrary."'";
+ $resultString = " AND sla.ank_id=sa.id AND sla.folder IN (".$this->currentLibrary . $childrenString.")";
+ }
+
+ $this->libraryCondition = $resultString;
+
+ return $this->libraryCondition;
+ }
+
+ private function getLibraryChildren($folder_id, $children){
+
+ // Pridobimo vse childe
+ $sql = sisplet_query("SELECT id, parent FROM srv_library_folder WHERE parent='".$folder_id."'");
+
+ // Izstopni pogoj
+ if(mysqli_num_rows($sql) == 0)
+ return ($children);
+
+ while($row = mysqli_fetch_array($sql)){
+ $children[] = $row['id'];
+ $children2 = $this->getLibraryChildren($row['id'], $children);
+
+ $children = array_merge($children, $children2);
+ }
+
+ return array_unique($children);
+ }
+
+ /** vrne sql string za omejevanje dostopa uporabniku */
+ function getLanguageLimit() {
+ global $global_admin_type;
+
+ if ((int)$this->lang_id > 0) {
+ return " AND lang_admin ='".(int)$this->lang_id."'";
+ }
+ }
+
+ /** vrne sql string za omejevanje dostopa uporabniku */
+ function getDostopAnketa() {
+ global $global_admin_type;
+ global $global_user_id;
+
+ if ($this->dostopCondition == null) {
+ // posebej za managerje, ki vidijo ankete svojih uporabnikov
+ $manage = '';
+
+ #generalni dostop glede na tip uporabnikov --> $admin_type <= $row['dostop']
+ # posebej dostop za vsazga userja posebej --> sisplet_query("SELECT * FROM srv_dostop WHERE ank_id = '$anketa' AND uid='$uid'") -> if (mysqli_num_rows($sql) > 0)
+ if ($this->user_id == null) {
+ if ($this->g_adminType == 1 || $this->g_adminType == 0)
+ $manage = " OR uid IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT user FROM srv_dostop_manage WHERE manager = '".$this->g_uid."' ")).") ";
+
+ $this->dostopCondition = (SRV_LIST_CHECK_DOSTOP ? " AND (sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop WHERE uid='".$this->g_uid."' $manage"))."))" : "");
+ }
+ else {
+ if ($this->g_adminType == 1 || $this->g_adminType == 0)
+ $manage = " OR uid IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT user FROM srv_dostop_manage WHERE manager = '".$this->g_uid."'")).") ";
+
+ $this->dostopCondition = (SRV_LIST_CHECK_DOSTOP ? " AND (insert_uid = '".$this->user_id."') AND (sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop WHERE uid='".$this->g_uid."' $manage"))."))" : "");
+ }
+
+ # če ni admin odstranimo ankete kjer je uporabnik označen samo kot anketar
+ if ( true /*$this->g_adminType != '0'*/ ) {
+ $this->dostopCondition .= " AND sa.id".($this->onlyPhone == false ? " NOT":"")." IN"
+ ." (SELECT ank_id FROM srv_dostop AS sd WHERE sd.aktiven = '1' AND sd.uid = '$this->g_uid' AND FIND_IN_SET('phone',sd.dostop )>0 AND FIND_IN_SET('edit',sd.dostop ) = 0) ";
+ }
+ else {
+ }
+ }
+
+
+ // meta admin vidi kao spet vse
+ if ( Dostop::isMetaAdmin() ) {
+
+ if ($this->user_id == null) {
+ $this->dostopCondition = (SRV_LIST_CHECK_DOSTOP ? " AND (sa.dostop >= '".$this->g_adminType."' OR sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop WHERE uid='".$this->g_uid."' $manage"))."))" : "");
+ }
+ // filtriranje
+ else {
+ $manage = " OR uid IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT user FROM srv_dostop_manage WHERE manager = '".$this->g_uid."'")).") ";
+ $this->dostopCondition = (SRV_LIST_CHECK_DOSTOP ? " AND (insert_uid = '".$this->user_id."') AND (sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop WHERE uid='".$this->g_uid."' $manage"))."))" : "");
+ }
+
+ // Včasih se za meta admina nekaj porusi in ne prikaze nobene ankete...
+ //$this->dostopCondition = '';
+ }
+
+ return $this->dostopCondition;
+ }
+
+ /** vrne order string za SQL s katerim sortiramo */
+ private function getOrderString() {
+
+ if (!isset($this->sortby) || (int)$this->sortby == 0) {
+ $this->sortby = SRV_LIST_ORDER_BY;
+ }
+
+ if (isset($this->order_by_options[$this->sortby])) {
+ $order_by = $this->order_by_options[$this->sortby];
+ } else {
+ $order_by = $this->order_by_options[SRV_LIST_ORDER_BY];
+ }
+
+ // UPPER damo, ker drugace sortira najprej vlke crke potem pa male
+ if($this->sortby == 1 || $this->sortby == 7 || $this->sortby == 11){
+ // Zamenjamo nacin sortiranja pri besedilu (drugace zacnemo od zadaj)
+ $sorttype = ($this->sorttype == 1) ? 2 : 1;
+ $result = " ORDER BY upper(" . $order_by . ") " . $this->sort_types_options[$sorttype];
+ }
+ // Dodamo opcije sortiranja pri statusu (18), ker ni dovolj sortiranje po "expired"
+ elseif($this->sortby == 18){
+ $sorttypeReverse = ($this->sorttype == 1) ? 2 : 1;
+ $result = " ORDER BY
+ sa.active ".$this->sort_types_options[$this->sorttype].",
+ (SELECT IF(COUNT(sac.sid) > 0, 1, 0) FROM srv_activity sac WHERE sac.sid=sa.id) ".$this->sort_types_options[$this->sorttype].",
+ ".$order_by." ".$this->sort_types_options[$sorttypeReverse];
+ }
+ else
+ $result = " ORDER BY " . $order_by . " ".$this->sort_types_options[$this->sorttype];
+
+ return $result;
+ }
+
+ /** vrne Limit string za SQL s katerim prika?emo posamezno stran */
+ private function getLimitString() {
+ $result = " LIMIT " . ($this->pageno * $this->rec_per_page - $this->rec_per_page) . ", " . $this->rec_per_page;
+ return $result;
+ }
+
+ // vrne sql string za search po anketah glede na nastavitve searcha
+ private function getSearchString(){
+
+ $search_text = mysqli_real_escape_string($GLOBALS['connect_db'], $this->searchString);
+ $search_text = stripslashes(stripslashes($search_text));
+
+ // Vse gre v lowerstring
+ $search_text = strtolower($search_text);
+
+ // Ce gre za string v narekovajih
+ if($search_text[0] == '"' && $search_text[strlen($search_text) - 1] == '"'){
+ $search_text = trim($search_text, '"');
+ $this->searchStringProcessed[] = $search_text;
+ $search_text = '%'.$search_text.'%';
+ }
+ else{
+ // Sklanjamo po search besedi - ce gre za search po naslovu ali kljucnih besedah
+ if ($this->searchSettings['stype'] == '0' || $this->searchSettings['stype'] == '2') {
+
+ // odstrani vse zvezdice in pluse in skrajsaj besede za dva znaka, dodaj *.
+ $search_text = explode (" ", $search_text);
+
+ for ($a=0; $a<sizeof($search_text); $a++) {
+ if (strlen ($search_text[$a]) > 5)
+ $search_text[$a] = substr ($search_text[$a], 0, -2);
+ elseif (strlen ($search_text[$a]) > 2)
+ $search_text[$a] = substr ($search_text[$a], 0, -1);
+ else
+ $search_text[$a] = $search_text[$a];
+
+ $this->searchStringProcessed[$a] = $search_text[$a];
+ $search_text[$a] = '%'.$search_text[$a].'%';
+ }
+
+ $search_text = implode(" ", $search_text);
+ }
+ else{
+ $this->searchStringProcessed[] = $search_text;
+ $search_text = '%'.$search_text.'%';
+ }
+ }
+
+ // Search po avtorju
+ if($this->searchSettings['stype'] == '1'){
+ $result = " AND (i_name LIKE '".$search_text."' OR i_surname LIKE '".$search_text."' OR i_email LIKE '".$search_text."')";
+ }
+ // Search po kljucnih besedah znotraj vprasanj (naslovi vprasanj in vrednosti)
+ elseif($this->searchSettings['stype'] == '2'){
+ $result = " AND (LOWER(introduction) LIKE LOWER('".$search_text."')
+ OR LOWER(conclusion) LIKE LOWER('".$search_text."')
+ OR LOWER(ss.naslov) LIKE LOWER('".$search_text."')
+ OR LOWER(sv.naslov) LIKE LOWER('".$search_text."'))";
+ }
+ // Search po naslovu
+ else{
+ $result = " AND (LOWER(sa.naslov) LIKE LOWER('".$search_text."') OR LOWER(sa.akronim) LIKE LOWER('".$search_text."'))";
+ }
+
+ // Search po statusu (aktivne, neaktivne)
+ if($this->searchSettings['sstatus'] == '1')
+ $result .= " AND active > '0'";
+ if($this->searchSettings['sstatus'] == '2')
+ $result .= " AND active = '0'";
+
+ // Search po datumu ustvarjanja (od)
+ if($this->searchSettings['sidatefrom'] != ''){
+ $date = date('Y-m-d H:i:s', strtotime($this->searchSettings['sidatefrom']));
+ $result .= " AND insert_time >= '".$date."'";
+ }
+ // Search po datumu ustvarjanja (do)
+ if($this->searchSettings['sidateto'] != ''){
+ $date = date('Y-m-d H:i:s', strtotime($this->searchSettings['sidateto']));
+ $result .= " AND insert_time <= '".$date."'";
+ }
+
+ // Search po datumu zadnjega urejanja (od)
+ if($this->searchSettings['sedatefrom'] != ''){
+ $date = date('Y-m-d H:i:s', strtotime($this->searchSettings['sedatefrom']));
+ $result .= " AND edit_time >= '".$date."'";
+ }
+ // Search po datumu zadnjega urejanja (do)
+ if($this->searchSettings['sedateto'] != ''){
+ $date = date('Y-m-d H:i:s', strtotime($this->searchSettings['sedateto']));
+ $result .= " AND edit_time <= '".$date."'";
+ }
+
+ // Dodaten search po avtorju samo za metaadmine
+ if($this->searchSettings['onlyAuthor'] != ''){
+ $onlyAuthorString = mysqli_real_escape_string($GLOBALS['connect_db'], $this->searchSettings['onlyAuthor']);
+ $onlyAuthorString = stripslashes(stripslashes($onlyAuthorString));
+
+ $result .= " AND (i_name LIKE '%".$onlyAuthorString."%'
+ OR i_surname LIKE '%".$onlyAuthorString."%'
+ OR i_email LIKE '%".$onlyAuthorString."%')";
+ }
+
+ return $result;
+ }
+
+ // Dobimo vse parametri searcha
+ private function getSearchParams(){
+ global $site_url;
+
+ $params = '';
+
+ if($this->isSearch == 1){
+ $params .= 'search='.urlencode($this->searchString);
+
+ if(!empty($this->searchSettings)){
+ foreach($this->searchSettings as $key => $val){
+ $params .= '&'.$key.'='.urlencode($val);
+ }
+ }
+ }
+
+ return $params;
+ }
+
+
+ /**
+ * shranimo širine celic
+ */
+ public function saveCssSettings($data) {
+ $new_data = array();
+ if (isset($data) && $data != null) {
+ $new_data = $this->getCssSetings();
+ // nato popravimo vrednost
+ $_tmp_new_data = array_unique(explode(",",$data));
+ $new_data[$_tmp_new_data[0]] = $_tmp_new_data[1];
+ // nato zdru?imo v primerno obliko in shranimo
+ $saveString = "";
+ $saveStringPrefix = "";
+ if (isset($new_data) && $new_data != null && count($new_data) > 0) {
+ foreach ( $new_data as $tmp_new_key => $tmp_new_data ) {
+ $saveString .= $saveStringPrefix.$tmp_new_key.",".$tmp_new_data;
+ $saveStringPrefix = ";";
+ }
+ }
+ UserSetting::getInstance()->setUserSetting('survey_list_widths', $saveString);
+ } else {
+ UserSetting::getInstance()->setUserSetting('survey_list_widths', "");
+ }
+ // shranimo
+ UserSetting::getInstance()->saveUserSetting('survey_list_widths', $saveString);
+ }
+ /* SETERS */
+ private function setParentFolder($parentFolder = 0) { $this->parentFolder = $parentFolder; }
+ private function setCurrentFolder($currentFolder = 0) { $this->currentFolder = $currentFolder; }
+
+ private function UpdateSystemLibrary () {
+ global $lang, $site_url;
+
+ $anketa = $_POST['anketa'];
+
+ echo '<a href="/" onclick="surveyList_knjiznica(\''.$anketa.'\'); return false;">';
+
+ $sql = sisplet_query("SELECT * FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='0'");
+ if (mysqli_num_rows($sql) == 0) {
+ $sql1 = sisplet_query("SELECT * FROM srv_library_folder WHERE uid='0' AND tip='1' AND parent='0' AND lang='$lang[id]'");
+ $row1 = mysqli_fetch_array($sql1);
+ sisplet_query("INSERT INTO srv_library_anketa (ank_id, uid, folder) VALUES ('$anketa', '0', '$row1[id]')");
+ echo '<span class="sprites library_admin_on" title="'.$lang['srv_ank_lib_on'].'"></span>';
+ } else {
+ sisplet_query("DELETE FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='0'");
+ echo '<span class="sprites library_admin_off" title="'.$lang['srv_ank_lib_off'].'"></span>';
+ }
+
+ echo '</a>';
+ }
+
+ private function UpdateUserLibrary () {
+ global $global_user_id, $site_url, $lang;
+
+ $anketa = $_POST['anketa'];
+
+ echo '<a href="/" onclick="surveyList_myknjiznica(\''.$anketa.'\'); return false;">';
+
+ $sql = sisplet_query("SELECT * FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='$global_user_id'");
+ if (mysqli_num_rows($sql) > 0) {
+ sisplet_query("DELETE FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='$global_user_id'");
+ echo '<span class="sprites library_off" title="'.$lang['srv_ank_mylib_off'].'"></span>';
+ } else {
+ $sql1 = sisplet_query("SELECT * FROM srv_library_folder WHERE uid='$global_user_id' AND tip='1' AND parent='0'");
+ $row1 = mysqli_fetch_array($sql1);
+ sisplet_query("INSERT INTO srv_library_anketa (ank_id, uid, folder) VALUES ('$anketa', '$global_user_id', '$row1[id]')");
+ echo '<span class="sprites library_on" title="'.$lang['srv_ank_mylib_on'].'"></span>';
+ }
+
+ echo '</a>';
+ }
+
+ private function UpdateSystemLibraryNew () {
+ global $lang, $site_url;
+
+ $anketa = $_POST['anketa'];
+
+ $sql = sisplet_query("SELECT * FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='0'");
+
+ if (mysqli_num_rows($sql) == 0) {
+ $sql1 = sisplet_query("SELECT * FROM srv_library_folder WHERE uid='0' AND tip='1' AND parent='0' AND lang='$lang[id]'");
+ $row1 = mysqli_fetch_array($sql1);
+
+ sisplet_query("INSERT INTO srv_library_anketa (ank_id, uid, folder) VALUES ('$anketa', '0', '$row1[id]')");
+ sisplet_query("UPDATE srv_survey_list SET lib_glb='1' WHERE id='$anketa'");
+ }
+ else {
+ sisplet_query("DELETE FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='0'");
+ sisplet_query("UPDATE srv_survey_list SET lib_glb='0' WHERE id='$anketa'");
+ }
+ }
+
+ private function UpdateUserLibraryNew () {
+ global $global_user_id, $site_url;
+
+ $anketa = $_POST['anketa'];
+
+ $sql = sisplet_query("SELECT * FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='$global_user_id'");
+ if (mysqli_num_rows($sql) > 0) {
+ sisplet_query("DELETE FROM srv_library_anketa WHERE ank_id='$anketa' AND uid='$global_user_id'");
+ sisplet_query("UPDATE srv_survey_list SET lib_usr='0' WHERE id='$anketa'");
+ } else {
+ $sql1 = sisplet_query("SELECT * FROM srv_library_folder WHERE uid='$global_user_id' AND tip='1' AND parent='0'");
+ $row1 = mysqli_fetch_array($sql1);
+ sisplet_query("INSERT INTO srv_library_anketa (ank_id, uid, folder) VALUES ('$anketa', '$global_user_id', '$row1[id]')");
+ sisplet_query("UPDATE srv_survey_list SET lib_usr='1' WHERE id='$anketa'");
+ }
+ }
+
+ private function DisplayInfo () {
+ global $global_user_id, $site_url;
+
+ $anketa = $_POST['anketa'];
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+
+ SurveyInfo::DisplayInfoBox();
+ }
+
+ // ajax, ki poskrbi za vse update glelde razvrscanja mojih anket v folderje
+ private function updateMySurveyFolders(){
+ global $global_user_id, $site_url, $lang;
+
+ // Prenesli smo anketo v drug folder
+ if($_GET['a'] == 'survey_dropped'){
+ $parent = isset($_POST['parent']) ? $_POST['parent'] : '0';
+ $drag_survey = isset($_POST['drag_survey']) ? $_POST['drag_survey'] : '0';
+
+ // Ce smo spustili v root folder samo pobrisemo anketo
+ if($parent == '0'){
+ $sql = sisplet_query("DELETE FROM srv_mysurvey_anketa WHERE ank_id='".$drag_survey."' AND usr_id='$global_user_id'");
+ }
+ else{
+ // Razpremo parent folder
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET open='1' WHERE id='".$parent."' AND usr_id='$global_user_id'");
+
+ $sql = sisplet_query("INSERT INTO srv_mysurvey_anketa (ank_id, usr_id, folder) VALUES ('".$drag_survey."', '".$global_user_id."', '".$parent."') ON DUPLICATE KEY UPDATE folder='".$parent."'");
+ }
+ }
+
+ // Prenesli smo celoten folder v drug folder
+ elseif($_GET['a'] == 'folder_dropped'){
+ $parent = isset($_POST['parent']) ? $_POST['parent'] : '0';
+ $drag_folder = isset($_POST['drag_folder']) ? $_POST['drag_folder'] : '0';
+
+ // Preverimo da nismo slucajno prenesli v child folder - ne pustimo, ker drugace se zadeva porusi
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE id='".$parent."' AND parent='".$drag_folder."' AND usr_id='$global_user_id'");
+ if(mysqli_num_rows($sql) == 0){
+ // Razpremo parent folder
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET open='1' WHERE id='".$parent."' AND usr_id='$global_user_id'");
+
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET parent='".$parent."' WHERE id='".$drag_folder."' AND usr_id='$global_user_id'");
+ }
+ }
+
+ // prikazemo/skrijemo ankete znotraj folderja
+ elseif($_GET['a'] == 'folder_toggle'){
+ $folder = isset($_POST['folder']) ? $_POST['folder'] : '0';
+ $open = isset($_POST['open']) ? $_POST['open'] : '0';
+
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET open='".$open."' WHERE id='".$folder."' AND usr_id='$global_user_id'");
+ }
+
+ // Ustvarili smo nov folder
+ elseif($_GET['a'] == 'folder_create'){
+ $parent = isset($_POST['parent']) ? $_POST['parent'] : '0';
+
+ // Razpremo parent folder
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET open='1' WHERE id='".$parent."' AND usr_id='$global_user_id'");
+
+ $sql = sisplet_query("INSERT INTO srv_mysurvey_folder (usr_id, parent, naslov) VALUES ('".$global_user_id."','".$parent."', '".$lang['srv_mySurvey_new_folder']."')");
+
+ $new_folder_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $SL = new SurveyList();
+ $SL->getSurveys();
+
+ echo '<input type="hidden" id="new_added_folder" value="'.$new_folder_id.'">';
+ }
+
+ // Pobrisali smo obstojec folder
+ elseif($_GET['a'] == 'folder_delete'){
+ $folder = isset($_POST['folder']) ? $_POST['folder'] : '0';
+
+ //Pobrisemo ankete ki so bile znotraj folderja
+ $sql = sisplet_query("DELETE FROM srv_mysurvey_anketa WHERE folder='".$folder."' AND usr_id='$global_user_id'");
+
+ // Na koncu se pobrisemo prazen folder
+ $sql = sisplet_query("DELETE FROM srv_mysurvey_folder WHERE id='".$folder."' AND usr_id='$global_user_id'");
+
+ // Rekurzivno pobrisemo vse poddirektorije z anketami - TODO!!!
+ }
+
+ // Preimenovali smo obstojec folder
+ elseif($_GET['a'] == 'folder_rename'){
+ $folder = isset($_POST['folder']) ? $_POST['folder'] : '0';
+ $text = isset($_POST['text']) ? $_POST['text'] : '';
+ $text = strip_tags($text);
+
+ $sql = sisplet_query("UPDATE srv_mysurvey_folder SET naslov='".$text."' WHERE id='".$folder."' AND usr_id='$global_user_id'");
+ }
+
+ // Kopiramo obstojec folder z vsemi anketami
+ elseif($_GET['a'] == 'folder_copy'){
+
+ $folder = isset($_POST['folder']) ? $_POST['folder'] : '0';
+ if($folder > 0)
+ $this->copyMySurveyFolder($folder);
+ }
+ }
+
+ // Kopiramo obstojec folder z vsemi folderji in anketami (rekurzivno)
+ private function copyMySurveyFolder($folder_id, $parent=0){
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT * FROM srv_mysurvey_folder WHERE id='".$folder_id."' AND usr_id='".$global_user_id."'");
+ if(mysqli_num_rows($sql) == 0)
+ return;
+
+ $row = mysqli_fetch_array($sql);
+
+ // Najprej ustvarimo kopijo folderja
+ if($parent == 0)
+ $sql2 = sisplet_query("INSERT INTO srv_mysurvey_folder (usr_id, parent, naslov, open) VALUES ('".$global_user_id."', '".$row['parent']."', '".$row['naslov']."_copy', '1')");
+ else
+ $sql2 = sisplet_query("INSERT INTO srv_mysurvey_folder (usr_id, parent, naslov, open) VALUES ('".$global_user_id."', '".$parent."', '".$row['naslov']."_copy', '1')");
+
+ $new_folder_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ // Loop cez ankete v folderju
+ $sqlA = sisplet_query("SELECT * FROM srv_mysurvey_anketa WHERE folder='".$folder_id."'");
+ while($rowA = mysqli_fetch_array($sqlA)){
+
+ // Kopiramo anketo
+ $sas = new SurveyAdminSettings();
+ $ank_id = $sas->anketa_copy($rowA['ank_id']);
+
+ // Kopirano anketo vstavimo v nov folder
+ $sql2 = sisplet_query("INSERT INTO srv_mysurvey_anketa (ank_id, usr_id, folder) VALUES ('".$ank_id."', '".$global_user_id."', '".$new_folder_id."')");
+ }
+
+ // Na koncu rekurzivno kopiramo se vse notranje folderje
+ $sqlF = sisplet_query("SELECT id FROM srv_mysurvey_folder WHERE parent='".$folder_id."' AND usr_id='".$global_user_id."'");
+ while($rowF = mysqli_fetch_array($sqlF)){
+
+ $this->copyMySurveyFolder($rowF['id'], $new_folder_id);
+ }
+
+ return;
+ }
+
+
+ /** Funkcija ki kiče podfunkcije za ajax del
+ *
+ */
+ public function Ajax() {
+ switch ( $_GET['a'] ) {
+ case 'surveyList_knjiznica':
+ $this->UpdateSystemLibrary();
+ break;
+ case 'surveyList_myknjiznica':
+ $this->UpdateUserLibrary();
+ break;
+ case 'surveyList_myknjiznica_new':
+ $this->UpdateUserLibraryNew();
+ break;
+ case 'surveyList_knjiznica_new':
+ $this->UpdateSystemLibraryNew();
+ break;
+ case 'surveyList_display_info':
+ $this->DisplayInfo();
+ break;
+ case 'survey_dropped':
+ case 'folder_dropped':
+ case 'folder_create':
+ case 'folder_delete':
+ case 'folder_toggle':
+ case 'folder_rename':
+ case 'folder_copy':
+ $this->updateMySurveyFolders();
+ break;
+ case 'language_change':
+ $this->switch_language();
+ break;
+ default:
+ print_r($_POST);
+ print_r($_GET);
+ break;
+ }
+ }
+
+
+ /** Osveži datoteko z dodatnimi podatki anket
+ * za tiste ankete ki so bile spremenjene ali so imele kakšne vnose
+ */
+ private function refreshData() {
+
+ # polovimo vse obstoječe podatke v združeni datoteki
+ if (count($this->surveys_ids)>0 ) {
+
+ // Metaadmin updata samo svoje ankete (drugace jih je prevec in lahko zasteka)
+ if(Dostop::isMetaAdmin()){
+
+ # polovimo seznam metaadminovih anket
+ $meta_surveys_ids = array();
+ $dostopCondition = (SRV_LIST_CHECK_DOSTOP ? " AND (insert_uid = '".$this->user_id."') AND (sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop WHERE uid='".$this->g_uid."'"))."))" : "");
+ $stringSurveyList = "SELECT id, backup, active, folder, dostop FROM srv_anketa sa WHERE sa.backup='0' AND sa.id > 0 AND sa.active >= 0 AND sa.invisible = '0' ".$dostopCondition;
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ while ( $rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+ $meta_surveys_ids[$rowSurveyList['id']] = $rowSurveyList['id'];
+ }
+
+ $to_update = $meta_surveys_ids;
+
+ # poiščemmo katere ankete so OK, in jih odstranimo iz seznama anket potrebnih za update
+ $stringSurveyList = "SELECT id FROM srv_survey_list WHERE id IN (".implode(',', $meta_surveys_ids).")"
+ #. " AND (updated = '0' OR (updated = '1' AND TIME_TO_SEC(TIMEDIFF(NOW(),last_updated)) < ".SRV_LIST_UPDATE_TIME_LIMIT.")) AND ( last_updated IS NOT NULL)";
+ . " AND updated = '0' AND last_updated IS NOT NULL";
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ while ( $rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+ if (isset($to_update[$rowSurveyList['id']])) {
+ unset($to_update[$rowSurveyList['id']]);
+ }
+ }
+ }
+ else{
+ $to_update = $this->surveys_ids;
+
+ # poiščemmo katere ankete so OK, in jih odstranimo iz seznama anket potrebnih za update
+ $stringSurveyList = "SELECT id FROM srv_survey_list WHERE id IN (".implode(',', $this->surveys_ids).")"
+ #. " AND (updated = '0' OR (updated = '1' AND TIME_TO_SEC(TIMEDIFF(NOW(),last_updated)) < ".SRV_LIST_UPDATE_TIME_LIMIT.")) AND ( last_updated IS NOT NULL)";
+ . " AND updated = '0' AND last_updated IS NOT NULL";
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ while ( $rowSurveyList = mysqli_fetch_assoc($sqlSurveyList)) {
+ if (isset($to_update[$rowSurveyList['id']])) {
+ unset($to_update[$rowSurveyList['id']]);
+ }
+ }
+ }
+
+ # če je treba kaj updejtat
+ if (count($to_update) > 0) {
+ $stringUpdateList =
+ " SELECT sa.id, "
+
+ . ' IF(ISNULL(sla1.lib_glb),0,sla1.lib_glb) AS lib_glb,'
+ . ' IF(ISNULL(sla2.lib_usr),0,sla2.lib_usr) AS lib_usr,'
+
+ // Po novem ne joinamo s tabelo "users", ker je lahko query pocasen in zaklene tabelo - potem pa vse zasteka (dodano preventivno)
+ //. ' sa.edit_uid, us1.name AS e_name, us1.surname AS e_surname, us1.email AS e_email,'
+ //. ' sa.insert_uid, us2.name AS i_name, us2.surname AS i_surname, us2.email AS i_email,'
+
+ . " us3.vnos_time_first AS v_time_first, us3.vnos_time_last AS v_time_last,"
+ . ' IF(ISNULL(us3.answers),0,us3.answers) as answers,'
+ . ' IF(ISNULL(g.variables),0,g.variables) as variables,'
+ . ' IF(ISNULL(us5.approp),0,us5.approp) as approp'
+
+ . ' FROM srv_anketa sa'
+
+ . " LEFT OUTER JOIN ( SELECT ank_id, uid, COUNT(*) AS lib_glb FROM srv_library_anketa as sla WHERE sla.uid = '0' AND sla.ank_id IN (".implode(',', $to_update).") GROUP BY ank_id )
+ AS sla1 ON sla1.ank_id = sa.id"
+ . " LEFT OUTER JOIN ( SELECT ank_id, uid, COUNT(*) AS lib_usr FROM srv_library_anketa as sla WHERE sla.uid = '".$this->g_uid."' AND sla.ank_id IN (".implode(',', $to_update).") GROUP BY ank_id )
+ AS sla2 ON sla2.ank_id = sa.id"
+
+ //. ' LEFT OUTER JOIN users AS us1 ON us1.id = sa.edit_uid'
+ //. ' LEFT OUTER JOIN users AS us2 ON us2.id = sa.insert_uid'
+
+ . ' LEFT OUTER JOIN ( SELECT us3.ank_id, COUNT(us3.ank_id) as answers, MIN( us3.time_insert ) as vnos_time_first, MAX( us3.time_insert ) as vnos_time_last, preview FROM srv_user as us3 WHERE us3.ank_id IN ('.implode(',', $to_update).') AND us3.preview = \'0\' AND us3.deleted=\'0\' GROUP BY us3.ank_id )
+ AS us3 ON us3.ank_id = sa.id'
+
+ . ' LEFT OUTER JOIN ( SELECT g.ank_id, COUNT(s.gru_id) as variables FROM srv_grupa g, srv_spremenljivka s WHERE g.id = s.gru_id AND g.ank_id IN ('.implode(',', $to_update).') GROUP BY g.ank_id )
+ AS g ON g.ank_id = sa.id'
+ //spodaj dodaj AND us5.lurker=\'0\'
+ . ' LEFT OUTER JOIN ( SELECT us5.ank_id, COUNT(us5.ank_id) as approp, preview FROM srv_user as us5 WHERE last_status IN (' . $this->appropriateStatus . ') AND us5.ank_id IN ('.implode(',', $to_update).') AND us5.preview =\'0\' AND us5.deleted=\'0\' GROUP BY us5.ank_id )
+ AS us5 ON us5.ank_id = sa.id'
+
+ . ' WHERE sa.id IN ('.implode(',', $to_update).')';
+
+ $sqlUpdateList = sisplet_query($stringUpdateList);
+ if (!$sqlUpdateList) echo mysqli_error($GLOBALS['connect_db']);
+
+ if (mysqli_num_rows($sqlUpdateList) > 0) {
+
+ // Po novem zakesiramo podatke iz tabele "users" posebej (da ne zaklene zgornji query tabele za dalj casa)
+ $users = array();
+ $sqlUsers = sisplet_query("SELECT sa.id AS ank_id, sa.edit_uid, us1.name AS e_name, us1.surname AS e_surname, us1.email AS e_email,
+ sa.insert_uid, us2.name AS i_name, us2.surname AS i_surname, us2.email AS i_email
+ FROM srv_anketa sa
+ LEFT OUTER JOIN users AS us1 ON us1.id = sa.edit_uid
+ LEFT OUTER JOIN users AS us2 ON us2.id = sa.insert_uid
+ WHERE sa.id IN (".implode(',', $to_update).")");
+ while($rowUsers = mysqli_fetch_array($sqlUsers)){
+ $users[$rowUsers['ank_id']] = $rowUsers;
+ }
+
+ $values = array();
+ while ( $row = mysqli_fetch_assoc($sqlUpdateList)) {
+ /*$row[i_name] = mysqli_real_escape_string($GLOBALS['connect_db'], $row[i_name]);
+ $row[i_surname] = mysqli_real_escape_string($GLOBALS['connect_db'], $row[i_surname]);
+ $row[i_email] = mysqli_real_escape_string($GLOBALS['connect_db'], $row[i_email]);
+ $row[e_name] = mysqli_real_escape_string($GLOBALS['connect_db'], $row[e_name]);
+ $row[e_surname] = mysqli_real_escape_string($GLOBALS['connect_db'], $row[e_surname]);
+ $row[e_email] = mysqli_real_escape_string($GLOBALS['connect_db'], $row[e_email]);*/
+
+ $row['i_name'] = mysqli_real_escape_string($GLOBALS['connect_db'], $users[$row['id']]['i_name']);
+ $row['i_surname'] = mysqli_real_escape_string($GLOBALS['connect_db'], $users[$row['id']]['i_surname']);
+ $row['i_email'] = mysqli_real_escape_string($GLOBALS['connect_db'], $users[$row['id']]['i_email']);
+ $row['e_name'] = mysqli_real_escape_string($GLOBALS['connect_db'], $users[$row['id']]['e_name']);
+ $row['e_surname'] = mysqli_real_escape_string($GLOBALS['connect_db'], $users[$row['id']]['e_surname']);
+ $row['e_email'] = mysqli_real_escape_string($GLOBALS['connect_db'], $users[$row['id']]['e_email']);
+
+ $values[] = "('$row[id]','$row[lib_glb]','$row[lib_usr]','$row[answers]','$row[variables]','$row[approp]','$row[i_name]','$row[i_surname]','$row[i_email]','$row[e_name]','$row[e_surname]','$row[e_email]','$row[v_time_first]','$row[v_time_last]','0', NOW())";
+ }
+
+ $updateString = "INSERT INTO srv_survey_list (id, lib_glb, lib_usr, answers, variables, approp, i_name, i_surname, i_email, e_name, e_surname, e_email, a_first, a_last, updated, last_updated) "
+ ." VALUES ".implode(',', $values)." ON DUPLICATE KEY UPDATE id=VALUES(id), lib_glb=VALUES(lib_glb), lib_usr=VALUES(lib_usr), answers=VALUES(answers), variables=VALUES(variables), approp=VALUES(approp), i_name=VALUES(i_name), i_surname=VALUES(i_surname), i_email=VALUES(i_email), e_name=VALUES(e_name), e_surname=VALUES(e_surname), e_email=VALUES(e_email), a_first=VALUES(a_first), a_last=VALUES(a_last), updated='0', last_updated=NOW()";
+
+ sisplet_query($updateString);
+
+ }
+ sisplet_query("COMMIT");
+ }
+ }
+
+ # polovimo nastavitve uporabnika
+ $this->settingsArray = $this->getSettings();
+
+
+ # koliko imamo strani
+ $this->max_pages = (int)$this->rec_per_page > 0 ? ceil($this->countSurveys() / $this->rec_per_page) : 1;
+
+ # ce imamo direktorije, imamo manj strani zaradi anket v direktorijih
+ if($this->show_folders == 1 && $this->max_pages > 1){
+ $this->max_pages = ceil($this->countRootSurveys() / $this->rec_per_page);
+ }
+
+ # katera je trenutna stran
+ if (isset($_GET['pageno']) && (int)$_GET['pageno'] > 0) {
+ # izbrana stran ne more biti večja, kot pa imamo vseh strani
+ $this->pageno = min((int)$_GET['pageno'], $this->max_pages );
+ }
+ }
+
+ function setFilter() {
+ if (isset($_POST['sl_filter']) && trim($_POST['sl_filter']) != "") {
+ $this->filter = trim($_POST['sl_filter']);
+ }
+ }
+
+ public function countPhoneSurveys() {
+ # če ni admin odstranimo ankete kjer je uporabnik označen samo kot anketar
+
+ $stringSurveyList = "SELECT count(*) FROM srv_anketa sa WHERE sa.backup='0' AND sa.id > 0 AND sa.active >= 0 AND sa.invisible = '0' "
+ .$this->getFolderCondition();
+ if ($this->g_adminType != '0') {
+ $stringSurveyList .= " AND sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop AS sd WHERE sd.aktiven = '1' AND sd.uid = '$this->g_uid' AND FIND_IN_SET('phone',sd.dostop )>0 AND FIND_IN_SET('edit',sd.dostop ) = 0")).")";
+ } else {
+ $stringSurveyList .= " AND sa.id IN (".SurveyCopy::prepareSubquery(sisplet_query("SELECT ank_id FROM srv_dostop AS sd WHERE sd.aktiven = '1' AND FIND_IN_SET('phone',sd.dostop )>0 AND FIND_IN_SET('edit',sd.dostop ) = 0")).")";
+ }
+
+ $sqlSurveyList = sisplet_query($stringSurveyList);
+ [$count] = mysqli_fetch_row($sqlSurveyList);
+
+ return (int)$count;
+ }
+
+ // Preklopimo jezik
+ private function switch_language(){
+ global $global_user_id;
+
+ $lang = $_POST['lang'];
+
+ sisplet_query("UPDATE users SET lang = '$lang' WHERE id = '$global_user_id'");
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyMapData.php b/admin/survey/classes/class.SurveyMapData.php
new file mode 100644
index 0000000..07fda90
--- /dev/null
+++ b/admin/survey/classes/class.SurveyMapData.php
@@ -0,0 +1,255 @@
+<?php
+/**
+ * June 2016
+ *
+ * Pridobi podatke o markerjih, za za njihov prikaz v mapi v podatkih in analizah
+ *
+ * @author Uros Podkriznik
+ */
+class SurveyMapData
+{
+ function __construct() {
+ }
+
+ //podatki o markerjih za vsakega userja posebej
+ function mapData() {
+ if(isset($_POST['map_data'])) {
+ $json = $_POST['map_data'];
+
+ //get multi_input_type (marker, polyline, polygon)
+ $row = Cache::srv_spremenljivka($json['spr_id']);
+
+ $newParams = new enkaParameters($row['params']);
+ $input = $newParams->get('multi_input_type');
+ $marpod = $newParams->get('marker_podvprasanje'); //ali dodam podvprasanje v infowindow
+ $naslovpod = $newParams->get('naslov_podvprasanja_map'); //dobi naslov podvprasanja mape
+
+ /*
+ * tukaj se pogleda, ali ima user nastavljeno na prikaz vseh enot (1) ali samo ustrezne (2)
+ global $global_user_id;
+
+ SurveyUserSetting :: getInstance()->Init($json['ank_id'], $global_user_id);
+ $currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_status_profile_'.A_ANALYSIS);
+ error_log(json_encode($currentProfileId)); */
+
+ if($row['enota'] == 3){
+ $sql1 = sisplet_query("SELECT vm.vre_id, vm.lat, vm.lng, vm.address, v.naslov FROM srv_vrednost AS v
+ LEFT JOIN srv_vrednost_map AS vm ON v.id = vm.vre_id
+ WHERE v.spr_id='".$json['spr_id']."'", 'array');
+
+ //je vec vrednosti
+ if(!isset($sql1['lat']))
+ $map_data['data'] = $sql1;
+ //je ena vrednost
+ else
+ $map_data['data'][] = $sql1;
+
+ //get info shapes
+ $sql2 = sisplet_query("SELECT lat, lng, address, overlay_id FROM srv_vrednost_map
+ WHERE spr_id='".$json['spr_id']."' AND overlay_type='polyline' ORDER BY overlay_id, vrstni_red", 'array');
+
+ $map_data_info_shapes = array();
+
+ //create json data for info shapes
+ $st_linij=0;
+ $last_id=0;
+ foreach ($sql2 as $line_row) {
+ if($line_row['overlay_id'] != $last_id){
+ $st_linij++;
+ $last_id = $line_row['overlay_id'];
+ $map_data_info_shapes[$st_linij-1]['overlay_id']=$line_row['overlay_id'];
+ $map_data_info_shapes[$st_linij-1]['address']=$line_row['address'];
+ $map_data_info_shapes[$st_linij-1]['path']= array();
+ }
+
+ $path = array();
+ $path['lat']=floatval($line_row['lat']);
+ $path['lng']=floatval($line_row['lng']);
+
+ array_push($map_data_info_shapes[$st_linij-1]['path'], $path);
+ }
+ $map_data['info_shapes'] = $map_data_info_shapes;
+ }
+ else{
+ if($input == 'marker')
+ $str_query = "SELECT REPLACE(REPLACE(REPLACE(sdm.address,'\n',' '),'\r',' '),'|',' ') as address, "
+ . "REPLACE(REPLACE(REPLACE(sdm.text,'\n',' '),'\r',' '),'|',' ') as text, sdm.lat, sdm.lng "
+ . "FROM srv_data_map AS sdm JOIN srv_user AS u ON sdm.usr_id = u.id WHERE u.deleted = '0' AND sdm.spr_id = ". $json['spr_id'];
+ else
+ $str_query = "SELECT sdm.lat, sdm.lng, sdm.usr_id "
+ . "FROM srv_data_map AS sdm JOIN srv_user AS u ON sdm.usr_id = u.id WHERE u.deleted = '0' AND sdm.spr_id = ". $json['spr_id'];
+
+ if($json['usr_id'] != '-1')
+ $str_query.=" AND usr_id = ". $json['usr_id'];
+
+ if($json['loop_id'] != '0' && $json['loop_id'] != '-1')
+ $str_query.=" AND loop_id = ". $json['loop_id'];
+
+ if($input != 'marker'){
+ $str_query.=" ORDER BY sdm.usr_id, sdm.vrstni_red";
+ $map_data1 = sisplet_query($str_query, 'array');
+
+ //iterate and convert all coordinates to float - needed for JS
+ /*for($i=0; $i<count($map_data['data']); $i++){
+ $map_data['data'][$i]['lat'] = floatval($map_data['data'][$i]['lat']);
+ $map_data['data'][$i]['lng'] = floatval($map_data['data'][$i]['lng']);
+ }*/
+
+ $i=0;
+ $user_id=null;
+ foreach($map_data1 as $item)
+ {
+ if($user_id!=null && $user_id!=$item['usr_id'])
+ $i=0;
+
+ $user_id = $item['usr_id'];
+ //error_log(json_encode($key.' '.json_encode($item)));
+ $map_data['data'][$user_id][$i]['lat'] = floatval($item['lat']);
+ $map_data['data'][$user_id][$i]['lng'] = floatval($item['lng']);
+ $i++;
+ }
+ }
+ else{
+ $map_data = array();
+ $data = sisplet_query($str_query);
+
+ while ($row1 = mysqli_fetch_array($data)) {
+ $map_data[] = $row1;
+ }
+ }
+ }
+ $map_data['input_type'] = $input;
+ $map_data['enota'] = $row['enota'];
+ $map_data['podvprasanje'] = ($marpod > 0) ? true : false;
+ if($marpod > 0 && $naslovpod != '')
+ $map_data['podvprasanje_naslov'] = $naslovpod;
+
+ echo json_encode($map_data);
+ }
+ exit();
+ }
+
+ //podatki o markerjih o vseh userjih za to spremenljivko glede na filterje
+ function mapDataAll() {
+ if(isset($_POST['map_data'])) {
+ $json = $_POST['map_data'];
+
+ //nastavimo podstran, da nam naredi pravilen profileId pri kreiranju filterjev
+ $_POST['podstran'] = A_ANALYSIS;
+
+ //zazenemo in pridobimo podatke o spremenljivki
+ $a = new SurveyAnalysis();
+ $a->Init($json['ank_id']);
+
+ $spremenljivka = $a::$_HEADERS[$json['spr_id']."_".$json['loop_id']];
+
+ $_answers = $a->getAnswers($spremenljivka, -1, true);
+ $_valid_answers = $_answers['valid'];
+
+ //pridobimo predelan json pripravljen za js
+ $map_data = $this->prepareMapDataAll($json['spr_id'], $_valid_answers);
+
+ echo json_encode($map_data);
+
+ }
+ exit();
+ }
+
+ /**
+ *
+ * @global type $lang
+ * @param int $spid - id spremenljivke
+ * @param array $_valid_answers - array vseh valid answers pridobljen iz SurveyAnalysis->getAnswers()
+ * @return array json predelanih podatkov, pripravljenih za filanje markerjev na mapo v js
+ */
+ private static function prepareMapDataAll($spid, $_valid_answers){
+ global $lang;
+
+ $spremenljivka = Cache::srv_spremenljivka($spid);
+ $newParams = new enkaParameters($spremenljivka['params']);
+
+ $input = $newParams->get('multi_input_type');
+ $marpod = $newParams->get('marker_podvprasanje'); //ali dodam podvprasanje v infowindow
+ $naslovpod = $newParams->get('naslov_podvprasanja_map'); //dobi naslov podvprasanja mape
+ $enota = $spremenljivka["enota"];
+
+ //tukaj ni choose location, zato locujemo samo med markerji ali shape
+ //ali je shape
+ if($input != 'marker'){
+ $map_data = array('data' => array());
+
+ //gremo cez vsak odgovor
+ foreach ($_valid_answers as $user_id => $row1) {
+
+ $new_row = array();
+
+ //v podatkih so podatki o koordinatah deljena s <br>, zato je treba to razbit
+ $values = array_values($row1);
+ //dobimo array vseh koordinat za ta odgovor
+ $latlngs = explode('<br>',$values[0]);
+
+ //kreiraj array za vsak marker posebej in ga dodaj v parent array
+ for($i = 0; $i < count($latlngs); $i++){
+
+ //v podatkih so lat in lng deljena z vejico, razbij
+ $latlng = explode(', ',$latlngs[$i]);
+ $new_row = array("lat" => floatval($latlng[0]), "lng" => floatval($latlng[1]));
+
+ //filaj koordinate v array
+ if($map_data['data'][$user_id])
+ array_push($map_data['data'][$user_id], $new_row);
+ else
+ $map_data['data'][$user_id] = array($new_row);
+ }
+ }
+ }
+ //markerji
+ else{
+ $map_data = array();
+
+ //gremo cez vsak odgovor
+ foreach ($_valid_answers as $row1) {
+ $new_row = array();
+ $values = array_values($row1);
+
+ //addres je vedno prva, razbij jo
+ $addresses = explode('<br>',$values[0]);
+
+ //ce marker nima nastavljene podvprasanja, sta samo address in koordinate
+ if(count($values) == 2){
+ $latlngs = explode('<br>',$values[1]);
+ $texts = null;
+ }
+ //verjetno je nastavljeno podvprasanje, zato so 3 kolumne (address, text, koordinate)
+ else{
+ $latlngs = explode('<br>',$values[2]);
+ $texts = explode('<br>',$values[1]);
+ }
+
+ //kreiraj array za vsak marker posebej in ga dodaj v parent array
+ for($i = 0; $i < count($addresses); $i++){
+
+ //v podatkih so lat in lng deljena z vejico, razbij
+ $latlng = explode(', ',$latlngs[$i]);
+
+ //ce je nastavljeno podvprasanje, dodaj tudi to v array
+ if($texts)
+ $new_row = array("address" => $addresses[$i], "text" => $texts[$i], "lat" => floatval($latlng[0]), "lng" => floatval($latlng[1]));
+ else
+ $new_row = array("address" => $addresses[$i], "lat" => floatval($latlng[0]), "lng" => floatval($latlng[1]));
+
+ array_push($map_data, $new_row);
+ }
+ }
+ }
+
+ //dodaj se osnovne info oz. parametre o spremenljivki
+ $map_data['input_type'] = $input;
+ $map_data['enota'] = $enota;
+ $map_data['podvprasanje'] = ($marpod > 0) ? true : false;
+ if($marpod > 0 && $naslovpod != '')
+ $map_data['podvprasanje_naslov'] = $naslovpod;
+
+ return ($map_data);
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyMissingProfiles.php b/admin/survey/classes/class.SurveyMissingProfiles.php
new file mode 100644
index 0000000..d957a29
--- /dev/null
+++ b/admin/survey/classes/class.SurveyMissingProfiles.php
@@ -0,0 +1,643 @@
+<?php
+/** @author: Gorazd Veselič
+ *
+ * @Desc: za upravljanje z profili missingov za analize
+
+ * @Date: 28.09.2010
+ */
+
+session_start();
+define('SMP_DEFAULT_PROFILE', 1);
+
+class SurveyMissingProfiles
+{
+ static private $sid = null; # id ankete
+ static private $uid = null; # id userja
+ static private $inited = false; # ali so profili ze inicializirani
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+ static private $smv = null; # manjkajoče vrednosti
+
+
+ // lurker je mal poseben, ker je neodvisen od ostalih (user je npr. 6 in lurker)
+// static private $allStatus = array('null',0,1,2,3,4,5,6,'lurker'); // Statusi anket katere štejemo kot ustrezne
+// static private $appropriateStatus = array(6,5); // Statusi anket katere štejemo kot ustrezne
+// static private $unAppropriateStatus = array(4,3,2,1,0); // Statusi anket katere štejemo kot neustrezne
+// static private $unKnownStatus = array('null'); // Statusi anket katere štejemo kot neustrezne
+// # za awk komando
+// static private $_AWK_FILTER_TEXT = array(6=>'6',5=>'5',4=>'4',3=>'3',2=>'2',1=>'^1',0=>'0','null'=>'-1'); # texti za statuse. 6=>'6',5=>'5',4=>'4',3=>'3',2=>'2',1=>'^1',0=>'0',null=>'-1' Pri 1 je ^pomemben, če ne lahko vzame tudi -1
+
+ static function Init($sid, $uid = null) {
+ # nastavimo surveyId
+ self::setSId($sid);
+ self::$smv = new SurveyMissingValues($sid);
+ self::$smv -> Init();
+ # nastavimo userja
+ self::setGlobalUserId($uid);
+ SurveyUserSetting :: getInstance()->Init(self::$sid, self::getGlobalUserId());
+ if (self::$inited == false) {
+ self::$inited = self :: RefreshData();
+ }
+ }
+
+ static function RefreshData() {
+
+ self::$profiles = array();
+ # dodamo sejo če obstaja
+
+ if (isset($_SESSION['missingProfile'])) {
+ self::$profiles[$_SESSION['missingProfile']['id']] = $_SESSION['missingProfile'];
+ }
+ # dodamo sistemske profile, skreiramo jih "on the fly"
+ self :: addSystemProfiles();
+
+ # preberemo podatke vseh porfilov ki so na voljo in jih dodamo v array
+ $stringSelect = "SELECT * FROM srv_missing_profiles WHERE uid = '".self::getGlobalUserId()."' OR (uid = '0' AND `system` = 1) ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+
+ if (mysqli_num_rows($querySelect)) {
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ }
+ }
+ # poiscemo privzet profil
+ self::$currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+
+ if (!self::$currentProfileId || self::$currentProfileId == 1)
+ self::$currentProfileId = 1;
+
+ # ce imamo nastavljen curent pid in profil z tem pid ne obstaja nastavomo na privzet profil
+ if (self::$currentProfileId != 1) {
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ self::$currentProfileId = 1;
+ self::setDefaultProfileId(self::$currentProfileId);
+ }
+ }
+
+ # ce ne obstajajo podatki za cpid damo error
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ die("Profile data is missing!");
+ return false;
+ } else {
+ return true;
+ }
+
+ }
+ static function DisplayProfile( $pid = null) {
+ global $lang;
+
+ echo '<h2>'.$lang['srv_missing_settings'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="missingProfileAction(\'cancle\'); return false;">✕</a></div>';
+
+ if ($pid == null ) {
+ $pid = self::$currentProfileId;
+ }
+
+ if ( self::$currentProfileId != SMP_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+
+ echo ' <div id="missing_profile_holder">';
+ self :: DisplayProfileOptions($pid);
+ echo ' </div>';
+
+
+ echo ' <div id="missing_profile_data_holder">';
+ self :: DisplayProfileData($pid);
+ echo ' </div>';
+
+
+ // GUMBI
+ echo '<div style="margin: 15px 0 0 0; float:right;">';
+ # shrani kot seja
+ if (self::$profiles[$pid]['system'] == 1 || $pid == -1) {
+ $run_lbl = $lang['srv_run_as_session_profile'];
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="missingProfileAction(\'runSession\'); return false;"><span>'.$run_lbl.'</span></a></span></span>';
+ } else {
+ # shrani - pozeni
+ $run_lbl = $lang['srv_run_profile'];
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="missingProfileAction(\'run\'); return false;"><span>'.$run_lbl.'</span></a></span></span>';
+ }
+ # shrani kot nov profil
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="missingProfileAction(\'newName\'); return false;"><span>'.$lang['srv_create_new_profile'].'</span></a></span></span>';
+ # preklici - zapri
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="missingProfileAction(\'cancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '</div>';
+
+
+ // cover Div
+ echo '<div id="missingProfileCoverDiv"></div>'."\n";
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfile">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="missingProfileAction(\'newSave\'); return false;"><span>'.$lang['srv_save_profile'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="missingProfileAction(\'newCancle\');; return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . self::$profiles[$pid]['name'] . '" size="45" />'."\n";
+ echo '<input id="renameProfileId" type="hidden" value="' . $pid . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="missingProfileAction(\'rename\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="missingProfileAction(\'renameCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . self::$profiles[$pid]['name'] . '</b>?'."\n";
+ echo '<input id="deleteProfileId" type="hidden" value="' . $pid . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="missingProfileAction(\'deleteCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="missingProfileAction(\'deleteConfirm\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+
+ }
+
+ static function DisplayProfileData($pid) {
+ global $lang;
+ $curentProfileData = self :: getProfileValues($pid);
+
+ $_tpes_array = array(MISSING_TYPE_DESCRIPTOR=>$lang['srv_analiza_arhiviraj_type_'.MISSING_TYPE_DESCRIPTOR],MISSING_TYPE_FREQUENCY=>$lang['srv_analiza_arhiviraj_type_'.MISSING_TYPE_FREQUENCY],MISSING_TYPE_CROSSTAB=>$lang['srv_analiza_arhiviraj_type_'.MISSING_TYPE_CROSSTAB]);
+ $_sys_missings = self::$smv->GetMissingValuesForSurvey();
+ $_sys_unset = self::$smv->GetUnsetValuesForSurvey();
+ echo '<div id="infoMissingProfile">' . $lang['srv_missing_profile_title1'] . '</div >';
+ echo '<div id="missingProfileFieldsetHolder1">'.NEW_LINE;
+
+ echo '<fieldset id="missingProfileFieldset">'.NEW_LINE;
+ echo '<legend>' . $lang['srv_missing_profile_title2'] . '</legend>'.NEW_LINE;
+ foreach ($_tpes_array AS $tkey => $tlabel) {
+ echo '<div style="float:left; width:100px; text-align:center;">'. $tlabel .'</div>'.NEW_LINE;
+ }
+ echo '<div class="clr"></div>'.NEW_LINE;
+ echo '<form name="" id="" autocomplete="off">'.NEW_LINE;
+ # loop sozi sistemske missinge
+ foreach ($_sys_unset as $mkey => $mvalue) {
+ # loop skozi tipe
+ foreach ($_tpes_array AS $tkey => $tlabel) {
+ echo '<div style="float:left; width:100px; text-align:center;">'.NEW_LINE;
+ echo '<input name="profile_value[]" type="checkbox" id="mv_'.$tkey.'_'.$mkey . '"' .
+ (isset($curentProfileData[$tkey][$mkey]) ? ' checked' : '').
+ '/>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ }
+ echo '<div style="float:left; width:150px;">'.NEW_LINE;
+ echo '(' . $mkey . ") " . $mvalue;
+ echo '</div>'.NEW_LINE;
+ echo '<div class="clr"></div>'.NEW_LINE;
+ }
+ echo '</form>'.NEW_LINE;
+ echo '</fieldset>'.NEW_LINE;
+
+ echo '<fieldset id="missingProfileFieldset">'.NEW_LINE;
+ echo '<legend>' . $lang['srv_missing_profile_title3'] . '</legend>'.NEW_LINE;
+ foreach ($_tpes_array AS $tkey => $tlabel) {
+ echo '<div style="float:left; width:100px; text-align:center;">'. $tlabel .'</div>'.NEW_LINE;
+ }
+ echo '<div class="clr"></div>'.NEW_LINE;
+ echo '<form name="" id="" autocomplete="off">'.NEW_LINE;
+ # loop sozi sistemske missinge
+ foreach ($_sys_missings as $mkey => $mvalue) {
+ # loop skozi tipe
+ foreach ($_tpes_array AS $tkey => $tlabel) {
+ echo '<div style="float:left; width:100px; text-align:center;">'.NEW_LINE;
+ echo '<input name="profile_value[]" type="checkbox" id="mv_'.$tkey.'_'.$mkey . '"' .
+ (isset($curentProfileData[$tkey][$mkey]) ? ' checked' : '').
+ '/>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ }
+ echo '<div style="float:left; width:150px;">'.NEW_LINE;
+ echo '(' . $mkey . ") " . $mvalue;
+ echo '</div>'.NEW_LINE;
+ echo '<div class="clr"></div>'.NEW_LINE;
+ }
+ echo '</form>'.NEW_LINE;
+ echo '</fieldset>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+
+ echo '<div id="missingProfileFieldsetHolder1">'.NEW_LINE;
+ echo '<fieldset id="missingProfileFieldset">';
+ echo '<legend>'.$lang['srv_missing_profile_title5'].'</legend>';
+ # prikažemo še radio gumbe za način prikaza MV
+
+ $radio_selected = self::$profiles[$pid]['display_mv_type'];
+ echo '<div style="margin-bottom:8px;">';
+ echo '<input name="display_mv_type" id="display_mv_type_0" type="radio" value="0"'.($radio_selected == 0 ? ' checked' : '').'><label for="display_mv_type_0">'.$lang['srv_missing_profile_display_radio0'].'</label>';
+ echo '&nbsp;&nbsp;<input name="display_mv_type" id="display_mv_type_1" type="radio" value="1"'.($radio_selected == 1 ? ' checked' : '').'><label for="display_mv_type_1">'.$lang['srv_missing_profile_display_radio1'].'</label>';
+ echo '&nbsp;&nbsp;<input name="display_mv_type" id="display_mv_type_2" type="radio" value="2"'.($radio_selected == 2 ? ' checked' : '').'><label for="display_mv_type_2">'.$lang['srv_missing_profile_display_radio2'].'</label>';
+ echo '</div>';
+ echo '<div style=" width:auto; text-align:left;">'.NEW_LINE;
+ echo '<input name="show_zerro" id="show_zerro" type="checkbox" ' .
+ (self::$profiles[$pid]['show_zerro'] == 1 ? ' checked="checked"' : '') . ' autocomplete="off"/>'.NEW_LINE;
+ echo $lang['srv_missing_profile_other_show_zerro'];
+ echo '</div>'.NEW_LINE;
+ echo '<div style=" width:auto; text-align:left;">'.NEW_LINE;
+ echo '<input name="merge_missing" id="merge_missing" type="checkbox" ' .
+ (self::$profiles[$pid]['merge_missing'] == 1 ? ' checked="checked"' : '') . ' autocomplete="off"/>'.NEW_LINE;
+ echo $lang['srv_missing_profile_other_merge_missing'];
+ echo '</div>';
+ echo ' <div class="clr"></div>';
+ echo '</fieldset>';
+ echo '</div>'.NEW_LINE;
+ }
+
+ static function DisplayProfileOptions($pid) {
+ global $lang;
+
+ echo '<div id="missing_profile" class="select">';
+ foreach ( self::$profiles as $key => $profile ) {
+
+ echo '<div id="missing_profile_'.$profile['id'].'" class="option' . ($profile['id'] == $pid ? ' active' : '') . '" value="' . $profile['id'] . '">';
+
+ echo $profile['name'];
+
+ if($profile['id'] == $pid){
+ if (self::$profiles[$pid]['system'] != 1 ) {
+ echo '<a href="#" title="'.$lang['srv_delete_profile'].'" onclick="missingProfileAction(\'deleteAsk\'); return false;"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'."\n";
+ }
+ if (self::$profiles[$pid]['system'] != 1 && $pid != -1) {
+ echo '<a href="#" title="'.$lang['srv_rename_profile'].'" onclick="missingProfileAction(\'renameAsk\'); return false;"><span class="faicon edit floatRight spaceRight"></span></a>'."\n";
+ }
+ }
+
+ echo '</div>';
+ }
+ echo '</div>';
+
+ echo '<script>';
+ echo '$(function() {';
+ echo 'scrollToProfile("#missing_profile_'.$pid.'");';
+ echo '});';
+ echo '</script>';
+
+ }
+
+ /** klici ajax funkcij
+ *
+ */
+ static function ajax() {
+
+ $pid = $_POST['pid'];
+ switch ($_GET['a']) {
+ case 'change_profile' :
+ self :: setDefaultProfileId($pid);
+ break;
+
+ break;
+ case 'show_profile' :
+ self :: DisplayProfile($pid);
+ break;
+ case 'run_profile' :
+ self :: SaveProfile($pid);
+ self :: setDefaultProfileId($pid);
+ break;
+ case 'delete_profile':
+ self :: DeleteProfile($pid);
+ self :: setDefaultProfileId(1);
+ break;
+ case 'save_profile':
+ $new_id = self :: saveNewProfile();
+ self :: setDefaultProfileId($new_id);
+ echo $new_id;
+ break;
+ case 'rename_profile':
+ $_rename = self :: RenameProfile($pid);
+ echo $_rename;
+ break;
+
+ default:
+ echo 'ERROR! Missing function for action: '.$_GET['a'].'!';
+ break;
+ }
+ }
+
+ /** getProfiles
+ *
+ */
+ static function getProfiles() {
+ return self::$profiles;
+ }
+
+ static public function getProfile($pid) {
+ return self::$profiles[$pid];
+ }
+
+ /** setSurveyId
+ *
+ */
+ static function setSId($surveyId) {
+ self::$sid = $surveyId;
+ }
+
+ /** setGlobalUserId
+ *
+ */
+ static function setGlobalUserId($uid = null) {
+ if ($uid == null) {
+ global $global_user_id;
+ self::$uid = $global_user_id;
+ } else {
+ self::$uid = $uid;
+ }
+ }
+
+ /** getGlobalUserId
+ *
+ */
+ static function getGlobalUserId() {
+ return self::$uid;
+ }
+ static function getCurentProfileId() {
+ return self::$currentProfileId;
+ }
+ /**
+ *
+ * @param unknown_type $pid
+ */
+ static function setCurentProfileId($pid) {
+ # ce je seja, preverimo ali obstaja cene nardimo privzetega 1
+ if ($pid == -1) {
+ if (!(isset($_SESSION['missingProfile']['-1'])))
+ $pid = 1;
+ } else if (!$pid) {
+ $pid = 1;
+ }
+
+ return self::$currentProfileId = $pid;
+ }
+
+ static function setDefaultProfileId($pid) {
+ # ce je seja, preverimo ali obstaja cene nardimo privzetega 1
+ if ($pid == -1) {
+ if (!(isset($_SESSION['missingProfile']))) {
+ $pid = 1;
+ }
+ } else if (!$pid) {
+ $pid = 1;
+ }
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_missing_profile', $pid);
+ self::$currentProfileId = $pid;
+ return true;
+ }
+
+ static function SaveProfile($pid) {
+ global $lang;
+ $insert_id = 0;
+ $missing_values = $_POST['missing_values'];
+ $display_mv_type = isset($_POST['display_mv_type']) ? $_POST['display_mv_type'] : 0;
+
+ if (isset($pid) && $pid != null) {
+ # ce mamo sistemski profil ga ne shranjujemo
+ $checkSelect = "SELECT * as cnt FROM srv_missing_profiles WHERE id = '".$pid."' and `system` = 1";
+ $checkQry = sisplet_query($checkSelect);
+ if (mysqli_num_rows($checkQry) > 0) {
+ return $pid;
+ }
+
+ $show_zerro = (isset($_POST['show_zerro']) && $_POST['show_zerro'] == 'true') ? 1 : 0;
+ $merge_missing = (isset($_POST['merge_missing']) && $_POST['merge_missing'] == 'true') ? 1 : 0;
+
+ # ce imamo session pozenemo kot sejo
+ if ($pid == -1) {
+ $missing_values = explode(',',$missing_values);
+ $_SESSION['missingProfile'] = array('id'=>'-1','uid'=>0,'name'=>$lang['srv_temp_profile'],'system'=>0, 'display_mv_type'=>$display_mv_type, 'show_zerro'=>$show_zerro, 'merge_missing'=>$merge_missing);
+ # pobrišemo predhodne nastavitve
+ unset($_SESSION['missingProfile']['values']);
+ if (count($missing_values) > 0) {
+ foreach ($missing_values as $_missing_value) {
+ $_missing_value = substr($_missing_value,3);
+ list($type,$key) = explode('_',$_missing_value);
+ $_SESSION['missingProfile']['values'][$type][$key] = true;
+ }
+ }
+ return -1;
+ }
+ # imamo podatke, updejtamo profil v bazi (profili z id 1,2,3 so sitemski)
+ if ($pid > 3) {
+ # shranimo morebitno spremembo nastavitve display_mv_type
+ $updateString = "UPDATE srv_missing_profiles SET display_mv_type='".$display_mv_type."', show_zerro='".$show_zerro."', merge_missing='".$merge_missing."' WHERE id='".$pid."' AND `system` = 0";
+ $updatequery = sisplet_query($updateString);
+
+ # najprej pobrišemo stare podatke za ta profil
+ $stringDelete = "DELETE FROM srv_missing_profiles_values WHERE missing_pid ='".$pid."'";
+ $deleteQuery = sisplet_query($stringDelete);
+
+ # shranimo nove vrednosti
+ $missing_values = explode(',',$missing_values);
+ if (count($missing_values ) > 0) {
+ $insertString = "INSERT INTO srv_missing_profiles_values (missing_pid, missing_value, type) VALUES";
+ $prefix = '';
+
+ foreach ($missing_values as $_missing_value) {
+ $_missing_value = substr($_missing_value,3);
+ list($type,$key) = explode('_',$_missing_value);
+ $insertString .= $prefix . " (".$pid.", ".$key.", ".$type.")";
+ $prefix = ',';
+ }
+ $queryInsert = sisplet_query($insertString)
+ or die(mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ return $pid;
+ }
+
+ }
+
+ static function saveNewProfile() {
+
+ $name = $_POST['name'];
+ $missing_values = $_POST['missing_values'];
+ $display_mv_type = isset($_POST['display_mv_type']) ? $_POST['display_mv_type'] : 0;
+
+ $insert_id = 0;
+ if (isset($name) && $name != null ) {
+ # imamo podatke, vstavimo nov profil v bazo
+ $show_zerro = (isset($_POST['show_zerro']) && $_POST['show_zerro'] == 'true') ? 1 : 0;
+ $merge_missing = (isset($_POST['merge_missing']) && $_POST['merge_missing'] == 'true') ? 1 : 0;
+
+ $insertString = "INSERT INTO srv_missing_profiles (uid,name,system,display_mv_type,show_zerro,merge_missing) VALUES ('".self::getGlobalUserId()."', '".$name."', 0, '".$display_mv_type."', '".$show_zerro."', '".$merge_missing."')";
+ $queryInsert = sisplet_query($insertString);
+ $insert_id = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($insert_id > 0) {
+ # če je insert id <= 3 ga popravimo da je večji od 3.
+ if ($insert_id <= 3) {
+ $selectId = "SELECT max(id) FROM srv_missing_profiles";
+ list($maxInseredId) = mysqli_fetch_row(sisplet_query($selectId));
+ $newInsert_id = max(4,$maxInseredId);
+ $updateString = "UPDATE srv_missing_profiles SET id='".$newInsert_id."' WHERE id='".$insert_id."'";
+ $updatequery = sisplet_query($updateString);
+ $insert_id = $newInsert_id;
+ }
+
+ self::$profiles[$insert_id] = array('id'=>$insert_id,'uid'=>self::getGlobalUserId(),'name'=>$name,'system'=>0);
+
+ # shranimo nove vrednosti
+ $missing_values = explode(',',$missing_values);
+ if (count($missing_values ) > 0) {
+ $insertString = "INSERT INTO srv_missing_profiles_values (missing_pid, missing_value, type) VALUES";
+ $prefix = '';
+
+ foreach ($missing_values as $_missing_value) {
+ $_missing_value = substr($_missing_value,3);
+ list($type,$key) = explode('_',$_missing_value);
+ $insertString .= $prefix . " (".$insert_id.", ".$key.", ".$type.")";
+ $prefix = ',';
+ }
+ $queryInsert = sisplet_query($insertString);
+ }
+
+ } else {
+
+ }
+ }
+ return $insert_id;
+ }
+
+ static function RenameProfile($pid) {
+ $name = $_POST['name'];
+ if (isset($pid) && $pid != null && isset($name) && $name != null ) {
+ $updateString = "UPDATE srv_missing_profiles SET name = '".$name."' WHERE id = ".$pid;
+ $updated = sisplet_query($updateString);
+ if ($updated) {
+ return 0;
+ } else {
+ return mysqli_error($GLOBALS['connect_db']);
+ }
+ } else {
+ if (!isset($pid) || $pid == null || trim($pid) == '') {
+ return 'Invalid profile Id';
+ } else if (!isset($name) || $name == null || trim($name) == '') {
+ return 'Invalid profile name';
+ } else {
+ return 'Error!';
+ }
+ }
+
+ }
+
+ static function DeleteProfile($pid) {
+ if ($pid == -1) {
+ unset($_SESSION['missingProfile']);
+ }
+ # izbrišemo lahko samo nesistemske profile
+ if (self::$profiles[$pid]['system'] != 1) {
+ # zaradi ključev se avtomatsko pobriše tudi: srv_missing_profiles_values
+ $sqlDelete = sisplet_query("DELETE FROM srv_missing_profiles WHERE id = '$pid' AND `system` != '1'");
+ }
+ }
+
+ static function DisplayLink($hideAdvanced = true) {
+ global $lang;
+ // profili missingov
+ $missingProfiles = self :: getProfiles();
+ $izbranMissingProfile = self :: getCurentProfileId();
+
+ $css = ($izbranMissingProfile == SMP_DEFAULT_PROFILE ? ' gray' : '');
+ if ($hideAdvanced == false || $izbranMissingProfile != SMP_DEFAULT_PROFILE ) {
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="link_missing_profile" title="' . $lang['srv_analiza_setup_profile'] . '" onClick="show_missing_profiles();">' . $lang['srv_analiza_setup_profile'] . '</span>'."\n";
+ echo '</li>';
+
+ }
+ }
+
+ /** Ustvarimo tri sistemske profile ustvarimo jih navidezno
+ *
+ * Brez manjkajočih vrednosti - ne prikazuje manjkajočih vrednosti (display_mv_type = 0)
+ * Skupaj MV - prikaže samo skupaj manjkajoče vrednosti (display_mv_type = 1)
+ * Podrobno MV - prikaže razširjeno manjkajoče vrednosti (display_mv_type = 2)
+ */
+ static function addSystemProfiles() {
+ global $lang;
+
+ # skreiramo 3 sistemske manjkajoče profile
+ for ( $i = 1; $i <= 3; $i++ ) {
+ self::$profiles[$i] = array('id'=>$i,'uid'=>self::getGlobalUserId(),'name'=>$lang['srv_missing_profiles_profile'.$i.'_lbl'],'system'=>1, 'display_mv_type'=>(int)$i-1);
+ }
+ }
+
+ /** Vrenmo podatke o izbranem profilu v obliki arraya
+ *
+ * @param unknown_type $pid
+ */
+ static function getProfileValues($pid) {
+ $result = array();
+
+ if ($pid == -1) {
+ # beremo iz seje
+ if (isset($_SESSION['missingProfile'])) {
+ $result = $_SESSION['missingProfile']['values'];
+ return $result;
+ } else {
+ $pid = 1;
+ }
+ }
+ # če je sistemski profil preberemo iz avtomatsko skreiranih
+ if ( ($pid < 3 && $pid >= 0) || (isset(self::$profiles[$pid]) && self::$profiles[$pid]['system'] == 1)) {
+ # imamo sistemski profil, preberemo podatke ki so bili skreirani "on the fly"
+ #najprej poiščemo sistemske missinge
+ $_sys_missings = self::$smv->GetMissingValuesForSurvey();
+ $_sys_unset = self::$smv->GetUnsetValuesForSurvey(array(2,3));
+
+ # sistemske missinge (-1,-2,-3,-4) dodamo k vsem profilom
+ if (count($_sys_missings) > 0) {
+ foreach($_sys_missings AS $key => $value) {
+ $result[MISSING_TYPE_DESCRIPTOR][$key] = true;
+ $result[MISSING_TYPE_FREQUENCY][$key] = true;
+ $result[MISSING_TYPE_CROSSTAB][$key] = true;
+ }
+
+ }
+ # neopredeljene vrednosti (-99,-98,-97) dodamo samo k opisnim in krostabulacijam
+ if (count($_sys_unset) > 0) {
+ foreach($_sys_unset AS $key => $value) {
+ $result[MISSING_TYPE_DESCRIPTOR][$key] = true;
+ $result[MISSING_TYPE_CROSSTAB][$key] = true;
+ }
+
+ }
+ } else {
+ $selectString = "SELECT missing_value, type FROM srv_missing_profiles_values WHERE missing_pid = '".$pid."'";
+ $querySelect = sisplet_query($selectString);
+ if (mysqli_num_rows($querySelect)) {
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ $result[$rowSelect['type']][$rowSelect['missing_value']] = true;
+ }
+ }
+ }
+
+ return $result;
+ }
+
+ /*
+ * type = 1 => opisne
+ * type = 2 => frekvence
+ */
+ static function GetMissingValuesForAnalysis($type,$pid=null) {
+ $result = array();
+
+ #poiščemo sistemske missinge, z labele
+
+ $_survey_missings = self::$smv->GetMissingValuesForSurvey(array(1,2,3));
+
+ if ($pid == null)
+ {
+ $pid = self::$currentProfileId;
+ }
+ $curentProfileData = self :: getProfileValues($pid);
+ if (count($curentProfileData[$type]) > 0) {
+ foreach ($curentProfileData[$type] AS $key => $is_set) {
+ $result[$key] = isset($_survey_missings[$key]) ? $_survey_missings[$key] : $key;
+ }
+ }
+ return $result;
+
+ }
+}
+
+?>
diff --git a/admin/survey/classes/class.SurveyMissingValues.php b/admin/survey/classes/class.SurveyMissingValues.php
new file mode 100644
index 0000000..5ea0377
--- /dev/null
+++ b/admin/survey/classes/class.SurveyMissingValues.php
@@ -0,0 +1,724 @@
+<?php
+/* Class skribi za nastavitve missingov,
+ * najprej na nivoju sistema.
+ * potem na nivoju ankete
+ *
+ * prav tako skrbi za missinge pri izpolnjevanju ankete in lovljenju podatkov, kakor tudi analizah
+ *
+ * v srv_anketa na anketi nastavimo missing_values_type = 1, kadar imamo missinge nastavljene na nivoju ankete
+ *
+ * # neodgovori (type = 1):
+ * -1 - ni odgovoril
+ * -2 - preskok (if)
+ * -3 - prekinjeno
+ * -4 - naknadno vprašanje
+ *
+ * # neopredeljeni odgovori (type = 2)
+ * -99 Ne vem
+ * -98 Zavrnil
+ * -97 Neustrezno
+ *
+ * # ostali so uporabniško določeni (type = 3)
+ * - 96 Drugo.....
+ *
+ *
+ *
+ * Created on 21.9.2010 (Gorazd Veselič
+ */
+
+class SurveyMissingValues
+{
+ private static $anketa = null; # trenutna anketa
+ private static $srv_old_missing = 1; # ali imamo misinge na star način
+
+ private static $sysNeodgovori = array(); # array z sistemskimi neodgovori
+ private static $sysNeopredeljeni = array(); # array z sistemskimi neopredeljenimi
+ private static $sysUserSet = array(); # array z sistemskimi uporabniško nastavljenimi
+ private static $missing_values_type = 0; # Nivo missingov: 0 - sistemski, 1 - uporabniško nastavljen
+
+ private static $mySqlErrNo = null; # ali imamo mysql napako
+
+ /**
+ * konstruktor
+ *
+ * @param mixed $anketa
+ */
+ function __construct ($anketa = 0) {
+ if (self::$anketa == null) {
+ if (isset ($_GET['anketa']) && (int)$_GET['anketa'] > 0) {
+ self::$anketa = $_GET['anketa'];
+ } elseif (isset ($_POST['anketa']) && (int)$_POST['anketa'] > 0) {
+ self::$anketa = $_POST['anketa'];
+ } elseif ((int)$anketa > 0) {
+ self::$anketa = (int)$anketa;
+ }
+
+ # polovimo nastavitve ankete če obstaja
+ if (self::$anketa != null && (int)self::$anketa > 0) {
+ SurveyInfo::getInstance()->SurveyInit(self::$anketa);
+ SurveyInfo::getInstance()->resetSurveyData();
+ self::$missing_values_type = SurveyInfo::getInstance()->getSurveyColumn('missing_values_type') == 1 ? 1 : 0;
+
+ # če še nismo nastavili manjkajočih vrednosti jih prepišemo iz sistemskih
+ if ((int)self::$missing_values_type == 0) {
+ self :: SetUpSurvyeMissingValues();
+ }
+ }
+ self::Init();
+ }
+ }
+
+ /** Inicializacija, prebere sistemske vrednoasti iz baze
+ *
+ */
+ static function Init() {
+ # če nimamo missingov dodamo sistemske
+ $countSystem = "SELECT count(*) FROM srv_missing_values WHERE sid='".self::$anketa."'" ;
+ list($cntMissing) = mysqli_fetch_row(sisplet_query($countSystem));
+ if ((int)$cntMissing == 0) {
+ self::useSystemMissingValues();
+ }
+ # preberemo sistemske nastavitve
+ self::selectSysNeodgovori();
+ self::selectSysNeopredeljeni();
+ self::selectSysUserSet();
+ }
+
+
+ # AJAX funkcije
+ /** Ajax handler
+ *
+ */
+ public function ajax() {
+ if ($_GET['a'] == 'sysMissingValuesChangeMode') {
+ $_mode = $_POST['mode'];
+ if ($_mode == 'normal') {
+ self::displayNormalMode($_mode);
+ }
+ if ($_mode == 'edit') {
+ self::sysMissingValuesChangeMode($_mode);
+ }
+ if ($_mode == 'new') {
+ self::sysMissingValuesChangeMode($_mode);
+ }
+ }
+ if ($_GET['a'] == 'sysMissingValuesSave') {
+ self::SaveSystemFilters( $_POST['id'], $_POST['filter'], $_POST['text']);
+ self::Init();
+ $_mode = 'edit';
+ self::sysMissingValuesChangeMode($_mode);
+ }
+ if ($_GET['a'] == 'sysMissingValuesAdd') {
+ self::AddSystemFilters( $_POST['filter'], $_POST['text'], $_POST['filter']);
+ self::Init();
+ $_mode = 'edit';
+ self::sysMissingValuesChangeMode($_mode);
+ }
+ if ($_GET['a'] == 'sysMissingValuesDelete') {
+ self::DeleteSystemFilters($_POST['id']);
+ self::Init();
+ $_mode = 'edit';
+ self::sysMissingValuesChangeMode($_mode);
+ }
+ if ($_GET['a'] == 'changeSurveyMissingSettings') {
+ self::saveMisingValueTypeForSurvey();
+ self::displayMissingForSurvey();
+ }
+ if ($_GET['a'] == 'useSystemMissingValues') {
+ self::useSystemMissingValues();
+ self::displayMissingForSurvey();
+ }
+ if ($_GET['a'] == 'saveSurveyMissingValue') {
+ self::saveSurveyMissingValue();
+ self::displayMissingForSurvey();
+ }
+ if ($_GET['a'] == 'srv_missing_confirm_delete') {
+ self::deleteMissingForSurvey();
+ self::displayMissingForSurvey();
+ }
+ if ($_GET['a'] == 'srv_missing_add_new') {
+ self::displayAddMissingValue();
+ }
+ if ($_GET['a'] == 'srv_missing_confirm_add') {
+ self::addSurveyFilters();
+ }
+ if ($_GET['a'] == 'srv_missing_display') {
+ self::displayMissingForSurvey();
+ }
+
+ }
+
+ /* polovi sistemske neodgovore,
+ * type = 1
+ */
+ private static function selectSysNeodgovori() {
+ self::$sysNeodgovori = array();
+ $str_select = "SELECT filter,text FROM srv_sys_filters WHERE type = 1";
+
+ $qry_select = sisplet_query($str_select);
+ while ($row_select = mysqli_fetch_assoc($qry_select)) {
+ self::$sysNeodgovori[$row_select['filter']] = $row_select['text'];
+ }
+ }
+
+ /* polovi sistemske neopredeljene,
+ * type = 2
+ */
+ private static function selectSysNeopredeljeni() {
+ self::$sysNeopredeljeni = array();
+ $str_select = "SELECT filter,text FROM srv_sys_filters WHERE type = 2";
+ $qry_select = sisplet_query($str_select);
+ while ($row_select = mysqli_fetch_assoc($qry_select)) {
+ self::$sysNeopredeljeni[$row_select['filter']] = $row_select['text'];
+ }
+ }
+
+ /* polovi sistemske uporabniško nastavljene,
+ * type = 3
+ */
+ private static function selectSysUserSet() {
+ self::$sysUserSet = array();
+ $str_select = "SELECT filter,text FROM srv_sys_filters WHERE type = 3";
+ $qry_select = sisplet_query($str_select);
+ while ($row_select = mysqli_fetch_assoc($qry_select)) {
+ self::$sysUserSet[$row_select['filter']] = $row_select['text'];
+ }
+ }
+
+ /** polovimo missinge za anketo
+ * če obstaja nastavitev za anketo, (TODO)
+ * če ne vzamemo privzete sistenmske misinge
+ *
+ *
+ * @var unknown_type
+ */
+ private static $_systemFiltersByType = array();
+ static function GetSystemFlterByType($type, $forceSystem = false) {
+ global $lang;
+
+ if (is_array($type)) {
+ $type = (string)implode(',',$type);
+ $_type = "type IN (".$type.")";
+ } else {
+ $_type = "type = '".$type."'";
+ }
+
+ if (isset(self::$_systemFiltersByType[$type])) {
+ return self::$_systemFiltersByType[$type];
+ } else {
+ $result = array();
+
+ # preverimo iz katere tabele lovimo lahko imamo na nivoju ankete ali na nivoju sistema
+ if ((int)self::$missing_values_type == 1 && $forceSystem == false) {
+
+ $stringSystemSetting_filters = "SELECT value AS filter, text FROM srv_missing_values WHERE sid='".self::$anketa."' AND ".$_type." AND active = 1 ORDER BY type ASC, value ASC" ;
+ } else {
+
+ $stringSystemSetting_filters = "SELECT filter, text FROM srv_sys_filters WHERE ".$_type." ORDER BY filter ASC";
+ }
+ $sqlSystemSetting_filters = sisplet_query($stringSystemSetting_filters );
+ while ( $rowSystemSetting_filters = mysqli_fetch_assoc($sqlSystemSetting_filters) )
+ {
+ # naredimo prevode:
+ $result[$rowSystemSetting_filters['filter']] = $lang['srv_mv_'.$rowSystemSetting_filters['text']] != '' ? $lang['srv_mv_'.$rowSystemSetting_filters['text']] : $rowSystemSetting_filters['text'];;
+ }
+ self::$_systemFiltersByType[$type] = $result;
+ return self::$_systemFiltersByType[$type];
+ }
+ }
+
+ # urejanje sistemskih missingov
+ /* Prikaže osnovni okvir za urejanje missingov
+ *
+ */
+ static public function SystemFilters() {
+ global $lang;
+ echo '<fieldset>';
+ echo '<legend>' . $lang['srv_filtri'] . '</legend>';
+ echo '<div class="nastavitveSpan1" style="height:auto; float:left;"><label>' . $lang['srv_filtri_text'] . ':</label></div>';
+ echo '<div id="sys_missing_values" style="display:block; float:left; width:auto; margin:0px 0px 5px 5px; padding: 0px; 5px;">';
+ self::displayNormalMode();
+ echo '</div>';
+ echo '</fieldset>';
+ }
+
+ /** Prikaže navaden način misingov - predogled
+ *
+ * @param $_mode
+ */
+ private static function displayNormalMode($_mode = null) {
+ global $lang;
+
+ //echo '<a href="#" onClick="sysFilterEditMode(\'edit\'); return false;">';
+ echo '<a href="#" onClick="sysMissingValuesChangeMode(\'edit\'); return false;">';
+ echo '<span class="faicon edit small"></span>'
+ .$lang['srv_settings_filter_edit_mode']. '</a>';
+ echo '<div class="clr"></div>';
+ echo '<div style="clear:both; padding:5px; height:1.2em">';
+ echo '<div style="width:50px; float:left; text-align:left; padding-right:15px;">';
+ echo '<i style="color:gray;text-align:right">'.$lang['srv_filter_vrednost'].'</i>';
+ echo '</div>';
+ echo '<div class="" style="width:250px; float:left; color: gray">';
+ echo '<i style="color:gray;">'.$lang['srv_filter_variabla'].'</i>';
+ echo '</div>';
+ echo '</div>';
+ # neodgovori
+ if ( count(self::$sysNeodgovori) > 0 ) {
+ foreach ( self::$sysNeodgovori as $key => $text) {
+ echo '<div id="sysfilter_div_'.$key.'" style="clear:both; padding-bottom:0px; height:1.2em;">';
+ echo '<div id="sysfilter_filter_'.$key.'" class="spr_sysFilter1" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">'.$key.'</div>';
+ echo '<div id="sysfilter_text_'.$key.'" class="spr_sysFilter1" style="width:250px; float:left;">'.$text.'</div>';
+ echo '</div>';
+ }
+ }
+ # neopredeljeni
+ if ( count(self::$sysNeopredeljeni) > 0 ) {
+ foreach ( self::$sysNeopredeljeni as $key => $text) {
+ echo '<div id="sysfilter_div_'.$key.'" style="clear:both; padding-bottom:0px; height:1.2em;">';
+ echo '<div id="sysfilter_filter_'.$key.'" class="spr_sysFilter2" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">'.$key.'</div>';
+ echo '<div id="sysfilter_text_'.$key.'" class="spr_sysFilter2" style="width:250px; float:left;">'.$text.'</div>';
+ echo '</div>';
+ }
+ }
+ # uporabniški
+ if ( count(self::$sysUserSet) > 0 ) {
+ foreach ( self::$sysUserSet as $key => $text) {
+ echo '<div id="sysfilter_div_'.$key.'" style="clear:both; padding-bottom:0px; height:1.2em;">';
+ echo '<div id="sysfilter_filter_'.$key.'" class="spr_sysFilter3" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">'.$key.'</div>';
+ echo '<div id="sysfilter_text_'.$key.'" class="spr_sysFilter3" style="width:250px; float:left;">'.$text.'</div>';
+ echo '</div>';
+ }
+ }
+ }
+
+ /** Prikaže edit mode za misinge
+ *
+ * @param unknown_type $mode
+ */
+ private static function sysMissingValuesChangeMode($mode = '') {
+ global $lang;
+ echo '<a href="/" onClick="sysMissingValuesChangeMode(\'normal\'); return false;">';
+ echo '<span class="faicon mapca anketa small"></span>'
+ .$lang['srv_settings_filter_view_mode']. '</a>';
+
+ echo '<div style="clear:both; padding:5px; height:1.2em">';
+ echo '<div style="width:50px; float:left; text-align:left; padding-right:15px;">';
+ echo '<i style="color:gray;">'.$lang['srv_filter_vrednost'].'</i>';
+ echo '</div>';
+ echo '<div class="" style="width:250px; float:left; color: gray">';
+ echo '<i style="color:gray;">'.$lang['srv_filter_variabla'].'</i>';
+ echo '</div>';
+ echo '</div>';
+ # neodgovori
+ if ( count(self::$sysNeodgovori) > 0 ) {
+ foreach ( self::$sysNeodgovori as $key => $text) {
+ echo '<div id="sysMissingValues_div_'.$key.'" style="clear:both; padding:5px; height:1.2em">';
+ echo ' <div id="sysMissingValues_filter_'.$key.'" class="" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">';
+ echo ' <input id="sysMissingValues_filter_input_'.$key.'" type="text" value="'.$key.'" title="'.$key.'" size="6" maxlength="6" onBlur="sysMissingValuesSave('.$key.')" autocomplete="off">';
+ echo ' </div>';
+ echo ' <div id="sysMissingValues_text_'.$key.'" class="" style="width:250px; float:left;">';
+ echo ' <input id="sysMissingValues_text_input_'.$key.'" type="text" value="'.$text.'" title="'.$text.'" size="45" maxlength="100" onBlur="sysMissingValuesSave('.$key.')" autocomplete="off">';
+ echo ' </div>';
+ echo '</div>';
+ }
+ }
+ # neopredeljeni
+ if ( count(self::$sysNeopredeljeni) > 0 ) {
+ foreach ( self::$sysNeopredeljeni as $key => $text) {
+ echo '<div id="sysMissingValues_div_'.$key.'" style="clear:both; padding:5px; height:1.2em">';
+ echo ' <div id="sysMissingValues_filter_'.$key.'" class="" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">';
+ echo ' <input id="sysMissingValues_filter_input_'.$key.'" type="text" value="'.$key.'" title="'.$key.'" size="6" maxlength="6" onBlur="sysMissingValuesSave('.$key.')" autocomplete="off">';
+ echo ' </div>';
+ echo ' <div id="sysMissingValues_text_'.$key.'" class="" style="width:250px; float:left;">';
+ echo ' <input id="sysMissingValues_text_input_'.$key.'" type="text" value="'.$text.'" title="'.$text.'" size="45" maxlength="100" onBlur="sysMissingValuesSave('.$key.')" autocomplete="off">';
+ echo ' </div>';
+ echo '</div>';
+ }
+ }
+ # User defined
+ if ( count(self::$sysUserSet) > 0 ) {
+ foreach ( self::$sysUserSet as $key => $text) {
+ echo '<div id="sysMissingValues_div_'.$key.'" style="clear:both; padding:5px; height:1.2em">';
+ echo ' <div id="sysMissingValues_filter_'.$key.'" style="width:50px; float:left; text-align:left; padding-right:15px; text-align:right;">';
+ echo ' <input id="sysMissingValues_filter_input_'.$key.'" type="text" value="'.$key.'" title="'.$key.'" size="6" maxlength="6" onBlur="sysMissingValuesSave('.$key.')" autocomplete="off">';
+ echo ' </div>';
+ echo ' <div id="sysMissingValues_text_'.$key.'" class="" style="width:250px; float:left;">';
+ echo ' <input id="sysMissingValues_text_input_'.$key.'" type="text" value="'.$text.'" title="'.$text.'" size="45" maxlength="100" onBlur="sysMissingValuesSave('.$key.')" autocomplete="off">';
+ echo ' </div>';
+ echo '<div id="sysMissingValues_edit_'.$key.'" class="" style="width:100px; float:left;">';
+ echo '<a href="#" onClick="sysMissingValuesDelete('.$key.'); return false;">';
+ echo '<img id="sysMissingValues_delete_'.$key.'" src="img_0/delete_red.png" alt="'.$lang['srv_filtri_izbrisi_filter'].'" style="vertical-align:text-bottom " />';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+ }
+ }
+ echo '<div id="sysMissingValues_new" style="padding-top:10px;">';
+ if ($mode == 'new')
+ {
+ echo '<div id="sysMissingValues_div_add" style="clear:both; padding:5px; height:1.2em">';
+ echo '<div id="sysMissingValues_filter_add" class="" style="width:50px; float:left; text-align:left; padding-right:15px;">';
+ echo '<input id="sysMissingValues_filter_input_add" type="text" value="'.$filter['filter'].'" title="'.$filter['filter'].'" size="6" maxlength="6" autocomplete="off">';
+ echo '</div>';
+ echo '<div id="sysMissingValues_text_add" class="" style="width:250px; float:left;">';
+ echo '<input id="sysMissingValues_text_input_add" type="text" value="'.$filter['text'].'" title="'.$filter['text'].'" size="45" maxlength="100" autocomplete="off">';
+ echo '</div>';
+ echo '<div class="" style="width:50px; float:left;">';
+ echo '<a href="#" onClick="sysMissingValuesAdd(); return false;"><img id="sysMissingValues_add_img" src="icons/icons/accept.png" alt="'.$lang['srv_novfilter'].'" style="vertical-align:text-bottom " /></a>';
+ echo '</div>';
+ } else {
+ echo '<a href="#" onClick="sysMissingValuesChangeMode(\'new\'); return false;"><span class="faicon add small"></span> '.$lang['srv_novfilter'].'</a>';
+ }
+ echo '</div>';
+
+ // pohendlamo error: duplicate
+ if (self::$mySqlErrNo == 1062)
+ {
+ echo '<div id="error" class="red">';
+ echo $lang['srv_duplicateEntry'];
+ echo '</div>';
+ }
+ }
+
+ /** Doda sistemski missing
+ *
+ * @param $filter
+ * @param $text
+ * @param $fid
+ */
+ static function AddSystemFilters( $filter, $text, $fid) {
+ global $global_user_id;
+ self::$mySqlErrNo = null;
+ $insertString = "INSERT INTO srv_sys_filters (fid,filter,text,uid,type) ".
+ "VALUES ('".$fid."', '".$filter."', '".$text."', '".$global_user_id."', '3');";
+ $mySqlResult = sisplet_query($insertString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+
+ /** Izbriše sistemski missing
+ *
+ * @param $id
+ */
+ static function DeleteSystemFilters( $id) {
+ self::$mySqlErrNo = null;
+ $deleteString = "DELETE FROM srv_sys_filters WHERE filter = '".$id."' AND type = '3'";
+ $mySqlResult = sisplet_query($deleteString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+
+ /** Shrani sistemski missing
+ *
+ * @param $id
+ * @param $filter
+ * @param $text
+ */
+ static function SaveSystemFilters($id,$filter,$text) {
+ self::$mySqlErrNo = null;
+ $updateString = "UPDATE srv_sys_filters " .
+ "SET filter = '".$filter."', text = '".$text."' ".
+ "WHERE filter = '".$id."'";
+ $mySqlResult = sisplet_query($updateString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+
+ /** Vrne manjkajoče vrednosti za anketo
+ * # če ni nastavljeno na nivoju ankete vrne sistemske nastavitve
+ *
+ */
+ static public function GetUnsetValuesForSurvey($type = array(2,3)) {
+ # TODO preverit ali je na nivoju ankete če ne na nivoju sistema
+ return self::GetSystemFlterByType($type);
+ }
+
+ /** Vrne neodgovore za anketo
+ * # če ni nastavljeno na nivoju ankete vrne sistemske nastavitve
+ *
+ */
+ static public function GetMissingValuesForSurvey($type = array(1)) {
+ # TODO preverit ali je na nivoju ankete če ne na nivoju sistema
+ return self::GetSystemFlterByType($type);
+ }
+ static public function GetSurveyMissingValues($anketa_id = null) {
+ if ($anketa_id == null) {
+
+ $anketa_id = self::$anketa;
+ }
+ $result = array();
+
+ if ($anketa_id != null && $anketa_id > 0) {
+
+ $stringSurveyMissingValues = "SELECT * FROM srv_missing_values WHERE sid ='".$anketa_id ."' AND active = '1' ORDER BY type ASC, systemValue DESC,value ASC";
+ $sqlSurveyMissingValues = sisplet_query($stringSurveyMissingValues);
+
+ while ( $row = mysqli_fetch_assoc($sqlSurveyMissingValues) ) {
+ $result[$row['type']][] = array('value'=>$row['value'],'text'=> $row['text'],'defSysVal'=>$row['systemValue']);
+ }
+ }
+ return $result;
+
+ }
+
+ static public function displayMissingForSurvey() {
+ global $lang;
+
+ self::displayLeftNavigation('start');
+
+ $si_mv = SurveyInfo::getInstance()->getSurveyColumn('missing_values_type') == 1 ? '1' : '0';
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_survey_missing_title'].':</legend>';
+ $_survey_missing_values = self::GetSurveyMissingValues();
+
+ if (self::$mySqlErrNo == '1062') {
+ echo '<br/><span class="red">'.$lang['srv_survey_missing_error1'].'</span>';
+ }
+
+ if ( count($_survey_missing_values) > 0 ) {
+ echo '<table class="mv_tbl">';
+ echo '<tr>';
+
+ echo '<th style="width:50px;">';
+ echo ' <i style="color:gray;text-align:right">'.$lang['srv_filter_vrednost'].'</i>';
+ echo '</th>';
+ echo '<th style="width:250px;">';
+ echo ' <i style="color:gray;">'.$lang['srv_label'].'</i>';
+ echo '</th>';
+ echo '<th style="width:20px;">';
+ echo ' <i style="color:gray;text-align:right">'.'</i>';
+ echo '</th>';
+ echo '<th>&nbsp;</th>';
+ echo '</tr>';
+ foreach ( $_survey_missing_values as $type => $type_missing_values) {
+ foreach ($type_missing_values AS $type_missing_value) {
+ $key = $type_missing_value['value'];
+ $text = $type_missing_value['text'];
+ $sysValue = $type_missing_value['defSysVal'];
+ echo '<tr class="spr_sysFilter'.$type.'">';
+
+ echo '<td>';
+ echo '<input name="mv_value_input" id="mv_value_'.$type.'_'.$key.'" type="text" value="'.$key.'" class="mv_value_input">';
+ echo '</td>';
+ echo '<td>';
+ echo '<input name="mv_text_input" id="mv_text_'.$type.'_'.$key.'" type="text" value="'.$text.'" class="mv_text_input">';
+ echo '</td>';
+ echo '<td class="anl_ac">';
+ if ($sysValue != null) {
+ echo '['.$sysValue.']';
+ }
+ echo '</td>';
+ echo '<td>';
+ echo '&nbsp;<span class="faicon remove smaller orange pointer" name="mv_delete_img" id="mv_img_'.$type.'_'.$key.'" title="'.$lang['srv_filtri_izbrisi_filter'].'"/>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ }
+ echo '<tr class="spr_sysFilter3">';
+ echo '<td>&nbsp;</td>';
+ echo '<td>&nbsp;</td>';
+ echo '<td>';
+ echo '&nbsp;<span name="mv_add_img" id="mv_add_img" class="faicon add icon-blue smaller pointer"></span>';
+ echo '</td>';
+ echo '</tr>';
+ echo '</table>';
+ }
+ if ($si_mv == '0') {
+ echo '<span class="mv_link_disabled">'.$lang['srv_survey_missing_default'].'</span><br/>';
+ } else {
+ echo '<span id="link_use_sistem_mv" onclick="useSystemMissingValues(); return false;" class="as_link">'.$lang['srv_survey_missing_default'].'</span><br/>';
+ }
+ echo '</div>';
+
+ echo '</fieldset>';
+ echo '<br class="clr" />';
+ echo '</div>';
+ self::displayLeftNavigation();
+ }
+
+ /* shranimo tip missingov za anketo
+ *
+ */
+ static private function saveMisingValueTypeForSurvey() {
+ if (self::$anketa) {
+ $missing_values_type = (isset($_POST['missing_values_type']) && $_POST['missing_values_type'] == '1') ? '1' : '0';
+ $updateString = "UPDATE srv_anketa SET missing_values_type = '".$missing_values_type."' WHERE id = '".self::$anketa."'";
+ $mySqlResult = sisplet_query($updateString);
+ }
+ #uprejtamo timestamp
+ Common::updateEditStamp();
+
+ SurveyInfo::getInstance()->resetSurveyData();
+ }
+ /* Na nivoju ankete nastavimo enake majkajoče vrednosti kot so sistemske
+ *
+ */
+ static private function useSystemMissingValues() {
+ if (self::$anketa) {
+ # najprej pobrišemo vse missinge ki so nastavljeni za obstoječo anketo
+ $deleteString = "DELETE FROM srv_missing_values WHERE sid = '".self::$anketa."'";
+ sisplet_query($deleteString);
+
+ # nato prekopiramo sistemske missinge v anketo
+ $sf_1 = self::GetSystemFlterByType(array(1),true);
+ $sf_2 = self::GetSystemFlterByType(array(2),true);
+ $sf_3 = self::GetSystemFlterByType(array(3),true);
+ if ( ( count($sf_1) + count($sf_2)+ count($sf_3) ) > 0) {
+
+ $insertString = "INSERT INTO srv_missing_values (sid,type,value,text,active,systemValue) VALUES ";
+
+ $prefix = '';
+ foreach ($sf_1 AS $key => $value) {
+ $insertString.= $prefix."( '".self::$anketa."', '1', '$key', '".addslashes($value)."', '1','$key')";
+ $prefix = ', ';
+ }
+ foreach ($sf_2 AS $key => $value) {
+ $insertString.= $prefix."( '".self::$anketa."', '2', '$key', '".addslashes($value)."', '1','$key')";
+ $prefix = ', ';
+ }
+ foreach ($sf_3 AS $key => $value) {
+ $insertString.= $prefix."( '".self::$anketa."', '3', '$key', '".addslashes($value)."', '1','$key')";
+ $prefix = ', ';
+ }
+
+ $mySqlResult = sisplet_query($insertString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+ #uprejtamo timestamp
+ Common::updateEditStamp();
+ }
+
+ }
+
+ private static function saveSurveyMissingValue() {
+ list($_mv, $_what, $_type, $_old_value) = explode('_',$_POST['el_id']);
+ $new_value = str_replace('_','',$_POST['new_value']);
+ if ( isset($_type) && $_type != '' &&
+ ( $_what == 'text' || $_what == 'value' ) &&
+ isset($_old_value) && $_old_value != '' && is_numeric($_old_value) &&
+ isset($new_value) && $new_value != '' && is_numeric($new_value) &&
+ isset(self::$anketa) && self::$anketa > 0) {
+ $updateString = "UPDATE srv_missing_values " .
+ "SET $_what = '".$new_value."' ".
+ "WHERE sid = '".self::$anketa."' AND type='".$_type."' AND value = '".$_old_value."'";
+ $mySqlResult = sisplet_query($updateString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+
+ # updejtamo še srv_vrednost, če smo slučajno imeli že nastavljen missing
+ $selStr = "SELECT v.id FROM srv_vrednost v, srv_spremenljivka s, srv_grupa g WHERE v.spr_id=s.id AND s.gru_id=g.id AND g.ank_id='".self::$anketa."' AND v.other='$_old_value'";
+ list($vre_id) = mysqli_fetch_row(sisplet_query($selStr));
+ if ((int)$vre_id > 0) {
+ $updateVreString = "UPDATE srv_vrednost SET variable = '$new_value', other='$new_value' WHERE id ='$vre_id'";
+ $sqlVreResult = sisplet_query($updateVreString);
+ self::$mySqlErrNo = mysqli_errno($GLOBALS['connect_db']);
+ }
+ #uprejtamo timestamp
+ Common::updateEditStamp();
+
+ }
+ }
+
+ private static function deleteMissingForSurvey() {
+ list($_mv, $_what, $_type, $_value) = explode('_',$_POST['delete_id']);
+ if ( isset($_type) && $_type != '' &&
+ $_what == 'img' &&
+ isset($_value) && $_value != '' &&
+ isset(self::$anketa) && self::$anketa > 0) {
+
+ $deleteString = "DELETE FROM srv_missing_values " .
+ "WHERE sid = '".self::$anketa."' AND type='".$_type."' AND value = '".$_value."'";
+ $mySqlResult = sisplet_query($deleteString);
+ #uprejtamo timestamp
+ Common::updateEditStamp();
+
+ }
+ }
+
+ private static function SetUpSurvyeMissingValues() {
+ self::useSystemMissingValues();
+ $updateString = "UPDATE srv_anketa SET missing_values_type = '1' WHERE id = '".self::$anketa."'";
+ $mySqlResult = sisplet_query($updateString);
+ SurveyInfo::getInstance()->resetSurveyData();
+
+ #uprejtamo timestamp
+ Common::updateEditStamp();
+
+ }
+
+ private function displayAddMissingValue() {
+ global $lang;
+
+ echo '<div id="mv_add_quick">';
+ echo '<span>'.$lang['srv_filter_add_note'].'</span>';
+ echo '<br /><br />';
+ echo '<table class="mv_tbl">';
+ echo '<tr>';
+ echo '<th style="width:50px;">';
+ echo ' <i style="color:gray;text-align:right">'.$lang['srv_filter_vrednost'].'</i>';
+ echo '</th>';
+ echo '<th style="width:250px;">';
+ echo ' <i style="color:gray;">'.$lang['srv_filter_variabla'].'</i>';
+ echo '</th>';
+ echo '<th>&nbsp;</th>';
+ echo '</tr>';
+
+ echo '<tr>';
+ echo '<th style="width:50px;">';
+ echo '<input id="mv_add_filter" type="text" size="6" maxlength="6" autocomplete="off">';
+ echo '</th>';
+ echo '<th style="width:250px;">';
+ echo '<input id="mv_add_text" type="text" size="45" maxlength="100" autocomplete="off">';
+ echo '</th>';
+ echo '</tr>';
+ echo '</table>';
+ echo '<br class="clr" />';
+ echo '<span class="floatRight spaceRight buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="addSurveyMissingValueConfirm(); return false;"><span>'.$lang['add'].'</span></a></span>';
+ echo '<span class="floatRight spaceRight buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="addSurveyMissingValueCancel(); return false;"><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</div>';
+ }
+
+ private function addSurveyFilters() {
+ if (isset($_POST['mv_add_filter']) && trim($_POST['mv_add_filter']) != ""
+ && isset($_POST['mv_add_text']) && trim($_POST['mv_add_text']) != "") {
+ $insertString = "INSERT INTO srv_missing_values (sid,type,value,text,active) VALUES ( '".self::$anketa."', '3', '".$_POST['mv_add_filter']."', '".addslashes($_POST['mv_add_text'])."', '1') ON DUPLICATE KEY UPDATE value='".$_POST['mv_add_filter']."', text='".addslashes($_POST['mv_add_text'])."', active='1'";
+
+ $mySqlResult = sisplet_query($insertString);
+
+ if (!$mySqlResult) {
+ echo 'Napaka! ';
+ return;
+ } else {
+ #updejtamo timestamp
+ Common::updateEditStamp();
+ echo 'true';
+ return;
+ }
+ } else {
+ echo 'Napaka! Polja ne smejo biti prazna';
+ return;
+
+ }
+ }
+
+ private static function displayLeftNavigation($what=null) {
+ if ($_REQUEST['a'] != 'missing') {
+ if ($what == 'start') {
+ $sa=new SurveyAdmin(self::$anketa);
+ echo '<span class="floatLeft">';
+ echo '<div id="globalSetingsLinks" class="baseSettings">';
+ $sa->showGlobalSettingsLinks();
+ echo '</div>';
+ echo '<br class="clr"/><br/>';
+ echo '<div id="globalSetingsLinks" class="aditionalSettings">';
+ $sa->showAdditionalSettingsLinks();
+ echo '</div>';
+ echo '<br class="clr"/>';
+ echo '</span>';
+ echo '<div id="globalSetingsList" >';
+
+ } else {
+ echo '</div>';
+ }
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyMobile.php b/admin/survey/classes/class.SurveyMobile.php
new file mode 100644
index 0000000..55ce2e7
--- /dev/null
+++ b/admin/survey/classes/class.SurveyMobile.php
@@ -0,0 +1,1142 @@
+<?php
+
+/**
+ *
+ * Class ki skrbi za komunikacijo z mobilno aplikacijo
+ *
+ */
+class SurveyMobile {
+
+ private $anketa; // id ankete
+
+ function __construct($anketa = 0) {
+ global $lang;
+
+ if ((int) $anketa > 0) {
+
+ $this->anketa = $anketa;
+ }
+ }
+
+ // Vrne string zadnje verzije mobilne app
+ //!! to je samo nek ostanek, ki se trenutno rabi samo zato, da se pac gre cez login in da po loginu klice neko funkcijo
+ public function getMobileVersion() {
+
+ /* $sql = sisplet_query("SELECT value FROM misc WHERE what='mobileApp_version'");
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_array($sql);
+ return $row['value'];
+ }
+ else
+ return 0; */
+
+ return 'ABORTED';
+ }
+
+ // Preveri username in pass ce sta ok za login
+ public function checkLogin($pass, $uname) {
+ global $lang;
+ global $pass_salt;
+
+ $login_check = false;
+
+ $sql = sisplet_query("SELECT id, pass, status FROM users WHERE email='" . $uname . "'");
+ if (mysqli_num_rows($sql) > 0) {
+ $row = mysqli_fetch_array($sql);
+
+ //if($row['pass'] == base64_encode(bin2hex(hash(SHA256, $pass.$pass_salt))))
+ if ($row['pass'] == base64_encode(hash('SHA256', $pass . $pass_salt)))
+ $login_check = true;
+ }
+
+ if ($login_check && $row['id'] > 0 && $row['status'] > 0)
+ return $row['id'];
+ else if ($login_check && $row['id'] > 0 && $row['status'] == 0)
+ return -1;
+ else
+ return 0;
+ }
+
+ // Login preko google account api
+ public function googleLogin($user_email) {
+
+ if ($user_email != '') {
+ $res = sisplet_query("SELECT id, pass FROM users WHERE email='" . $user_email . "'");
+
+ // Je noter, ga samo prijavim...
+ if (mysqli_num_rows($res) > 0) {
+ $r = mysqli_fetch_row($res);
+ return $r[0];
+ }
+ // Ni se registriran, ga je potrebno dodati na prijavno formo
+ else {
+ // geslo med 00000 in zzzzz
+ $pass = base_convert(mt_rand(0x19A100, 0x39AA3FF), 10, 36);
+
+ $EncPass = base64_encode((hash('SHA256', $pass)));
+ $fn = explode("@", $user_email);
+
+ sisplet_query("INSERT INTO users (name, surname, email, pass, lang) VALUES ('" . $fn[0] . "', '', '" . $user_email . "', '" . $EncPass . "', '" . (isset($_GET['regFromEnglish']) && $_GET['regFromEnglish'] == "1" ? '2' : '1') . "')");
+ $uid = mysqli_insert_id($GLOBALS['connect_db']);
+
+ sisplet_query("INSERT INTO oid_users (uid) VALUES ('$uid')");
+
+ return $uid;
+ }
+ } else
+ return 0;
+ }
+
+ // update vrstnega reda vprasanj
+ public function updateQuestionOrder($ank_id, $data) {
+
+ if (!isset($data['to_place']) && !isset($data['que_id'])){
+ $json_array['error'] = 'Question ID or order number missing';
+ return $json_array;
+ }
+
+ //poizvedi, koliko je vseh spremenljivk
+ $sql = sisplet_query("SELECT MAX(vrstni_red) FROM srv_branching WHERE ank_id = '$ank_id'");
+ $row = mysqli_fetch_assoc($sql);
+ //ali se da spremenljivko na zadnje mesto? ce da, nastavi page_break = 2
+ $page_break = $row['MAX(vrstni_red)'] == $data['to_place'] ? 2 : 0;
+
+ //poizvedi, ali se premakne vprasanje navzgor ali navzdol
+ //to se rabi, ker ce se prestavi navzgor, je treba odsteti vrstni_red za 1
+ //zato, ker se v branchingu lahko razvrsca med vsako spremenljivko, pred prvo ter za zadnjo - to je skupaj vse +1
+ $sql = sisplet_query("SELECT vrstni_red FROM srv_branching WHERE element_spr = '" . $data['que_id'] . "'");
+ $row = mysqli_fetch_assoc($sql);
+ $vrstni_red = $row['vrstni_red'] >= $data['to_place'] ? $data['to_place'] - 1 : $data['to_place'];
+
+ $ba = new BranchingAjax($ank_id);
+ $json_array = $ba->ajax_accept_droppable($data['que_id'], $vrstni_red, $page_break, true);
+
+ if (empty($json_array))
+ $json_array['note'] = 'Question order updated';
+
+ Common::getInstance()->updateEditStamp();
+ Common::prestevilci();
+
+ return $json_array;
+ }
+
+ //MAZA
+ /**
+ * Check login data for MAZA modul app
+ * @param boolean $loginAction - true if action is only to check login, false otherwise
+ * @param type $identifier - identifier code for maza app user
+ * @param type $id_server - id of maza app user on server
+ * @return if $loginAction is true, return object with data, otherwise return id of maza app user
+ */
+ public function checkMazaLogin($loginAction, $identifier, $id_server, $registration_id) {
+ global $lang;
+ global $pass_salt;
+
+ $login_check = false;
+ $id = 0;
+ $response;
+
+ if ($identifier == 'no_identifier') {
+
+ $maza = new MAZA();
+ $newuser = $maza -> insertNewUsers('self');
+
+ $login_check = true;
+ $id = $newuser['id'];
+
+ $response['note'] = "login OK";
+ $response['identifier'] = $newuser['identifier'];
+ $response['id_server'] = $newuser['id'];
+ $response['update'] = 'deviceInfo';
+ }
+ elseif($identifier == 'no_login'){
+ $response['note'] = "login OK";
+ }
+ else {
+ //$salted_identifier = base64_encode(hash(SHA256, $identifier . $pass_salt));
+ $check_id = '';
+ $does_id_serever_exist = false;
+
+ if(!$loginAction || ($loginAction && (isset($id_server) && $id_server!=''))){
+ $check_id = "id='".$id_server."' AND ";
+ $does_id_serever_exist = true;
+ }
+
+ $sql = sisplet_query("SELECT id, deviceInfo FROM maza_app_users WHERE ".$check_id."identifier='" . $identifier . "'");
+ if (mysqli_num_rows($sql) > 0) {
+ $row = mysqli_fetch_array($sql);
+ $login_check = true;
+ $id = $row['id'];
+ $deviceInfo = $row['deviceInfo'];
+
+ //update datetime_last_active
+ $maza = new MAZA();
+ $maza -> maza_update_user_active($id, $registration_id);
+
+ if(!isset($deviceInfo))
+ $response['update'] = 'deviceInfo';
+ if(!$does_id_serever_exist){
+ $response['identifier'] = $identifier;
+ $response['id_server'] = $id;
+ }
+
+ $response['note'] = "login OK";
+ }
+
+ //if only login
+ if($loginAction){
+ //update datetime_started in table maza_user_srv_access to set datetime of user linking to his survey is already existing (generated users)
+ sisplet_query("UPDATE maza_user_srv_access SET datetime_started = NOW() WHERE maza_user_id = '$id' AND datetime_started IS NULL;");
+ }
+ }
+
+ if ($login_check && $id > 0)
+ return $loginAction ? $response : $id;
+ else
+ return 0;
+ }
+
+ /**
+ * Udates device info with sensors
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaUpdateDeviceInfo($data) {
+ global $global_user_id;
+
+ $gotData = json_decode($data);
+ $sqldi = sisplet_query("SELECT deviceInfo FROM maza_app_users WHERE id = '$global_user_id'", 'obj');
+
+ if($sqldi->deviceInfo[0] == '{'){
+ $odlInfo = json_decode($sqldi->deviceInfo);
+
+ $lastInfo = end($odlInfo)->device_info;
+ $gotInfo = $gotData->device_info;
+
+ if($lastInfo->os_version == $gotInfo->os_version && $lastInfo->release == $gotInfo->release &&
+ $lastInfo->serial == $gotInfo->serial){
+ $json_array['note'] = 'Device info already up to date';
+ }
+ else{
+ $temptime = time();
+ $odlInfo->$temptime = $gotData;
+ $newInfo = $odlInfo;
+ sisplet_query("UPDATE maza_app_users SET deviceInfo = '" . json_encode($newInfo) . "' WHERE id = '$global_user_id'");
+ $json_array['note'] = 'Device info added';
+ }
+ }
+ else{
+ $newInfo = array(time()=>$gotData);
+ sisplet_query("UPDATE maza_app_users SET deviceInfo = '" . json_encode($newInfo) . "' WHERE id = '$global_user_id'");
+ $json_array['note'] = 'Device info inserted';
+ }
+
+ return $json_array;
+ }
+
+ /**
+ * Get all alarms of surveys for this user
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaGetAlarms() {
+ global $global_user_id;
+
+ $sql_arr = sisplet_query("SELECT ma.alarm_notif_title, ma.alarm_notif_message, ma.repeat_by AS alarm_repeat_by, "
+ . "ma.alarm_notif_sound, ma.time_in_day AS alarm_time_in_day, ma.day_in_week AS alarm_day_in_week, "
+ . "ma.every_which_day AS alarm_every_which_day, mr.every_which_day AS repeater_every_which_day, "
+ . "mr.time_in_day AS repeater_time_in_day, mr.repeat_by AS repeater_repeat_by, ma.ank_id, an.url, an.naslov, "
+ . "mr.day_in_week AS repeater_day_in_week, mr.datetime_start, mr.datetime_end, MAX(sa.srv_version_datetime) AS last_answered_version_datetime, "
+ . "CASE WHEN sa.datetime_started < mr.datetime_start THEN mr.datetime_start ELSE sa.datetime_started END AS datetime_user_started FROM maza_srv_alarms AS ma "
+ . "LEFT JOIN (SELECT sua.ank_id, sua.maza_user_id, sua.datetime_started, su.srv_version_datetime FROM maza_user_srv_access AS sua "
+ . "LEFT JOIN (SELECT msu.srv_version_datetime, msu.maza_user_id, su.ank_id FROM maza_srv_users AS msu "
+ . "LEFT JOIN (SELECT id, ank_id FROM srv_user) AS su ON su.id=msu.srv_user_id) AS su "
+ . "ON sua.maza_user_id=su.maza_user_id AND su.ank_id=sua.ank_id) AS sa ON ma.ank_id = sa.ank_id "
+ . "LEFT JOIN maza_srv_repeaters AS mr ON mr.ank_id = sa.ank_id "
+ . "LEFT JOIN (SELECT id, url, naslov FROM srv_anketa) AS an ON an.id = sa.ank_id "
+ . "WHERE sa.maza_user_id='$global_user_id' AND mr.repeater_on='1' GROUP BY ma.ank_id", 'array');
+
+ $alarms = array();
+ foreach ($sql_arr as $row) {
+ $last_answered_version_datetime = ($row['last_answered_version_datetime']) ? $row['last_answered_version_datetime'] : null;
+
+ $alarm = array('title' => $row['alarm_notif_title'], 'message' => $row['alarm_notif_message'], 'ank_id' => $row['ank_id'], 'sound' => $row['alarm_notif_sound'], 'link' => $row['url'].'a/'.$row['ank_id'], 'srv_title' => $row['naslov'],
+ 'repeat' => array("repeat_by" => $row['alarm_repeat_by'], "time_in_day" => json_decode($row['alarm_time_in_day']), "day_in_week" => json_decode($row['alarm_day_in_week']),
+ "every_which_day" => $row['alarm_every_which_day']),
+ 'repeater' => array("repeat_by" => $row['repeater_repeat_by'], "time_in_day" => json_decode($row['repeater_time_in_day']), "day_in_week" => json_decode($row['repeater_day_in_week']),
+ "every_which_day" => $row['repeater_every_which_day'], "datetime_start" => $row['datetime_start'], "datetime_end" => $row['datetime_end'],
+ "last_answered_version_datetime" => $last_answered_version_datetime, "datetime_user_started" => $row['datetime_user_started']));
+ array_push($alarms, $alarm);
+ }
+ return $alarms;
+ }
+
+ /**
+ * Get all geofences of surveys for this user
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaGetGeofences() {
+ global $global_user_id;
+
+ $sql_arr = sisplet_query("SELECT mg.id, mg.ank_id, mg.geofence_on, mg.lat, mg.lng, mg.radius, mg.address, mg.name, mg.notif_title, mg.trigger_survey, "
+ . "mg.notif_message, mg.notif_sound, mg.on_transition, mg.after_seconds, mg.location_triggered, an.url, an.naslov FROM maza_srv_geofences AS mg "
+ . "LEFT JOIN (SELECT ank_id, maza_user_id FROM maza_user_srv_access) AS sua ON mg.ank_id = sua.ank_id "
+ . "LEFT JOIN (SELECT id, url, naslov, active FROM srv_anketa) AS an ON an.id = sua.ank_id "
+ . "WHERE sua.maza_user_id='$global_user_id' AND mg.geofence_on='1' AND an.active='1'", 'array');
+
+ //array of all surveys with geofences
+ $surveys = array();
+ //object of one survey with its geofences
+ $survey = array();
+ //array of geofences of one survey
+ $geofences = array();
+ //temporary survey id
+ $srv_id_temp = -1;
+
+ //loop trough geofences
+ foreach ($sql_arr as $row) {
+ //if survey id is not equal to previous, create new survey array
+ if($srv_id_temp != $row['ank_id']){
+ //ingor first time
+ if($srv_id_temp > -1){
+ $survey['geofences'] = $geofences;
+ array_push($surveys, $survey);
+ }
+
+ //set survey array
+ $survey = array('ank_id' => $row['ank_id'], 'link' => $row['url'].'a/'.$row['ank_id'], 'srv_title' => $row['naslov']);
+ //reset geofences
+ $geofences = array();
+ //set temporary survey id
+ $srv_id_temp = $row['ank_id'];
+ }
+
+ //set geofence array
+ $geofence = array('id' => $row['id'], 'lat' => $row['lat'], 'lng' => $row['lng'], 'radius' => $row['radius'],
+ 'address' => $row['address'], 'notif_title' => $row['notif_title'], 'notif_message' => $row['notif_message'],
+ 'notif_sound' => $row['notif_sound'], 'on_transition' => $row['on_transition'], 'name' => $row['name'],
+ 'after_seconds' => $row['after_seconds'], 'location_triggered' => $row['location_triggered'], 'trigger_survey' => $row['trigger_survey']);
+
+ //add geofence to geofences array of one survey
+ array_push($geofences, $geofence);
+ }
+ if(sizeof($sql_arr) > 0){
+ //add geofences to last survey
+ $survey['geofences'] = $geofences;
+ //add last survey to surveys aray
+ array_push($surveys, $survey);
+ }
+
+ return $surveys;
+ }
+
+ /**
+ * Get all activities of surveys for this user
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaGetActivities() {
+ global $global_user_id;
+
+ $sql_arr = sisplet_query("SELECT ma.id, ma.ank_id, ma.activity_on, ma.notif_title, ma.notif_message, ma.notif_sound, "
+ . "ma.activity_type, ma.after_seconds, ank.naslov, ank.id as ank_id, ank.url, sua.nextpin_tracking_permitted FROM maza_srv_activity AS ma "
+ . "LEFT JOIN (SELECT ank_id, maza_user_id, nextpin_tracking_permitted FROM maza_user_srv_access) AS sua ON ma.ank_id = sua.ank_id "
+ . "LEFT JOIN (SELECT id, url, naslov FROM srv_anketa) AS ank ON ma.ank_id = ank.id "
+ . "WHERE sua.maza_user_id='$global_user_id' AND ma.activity_on='1'", 'array');
+
+ //array of all surveys with activities
+ $surveys = array();
+ //object of one survey with its activities
+ $survey = array();
+
+ //loop trough activities
+ foreach ($sql_arr as $row) {
+ //set survey array
+ $survey = array('ank_id' => $row['ank_id'], 'link' => $row['url'].'a/'.$row['ank_id'], 'srv_title' => $row['naslov'],
+ 'notif_title' => $row['notif_title'], 'notif_message' => $row['notif_message'], 'notif_sound' => $row['notif_sound'],
+ 'activity' => array('id' => $row['id'], 'activity_type' => $row['activity_type'], 'after_seconds' => $row['after_seconds']), 'permitted'=>$row['nextpin_tracking_permitted']);
+
+ array_push($surveys, $survey);
+ }
+ return $surveys;
+ }
+
+ /**
+ * Get all tracking of surveys for this user
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaGetTracking() {
+ global $global_user_id;
+
+ $sql_arr = sisplet_query("SELECT ank.id, ma.ank_id, ma.tracking_on, ma.activity_recognition, ma.tracking_accuracy, ma.interval_wanted, "
+ . "ma.interval_fastes, ma.displacement_min, ma.ar_interval_wanted, ank.naslov, ank.url, sua.tracking_permitted FROM maza_srv_tracking AS ma "
+ . "LEFT JOIN (SELECT ank_id, maza_user_id, tracking_permitted FROM maza_user_srv_access) AS sua ON ma.ank_id = sua.ank_id "
+ . "LEFT JOIN (SELECT id, url, naslov, active FROM srv_anketa) AS ank ON ma.ank_id = ank.id "
+ . "WHERE sua.maza_user_id='$global_user_id' AND ma.tracking_on='1' AND ank.active='1'", 'array');
+
+ //array of all surveys with tracking
+ $surveys = array();
+ //object of one survey with its tracking
+ $survey = array();
+
+ //loop trough trackings
+ foreach ($sql_arr as $row) {
+ //set survey array
+ $survey = array('ank_id' => $row['ank_id'], 'link' => $row['url'].'a/'.$row['ank_id'], 'srv_title' => $row['naslov'],
+ 'tracking' => array('id' => $row['id'], 'activity_recognition' => $row['activity_recognition'], 'tracking_accuracy' => $row['tracking_accuracy'],
+ 'displacement_min' => $row['displacement_min'], 'interval_wanted' => $row['interval_wanted'], 'interval_fastes' => $row['interval_fastes'],
+ 'ar_interval_wanted' => $row['ar_interval_wanted'], 'permitted'=>$row['tracking_permitted']));
+
+ array_push($surveys, $survey);
+ }
+ return $surveys;
+ }
+
+ /**
+ * Get all data entries of surveys for this user
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaGetEntries() {
+ global $global_user_id;
+
+ $sql_arr = sisplet_query("SELECT ank.id, me.ank_id, me.entry_on, me.location_check, ank.naslov, ank.url FROM maza_srv_entry AS me "
+ . "LEFT JOIN (SELECT ank_id, maza_user_id FROM maza_user_srv_access) AS sua ON me.ank_id = sua.ank_id "
+ . "LEFT JOIN (SELECT id, url, naslov, active FROM srv_anketa) AS ank ON sua.ank_id = ank.id "
+ . "WHERE sua.maza_user_id='$global_user_id' AND me.entry_on='1' AND ank.active='1'", 'array');
+
+ //array of all surveys with tracking
+ $surveys = array();
+ //object of one survey with its tracking
+ $survey = array();
+
+ //loop trough trackings
+ foreach ($sql_arr as $row) {
+ //set survey array
+ $survey = array('ank_id' => $row['ank_id'], 'link' => $row['url'].'a/'.$row['ank_id'], 'srv_title' => $row['naslov'],
+ 'entry' => array('id' => $row['id'], 'location_check' => $row['location_check']));
+
+ array_push($surveys, $survey);
+ }
+ return $surveys;
+ }
+
+ /**
+ * Get all locations and AR of user
+ * @global type $global_user_id
+ * @return array
+ */
+ public function mazaGetMyLocations() {
+ global $global_user_id;
+
+ //array of locations of user
+ $sql_loc = sisplet_query("SELECT lat, lng, provider, UNIX_TIMESTAMP(timestamp) as timestamp, "
+ . "accuracy, altitude, bearing, speed, vertical_acc, bearing_acc, speed_acc, extras, is_mock "
+ . "FROM maza_user_locations WHERE maza_user_id='$global_user_id' ORDER BY timestamp ASC", 'array');
+
+ //array of all AR of user
+ $sql_ar = sisplet_query("SELECT UNIX_TIMESTAMP(timestamp) as timestamp, in_vehicle, on_bicycle, "
+ . "on_foot, still, unknown, tilting, running, walking FROM maza_user_activity_recognition "
+ . "WHERE maza_user_id='$global_user_id' ORDER BY timestamp ASC", 'array');
+
+ return array("locations" => $sql_loc, "ar" => $sql_ar);
+ }
+
+ /**
+ * Update tracking log for this user
+ * @global type $global_user_id
+ * @param type $jsonArray - array of logs to save
+ */
+ public function mazaUpdateTrackingLog($jsonArray) {
+ global $global_user_id;
+
+ $update = "";
+ foreach ($jsonArray as $obj) {
+ $date = new DateTime();
+ $date->setTimestamp($obj['tsSec']);
+
+ $update .= $obj['value'] . " " . $obj['event'] . " " . $date->format('Y-m-d H:i:s') . "; ";
+ }
+ sisplet_query("UPDATE maza_app_users SET tracking_log = CONCAT(tracking_log, '" . $update . "') WHERE id = '$global_user_id'");
+ }
+
+ /**
+ * Insert tracking locations for this user
+ * @global type $global_user_id
+ * @param type $jsonArray - array of locations to insert
+ * @param type $triggered_geofence_id - ID of triggered geofence to pin location on
+ */
+ public function mazaInsertTrackingLocations($jsonArray, $triggered_geofence_id=null) {
+ global $global_user_id;
+
+ $querryFirst = $querry = "INSERT INTO maza_user_locations (maza_user_id, lat, lng, provider, timestamp, accuracy, altitude, bearing, speed, vertical_acc, bearing_acc, speed_acc, extras, is_mock, tgeof_id) VALUES ";
+ foreach ($jsonArray as $obj) {
+ $date = new DateTime();
+ $date->setTimestamp($obj['timestamp']);
+ $date = $date->format('Y-m-d H:i:s');
+
+ if(!isset($obj['server_input_id']) || $obj['server_input_id'] == -1){
+ $querry .= "($global_user_id, ".$obj['lat'].", ".$obj['lng'].", '".$obj['provider']."', '".$date."', ".($obj['accuracy'] ? $obj['accuracy'] : "NULL").", ".
+ ($obj['altitude'] ? $obj['altitude'] : "NULL").", ".($obj['bearing'] ? $obj['bearing'] : "NULL").", ".($obj['speed'] ? $obj['speed'] : "NULL").", ".
+ ($obj['vertical_acc'] ? $obj['vertical_acc'] : "NULL").", ".($obj['bearing_acc'] ? $obj['bearing_acc'] : "NULL").", ".
+ ($obj['speed_acc'] ? $obj['speed_acc'] : "NULL").", '".($obj['extras'] ? $obj['extras'] : "")."', ".$obj['is_mock'].", ".($triggered_geofence_id ? $triggered_geofence_id : "NULL")."), ";
+ }
+ else{
+ $querry1 = "INSERT INTO maza_user_locations (maza_user_id, lat, lng, provider, timestamp, accuracy, altitude, bearing, speed, vertical_acc, bearing_acc, speed_acc, extras, is_mock, tgeof_id) VALUES "
+ . "($global_user_id, ".$obj['lat'].", ".$obj['lng'].", '".$obj['provider']."', '".$date."', ".($obj['accuracy'] ? $obj['accuracy'] : "NULL").", ".
+ ($obj['altitude'] ? $obj['altitude'] : "NULL").", ".($obj['bearing'] ? $obj['bearing'] : "NULL").", ".($obj['speed'] ? $obj['speed'] : "NULL").", ".
+ ($obj['vertical_acc'] ? $obj['vertical_acc'] : "NULL").", ".($obj['bearing_acc'] ? $obj['bearing_acc'] : "NULL").", ".
+ ($obj['speed_acc'] ? $obj['speed_acc'] : "NULL").", '".($obj['extras'] ? $obj['extras'] : "")."', ".$obj['is_mock'].", ".($triggered_geofence_id ? $triggered_geofence_id : "NULL").");";
+ $loc_id = sisplet_query($querry1, 'id');
+ $querry2 = "UPDATE maza_srv_users SET loc_id='$loc_id' WHERE srv_user_id='".$obj['server_input_id']."';";
+ sisplet_query($querry2);
+ }
+ }
+ if($querryFirst != $querry){
+ $querry = substr($querry, 0, -2);
+ sisplet_query($querry);
+ }
+ }
+
+ /**
+ * Edit tracking locations for this user
+ * @global type $global_user_id
+ * @param type $jsonArray - array of locations to edit
+ */
+ public function mazaEditTrackingLocations($jsonArray) {
+ global $global_user_id;
+
+ if(isset($jsonArray['delete']) && !empty($jsonArray['delete'])){
+ $set_timestamp = "";
+ $where_delete="";
+
+ foreach ($jsonArray['delete'] as $obj) {
+ $set_timestamp.=" when UNIX_TIMESTAMP(timestamp)=".$obj['timestamp']." then FROM_UNIXTIME(".$obj['extras'].")";
+ $where_delete.=$obj['timestamp'].", ";
+ }
+ $where_delete = substr($where_delete, 0, -2);
+
+ $querry_delete = "UPDATE maza_user_locations SET timestamp = (case$set_timestamp end), "
+ . "lat=999, lng=999, provider='deleted', accuracy=NULL, altitude=NULL, bearing=NULL, speed=NULL, vertical_acc=NULL, bearing_acc=NULL, speed_acc=NULL, extras=NULL, is_mock=NULL WHERE maza_user_id=$global_user_id AND "
+ . "UNIX_TIMESTAMP(timestamp) IN (".$where_delete.");";
+
+ sisplet_query($querry_delete);
+ }
+
+ if(isset($jsonArray['edit']) && !empty($jsonArray['edit'])){
+ $set_lat = "";
+ $set_lng = "";
+ $where_edit="";
+
+ foreach ($jsonArray['edit'] as $obj) {
+ $set_lat.=" when UNIX_TIMESTAMP(timestamp)=".$obj['timestamp']." then ".$obj['lat'];
+ $set_lng.=" when UNIX_TIMESTAMP(timestamp)=".$obj['timestamp']." then ".$obj['lng'];
+ $where_edit.=$obj['timestamp'].", ";
+ }
+ $where_edit = substr($where_edit, 0, -2);
+
+ $querry_delete = "UPDATE maza_user_locations SET lat = (case$set_lat end), lng = (case$set_lng end), "
+ . "provider='manual' WHERE maza_user_id=$global_user_id AND "
+ . "UNIX_TIMESTAMP(timestamp) IN (".$where_edit.");";
+
+ sisplet_query($querry_delete);
+ }
+ }
+
+ /**
+ * Insert tracking locations for this user
+ * @global type $global_user_id
+ * @param type $jsonArray - array of locations to insert
+ */
+ public function mazaInsertTrackingAR($jsonArray) {
+ global $global_user_id;
+
+ $querry = "INSERT INTO maza_user_activity_recognition (maza_user_id, timestamp, in_vehicle, on_bicycle, on_foot, still, unknown, tilting, running, walking) VALUES ";
+ foreach ($jsonArray as $obj) {
+ $date = new DateTime();
+ $date->setTimestamp($obj['timestamp']);
+ $date = $date->format('Y-m-d H:i:s');
+
+ $querry .= "($global_user_id, '$date', ".$obj['in_vehicle'].", ".
+ $obj['on_bicycle'].", ".$obj['on_foot'].", ".$obj['still'].", ".
+ $obj['unknown'].", ".$obj['tilting'].", ".
+ $obj['running'].", ".$obj['walking']."), ";
+ }
+ $querry = substr($querry, 0, -2);
+ sisplet_query($querry);
+ }
+
+ /**
+ * Insert new triggered geofences
+ * @global type $global_user_id
+ * @param type $jsonArray - arrays of triggered geofences to save
+ */
+ public function mazaInsertTriggeredGeofences($jsonArray) {
+ global $global_user_id;
+ $new_tgeof_id = 0;
+
+ foreach ($jsonArray as $obj) {
+
+ $date = new DateTime();
+ $triggered_timestamp = $date->setTimestamp($obj['geofence']['tsSec'])->format('Y-m-d H:i:s');
+ $enter_timestamp = $date->setTimestamp($obj['geofence']['enter_timestamp'])->format('Y-m-d H:i:s');
+ $dwell_timestamp = $date->setTimestamp($obj['geofence']['dwell_timestamp'])->format('Y-m-d H:i:s');
+
+ $tgeo_id = sisplet_query("INSERT INTO maza_srv_triggered_geofences (geof_id, maza_user_id, triggered_timestamp, enter_timestamp, dwell_timestamp) VALUES "
+ . "('".$obj['geofence']['value']."','$global_user_id', '$triggered_timestamp', '$enter_timestamp' ,'$dwell_timestamp')", "id");
+ $this->mazaInsertTrackingLocations($obj['locations'], $tgeo_id);
+
+ if(isset($obj['geofence']['return_server_id']) && $obj['geofence']['return_server_id'] == true)
+ $new_tgeof_id = $tgeo_id;
+ }
+ return $new_tgeof_id;
+ }
+
+ /**
+ * Unsubscribe survey for this user
+ * @global type $global_user_id
+ * @param type $ank_id - survey ID to unsuscribe
+ */
+ public function mazaUnsubscribeSurvey($ank_id) {
+ global $global_user_id;
+
+ sisplet_query("UPDATE maza_user_srv_access SET datetime_unsubscribed = NOW() WHERE maza_user_id = '$global_user_id' AND ank_id = '$ank_id';");
+
+ $json_array['note'] = 'Unsubscribed from survey';
+ return $json_array;
+ }
+
+ /**
+ * Set agreed permission for tracking and register listener on nextpin API
+ * @global type $global_user_id
+ * @param type $data - array of data
+ */
+ public function mazaSetNextpinTrackingPermission($data) {
+ global $global_user_id;
+
+ if (isset($data['tracking_permission']) && isset($data['srv_id'])) {
+ sisplet_query("UPDATE maza_user_srv_access SET nextpin_tracking_permitted = '" . $data['tracking_permission'] . "' WHERE maza_user_id = '$global_user_id' AND ank_id = '".$data['srv_id']."'");
+
+ if($data['tracking_permission'] == 1){
+
+ $sql_pass = sisplet_query("SELECT nextpin_password, identifier FROM maza_app_users WHERE id='$global_user_id';", 'obj');
+ if($sql_pass){
+ $maza = new MAZA($data['srv_id']);
+ //password is null, user is not registered on nextpin yet
+ if(!$sql_pass->nextpin_password){
+ //generate new password
+ $newpass = $maza -> randomAlphaNumericCode(4);
+ //set password in db
+ sisplet_query("UPDATE maza_app_users SET nextpin_password = '$newpass' WHERE id = '$global_user_id'");
+ $json_array['data']['nextpin_password'] = $newpass;
+
+ //create new user in nextpin
+ $maza -> nextpin_create_user($sql_pass->identifier, $newpass);
+ }
+ //create new activity listener for this identifier
+ $maza -> nextpin_set_activity_listener($sql_pass->identifier);
+ }
+ }
+
+ $json_array['note'] = 'Tracking permission updated';
+ }
+ else
+ $json_array['error'] = 'Param tracking_permission or srv_id missing';
+
+ return $json_array;
+ }
+
+ /**
+ * Set agreed permission for tracking and register listener
+ * @global type $global_user_id
+ * @param type $data - array of data
+ */
+ public function mazaSetTrackingPermission($data) {
+ global $global_user_id;
+
+ if (isset($data['tracking_permission']) && isset($data['srv_id'])) {
+ sisplet_query("UPDATE maza_user_srv_access SET tracking_permitted = '" . $data['tracking_permission'] . "' WHERE maza_user_id = '$global_user_id' AND ank_id = '".$data['srv_id']."'");
+
+ $json_array['note'] = 'Tracking permission updated';
+ }
+ else
+ $json_array['error'] = 'Param tracking_permission or srv_id missing';
+
+ return $json_array;
+ }
+
+ /**
+ * Merge identifiers
+ * @global type $global_user_id
+ * @param type $identifier - identifier to merge
+ */
+ public function mazaMergeIdentifier($identifier) {
+ global $global_user_id;
+
+ //check if this identifier exists
+ $sql_arr = sisplet_query("SELECT id FROM maza_app_users WHERE identifier='$identifier';", 'obj');
+
+ if($sql_arr->id == $global_user_id)
+ return array('error' => 'incorrect identifier');
+ //identifier exsits
+ else if($sql_arr){
+ //get survey access of user
+ $sql_user_access = sisplet_query("SELECT ank_id FROM maza_user_srv_access WHERE maza_user_id='$global_user_id';", 'array');
+ //get survey access of identifier
+ $sql_identifier_access = sisplet_query("SELECT ank_id FROM maza_user_srv_access WHERE maza_user_id='$sql_arr->id';", 'array');
+ $user_access_arr = array();
+ $identifier_access_arr = array();
+
+ //create array of user accesses
+ foreach($sql_user_access as $ua)
+ array_push($user_access_arr, $ua['ank_id']);
+
+ //create array of identifier accesses
+ foreach($sql_identifier_access as $ia)
+ array_push($identifier_access_arr, $ia['ank_id']);
+
+ //array of which surveys does indentifier has access and not user
+ $what_to_add_array = array_diff($identifier_access_arr, $user_access_arr);
+
+ //if not empty, go insert
+ if($what_to_add_array){
+ $sql_values = "";
+ //create string of values(accesses) to insert to user access
+ foreach($what_to_add_array as $add)
+ $sql_values .= "('$global_user_id','$add', NOW()),";
+
+ //remove last comma
+ $sql_values = substr($sql_values, 0, -1);
+ //insert new accesses from identifier to user
+ sisplet_query("INSERT INTO maza_user_srv_access (maza_user_id, ank_id, datetime_started) VALUES $sql_values");
+ }
+
+ //delete all accesses of identifier
+ sisplet_query("DELETE FROM maza_user_srv_access WHERE maza_user_id = '$sql_arr->id'");
+ //delete identifier from user table
+ sisplet_query("DELETE FROM maza_app_users WHERE id = '$sql_arr->id'");
+
+ return array('note' => 'merge OK');
+ }
+ //identifier does not exist
+ else
+ return array('error' => 'identifier does not exist');
+ }
+
+ /**
+ * Get info of surveys to merge (by identifier)
+ * @global type $global_user_id
+ * @param type $identifier - identifier to get linked surveys info from
+ */
+ public function mazaGetSurveysInfoByIdentifier($identifier) {
+ global $global_user_id;
+
+ //check if this identifier exists
+ $sql_arr = sisplet_query("SELECT id FROM maza_app_users WHERE identifier='$identifier';", 'obj');
+
+ //identifier exsits
+ if($sql_arr){
+ //get survey access of user
+ $sql_user_access = sisplet_query("SELECT ank_id FROM maza_user_srv_access WHERE maza_user_id='$global_user_id';", 'array');
+ //get survey access of identifier
+ $sql_identifier_access = sisplet_query("SELECT ank_id FROM maza_user_srv_access WHERE maza_user_id='$sql_arr->id';", 'array');
+ $user_access_arr = array();
+ $identifier_access_arr = array();
+
+ //create array of user accesses
+ foreach($sql_user_access as $ua)
+ array_push($user_access_arr, $ua['ank_id']);
+
+ //create array of identifier accesses
+ foreach($sql_identifier_access as $ia)
+ array_push($identifier_access_arr, $ia['ank_id']);
+
+ //array of which surveys does indentifier has access and not user
+ $what_to_add_array = array_diff($identifier_access_arr, $user_access_arr);
+
+ //if not empty, or get info about users identifier, go selelct
+ if($sql_arr->id == $global_user_id || $what_to_add_array){
+ $sur_ids_in_string = "(".implode( ", ", $what_to_add_array ).")";
+
+ //get surveys info
+ $sql = "SELECT s.id, s.naslov, s.active, s.starts, s.expire, s.url, "
+ . "ge.geofences, sr.repeater_on, sr.repeat_by, sr.datetime_start, sr.datetime_end, "
+ . "ac.activities, se.entry_on, se.location_check, tr.tracking_on, tr.activity_recognition "
+ . "FROM srv_anketa AS s "
+ . "LEFT JOIN maza_srv_repeaters AS sr ON s.id = sr.ank_id "
+ . "LEFT JOIN (SELECT ank_id, COUNT(id) as geofences FROM maza_srv_geofences WHERE geofence_on='1' GROUP BY ank_id) AS ge ON s.id = ge.ank_id "
+ . "LEFT JOIN (SELECT ank_id, COUNT(id) as activities FROM maza_srv_activity WHERE activity_on='1' GROUP BY ank_id) AS ac ON s.id = ac.ank_id "
+ . "LEFT JOIN (SELECT entry_on, location_check, ank_id FROM maza_srv_entry) AS se ON s.id = se.ank_id "
+ . "LEFT JOIN (SELECT tracking_on, activity_recognition, ank_id FROM maza_srv_tracking) AS tr ON s.id = tr.ank_id "
+ . "WHERE s.id IN $sur_ids_in_string;";
+
+ $sql_surveys_info = sisplet_query($sql, 'array');
+
+ return $sql_surveys_info;
+ }
+ else
+ return array('note' => 'already participant');
+
+ }
+ //identifier does not exist
+ else
+ return array('error' => 'identifier does not exist');
+ }
+
+ /**
+ * Get all subscriptions/surveys of user
+ * @global type $global_user_id
+ * @return type
+ */
+ public function mazaGetSubscriptionsList($timeZone){
+ global $global_user_id;
+
+ //get surveys
+ $Sql = "SELECT *, UNIX_TIMESTAMP(datetime_started) as unixstart FROM maza_user_srv_access AS sa "
+ . "LEFT JOIN (SELECT id AS srv_id, naslov, active, starts, expire, url FROM srv_anketa) AS s ON s.srv_id = sa.ank_id "
+ . "LEFT JOIN maza_srv_repeaters AS sr ON s.srv_id = sr.ank_id "
+ . "LEFT JOIN (SELECT ank_id, COUNT(id) as geofences FROM maza_srv_geofences WHERE geofence_on='1' GROUP BY ank_id) AS ge ON s.srv_id = ge.ank_id "
+ . "LEFT JOIN (SELECT ank_id, COUNT(id) as activities FROM maza_srv_activity WHERE activity_on='1' GROUP BY ank_id) AS ac ON s.srv_id = ac.ank_id "
+ . "LEFT JOIN (SELECT entry_on, location_check, ank_id FROM maza_srv_entry) AS se ON s.srv_id = se.ank_id "
+ . "LEFT JOIN (SELECT tracking_on, activity_recognition, ank_id FROM maza_srv_tracking) AS tr ON s.srv_id = tr.ank_id "
+ . "LEFT JOIN (SELECT srv_description, srv_id as ank_id FROM maza_survey) AS ms ON ms.ank_id = s.srv_id "
+ . "WHERE sa.maza_user_id = '$global_user_id' AND s.active = '1' AND sa.datetime_unsubscribed IS NULL;";
+
+ //all active surveys on which user has access
+ $sarray = sisplet_query($Sql, 'array');
+
+ $resultarray = array();
+
+ //get nuber of unfidished questionnaires
+ $surveyListArray = $this->mazaGetSurveyList($timeZone);
+
+ foreach($sarray as $survey){
+ $survey['unfinished_cnt'] = $surveyListArray[$survey['srv_id']]['unfinished_cnt'];
+ $survey['url'] = $survey['url'].'a/'.$survey['srv_id'];
+ $resultarray[] = $survey;
+ }
+
+ return $resultarray;
+ }
+
+ /**
+ * Vrne seznam anket na katere je uporabnik narocen
+ * @param type $timeZone - timezone ID of user
+ * @return array
+ */
+ public function mazaGetSurveyList($timeZone, $srv_id = null) {
+ global $global_user_id;
+
+ $surveyWhere = $srv_id == null ? '' : ' AND s.srv_id = '.$srv_id;
+ $json_array = array();
+
+ //get surveys
+ $Sql = "SELECT * FROM maza_user_srv_access AS sa "
+ . "LEFT JOIN (SELECT id AS srv_id, naslov, active, starts, expire, url FROM srv_anketa) AS s ON s.srv_id = sa.ank_id "
+ . "LEFT JOIN maza_srv_repeaters AS sr ON s.srv_id = sr.ank_id "
+ . "LEFT JOIN (SELECT id, ank_id, COUNT(id) as geofences FROM maza_srv_geofences WHERE geofence_on='1' GROUP BY ank_id) AS ge ON s.srv_id = ge.ank_id "
+ . "LEFT JOIN (SELECT id, ank_id, COUNT(id) as activities FROM maza_srv_activity WHERE activity_on='1' GROUP BY ank_id) AS ac ON s.srv_id = ac.ank_id "
+ . "LEFT JOIN (SELECT tracking_on, ank_id FROM maza_srv_tracking) AS st ON s.srv_id = st.ank_id "
+ . "LEFT JOIN (SELECT entry_on, ank_id FROM maza_srv_entry) AS se ON s.srv_id = se.ank_id "
+ . "WHERE sa.maza_user_id = '$global_user_id' AND s.active = '1' AND sa.datetime_unsubscribed IS NULL$surveyWhere;";
+
+ //all active surveys on which user has access
+ $sarray = sisplet_query($Sql, 'array');
+
+ //get existing surveys for this user
+ $Sql = "SELECT *, UNIX_TIMESTAMP(srv_version_datetime) as unixver FROM maza_srv_users AS msu "
+ . "LEFT JOIN (SELECT id, cookie, ank_id, last_status, time_insert FROM srv_user) AS su ON msu.srv_user_id = su.id "
+ . "LEFT JOIN (SELECT id AS srv_id, active, starts, naslov, url FROM srv_anketa) AS s ON su.ank_id = s.srv_id "
+ . "LEFT JOIN (SELECT maza_user_id, ank_id, datetime_unsubscribed FROM maza_user_srv_access) AS sa ON sa.ank_id = s.srv_id "
+ . "WHERE s.active = '1' AND msu.maza_user_id = '$global_user_id' AND sa.maza_user_id = '$global_user_id' AND sa.datetime_unsubscribed IS NULL$surveyWhere;";
+
+ //cookies of surveys for all active surveys of this user
+ $uarray = sisplet_query($Sql, 'array');
+
+ //do we have any active survey with data entries?
+ $dataEntryArray = null;
+
+ //create array of users surveys to later access it
+ $cookies_array = array();
+ foreach($uarray as $row){
+ //if we have a entry mode and didnt get data entry array yet, run it
+ if($dataEntryArray == null && $row['mode'] == 'entry'){
+ $dataEntryArray = $this->getDataEntryArray();
+ }
+
+ $link = $row['url'].'a/'.$row['srv_id'].'&survey-'.$row['srv_id'].'='.$row['cookie'];
+
+ $srv_version_datetime = ($row['srv_version_datetime'] != null && $row['unixver'] != null) ? $row["srv_version_datetime"] : $row["time_insert"];
+ $temp_date = new DateTime($srv_version_datetime);
+ //$srv_version_datetime = $temp_date->format('Hi_d_m_Y');
+ $srv_version_timestamp = $row['unixver'] != null ? $row['unixver'] : $temp_date->getTimestamp();
+
+ $cookies_array[$row['srv_id']][$srv_version_timestamp] = array('status'=>$row['last_status'], 'link'=>$link, 'naslov'=>$row['naslov'], 'srv_id'=>$row['ank_id'],
+ 'timestamp'=>$srv_version_timestamp, 'datetime'=>$srv_version_datetime, 'mode'=>$row['mode'], 'srv_version'=>$srv_version_datetime,
+ 'latitude'=>$dataEntryArray[$row['srv_user_id']]['latitude'], 'longitude'=>$dataEntryArray[$row['srv_user_id']]['longitude'], 'srv_user_id'=>$row['srv_user_id']);
+ }
+
+ //set users timezone (all calculations are for users timezone)
+ $dateTz = new DateTimeZone($timeZone);
+ //what is now a time of users device
+ $Udate = new DateTime("now", $dateTz);
+ //get offset in hours of user timezone versus server timezone (for calculations of datetime from DB)
+ $offset = $dateTz->getOffset($Udate)-date('Z');
+ //set users timestamp based on time of DB datetimes
+ $user_timestamp_now = $Udate->getTimestamp()+$offset;
+
+ //geofences
+ $sql_geo = sisplet_query("SELECT g.ank_id, tg.id, tg.geof_id, tg.triggered_timestamp, g.address, g.name, g.trigger_survey, s.naslov, s.url, sa.ank_id, sa.maza_user_id, sa.datetime_unsubscribed "
+ . "FROM maza_srv_triggered_geofences AS tg "
+ . "LEFT JOIN (SELECT ank_id, geofence_on, id, address, name, trigger_survey FROM maza_srv_geofences) AS g ON g.id=tg.geof_id "
+ . "LEFT JOIN (SELECT id as srv_id, active, naslov, url FROM srv_anketa) AS s ON g.ank_id = s.srv_id "
+ . "LEFT JOIN (SELECT maza_user_id, ank_id, datetime_unsubscribed FROM maza_user_srv_access) AS sa ON sa.ank_id = g.ank_id "
+ . "WHERE tg.maza_user_id='$global_user_id' AND s.active = '1' AND sa.maza_user_id = '$global_user_id' AND sa.datetime_unsubscribed IS NULL$surveyWhere;", 'array');
+ //this survey has geofencing
+ if (count($sql_geo) > 0) {
+ foreach($sql_geo as $tgeo){
+ if($tgeo['trigger_survey']!=null){
+ $triggered_datetime = new DateTime($tgeo['triggered_timestamp']);
+ $triggered_timestamp = $triggered_datetime->getTimestamp();
+ $link = isset($cookies_array[$tgeo['ank_id']][$triggered_timestamp]) ? $cookies_array[$tgeo['ank_id']][$triggered_timestamp]['link'] : $tgeo['url'].'a/'.$tgeo['ank_id'];
+ $user_status = isset($cookies_array[$tgeo['ank_id']][$triggered_timestamp]) ? $cookies_array[$tgeo['ank_id']][$triggered_timestamp]['status'] : '';
+ $srv_user_id = isset($cookies_array[$tgeo['ank_id']][$triggered_timestamp]) ? $cookies_array[$tgeo['ank_id']][$triggered_timestamp]['srv_user_id'] : '';
+ //$srv_version = $temp_date->format('Hi_d_m_Y');
+ /*$new_array = array('timestamp' => $triggered_timestamp, 'datetime' => $tgeo['triggered_timestamp'], 'srv_id' => $tgeo['ank_id'], 'naslov' => $tgeo['naslov'], 'name' => $tgeo['name'],
+ 'srv_version' => $tgeo['triggered_timestamp'], 'link' => $link, 'status' => $user_status, 'address' => $tgeo['address'], 'tgeof_id' => $tgeo['id'], 'mode' => 'geofence', 'srv_user_id'=>$srv_user_id);*/
+ $unfinished = $user_status == 6 ? 0 : 1;
+
+ if(isset($json_array[$tgeo['ank_id']]['surveys'])){
+ $json_array[$tgeo['ank_id']]['surveys'][]=array('timestamp' => $triggered_timestamp, 'datetime' => $tgeo['triggered_timestamp'], 'srv_version' => $tgeo['triggered_timestamp'],
+ 'link' => $link, 'status' => $user_status, 'tgeof_id' => $tgeo['id'], 'mode' => 'geofence', 'srv_user_id'=>$srv_user_id, 'name' => $tgeo['name'], 'address' => $tgeo['address']);
+ $json_array[$tgeo['ank_id']]['unfinished_cnt']+=$unfinished;
+ }
+ else{
+ $json_array[$tgeo['ank_id']]=array('srv_id' => $tgeo['ank_id'], 'naslov' => $tgeo['naslov'], 'unfinished_cnt' => $unfinished,
+ 'surveys' => array(array('timestamp' => $triggered_timestamp, 'datetime' => $tgeo['triggered_timestamp'], 'srv_version' => $tgeo['triggered_timestamp'], 'link' => $link,
+ 'status' => $user_status, 'tgeof_id' => $tgeo['id'], 'mode' => 'geofence', 'srv_user_id'=>$srv_user_id, 'name' => $tgeo['name'], 'address' => $tgeo['address'])));
+ }
+
+ //array_push($json_array, $new_array);
+
+ if(isset($cookies_array[$tgeo['ank_id']][$triggered_timestamp]))
+ unset($cookies_array[$tgeo['ank_id']][$triggered_timestamp]);
+ }
+ }
+ }
+
+ //activity
+ $sql_act = sisplet_query("SELECT a.ank_id, ta.id, ta.act_id, ta.triggered_timestamp, s.naslov, s.url, sa.ank_id, sa.maza_user_id, sa.datetime_unsubscribed "
+ . "FROM maza_srv_triggered_activities AS ta "
+ . "LEFT JOIN (SELECT ank_id, activity_on, id FROM maza_srv_activity) AS a ON a.id=ta.act_id "
+ . "LEFT JOIN (SELECT id as srv_id, active, naslov, url FROM srv_anketa) AS s ON a.ank_id = s.srv_id "
+ . "LEFT JOIN (SELECT maza_user_id, ank_id, datetime_unsubscribed FROM maza_user_srv_access) AS sa ON sa.ank_id = g.ank_id "
+ . "WHERE ta.maza_user_id='$global_user_id' AND s.active = '1' AND sa.maza_user_id = '$global_user_id' AND sa.datetime_unsubscribed IS NULL$surveyWhere;", 'array');
+ //this survey has activities
+ if (count($sql_act) > 0) {
+ foreach($sql_act as $tact){
+ $triggered_datetime = new DateTime($tact['triggered_timestamp']);
+ $triggered_timestamp = $triggered_datetime->getTimestamp();
+ $link = isset($cookies_array[$tact['ank_id']][$triggered_timestamp]) ? $cookies_array[$tact['ank_id']][$triggered_timestamp]['link'] : $tact['url'].'a/'.$tact['ank_id'];
+ $user_status = isset($cookies_array[$tact['ank_id']][$triggered_timestamp]) ? $cookies_array[$tact['ank_id']][$triggered_timestamp]['status'] : '';
+ $srv_user_id = isset($cookies_array[$tact['ank_id']][$triggered_timestamp]) ? $cookies_array[$tact['ank_id']][$triggered_timestamp]['srv_user_id'] : '';
+ //$srv_version = $temp_date->format('Hi_d_m_Y');
+ /*$new_array = array('timestamp' => $triggered_timestamp, 'datetime' => $tact['triggered_timestamp'], 'srv_id' => $tact['ank_id'], 'naslov' => $tact['naslov'],
+ 'srv_version' => $tact['triggered_timestamp'], 'link' => $link, 'status' => $user_status, 'tact_id' => $tact['id'], 'mode' => 'activity', 'srv_user_id'=>$srv_user_id);*/
+ $unfinished = $user_status == 6 ? 0 : 1;
+
+ if(isset($json_array[$tact['ank_id']]['surveys'])){
+ $json_array[$tgeo['ank_id']]['surveys'][]= array('timestamp' => $triggered_timestamp, 'datetime' => $tact['triggered_timestamp'], 'srv_version' => $tact['triggered_timestamp'],
+ 'link' => $link, 'status' => $user_status, 'tact_id' => $tact['id'], 'mode' => 'activity', 'srv_user_id'=>$srv_user_id);
+ $json_array[$tgeo['ank_id']]['unfinished_cnt']+=$unfinished;
+ }
+ else
+ $json_array[$tact['ank_id']]=array('srv_id' => $tact['ank_id'], 'naslov' => $tact['naslov'], 'unfinished_cnt' => $unfinished,
+ 'surveys' => array(array('timestamp' => $triggered_timestamp, 'datetime' => $tact['triggered_timestamp'], 'srv_version' => $tact['triggered_timestamp'],
+ 'link' => $link, 'status' => $user_status, 'tact_id' => $tact['id'], 'mode' => 'activity', 'srv_user_id'=>$srv_user_id)));
+
+ //array_push($json_array, $new_array);
+
+ if(isset($cookies_array[$tact['ank_id']][$triggered_timestamp]))
+ unset($cookies_array[$tact['ank_id']][$triggered_timestamp]);
+ }
+ }
+
+ foreach($sarray as $survey){
+ //if($survey["repeater_on"] != '2'){
+ //survey with no repeater
+ if($survey["repeater_on"] == '0'){
+ //only basic survey with no answer
+ if(($survey['geofences'] == null || $survey['geofences'] == '0') &&
+ ($survey['activities'] == null || $survey['activities'] == '0') &&
+ ($survey['entry_on'] == null || $survey['entry_on'] == '0') &&
+ ($survey['tracking_on'] == null || $survey['tracking_on'] == '0') &&
+ !isset($cookies_array[$survey['srv_id']])){
+ $link = $survey['url'].'a/'.$survey['srv_id'];
+ $user_status = '';
+ $temp_timestamp = strtotime($survey['starts']);
+ //$srv_version = $temp_date->format('Hi_d_m_Y');
+ /*$new_array = array('timestamp' => $temp_timestamp, 'datetime' => $survey['starts'], 'srv_id' => $survey['srv_id'], 'naslov' => $survey['naslov'],
+ 'srv_version' => '', 'link' => $link, 'status' => $user_status, 'mode' => 'basic', 'srv_user_id'=>'');*/
+ $json_array[$survey['srv_id']] = array('srv_id' => $survey['srv_id'], 'naslov' => $survey['naslov'], 'unfinished_cnt' => 1,
+ 'surveys' => array(array('timestamp' => $temp_timestamp, 'datetime' => $survey['starts'], 'link' => $link, 'srv_version' => '', 'status' => $user_status, 'mode' => 'basic', 'srv_user_id'=>'')));
+ //array_push($json_array, $new_array);
+ }
+ }
+ //survey with repeater
+ else{
+ //use latest datetime to start repeater for this user (when repeater started or when user accessed)
+ $Accessdate = new DateTime($survey["datetime_started"]);
+ $Startdate = new DateTime($survey["datetime_start"]);
+ $Startdate = $Startdate < $Accessdate ? $Accessdate : $Startdate;
+ $Startdate_string = $Startdate->format('Y-m-d');
+
+ //if, based on timezone user-server differences, users timestamp is less than starting of repeater, there are no avalible surveys yet
+ //we have to wait until users date and time gets at least to date and time of servers datetime of repeater started
+ if(strtotime($Startdate_string) <= $user_timestamp_now /*&& $user_timestamp_now <= $Endtimestamp*/){
+ switch($survey["repeat_by"]){
+ case 'everyday':
+ $temp_date_by_day = new DateTime($Startdate_string);
+ $edited_arr = $this->createArrayRepeater($json_array, $temp_date_by_day, $user_timestamp_now, $survey, $cookies_array, 1);
+ $json_array = $edited_arr['surveys'];
+ $cookies_array = $edited_arr['cookies'];
+ break;
+ case 'daily':
+ $temp_date_by_day = new DateTime($Startdate_string);
+ $edited_arr = $this->createArrayRepeater($json_array, $temp_date_by_day, $user_timestamp_now, $survey, $cookies_array, $survey['every_which_day']);
+ $json_array = $edited_arr['surveys'];
+ $cookies_array = $edited_arr['cookies'];
+ break;
+ case 'weekly':
+ foreach(json_decode($survey['day_in_week']) as $dayinweek){
+ $temp_date_by_day = new DateTime($Startdate_string);
+ $dayinweek_string = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
+ if($temp_date_by_day->format('l') != $dayinweek_string[$dayinweek-1])
+ $temp_date_by_day->modify('next '.$dayinweek_string[$dayinweek-1]);
+
+ $edited_arr = $this->createArrayRepeater($json_array, $temp_date_by_day, $user_timestamp_now, $survey, $cookies_array, 7);
+ $json_array = $edited_arr['surveys'];
+ $cookies_array = $edited_arr['cookies'];
+ }
+ break;
+ }
+ }
+ }
+ //}
+ }
+
+ //for data entry surveys and basic survey with answer
+ foreach($cookies_array as $survey){
+ foreach($survey as $cookie){
+ //include basic survey with answer and data entry if it is still on
+ if(!isset($cookie['mode']) || ($cookie['mode'] == 'entry')){
+ //array_push($json_array, $cookie);
+ if(isset($json_array[$cookie['srv_id']]['surveys']))
+ $json_array[$cookie['srv_id']]['surveys'][] = $cookie;
+ else
+ $json_array[$cookie['srv_id']] = array('srv_id' => $cookie['srv_id'], 'naslov' => $cookie['naslov'], 'surveys'=>array($cookie));
+
+ $json_array[$cookie['srv_id']]['unfinished_cnt']+=($cookie['status']==6 ? 0:1);
+ }
+ }
+ }
+
+ //krsort($json_array);
+ //tole mislim da sicer razvrsti, ampak pobrise keye
+ /*usort($json_array, function ($a, $b)
+ {
+ return -strcmp($a['timestamp'], $b['timestamp']);
+ });*/
+
+ return $json_array;
+ }
+
+ /**
+ * Get array of data entry latitude and longitude values from answers
+ * @global type $global_user_id
+ * @return type array of data with usr_id as keys
+ */
+ private function getDataEntryArray(){
+ global $global_user_id;
+ $dataEntryArray = array();
+
+ $Sql = "SELECT * FROM maza_srv_users AS msu "
+ . "LEFT JOIN (SELECT id, ank_id FROM srv_user) AS su ON msu.srv_user_id = su.id "
+ . "LEFT JOIN (SELECT id AS srv_id, active FROM srv_anketa) AS s ON su.ank_id = s.srv_id "
+ . "LEFT JOIN (SELECT id as gru_id, ank_id FROM srv_grupa) AS gru ON su.ank_id = gru.ank_id "
+ . "LEFT JOIN (SELECT id AS lat_spr_id, gru_id FROM srv_spremenljivka WHERE variable='latitude' AND sistem='1') AS spr1 ON gru.gru_id = spr1.gru_id "
+ . "LEFT JOIN (SELECT text as latitude, usr_id, spr_id FROM srv_data_text_active) AS dt1 ON msu.srv_user_id = dt1.usr_id AND dt1.spr_id = spr1.lat_spr_id "
+ . "LEFT JOIN (SELECT id AS lng_spr_id, gru_id FROM srv_spremenljivka WHERE variable='longitude' AND sistem='1') AS spr2 ON gru.gru_id = spr2.gru_id "
+ . "LEFT JOIN (SELECT text as longitude, usr_id, spr_id FROM srv_data_text_active) AS dt2 ON msu.srv_user_id = dt2.usr_id AND dt2.spr_id = spr2.lng_spr_id "
+ . "WHERE s.active = '1' AND msu.maza_user_id = '$global_user_id' AND msu.mode='entry' AND dt1.latitude IS NOT NULL AND dt2.longitude IS NOT NULL;";
+
+ //coordinates of data entries for all active surveys of this user
+ $entryarray = sisplet_query($Sql, 'array');
+
+ foreach($entryarray as $array){
+ $dataEntryArray[$array['srv_user_id']] = $array;
+ }
+
+ return $dataEntryArray;
+ }
+
+ /**
+ * MAZA function
+ * Creates or modifies a json array of surveys with repeater
+ * @param type $json_array - array to modify or empty array
+ * @param type $temp_date_by_day - DateTime object of starting day
+ * @param type $user_timestamp_now - timestamp of users now (by users timezone)
+ * @param type $survey - array of surveys and repeaters data for survey, to which user has access
+ * @param type $cookies_array - array of existing surveys for this user
+ * @param type $every_which_day - every which day has to be repeated (every day - 1, weekly - 7,...)
+ * @return type json array of surveys for this user
+ */
+ private function createArrayRepeater($json_array, $temp_date_by_day, $user_timestamp_now, $survey, $cookies_array, $every_which_day){
+ //get ending timestamp time of repeater
+ $Endtimestamp = $survey["datetime_end"] != null ? (new DateTime($survey["datetime_end"]))->getTimestamp() : null;
+
+ //loop until users timestamp of now
+ while($temp_date_by_day->getTimestamp() <= $user_timestamp_now && ($Endtimestamp != null ? $temp_date_by_day->getTimestamp() <= $Endtimestamp : true)){
+ //iterate trough times in day
+ foreach(json_decode($survey['time_in_day']) as $timeinday){
+ //set temporary datetime of given date and time in day
+ $temp_date = DateTime::createFromFormat('Y-m-d Hi', $temp_date_by_day->format('Y-m-d').' '.$timeinday);
+ $temp_date_timestamp = $temp_date->getTimestamp();
+
+ if(/*$temp_date_timestamp > strtotime($survey["datetime_started"]) &&*/ $temp_date_timestamp < $user_timestamp_now){
+ $srv_version = $temp_date->format('Hi_d_m_Y');
+ $link = isset($cookies_array[$survey['srv_id']][$temp_date_timestamp]) ? $cookies_array[$survey['srv_id']][$temp_date_timestamp]['link'] : $survey['url'].'a/'.$survey['srv_id'];
+ $user_status = isset($cookies_array[$survey['srv_id']][$temp_date_timestamp]) ? $cookies_array[$survey['srv_id']][$temp_date_timestamp]['status'] : '';
+ $srv_user_id = isset($cookies_array[$survey['srv_id']][$temp_date_timestamp]) ? $cookies_array[$survey['srv_id']][$temp_date_timestamp]['srv_user_id'] : '';
+ /*$new_array = array('timestamp' => $temp_date_timestamp, 'datetime' => $temp_date->format('Y-m-d H:i:s'), 'srv_id' => $survey['srv_id'], 'naslov' => $survey['naslov'],
+ 'srv_version' => $srv_version, 'link' => $link, 'status' => $user_status, 'mode' => 'repeater', 'srv_user_id'=>$srv_user_id);*/
+ //array_push($json_array, $new_array);
+ $unfinished = $user_status == 6 ? 0:1;
+
+ $survey_array = array('timestamp' => $temp_date_timestamp, 'datetime' => $temp_date->format('Y-m-d H:i:s'), 'link' => $link,
+ 'srv_version' => $srv_version, 'status' => $user_status, 'mode' => 'repeater', 'srv_user_id'=>$srv_user_id);
+
+ if(isset($json_array[$survey['srv_id']]['surveys'])){
+ array_push($json_array[$survey['srv_id']]['surveys'], $survey_array);
+ $json_array[$survey['srv_id']]['unfinished_cnt']+=$unfinished;
+ }
+ else
+ $json_array[$survey['srv_id']] = array('srv_id' => $survey['srv_id'], 'naslov' => $survey['naslov'], 'unfinished_cnt' => $unfinished, 'surveys'=>array($survey_array));
+
+ if(isset($cookies_array[$survey['srv_id']][$temp_date_timestamp]))
+ unset($cookies_array[$survey['srv_id']][$temp_date_timestamp]);
+ }
+ }
+ //increase date by given number of days
+ $temp_date_by_day->modify('+'.$every_which_day.' day');
+ }
+
+ $result = array('surveys' => $json_array, 'cookies' => $cookies_array);
+ return $result;
+ }
+ //END MAZA
+}
+
+
diff --git a/admin/survey/classes/class.SurveyParaAnalysis.php b/admin/survey/classes/class.SurveyParaAnalysis.php
new file mode 100644
index 0000000..f5813cf
--- /dev/null
+++ b/admin/survey/classes/class.SurveyParaAnalysis.php
@@ -0,0 +1,1550 @@
+<?php
+
+class SurveyParaAnalysis{
+
+ private $anketa; # id ankete
+ private $db_table; # katere tabele uporabljamo
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo (zakeširamo)
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ public $_PROFILE_ID_VARIABLE = ''; # filter po statusih, privzeto izvažamo 6 in 5
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ private $decimal_point = ',';
+ private $thousands = '.';
+ private $num_digit_average = NUM_DIGIT_AVERAGE;
+ private $num_digit_percent = NUM_DIGIT_PERCENT;
+ private $_missings = array();
+ private $_unsets = array();
+
+ private $cols_with_value = array(); # kateri stolpci imajo vrednosti
+ private $show_with_zero = false; # Ali prikazujemo stolpce z vrednostmi 0
+ private $show_with_other = true; # Ali prikazujemo vrstice "Drugo"
+
+
+ private $show_question_basic = true; # Ali prikazujemo vprašanja v osnovnem načinu
+ private $show_graph_basic = true; # Ali prikazujemo graf v osnovnem načinu
+ private $show_question_breaks = true; # Ali prikazujemo vprašanja v prekinitvak
+ private $show_graph_breaks = true; # Ali prikazujemo graf v prekinitvah
+ private $show_question_advanced = false; # Ali prikazujemo vprašanja v naprednem načinu
+ private $show_graph_advanced = false; # Ali prikazujemo graf v naprednem načinu
+ private $show_graph_breaks_type = 0; # Kareri graf prikazujemo 0=>SP, 1=>SP bruto, 2=>SP neto
+
+ private $show_categories = true; # Ali prikazujemo kategorične spremenljivke
+ private $show_numbers = true; # Ali prikazujemo numeričnespremenljivke
+ private $show_text = true; # Ali prikazujemo textovne spremenljivke
+
+ private $spr_type;
+
+ function __construct($anketa)
+ {
+ if ((int)$anketa > 0)
+ {
+ $this->anketa = $anketa;
+
+ SurveyAnalysisHelper::getInstance()->Init($this->anketa);
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ Common::deletePreviewData($this->anketa);
+
+
+ // Poskrbimo za datoteko s podatki
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->anketa);
+ $this->SDF->prepareFiles();
+
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileName = $this->SDF->getDataFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->anketa);
+ SurveyUserSetting::getInstance()->Init($this->anketa, $global_user_id);
+ SurveyConditionProfiles :: Init($this->anketa, $global_user_id);
+ SurveyTimeProfiles :: Init($this->anketa, $global_user_id);
+ SurveyVariablesProfiles :: Init($this->anketa, $global_user_id);
+ SurveyDataSettingProfiles :: Init($this->anketa);
+ # polovimo decimalna mesta in vejice za tisočice
+ $this->decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $this->thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+ $this->num_digit_average = SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE');
+ $this->num_digit_percent = SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT');
+
+ $this->spr_type = SurveyDataSettingProfiles::$spr_type;
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->anketa);
+ $this->sessionData = SurveyUserSession::getData();
+
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED)
+ {
+ Common::noDataAlert();
+ exit();
+ }
+
+ if ($this->headFileName !== null && $this->headFileName != '')
+ {
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ # nastavimo filtre uporabnika
+ $this->setUserFilters();
+
+ }
+ else
+ {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter()
+ {
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED)
+ {
+ return false;
+ }
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ || ($_time_profile_awk != "" && $_time_profile_awk != null))
+ {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null)
+ {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD)
+ {
+ if (isset($this->_HEADERS['testdata']))
+ {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+
+ $smv = new SurveyMissingValues($this->anketa);
+ $smv -> Init();
+
+ $smv_array = $smv->GetSurveyMissingValues($this->anketa);
+ if (!empty($smv_array[1])){
+ foreach ($smv_array[1] AS $_survey_missings)
+ {
+ $this->_missings[$_survey_missings['value']] = $_survey_missings['text'];
+
+ }
+ }
+ if (!empty($smv_array[2])){
+ foreach ($smv_array[2] AS $_survey_unsets)
+ {
+ $this->_unsets[$_survey_unsets['value']] = $_survey_unsets['text'];
+ }
+ }
+ }
+
+ private function setUserFilters()
+ {
+ # Nastavimo filtre variabel
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+ if ($dvp != $_currentVariableProfile) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', $_currentVariableProfile);
+ }
+ $this->_PROFILE_ID_VARIABLE = $_currentVariableProfile;
+
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['para_analysis']['show_with_zero'])) {
+ $this->show_with_zero = $this->sessionData['para_analysis']['show_with_zero'];
+ }
+
+ # ali prikazujemo vrstice "Drugo"
+ if (isset($this->sessionData['para_analysis']['show_with_other'])) {
+ $this->show_with_other = $this->sessionData['para_analysis']['show_with_other'];
+ }
+/*
+ # ali prikazujemo vrstice tipa "besedilo"
+ if (isset($this->sessionData['para_analysis']['show_with_text'])) {
+ $this->show_with_text = $this->sessionData['para_analysis']['show_with_text'];
+ }
+*/
+
+ # Ali prikazujemo vprašanja v osnovnem nacinu
+ if (isset($this->sessionData['para_analysis']['show_question_basic'])) {
+ $this->show_question_basic = $this->sessionData['para_analysis']['show_question_basic'];
+ }
+ # Ali prikazujemo vprašanja v preinitvah
+ if (isset($this->sessionData['para_analysis']['show_question_breaks'])) {
+ $this->show_question_breaks = $this->sessionData['para_analysis']['show_question_breaks'];
+ }
+ # Ali prikazujemo vprašanja v naprednem nacinu
+ if (isset($this->sessionData['para_analysis']['show_question_advanced'])) {
+ $this->show_question_advanced = $this->sessionData['para_analysis']['show_question_advanced'];
+ }
+ # Ali prikazujemo graf v osnovnem nacinu
+ if (isset($this->sessionData['para_analysis']['show_graph_basic'])) {
+ $this->show_graph_basic = $this->sessionData['para_analysis']['show_graph_basic'];
+ }
+ # Ali prikazujemo graf v prekinitvah
+ if (isset($this->sessionData['para_analysis']['show_graph_breaks'])) {
+ $this->show_graph_breaks = $this->sessionData['para_analysis']['show_graph_breaks'];
+ }
+ # Ali prikazujemo graf v naprednem nacinu
+ if (isset($this->sessionData['para_analysis']['show_graph_advanced'])) {
+ $this->show_graph_advanced = $this->sessionData['para_analysis']['show_graph_advanced'];
+ }
+ # Kateri tip grafa prikazujemo v prekinitvah
+ if (isset($this->sessionData['para_analysis']['show_graph_breaks_type']) && in_array((int)$this->sessionData['para_analysis']['show_graph_breaks_type'], array(0,1,2))) {
+ $this->show_graph_breaks_type = $this->sessionData['para_analysis']['show_graph_breaks_type'];
+ }
+
+ # Ali prikazujemo kategorije, numerične, besedila
+ if (isset($this->sessionData['para_analysis']['show_categories'])) {
+ $this->show_categories = $this->sessionData['para_analysis']['show_categories'];
+ }
+ if (isset($this->sessionData['para_analysis']['show_numbers'])) {
+ $this->show_numbers = $this->sessionData['para_analysis']['show_numbers'];
+ }
+ if (isset($this->sessionData['para_analysis']['show_text'])) {
+ $this->show_text = $this->sessionData['para_analysis']['show_text'];
+ }
+
+ }
+
+ function Display() {
+ global $lang;
+
+
+ # ali imamo testne podatke
+ if ($this->_HAS_TEST_DATA){
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml($this->anketa);
+ $SSH -> displayTestDataBar(true);
+ }
+
+ //$this->DisplayLinks();
+
+ echo '<div id="displayFilterNotes">';
+ # če imamo filter zoom ga izpišemo
+ SurveyZoom::getConditionString();
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile();
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString();
+
+ SurveyDataSettingProfiles :: getVariableTypeNote($doNewLine );
+ echo '</div>';
+
+ echo '<div class="clr">&nbsp;</div>';
+
+
+ $this->displayData();
+ }
+
+
+ function DisplayGraph()
+ {
+ global $lang;
+ $paraType = 'basic';
+
+ if (isset($_GET['m']) && $_GET['m'] == 'advanced') {
+ $paraType = 'advanced';
+ }
+ if (isset($_GET['m']) && $_GET['m'] == 'breaks') {
+ $paraType = 'breaks';
+ }
+
+ $showSettings = false;
+ if (isset($_SESSION['sid_'.$this->anketa]['paraAnalysisGraph_settings']) && $_SESSION['sid_'.$this->anketa]['paraAnalysisGraph_settings'] == true) {
+
+ $showSettings = true;
+ }
+
+ echo '<div id="dataSettingsCheckboxes" class="paraAnalysisGraph" '.($showSettings ? '' : ' style="display:none;"').'>';
+ echo '<div id="toggleDataCheckboxes2" onClick="toggleDataCheckboxes(\'paraAnalysisGraph\');"><span class="faicon close icon-orange" style="padding-bottom:2px;"></span> '.$lang['srv_para_close_settings'].'</div>';
+
+ echo '<table id="para_settings"><tr><th>Spremenljivke</th><th rowspan="2" class="anl_bl spacer"></th><th>Prekinitve</th><th rowspan="2" class="anl_bl spacer"></th><th>Podrobno</th></tr>';
+ echo '<tr><td>';
+ # spremenljivke
+ echo '<div class="floatLeft">';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_question_basic" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_question_basic == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_para_show_question_basic'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_graph_basic" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_graph_basic == true ? ' checked="checked"' : '').' autocomplete="off" >';
+ echo $lang['srv_para_show_show_graph_basic'];
+ echo '</label>';
+ echo '</div>';
+ # end:spremenljivke
+ echo '</td><td>';
+ # prekinitve
+ echo '<div class="floatLeft">';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_question_breaks" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_question_breaks == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_para_show_question_breaks'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_graph_breaks" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_graph_breaks == true ? ' checked="checked"' : '').' autocomplete="off" >';
+ echo $lang['srv_para_show_show_graph_breaks'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>'.$lang['srv_para_graph_type'].':';
+ echo '<select id="show_graph_breaks_type" onchange="changeParaAnalysisSelect(this);" autocomplete="off">';
+ echo '<option value="0"'.((int)$this->show_graph_breaks_type == 0 ? ' selected="selected"' : '').'>'.$lang['srv_para_graph_type0'].'</option>';
+ echo '<option value="1"'.((int)$this->show_graph_breaks_type == 1 ? ' selected="selected"' : '').'>'.$lang['srv_para_graph_type1'].'</option>';
+ echo '<option value="2"'.((int)$this->show_graph_breaks_type == 2 ? ' selected="selected"' : '').'>'.$lang['srv_para_graph_type2'].'</option>';
+ echo '</select>';
+ echo '</label>';
+ echo '</div>';
+
+ # end: prekinitve
+ echo '</td><td>';
+ # podrobno
+ echo '<div class="floatLeft">';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_with_zero" onclick="changeParaAnalysisCbx(this,true);" '.($this->show_with_zero == false ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_para_only_valid'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_with_other" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_with_other == true ? ' checked="checked"' : '').' autocomplete="off" >';
+ echo $lang['srv_para_show_rows_other'];
+ echo '</label>';
+ echo '</div>';
+ echo '<div class="floatLeft spaceLeftBig anl_bl">';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_categories" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_categories == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_analiza_kategorialneSpremenljivke'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_numbers" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_numbers == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_analiza_numericneSpremenljivke'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_text" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_text == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_analiza_textovneSpremenljivke'];
+ echo '</label>';
+ echo '</div>';
+
+ echo '<div class="floatLeft spaceLeftBig">';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_question_advanced" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_question_advanced == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_para_show_question_advanced'];
+ echo '</label>';
+ echo '<br/>';
+ echo '<label>';
+ echo '<input type="checkbox" id="show_graph_advanced" onclick="changeParaAnalysisCbx(this,false);" '.($this->show_graph_advanced == true ? ' checked="checked"' : '').' autocomplete="off" >';
+ echo $lang['srv_para_show_show_graph_advanced'];
+ echo '</label>';
+ echo '</div>';
+
+ # end:podrobno
+ echo '</td></tr></table>';
+
+ if ($paraType == 'basic') {
+ }
+ if ($paraType == 'advanced') {
+ }
+
+ echo '<div class="clr"></div>';
+
+ echo '</div>'; // konec diva zapiranje nastavitev
+
+
+ echo '<div id="div_para_data">';
+
+ echo '<div id="displayFilterNotes">';
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString();
+ echo '</div>';
+
+
+ if ($paraType == 'basic') {
+ $this->displayGraphDataBasic();
+ }
+ if ($paraType == 'advanced') {
+ $this->displayGraphDataAdvanced();
+ }
+ if ($paraType == 'breaks') {
+ $this->displayGraphDataBreaks();
+ }
+ echo '</div>'; #id="div_pra_data"
+
+ }
+
+
+ function DisplayLinks()
+ {
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->anketa);
+ $SSH -> displayAnalizaSubNavigation();
+ }
+
+
+ /** Prikazuje filtre
+ *
+ */
+ function DisplayFilters()
+ {
+ global $lang;
+
+ if ($this->dataFileStatus == FILE_STATUS_SRV_DELETED || $this->dataFileStatus == FILE_STATUS_NO_DATA)
+ {
+ return false;
+ }
+
+ if ($this->setUpJSAnaliza == true)
+ {
+ echo '<script>
+ window.onload = function() {
+ __analiza = 1;
+ }
+ </script>';
+ }
+
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->anketa);
+ # izrišemo desne linke do posameznih nastavitev
+ $SSH -> displayAnalizaRightOptions(M_ANALYSIS_PARA);
+
+ }
+
+ function displayGraphDataBreaks() {
+ global $lang;
+ $pageUrl = "index.php?anketa=" . $this->anketa . "&a=nonresponse_graph&m=breaks";
+ $showGraph = $this->show_graph_breaks;
+ $showQuestion = $this->show_question_breaks;
+ $showGraphType = $this->show_graph_breaks_type;
+
+ // prestejemo vprasanja, če jih je več kot 1 ne moreš na glasovanja
+ $sqlQ = sisplet_query("SELECT g.id as g_id, g.naslov, s.id as spr_id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' ORDER BY g.vrstni_red, s.vrstni_red");
+
+
+ $pages = array();
+ $sprPage = array();
+ while ($row = mysqli_fetch_assoc($sqlQ)) {
+ $sprPage[$row['spr_id']] = $row['g_id'];
+ if (!isset($pages[$row['g_id']])) {
+ $pages[$row['g_id']] = $row['naslov'];
+ }
+ }
+ $headerVariablesId = $this->getVariables();
+
+ list($data, $show_delta) = $this->collectData();
+
+ $cnt_missing = 0;
+ $cnt_undefined = 0;
+ $valid = SurveyStatusProfiles::getAllValidCount();
+ $all = SurveyStatusProfiles::getAllUserCount();
+
+ $percent_all = SurveyStatusProfiles::getActiveProfileUserCount();
+ $sspid = SurveyStatusProfiles::getCurentProfileId();
+ $isNotStandardProfile = ($sspid != 1 && $sspid != 2);
+ $added_colspan = 5+1*$isNotStandardProfile;
+ $showPercent = true;
+
+ // sort bo treba dodelat.. glede na to da se ns, ns_neto, ns_bruto izmenično prikazujejo v grafu
+/*
+ $sort_type = SORT_ASC;
+ if (isset($_REQUEST['sort_type'])
+ && ((int)$_REQUEST['sort_type'] == SORT_DESC || (int)$_REQUEST['sort_type'] == SORT_ASC)) {
+ $sort_type = (int)$_REQUEST['sort_type'];
+ }
+ if ($sort_type != SORT_DESC) {
+ $sort_type = SORT_ASC;
+ }
+ $sort_type_sprite = $sort_type == SORT_ASC ? 'sort_ascending' : 'sort_descending';
+
+ $sort_field = 'variable';
+ if (isset($_REQUEST['sort'])) {
+ $sort_field = $_REQUEST['sort'];
+ }
+
+ if ($sort_field != 'ns') {
+ $sort_field = 'variable';
+ }
+
+ // če ni po spremenljivki
+ if ($sort_field != 'variable') {
+ #do sort
+ #sort_seq=10&sort_type=sort_asc
+ $sort = array();
+ foreach ($rows as $key => $row) {
+ if ($sort_field == 'ns') {
+ $sort[$key] = $row['ns'];
+ } else {
+ $sort[$key] = $row['variable'];
+ }
+ }
+
+ array_multisort($sort, $sort_type, $rows);
+ } else {
+
+ if ($sort_type != SORT_ASC ) {
+ $rows = array_reverse($rows);
+ }
+
+ }
+
+ // če imamo privzeto sortiranje izrisujemo še strani
+ $showPages = false;
+ if (count($pages) > 1 && $sort_field == 'variable') {
+ if ($sort_type == SORT_ASC) {
+
+ } else {
+ $sprPage = array_reverse($sprPage, true);
+ }
+ $showPages = true;
+ }
+*/
+ // ko bo rešen sort odstrani še tole spodaj
+ $showPages = true;
+
+ $this->displayFormula();
+
+ $rows = $data;
+
+ $baseColspan = 6;
+
+ echo '<table id="tbl_para_analitics" class="graph'.($showGraph ? ' showGraph' : '').'">';
+ echo '<tr class="persist-header">';
+ echo '<th class="anl_w50 pointer" ';
+ if ($sort_field == 'variable') {
+ if ($sort_type == SORT_DESC) {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=v&sort_type=" . SORT_ASC . "')\"";
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=v&sort_type=" . SORT_DESC . "')\"";
+ }
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=v&sort_type=" . SORT_ASC . "')\"";
+ }
+ echo '>';
+ echo '<span class="floatLeft pointer">' . $lang['srv_para_variable'] . '</span>';
+ if ($sort_field == 'variable') {
+ echo '<span class="floatRight faicon '.$sort_type_sprite.'">&nbsp;</span>';
+ }
+ echo'</th>';
+ if ($showQuestion) {
+ echo '<th class="anl_w200" >'.$lang['srv_para_question'].'</th>';
+ }
+ echo '<th class="anl_w50" title="'.$lang['srv_para_breaks'].'">'.$lang['srv_para_breaks_short'].'</th>';
+ if ($show_delta) {
+ echo '<th class="anl_w50" title="'.$lang['srv_para_breaks_delta'].'">'.$lang['srv_para_breaks_delta_short'].'</th>';
+ }
+
+/*
+ * echo '<th class="anl_w70" title="'.$lang['srv_para_breaks_value'].'"';
+ if ($sort_field == 'ns') {
+ if ($sort_type == SORT_DESC) {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=ns&sort_type=" . SORT_ASC . "')\"";
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=ns&sort_type=" . SORT_DESC . "')\"";
+ }
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=ns&sort_type=" . SORT_ASC . "')\"";
+ }
+
+ echo '>';
+ echo '<span>' . $lang['srv_para_breaks_short']. Help :: display('srv_item_nonresponse') . '</span>';
+ if ($sort_field == 'ns') {
+ echo '<span class="floatRight faicon '.$sort_type_sprite.'">&nbsp;</span>';
+ }
+*/
+ echo '<th class="anl_w50" title="'.$lang['srv_para_breaks_value'].'">';
+ echo '<span>' . $lang['srv_para_breaks_value_short']. '</span>';
+ echo '</th>';
+ echo '<th class="anl_w50" title="'.$lang['srv_para_breaks_value_bruto'].'">';
+ echo '<span>' . $lang['srv_para_breaks_value_bruto_short'].'</span>';
+ echo '</th>';
+ echo '<th class="anl_w50" title="'.$lang['srv_para_breaks_value_neto'].'">';
+ echo '<span>' . $lang['srv_para_breaks_value_neto_short'].'</span>';
+ echo '</th>';
+# echo '<th class="anl_w70 pointer" title="'.$lang['srv_para_breaks_value_bruto'].'">';
+# echo '<span>' . $lang['srv_para_breaks_value_bruto_short']. '</span>';
+# echo '</th>';
+# echo '<th class="anl_w75 pointer" title="'.$lang['srv_para_breaks_value_neto'].'">';
+# echo '<span>' . $lang['srv_para_breaks_value_neto_short']. '</span>';
+# echo '</th>';
+ if ($showGraph) {
+ echo '<th class="anl_bb" title="' . $lang['srv_para_breaks_graph_title'] . '">' . $lang['srv_para_breaks_graph_title'] . '</th>';
+ }
+ echo '</tr>';
+
+ if ($showPages) {
+ $oldPage = reset($sprPage);
+ $newPage = $oldPage;
+ echo '<tr>';
+ echo '<td colspan="' . ($baseColspan + (int)$showQuestion + (int)$showGraph). '" class=" para_page_break">
+ <span>' . $pages[$newPage] . '</span></td>';
+ //echo '<td class="empty_cell"></td>';
+ echo '</tr>';
+
+ }
+ foreach ($rows AS $row) {
+ if ($showPages) {
+ $newPage = $sprPage[$row['sid']];
+ if ($newPage != $oldPage) {
+ $oldPage = $newPage;
+ echo '<tr>';
+ echo '<td colspan="' . ($baseColspan + (int)$showQuestion + (int)$showGraph). '" class=" para_page_break">
+ <span>' . $pages[$newPage] . '</span></td>';
+ //echo '<td class="empty_cell"></td>';
+ echo '</tr>';
+ }
+ }
+
+ echo '<tr class="'.$css_sublcass.'">';
+ echo '<td >';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $row['spid'] . '\'); return false;" href="#">' . $row['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ if ($showQuestion) {
+ echo '<td>';
+ echo (strlen($row['naslov']) > 40 ? substr($row['naslov'],0,40)."..." : $row['naslov']);
+ echo '</td>';
+ }
+ $val = 0;
+ if (isset($row['values'][-3])) {
+ $val = $row['values'][-3];
+ }
+ echo '<td>'.$val.'</td>';
+ if ($show_delta) {
+ echo '<td>'.$row['delta'].'</td>';
+ }
+ echo '<td>'.common::formatNumber($row['sp']*100,1).'</td>';
+ echo '<td>'.common::formatNumber($row['sp_bruto']*100,1).'</td>';
+ echo '<td>'.common::formatNumber($row['sp_neto']*100,1).'</td>';
+
+ #echo '<td>'.common::formatNumber($value,2).'</td>';
+ if ($showGraph) {
+ $width = $row['sp'];
+ if ((int)$showGraphType == 1) {
+ $width = $row['sp_bruto'];
+ } elseif ((int)$showGraphType == 2) {
+ $width = $row['sp_neto'];
+ }
+
+ echo '<td class="empty_cell">';
+ if ($row['sp'] > 0) {
+ echo '<div class="para_analitics_bar" style="'.'width:'.($width*100).'%; text-align:right; padding-right:5px; color:green;"></div>';
+ } else {
+ echo '<div class="para_analitics_bar null_value" style="'.'width:1px"></div>';
+ }
+ echo '</td>';
+ }
+ echo '</tr>';
+
+ }
+ echo '</table>';
+ #SurveyAnalysisHelper::getInstance()->displayMissingLegend();
+
+ $this->displayLink();
+ echo '<br class="clr" />';
+ }
+
+
+ function displayGraphDataBasic() {
+ global $lang;
+
+ $pageUrl = "index.php?anketa=" . $this->anketa . "&a=nonresponse_graph";
+
+ $showGraph = $this->show_graph_basic;
+ $showQuestion = $this->show_question_basic;
+
+
+ $headerVariablesId = $this->getVariables();
+
+ list($data, $show_delta) = $this->collectData();
+ // delta naj se ne prikazuje pri Spremenljivke
+ $show_delta = false;
+
+ $cnt_missing = 0;
+ $cnt_undefined = 0;
+ $valid = SurveyStatusProfiles::getAllValidCount();
+ $all = SurveyStatusProfiles::getAllUserCount();
+
+ $percent_all = SurveyStatusProfiles::getActiveProfileUserCount();
+ $sspid = SurveyStatusProfiles::getCurentProfileId();
+ $isNotStandardProfile = ($sspid != 1 && $sspid != 2);
+ $added_colspan = 5+1*$isNotStandardProfile;
+ $showPercent = true;
+
+ $rows = $data;
+
+ /*
+ # pripravimo podatke
+ $rows = array();
+ foreach ($headerVariablesId AS $headerVariableId) {
+ $spr = $this->_HEADERS[$headerVariableId];
+ if (empty($spr['grids'])) {
+ continue;
+ }
+ $grids = $spr['grids'];
+ foreach ($grids AS $gid => $grid) {
+
+ $variables = $grid['variables'];
+ if (empty($variables)) {
+ continue;
+ }
+ foreach ($variables AS $vid => $variable) {
+ $data_seq = array();
+ $tip = $spr['tip'];
+ $seq = $variable['sequence'];
+
+ if (!isset($data[$seq])) {
+ continue;
+ }
+
+ $data_seq = $data[$seq];
+ $_value = 0;
+ $exposed = 0;
+
+ if (isset($data_seq[-1]) && (int)$data_seq[-1] > 0) {
+ $valid = isset($data_seq['valid']) ? (int)$data_seq['valid'] : 0;
+ // vsi nevsebinski -99, 98,97,96,95…
+ $non_conceptual_sum = 0;
+ foreach(array_keys($this->_unsets) AS $non_conceptual) {
+ if (isset($data_seq[$non_conceptual])) {
+ $non_conceptual_sum += $data_seq[$non_conceptual];
+ }
+ }
+ $exposed = ($data_seq[-1] + $valid + $non_conceptual_sum);
+ if ($exposed > 0 && $data_seq[-1] > 0) {
+ $_value = $data_seq[-1] / $exposed ;
+ }
+ }
+
+ $_variable = $variable['variable'];
+ $_naslov = $variable['naslov'];
+ if (count($variables) > 1 && in_array($tip, array(2,18,17))) {
+ $_variable = $spr['variable'];
+ $_naslov = $spr['naslov'];
+ }
+ if ($tip == 16 ) {
+ $_variable = $grid['variable'];
+ $_naslov = $grid['naslov'];
+
+ }
+
+ $row_data = array(
+ 't'=>$spr['tip'],
+ 'v'=>$_variable,
+ 'n'=>$_naslov,
+ 'w'=>$_value,
+ 'h'=>$headerVariableId,
+ 'e' => $exposed,
+ 'd'=>$data_seq['delta']
+ );
+ $rows[] = $row_data;
+ if (in_array($tip, array(2,18,17)) || $tip == 16) {
+ break;
+ }
+ }
+ }
+ }
+ */
+ $sort_type = SORT_ASC;
+ if (isset($_REQUEST['sort_type'])
+ && ((int)$_REQUEST['sort_type'] == SORT_DESC || (int)$_REQUEST['sort_type'] == SORT_ASC)) {
+ $sort_type = (int)$_REQUEST['sort_type'];
+ }
+ if ($sort_type != SORT_DESC) {
+ $sort_type = SORT_ASC;
+ }
+ $sort_type_sprite = $sort_type == SORT_ASC ? 'sort_ascending' : 'sort_descending';
+
+ $sort_field = 'variable';
+ if (isset($_REQUEST['sort'])) {
+ $sort_field = $_REQUEST['sort'];
+ }
+
+ if ($sort_field != 'ns') {
+ $sort_field = 'variable';
+ }
+
+ // če ni po spremenljivki
+ if ($sort_field != 'variable') {
+ #do sort
+ #sort_seq=10&sort_type=sort_asc
+ $sort = array();
+ foreach ($rows as $key => $row) {
+ if ($sort_field == 'ns') {
+ $sort[$key] = $row['ns'];
+ } else {
+ $sort[$key] = $row['variable'];
+ }
+ }
+
+ array_multisort($sort, $sort_type, $rows);
+ } else {
+
+ if ($sort_type != SORT_ASC ) {
+ $rows = array_reverse($rows);
+ }
+
+ }
+
+ $this->displayFormula();
+
+ echo '<table id="tbl_para_analitics" class="graph'.($showGraph ? ' showGraph' : '').'">';
+ echo '<tr class="persist-header">';
+ echo '<th class="pointer" ';
+ if ($sort_field == 'variable') {
+ if ($sort_type == SORT_DESC) {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=variable&sort_type=" . SORT_ASC . "')\"";
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=variable&sort_type=" . SORT_DESC . "')\"";
+ }
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=variable&sort_type=" . SORT_ASC . "')\"";
+ }
+ echo '>';
+ echo '<span class="floatLeft pointer">' . $lang['srv_para_variable'] . '</span>';
+ if ($sort_field == 'variable') {
+ echo '<span class="floatRight sprites '.$sort_type_sprite.'">&nbsp;</span>';
+ }
+ echo'</th>';
+ if ($showQuestion) {
+ echo '<th>'.$lang['srv_para_question'].'</th>';
+ }
+ if ($show_delta) {
+ echo '<th class="anl_w50" title="'.$lang[''].'">delta</th>';
+ }
+ echo '<th class="anl_w50 pointer" title="'.$lang['srv_para_unaswered'].'"';
+ if ($sort_field == 'ns') {
+ if ($sort_type == SORT_DESC) {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=ns&sort_type=" . SORT_ASC . "')\"";
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=ns&sort_type=" . SORT_DESC . "')\"";
+ }
+ } else {
+ echo " onclick=\"window.location.assign('" . $pageUrl . "&sort=ns&sort_type=" . SORT_ASC . "')\"";
+ }
+ echo '>';
+ echo '<span>' . $lang['srv_para_unaswered_short'] . ' %</span>'; // . Help :: display('srv_item_nonresponse')
+ if ($sort_field == 'ns') {
+ echo '<span class="floatRight sprites '.$sort_type_sprite.'">&nbsp;</span>';
+ }
+ echo '</th>';
+ if ($showGraph) {
+ echo '<th class="anl_bb" title="' . $lang['srv_para_unaswered_graph_title'] . '">' . $lang['srv_para_unaswered_graph_title'] . '</th>';
+ }
+ echo '</tr>';
+
+ foreach ($rows AS $row) {
+ echo '<tr class="'.$css_sublcass.'">';
+ echo '<td >';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $row['spid'] . '\'); return false;" href="#">' . $row['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ if ($showQuestion) {
+ echo '<td>';
+ echo (strlen($row['naslov']) > 40 ? substr($row['naslov'],0,40)."..." : $row['naslov']);
+ echo '</td>';
+ }
+ if ($show_delta) {
+ echo '<td>'.$row['delta'].'</td>';
+ }
+ echo '<td>'.common::formatNumber($row['ns']*100,1).'</td>';
+ #echo '<td>'.common::formatNumber($value,2).'</td>';
+ if ($showGraph) {
+ echo '<td class="empty_cell">';
+ if ($row['ns'] > 0) {
+ echo '<div class="para_analitics_bar" style="'.'width:'.($row['ns']*100).'%; text-align:right; padding-right:5px; color:green;"></div>';
+ } else {
+ echo '<div class="para_analitics_bar null_value" style="'.'width:1px"></div>';
+ }
+ echo '</td>';
+ }
+ echo '</tr>';
+
+ }
+ echo '</table>';
+ #SurveyAnalysisHelper::getInstance()->displayMissingLegend();
+
+ $this->displayLink();
+ echo '<br class="clr" />';
+ }
+
+ function displayGraphDataAdvanced( ) {
+ global $lang;
+ global $admin_type;
+
+ $showGraph = $this->show_graph_advanced;
+ $showQuestion = $this->show_question_advanced;
+
+ $headerVariablesId = $this->getVariables();
+
+ list($data, $show_delta) = $this->collectData();
+ # ali odstranimo stolpce kateri imajo same 0
+ if ($this->show_with_zero == false) {
+ # odstranimo missinge brez vrednosti
+ foreach ($this->_missings AS $_key => $_missing) {
+ if (!isset($this->cols_with_value[$_key]) || $this->cols_with_value[$_key] == false) {
+ unset($this->_missings[$_key]);
+ }
+ }
+ # odstranimo neveljavne brez vrednosti
+ foreach ($this->_unsets AS $_key => $_unset) {
+ if (!isset($this->cols_with_value[$_key]) || $this->cols_with_value[$_key] == false) {
+ unset($this->_unsets[$_key]);
+ }
+ }
+ }
+
+ $cnt_missing = 0;
+ $cnt_undefined = 0;
+
+ $valid = SurveyStatusProfiles::getAllValidCount();
+ $all = SurveyStatusProfiles::getAllUserCount();
+
+ $percent_all = SurveyStatusProfiles::getActiveProfileUserCount();
+ $sspid = SurveyStatusProfiles::getCurentProfileId();
+ $isNotStandardProfile = ($sspid != 1 && $sspid != 2);
+ $added_colspan = 5+1+$show_delta+1*$isNotStandardProfile;
+ $showPercent = true;
+
+
+ $this->displayFormula();
+
+
+ echo '<table id="tbl_para_analitics" class="persist-area">';
+ echo '<tr class="persist-header">';
+
+ // Dodatna stolpca zaradi izvoza za Katjo Lozar
+ if($admin_type == '0'){
+ echo '<th style="width:30px;">ID VPRASANJA</th>';
+ echo '<th style="width:30px;">ID VARIABLE</th>';
+ }
+
+ echo '<th>'.$lang['srv_para_variable'].'</th>';
+ if ($showQuestion) {
+ echo '<th>'.$lang['srv_para_question'].'</th>';
+ }
+ echo '<th >'.$lang['srv_para_valid'].'</th>';
+ foreach ($this->_missings AS $value => $text) {
+ $cnt_miss++;
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_mv_'.$text]."\" >{$value}<br/>(".$lang['srv_mv_'.$text].")</th>";
+ }
+ foreach ($this->_unsets AS $value => $text)
+ {
+ $cnt_undefined++;
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_mv_'.$text]."\">{$value}<br/>(".$lang['srv_mv_'.$text].")</th>";
+ }
+ if ($show_delta) {
+ echo "<th class=\"anl_w50\" title=\"".$lang['']."delta\">".$lang['']."&Delta;</th>";
+ }
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_para_nonconceptual']."\">".$lang['srv_para_nonconceptual']."</th>";
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_para_approp']."\">".$lang['srv_para_approp']."</th>";
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_para_all_units']."\">".$lang['srv_para_all_units']."</th>";
+ if ($isNotStandardProfile)
+ {
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_para_status']."\">".$lang['srv_para_status']."</th>";
+ }
+ echo "<th class=\"anl_w50\" title=\"".$lang['srv_para_unaswered']."\">".$lang['srv_para_unaswered_short']. Help :: display('srv_item_nonresponse')."</th>";
+ if ($showGraph) {
+ echo '<th class="anl_bb">' . $lang['srv_para_unaswered_graph_title'] . '</th>';
+ }
+
+ echo '</tr>';
+ foreach ($headerVariablesId AS $key => $headerVariableId)
+ {
+ $spr = $this->_HEADERS[$headerVariableId];
+ # ali preskočimo kategorije, numerične, besedilo
+ if (($this->show_categories == false && in_array($spr['tip'], $this->spr_type['showCategories']))
+ || ($this->show_numbers == false && in_array($spr['tip'], $this->spr_type['showNumbers']))
+ || ($this->show_text == false && in_array($spr['tip'], $this->spr_type['showText']))) {
+ # if ($this->show_with_text == false && in_array($spr['tip'], array(5, 4, 19, 21))) {
+ continue;
+ }
+
+ if (!empty($spr['grids'])) {
+ $grids = $spr['grids'];
+ if (count($grids) > 1) {
+ # če imamo več grup dodamo header vrstico
+ echo '<tr class="multiGroupHeader">';
+
+ if($admin_type == '0'){
+ echo '<td>'.$spr['spr_id'].'</td>';
+ echo '<td></td>';
+ }
+
+ if ($showQuestion) {
+ echo '<td class="showQuestion">';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $spr['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ echo '<td colspan="'.(count($this->_missings)+count($this->_unsets)+$added_colspan).'">';
+ echo $spr['naslov'];
+ echo '</td>';
+ } else {
+ echo '<td colspan="'.(count($this->_missings)+count($this->_unsets)+$added_colspan).'">';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $spr['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ }
+ if ($showGraph) {
+ echo '<td class="empty_cell30"></td>';
+ }
+ echo '</tr>';
+ }
+ else {
+ $css_GridSublcass = '';
+ }
+
+ foreach ($grids AS $gid => $grid)
+ {
+ $variables = $grid['variables'];
+
+ if (!empty($variables)) {
+ if (count($variables) > 1 ) {
+
+ # če imamo več variabel dodamo header vrstico, vrstice variabel pa obarvamo svetleje
+ $css_sublcass = 'subVar';
+ if (in_array($spr['tip'], array(2,18,17))) {
+ #razvššanje nima zapisa v grupi ampak preberemo iz spremenljivke
+
+ echo '<tr class="multiGroupHeader">';
+
+ if($admin_type == '0'){
+ echo '<td>'.$spr['spr_id'].'</td>';
+ echo '<td></td>';
+ }
+
+ if ($showQuestion) {
+ echo '<td class="showQuestion">';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $spr['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ echo '<td colspan="'.(count($this->_missings)+count($this->_unsets)+$added_colspan ).'">';
+ echo $spr['naslov'];
+ echo '</td>';
+ } else {
+ echo '<td colspan="'.(count($this->_missings)+count($this->_unsets)+$added_colspan ).'">';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $spr['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ }
+ if ($showGraph) {
+ echo '<td class="empty_cell30"></td>';
+ }
+ echo '</tr>';
+
+ }
+ else
+ { #dodamo header za grupo
+ echo '<tr class="multiVariablesHeader">';
+
+ if($admin_type == '0'){
+ echo '<td>'.$spr['spr_id'].'</td>';
+ echo '<td></td>';
+ }
+
+ if ($showQuestion) {
+ echo '<td class="showQuestion">';
+ if (count($grids) > 1) {
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $grid['variable'] . '</a>';
+ echo '</span>';
+ } else {
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $spr['variable'] . '</a>';
+ echo '</span>';
+ }
+ echo '</td>';
+ echo '<td colspan="'.(count($this->_missings)+count($this->_unsets)+$added_colspan).'">';
+ echo $grid['naslov'];
+ echo '</td>';
+ } else {
+ echo '<td colspan="'.(count($this->_missings)+count($this->_unsets)+$added_colspan).'">';
+ if (count($grids) > 1) {
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $grid['variable'] . '</a>';
+ echo '</span>';
+ } else {
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $spr['variable'] . '</a>';
+ echo '</span>';
+ }
+ echo '</td>';
+ }
+ if ($showGraph) {
+ echo '<td class="empty_cell30"></td>';
+ }
+ echo '</tr>';
+ }
+ }
+ else {
+ $css_sublcass = '';
+ }
+ foreach ($variables AS $vid => $variable)
+ {
+ // če ne prikazuemo polji "Drugo"
+ if ($this->show_with_other == false && $variable['other']) {
+ continue;
+ }
+
+ $seq = $variable['sequence'];
+ $data_seq = $data[$seq];
+/*
+ $valid = isset($data_seq['valid']) ? (int)$data_seq['valid'] : 0;
+ $nonresponse = 0;
+ $exposed = 0;
+ $non_conceptual_sum = 0;
+ if (isset($data_seq[-1]) && (int)$data_seq[-1] > 0) {
+ // vsi nevsebinski -99, 98,97,96,95…
+ $non_conceptual_sum = 0;
+ foreach(array_keys($this->_unsets) AS $non_conceptual) {
+ if (isset($data_seq[$non_conceptual])) {
+ $non_conceptual_sum += $data_seq[$non_conceptual];
+ }
+ }
+ $exposed = ($data_seq[-1] + $valid + $non_conceptual_sum);
+ if ($data_seq[-1] > 0 && $exposed > 0 ) {
+ $nonresponse = $data_seq[-1] / $exposed;
+ }
+ }
+ $delta = $data_seq['delta'];
+*/
+ echo '<tr class="'.$css_sublcass.'">';
+
+ if($admin_type == '0'){
+ echo '<td rowspan="'.($showPercent*2).'">'.$spr['spr_id'].'</td>';
+ echo '<td rowspan="'.($showPercent*2).'">'.$variable['vr_id'].'</td>';
+ }
+
+ //echo '<td style="border-top:0px none !important;border-bottom:0px none !important;">&nbsp;</td>';
+
+ echo '<td rowspan="'.($showPercent*2).'">';
+ echo '<span class="anl_variabla">';
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\'' . $key . '\'); return false;" href="#">' . $variable['variable'] . '</a>';
+ echo '</span>';
+ echo '</td>';
+ if ($showQuestion) {
+ echo '<td class="showQuestion" rowspan="'.($showPercent*2).'">';
+ echo $variable['naslov'];
+ echo '</td>';
+ }
+ echo '<td>';
+ echo (int)$data_seq['veljavni'];
+ echo '</td>';
+ foreach ($this->_missings AS $value => $text) {
+ $missing = 0;
+ if (isset($data_seq['values'][$value])) {
+ $missing = $data_seq['values'][$value];
+ }
+ echo '<td>'.(int)$missing.'</td>';
+ }
+ foreach ($this->_unsets AS $value => $text) {
+ $unset = 0;
+ if (isset($data_seq['values'][$value])) {
+ $unset = $data_seq['values'][$value];
+ }
+ echo '<td>'.(int)$unset.'</td>';
+ }
+ if ($show_delta) {
+ echo "<td rowspan=\"".($showPercent*2)."\">{$data_seq['delta']}</td>";
+ }
+ echo "<td rowspan=\"".($showPercent*2)."\">{$data_seq['prikazani']}</td>";
+ echo "<td rowspan=\"".($showPercent*2)."\">{$data_seq['veljavni']}</td>";
+ echo "<td rowspan=\"".($showPercent*2)."\">{$all}</td>";
+ if ($isNotStandardProfile)
+ {
+ echo "<td rowspan=\"".($showPercent*2)."\">{$percent_all}</td>";
+ }
+ echo "<td rowspan=\"".($showPercent*2)."\">" . common::formatNumber($data_seq['ns'],2) . "</td>";
+ if ($showGraph) {
+ echo "<td rowspan=\"".($showPercent*2)."\" class=\"empty_cell30\">";
+ if ($data_seq['ns'] > 0) {
+ echo '<div class="para_analitics_bar" style="'.'width:'.($data_seq['ns']*100).'%; text-align:right; padding-right:5px; color:green;"></div>';
+ } else {
+ echo '<div class="para_analitics_bar null_value" style="'.'width:1px"></div>';
+ }
+ echo '</td>';
+ }
+ echo '</tr>';
+
+ if ($showPercent)
+ {
+ echo '<tr class="'.$css_sublcass.' percent">';
+ echo '<td>';
+ $val = 0;
+ if ($percent_all > 0) {
+ $val = $data[$seq]['veljavni'] / $percent_all * 100;
+ }
+ echo common::formatNumber($val,0,null,'%') ;
+ echo '</td>';
+ foreach ($this->_missings AS $value => $text) {
+ $val = 0;
+ if ($percent_all > 0 && isset($data[$seq]['values'][$value])) {
+ $val = ($data[$seq]['values'][$value] / $percent_all * 100);
+ }
+ echo '<td>'.common::formatNumber($val,0,null,'%').'</td>';
+ }
+ foreach ($this->_unsets AS $value => $text)
+ {
+ $val = 0;
+ if ($percent_all > 0 && isset($data[$seq]['values'][$value])) {
+ $val = ($data[$seq]['values'][$value] / $percent_all * 100);
+ }
+ echo '<td>'.common::formatNumber($val,0,null,'%').'</td>';
+ }
+ echo '</tr>';
+ }
+ }
+ }
+ }
+ }
+ }
+ echo '</table>';
+ SurveyAnalysisHelper::getInstance()->displayMissingLegend();
+
+ echo '<br class="clr" />';
+
+ }
+
+ function getVariables()
+ {
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+ $tmp_svp_pv = SurveyVariablesProfiles :: getProfileVariables($this->_PROFILE_ID_VARIABLE );
+
+ # če je $svp_pv = null potem prikazujemo vse variable
+ # oziroma če je sistemski dodamo tudi vse, ker drugače lahko filter skrije telefon in email
+ if (empty($tmp_svp_pv))
+ {
+ $_sv = $this->SDF->getSurveyVariables();
+ if (count($_sv) > 0)
+ {
+ foreach ( $_sv as $vid => $variable)
+ {
+ $tmp_svp_pv[$vid] = $vid;
+ }
+ }
+ }
+ $svp_pv = array();
+ if (!empty($tmp_svp_pv))
+ {
+ foreach ($tmp_svp_pv AS $_svp_pv)
+ {
+ $svp_pv[$_svp_pv] = $_svp_pv;
+ }
+ }
+ return $svp_pv;
+ }
+
+ public function collectData() {
+ # polovimo 2 skupini podatkov 1. ustrezni (ko niso misisingi) 2. missinge)
+ global $site_path;
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ #array za imeni tmp fajlov, ki jih nato izbrišemo
+ $tmp_file = $folder.'tmp_export_'.$this->anketa.'_para_data.php';
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ # s katero sekvenco se začnejo podatki, da ne delamo po nepotrebnem za ostala polja
+ $start_sequence = $this->_HEADERS['_settings']['dataSequence'];
+ # s katero sekvenco se končajo podatki da ne delamo po nepotrebnem za ostala polja
+ $end_sequence = $this->_HEADERS['_settings']['metaSequence']-1;
+
+ # naredimo datoteko z frekvencami
+ # za windows sisteme in za linux sisteme
+ if (IS_WINDOWS ) {
+ # TEST z LINUX načinom
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}" '.$this->dataFileName;
+ $command .= ' | sed "s*\x27*`*g" ';
+ $command .= ' | awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} { print \"$frequency[\",$1,\"]\",\"[\x27\",$2,\"\x27]\",\"=\",$3,\";\"}" >> '.$tmp_file;
+ } else {
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" \'BEGIN {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}\' '.$this->dataFileName;
+ $command .= ' | sed \'s*\x27*`*g\' ';
+ $command .= ' | awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} { print "$frequency[",$1,"]","[\x27",$2,"\x27]","=\x27",$3,"\x27;"}\' >> '.$tmp_file;
+ }
+
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+
+ $out = shell_exec($command);
+
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ # zloopamo po frekvencah in polovimo pravilne
+ $result = array();
+ $hasDelta = false;
+
+ $neodgovor_spremenljivke = array();
+ $this->cols_with_value = array();
+ if (empty($frequency)) {
+ return array('data'=>$result, 'hasDelta'=>$hasDelta);
+ }
+
+ $old_break = 0;
+ //loop skozi header variable da imamo sort po seq vprašanj
+ $headerVariablesId = $this->getVariables();
+ $delta = 0;
+
+ foreach ($headerVariablesId AS $headerVariableId) {
+ $spr = $this->_HEADERS[$headerVariableId];
+ if (empty($spr['grids'])) {
+ continue;
+ }
+ $grids = $spr['grids'];
+ foreach ($grids AS $gid => $grid) {
+ $variables = $grid['variables'];
+ if (empty($variables)) {
+ continue;
+ }
+ foreach ($variables AS $vid => $variable) {
+ $seq = $variable['sequence'];
+ if (!isset($frequency[$seq]) || empty($frequency[$seq])) {
+ continue;
+ }
+ // loop skozi odgovore spremenljivke
+ $freqData = $frequency[$seq];
+
+ $vseEnote = 0;
+ $veljavni = 0;
+ $prikazani = 0;
+ $nevsebinski = 0;
+ $neodgovori = 0;
+ $ustrezni = 0;
+ $neustrezni = 0;
+ $neodgovorSpremenljivke = 0;
+ $stopnjaPrekinitve = 0;
+ $stopnjaPrekinitveNeto = 0;
+ $stopnjaPrekinitveBruto = 0;
+ $delta = 0;
+ $values = array();
+ foreach ($freqData AS $key => $cnt) {
+
+ $vseEnote += $cnt;
+ if (is_numeric($key) && (isset($this->_missings[(int)$key]) || isset($this->_unsets[(int)$key]))) {
+ // shranimo vrednosti -1 ... -99 za prikaz v tabeli podrobno
+ $values[(int)$key] += $cnt;
+
+ $this->cols_with_value[(int)$key] += $cnt;
+ if (isset($this->_unsets[$key])) {
+
+ $nevsebinski += $cnt;
+ } elseif (isset($this->_missings[(int)$key])) {
+
+ $neodgovori += $cnt;
+ # -1 je bil prikazan pa ni bil odgovorjen
+ if ($key == -1) {
+ $prikazani += $cnt;
+ }
+ if ($key == -3) {
+ $hasDelta = true;
+ $delta = (int)$cnt - (int)$old_break;
+ $old_break = $cnt;
+ }
+ if ($key == -5) {
+ $neustrezni += $cnt;
+ }
+ }
+
+ } else {
+
+ $this->cols_with_value['valid'] += $cnt;
+ $veljavni += $cnt;
+ }
+ }
+
+ $prikazani += $nevsebinski + $veljavni;
+
+ #neodgovorSpremenljivke so: -1 / PRIKAZANO (veljavne + (-1) -99.....-90)
+ $ns = 0;
+ if (isset($values[-1]) && $values[-1] > 0) {
+ $ns = $values[-1] / ($prikazani); // -1 je v prikazanih
+ }
+ # prekinitve
+ $ustrezni = $vseEnote;
+ if (isset($values[-5])) {
+ $ustrezni = $ustrezni - $values[-5];
+ }
+
+ $prekinitve = 0;
+ if (isset($values[-3])) {
+ $prekinitve = $values[-3];
+ }
+
+ #prekinitve so: -3 /(-3) + PRIKAZANO (veljavne + (-1) -99.....-90)
+ $sp = 0;
+ if (($prikazani + $prekinitve) > 0) {
+ $sp = $prekinitve / ($prikazani + $prekinitve);
+ }
+
+ #neto so DELTA/(-3+PRIKAZANO)
+ $neto_sp = 0;
+ if (($prikazani + $prekinitve) > 0) {
+ $neto_sp = $delta / ($prikazani + $prekinitve);
+ }
+
+ #bruto pa so (-3)/vse ustrezne enote (torej -3, -2, -1, -4, veljavni, -90...) vse razen empty
+ $bruto_sp = 0;
+ if ($ustrezni > 0) {
+ $bruto_sp = $prekinitve / $ustrezni;
+ }
+
+ $_variable = $variable['variable'];
+ $_naslov = $variable['naslov'];
+ if (count($variables) > 1 && in_array($tip, array(2,18,17))) {
+ $_variable = $spr['variable'];
+ $_naslov = $spr['naslov'];
+ }
+ if ($tip == 16 ) {
+ $_variable = $grid['variable'];
+ $_naslov = $grid['naslov'];
+ }
+
+ $result[$seq]['spid'] = $headerVariableId;
+ $result[$seq]['sid'] = $spr['spr_id'];
+ $result[$seq]['variable'] = $_variable;
+ $result[$seq]['naslov'] = $_naslov;
+
+ $result[$seq]['vse_enote'] = $vseEnote;
+ $result[$seq]['veljavni'] = $veljavni;
+ $result[$seq]['prikazani'] = $prikazani;
+ $result[$seq]['ustrezni'] = $ustrezni;
+ #$result[$seq]['nevsebinski'] = $nevsebinski;
+ #$result[$seq]['neodgovori'] = $neodgovori;
+ $result[$seq]['delta'] = $delta;
+ $result[$seq]['values'] = $values;
+
+ $result[$seq]['ns'] = $ns ;
+ $result[$seq]['sp'] = $sp ;
+ $result[$seq]['sp_neto'] = $neto_sp ;
+ $result[$seq]['sp_bruto'] = $bruto_sp ;
+
+ }
+ }
+ }
+
+ return array($result, $hasDelta);
+ }
+
+ function ajax()
+ {
+ $action = $_GET['a'];
+ switch ($action)
+ {
+ case 'setCbx' :
+ $this->setCbx();
+ break;
+ case 'setValue' :
+ $this->setValue();
+ break;
+ }
+ }
+ function setCbx() {
+ $value = $_REQUEST['value'];
+ if ($value == 'false') {
+ $value = false;
+ }
+ if ($value == 'true') {
+ $value = true;
+ }
+
+ $what = $_POST['what'];
+
+ $this->sessionData['para_analysis'][$what] = $value;
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ }
+ function setValue() {
+ $value = $_REQUEST['value'];
+ $what = $_POST['what'];
+ $this->sessionData['para_analysis'][$what] = $value;
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function displayLink() {
+# global $lang;
+# echo '<a href="index.php?anketa=' . $this->anketa .'&a=analysis&m=para">' . $lang['srv_napredno'] . '</a>';
+ }
+ function displayFormula() {
+ return false;
+ global $lang;
+ echo '<table><tr><td rowspan="2">' . $lang['srv_para_unaswered'] . ' (' . $lang['srv_para_unaswered_short'] . ')' . ' = </td><td class="anl_bb anl_ac">(-1)</td></tr><tr><td class="anl_ac">(' . $lang['srv_para_valid'] . ') + (-1) + (-97) + (-98) + (-99)</td></tr><table>';
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyParaGraph.php b/admin/survey/classes/class.SurveyParaGraph.php
new file mode 100644
index 0000000..891af1b
--- /dev/null
+++ b/admin/survey/classes/class.SurveyParaGraph.php
@@ -0,0 +1,437 @@
+<?php
+
+class SurveyParaGraph{
+
+ private $anketa; # id ankete
+ private $paraGraph_filter = array(); # Filtriranje parapodatkov (po napravi ali po statusu)
+
+ function __construct($anketa){
+ global $global_user_id;
+
+ if((int)$anketa > 0){
+ $this->anketa = $anketa;
+
+ SurveyStatusProfiles :: Init($this->anketa);
+ }
+ else{
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+ function setParaGraphFilter($pgf) {
+
+ $this->paraGraph_filter = $pgf;
+ }
+
+ function DisplayParaGraph(){
+ global $lang;
+ global $site_path;
+ global $admin_type;
+
+ // Nastavimo filter
+ $this->paraGraphSetFilter();
+
+ // Popravimo stare ankete -> v bazo vnesemo browser, os, device, popravljen js
+ $this->paraGraphFixOld();
+
+ // Zberemo podatke vseh userjev
+ $paraData = $this->collectParaGraphDataNew();
+
+
+ echo '<p>'.$lang['srv_para_graph_text'].'</p>';
+
+
+ // PC, tablica, mobi
+ echo '<fieldset><legend>'.$lang['srv_para_graph_device'].'</legend>';
+
+ // Filter po napravi
+ echo '<div style="margin:5px 0 15px 5px;">';
+ echo '<label>'.$lang['srv_analiza_filter'].': </label>';
+ echo '<label for="paraGraph_filter_pc"><input type="checkbox" id="paraGraph_filter_pc" '.($this->paraGraph_filter['pc']==1 ? ' checked="checked"' : '').' onClick="changeParaGraphFilter();">'.$lang['srv_para_graph_device0'].'</label>';
+ echo ' <label for="paraGraph_filter_mobi"><input type="checkbox" id="paraGraph_filter_mobi" '.($this->paraGraph_filter['mobi']==1 ? ' checked="checked"' : '').' onClick="changeParaGraphFilter();">'.$lang['srv_para_graph_device1'].'</label>';
+ echo ' <label for="paraGraph_filter_tablet"><input type="checkbox" id="paraGraph_filter_tablet" '.($this->paraGraph_filter['tablet']==1 ? ' checked="checked"' : '').' onClick="changeParaGraphFilter();">'.$lang['srv_para_graph_device2'].'</label>';
+ echo ' <label for="paraGraph_filter_robot"><input type="checkbox" id="paraGraph_filter_robot" '.($this->paraGraph_filter['robot']==1 ? ' checked="checked"' : '').' onClick="changeParaGraphFilter();">'.$lang['srv_para_graph_device3'].'</label>';
+ echo '&nbsp;&nbsp;&nbsp;<label>('.$lang['srv_para_graph_filteredCnt'].' '.$paraData['allCount'].')</label>';
+ echo '</div>';
+
+
+ echo '<table style="width:100%">';
+
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_device0'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['pcCount']/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['pcCount'].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_device1'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['mobiCount']/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['mobiCount'].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_device2'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['tabletCount']/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['tabletCount'].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+
+ // Zaenkrat nimamo detekcije robotov, ker se uporablja browscap lite
+ /*echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_device3'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['robotCount']/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['robotCount'].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+
+ //echo '<tr><td colspan="3" style="border-bottom:1px solid #E4E4F9"></td></tr>';
+ //echo '<tr><td></td><th style="text-align:left; padding-right: 20px" nowrap>'.$lang['srv_anl_suma1'].': '.$paraData['allCount'].'</th></tr>';*/
+
+ echo '</table>';
+
+ echo '</fieldset>';
+
+
+ // Browser
+ echo '<fieldset><legend>'.$lang['srv_para_graph_browser'].'</legend>';
+
+ echo '<table style="width:100%">';
+
+ if(count($paraData['browser']) > 0){
+ if(count($paraData['browser']) > 1)
+ ksort($paraData['browser'], SORT_REGULAR);
+
+ foreach($paraData['browser'] as $key => $browserCnt){
+
+ if($key != $lang['srv_para_graph_other_slo'] && $key != $lang['srv_para_graph_other_ang']){
+ echo '<tr>';
+ echo '<th nowrap>'.$key.'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $browserCnt/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$browserCnt.'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ }
+
+ if(isset($paraData['browser'][$lang['srv_para_graph_other_slo']]) && $paraData['browser'][$lang['srv_para_graph_other_slo']] > 0){
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_other'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['browser'][$lang['srv_para_graph_other_slo']]/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['browser'][$lang['srv_para_graph_other_slo']].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+
+ if(isset($paraData['browser'][$lang['srv_para_graph_other_ang']]) && $paraData['browser'][$lang['srv_para_graph_other_ang']] > 0){
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_other'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['browser'][$lang['srv_para_graph_other_ang']]/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['browser'][$lang['srv_para_graph_other_ang']].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+
+ //echo '<tr><td colspan="3" style="border-bottom:1px solid #E4E4F9"></td></tr>';
+ //echo '<tr><td></td><th style="text-align:left; padding-right: 20px" nowrap>'.$lang['srv_anl_suma1'].': '.$paraData['allCount'].'</th></tr>';
+ }
+
+ echo '</table>';
+
+ echo '</fieldset>';
+
+
+ // Operacijski sistem
+ echo '<fieldset><legend>'.$lang['srv_para_graph_os'].'</legend>';
+
+ echo '<table style="width:100%">';
+
+ if(count($paraData['os']) > 0){
+ if(count($paraData['os']) > 1)
+ ksort($paraData['os'], SORT_REGULAR);
+
+ foreach($paraData['os'] as $key => $osCnt){
+
+ if($key != $lang['srv_para_graph_other_slo'] && $key != $lang['srv_para_graph_other_ang']){
+ echo '<tr>';
+ echo '<th nowrap>'.$key.'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $osCnt/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$osCnt.'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ }
+
+ if(isset($paraData['os'][$lang['srv_para_graph_other_slo']]) && $paraData['os'][$lang['srv_para_graph_other_slo']] > 0){
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_other'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['os'][$lang['srv_para_graph_other_slo']]/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['os'][$lang['srv_para_graph_other_slo']].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+
+ if(isset($paraData['os'][$lang['srv_para_graph_other_ang']]) && $paraData['os'][$lang['srv_para_graph_other_ang']] > 0){
+ echo '<tr>';
+ echo '<th nowrap>'.$lang['srv_para_graph_other'].'</th>';
+ echo '<td style="width:100%">';
+ echo ' <div class="graph_lb" style="text-align: right; float: left; width: '.($paraData['allCount']>0 ? $paraData['os'][$lang['srv_para_graph_other_ang']]/$paraData['allCount']*85 : '0').'%">&nbsp;</div>';
+ echo ' <span style="display: block; margin: auto auto auto 5px; float: left">'.$paraData['os'][$lang['srv_para_graph_other_ang']].'</span></span>';
+ echo '</td>';
+ echo '</tr>';
+ }
+
+ //echo '<tr><td colspan="3" style="border-bottom:1px solid #E4E4F9"></td></tr>';
+ //echo '<tr><td></td><th style="text-align:left; padding-right: 20px" nowrap>'.$lang['srv_anl_suma1'].': '.$paraData['allCount'].'</th></tr>';
+ }
+
+ echo '</table>';
+
+ echo '</fieldset>';
+ }
+
+
+ function collectParaGraphData(){
+ global $lang;
+
+ SurveySetting::getInstance()->Init($this->anketa);
+
+ // Preberemo tabelo s podatki za izbrane filtre (ce ze obstaja)
+ $filterString = implode('_', $this->paraGraph_filter);
+ $paraData = unserialize(SurveySetting::getInstance()->getSurveyMiscSetting('para_graph_data_'.$filterString));
+
+ // Pogledamo kdaj je bila kreirana datoteka (ce imamo nove podatke)
+ $sqlTime = sisplet_query("SELECT UNIX_TIMESTAMP(last_update) AS last_update FROM srv_data_files WHERE sid='".$this->anketa."'");
+ $rowTime = mysqli_fetch_array($sqlTime);
+ $time = $rowTime['last_update'];
+
+ $status = ($this->paraGraph_filter['status'] == 1) ? ' AND last_status>\'4\'' : ' AND last_status>\'2\'';
+ $sqlu = sisplet_query("SELECT useragent FROM srv_user WHERE ank_id='".$this->anketa."' ".$status." AND preview='0' AND deleted='0'");
+
+ // Ce se nimamo shranjenih izracunov (timestamp datoteke se ne ujema), racunamo na novo
+ if(!isset($paraData['allCount']) || $paraData['timestamp'] != $time || $_GET['refresh'] == 1){
+
+ $sqlu2 = sisplet_query("SELECT id FROM srv_user WHERE ank_id='".$this->anketa."' AND last_status>'2' AND u.preview='0' AND u.deleted='0'");
+
+ $paraData = array(
+ 'timestamp' => $time,
+ 'unfilteredCount' => mysqli_num_rows($sqlu2),
+ 'allCount' => 0,
+ 'pcCount' => 0,
+ 'mobiCount' => 0,
+ 'tabletCount' => 0,
+ 'robotCount' => 0,
+ 'browser' => array(),
+ 'os' => array()
+ );
+
+ $detect = New Mobile_Detect();
+
+ // Loop cez vse ustrezne respondente
+ while($rowu = mysqli_fetch_array($sqlu)){
+
+ // Detect mobilnikov in tablic
+ $detect->setUserAgent($rowu['useragent']);
+
+ // Detect z browscap
+ $browserDetect = get_browser($rowu['useragent'], true);
+
+ // Filtriranje po napravi
+ if( ($this->paraGraph_filter['pc'] != 0 || $detect->isMobile() || $browserDetect['crawler'] == 1)
+ && ($this->paraGraph_filter['tablet'] != 0 || !$detect->isTablet())
+ && ($this->paraGraph_filter['mobi'] != 0 || !$detect->isMobile() || $detect->isTablet())
+ && ($this->paraGraph_filter['robot'] != 0 || $browserDetect['crawler'] != 1) ){
+
+ // Naprava
+ if($detect->isMobile()) {
+ if($detect->isTablet())
+ $paraData['tabletCount']++;
+ else
+ $paraData['mobiCount']++;
+ }
+ elseif($browserDetect['crawler'] == 1)
+ $paraData['robotCount']++;
+ else
+ $paraData['pcCount']++;
+
+ // Browser
+ if($browserDetect['browser'] == 'Default Browser')
+ $browser = $lang['srv_para_graph_other'];
+ else
+ $browser = $browserDetect['browser'].' '.$browserDetect['version'];
+ $paraData['browser'][$browser]++;
+
+ // OS
+ if($browserDetect['platform'] == 'unknown')
+ $os = $lang['srv_para_graph_other'];
+ else
+ $os = $browserDetect['platform'];
+
+ $paraData['os'][$os]++;
+
+
+ $paraData['allCount']++;
+ }
+ }
+
+ // Na koncu shranimo nove izracune v bazo
+ SurveySetting::getInstance()->setSurveyMiscSetting('para_graph_data_'.$filterString, serialize($paraData));
+ }
+
+ return $paraData;
+ }
+
+ function collectParaGraphDataNew(){
+ global $lang;
+
+ $paraData = array(
+ /*'timestamp' => $time,*/
+ 'unfilteredCount' => 0,
+ 'allCount' => 0,
+ 'pcCount' => 0,
+ 'mobiCount' => 0,
+ 'tabletCount' => 0,
+ 'robotCount' => 0,
+ 'browser' => array(),
+ 'os' => array()
+ );
+
+
+ // Filter za status
+ $status_filter = ($this->paraGraph_filter['status'] == 1) ? ' AND last_status>\'4\' AND lurker=\'0\'' : ' AND last_status>\'2\'';
+
+ // Filter za napravo
+ $device_filter = ' AND (';
+ $device_filter .= ($this->paraGraph_filter['pc'] != 0) ? 'device=\'0\' OR ' : '';
+ $device_filter .= ($this->paraGraph_filter['mobi'] != 0) ? 'device=\'1\' OR ' : '';
+ $device_filter .= ($this->paraGraph_filter['tablet'] != 0) ? 'device=\'2\' OR ' : '';
+ $device_filter .= ($this->paraGraph_filter['robot'] != 0) ? 'device=\'3\' OR ' : '';
+ $device_filter = substr($device_filter, 0, -4) . ')';
+
+
+ // Prestejemo vse
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE ank_id='".$this->anketa."' AND last_status>'2' AND useragent!='' AND preview='0' AND deleted='0'");
+ $paraData['unfilteredCount'] = mysqli_num_rows($sql);
+
+ // Prestejemo vse filtrirane
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE ank_id='".$this->anketa."' ".$status_filter." ".$device_filter." AND useragent!='' AND preview='0' AND deleted='0'");
+ $paraData['allCount'] = mysqli_num_rows($sql);
+
+ // Prestejemo naprave
+ $sql = sisplet_query("SELECT device, count(*) FROM srv_user WHERE ank_id='".$this->anketa."' ".$status_filter." ".$device_filter." AND useragent!='' AND preview='0' AND deleted='0'
+ GROUP BY device");
+ while($row = mysqli_fetch_array($sql)){
+ if($row['device'] == 0)
+ $paraData['pcCount'] = $row['count(*)'];
+ elseif($row['device'] == 1)
+ $paraData['mobiCount'] = $row['count(*)'];
+ elseif($row['device'] == 2)
+ $paraData['tabletCount'] = $row['count(*)'];
+ elseif($row['device'] == 3)
+ $paraData['robotCount'] = $row['count(*)'];
+ }
+
+ // Prestejemo browserje
+ $sql = sisplet_query("SELECT browser, count(*) FROM srv_user WHERE ank_id='".$this->anketa."' ".$status_filter." ".$device_filter." AND useragent!='' AND preview='0' AND deleted='0'
+ AND browser!='' GROUP BY browser");
+ while($row = mysqli_fetch_array($sql)){
+ $paraData['browser'][$row['browser']] = $row['count(*)'];
+ }
+
+ // Prestejemo os
+ $sql = sisplet_query("SELECT os, count(*) FROM srv_user WHERE ank_id='".$this->anketa."' ".$status_filter." ".$device_filter." AND useragent!='' AND preview='0' AND deleted='0'
+ AND os!='' GROUP BY os");
+ while($row = mysqli_fetch_array($sql)){
+ $paraData['os'][$row['os']] = $row['count(*)'];
+ }
+
+
+ return $paraData;
+ }
+
+
+ function paraGraphSetFilter(){
+
+ // Nastavimo filter po statusu (vsi ali ustrezni)
+ $this->paraGraph_filter['status'] = (SurveyStatusProfiles::getDefaultProfile() == 2) ? 1 : 0;
+ /*if(isset($_GET['status']))
+ $this->paraGraph_filter['status'] = $_GET['status'];
+ else
+ $this->paraGraph_filter['status'] = 0;*/
+
+ // Nastavimo filter po napravi (pc, mobi, tablica, crawler)
+ $this->paraGraph_filter['pc'] = (isset($_GET['pc'])) ? $_GET['pc'] : 1;
+ $this->paraGraph_filter['tablet'] = (isset($_GET['tablet'])) ? $_GET['tablet'] : 1;
+ $this->paraGraph_filter['mobi'] = (isset($_GET['mobi'])) ? $_GET['mobi'] : 1;
+ $this->paraGraph_filter['robot'] = (isset($_GET['robot'])) ? $_GET['robot'] : 1;
+ }
+
+
+ // Se pozene za stare ankete ki imajo v bazi samo useragent (samo prvic ko gledamo staro anketo) oz. ce hocemo na novo zracunat vse ($_GET['refresh'] == 1)
+ function paraGraphFixOld(){
+ global $lang;
+
+ if(isset($_GET['refresh']) && $_GET['refresh'] == 1)
+ $sqlu = sisplet_query("SELECT id, useragent FROM srv_user WHERE ank_id='".$this->anketa."' AND last_status>'2' AND useragent!='' AND preview='0' AND deleted='0'");
+ else
+ $sqlu = sisplet_query("SELECT id, useragent FROM srv_user WHERE ank_id='".$this->anketa."' AND last_status>'2' AND useragent!='' AND browser='' AND preview='0' AND deleted='0'");
+ if(mysqli_num_rows($sqlu) > 0){
+
+ $detect = New Mobile_Detect();
+
+ $cnt = 0;
+ while($rowu = mysqli_fetch_array($sqlu)){
+
+ // Detect mobilnikov in tablic
+ $detect->setUserAgent($rowu['useragent']);
+
+ // Detect z browscap
+ $browserDetect = get_browser($rowu['useragent'], true);
+
+ // Naprava
+ if($detect->isMobile()) {
+ if($detect->isTablet())
+ $device = 2;
+ else
+ $device = 1;
+ }
+ elseif($browserDetect['crawler'] == 1)
+ $device = 3;
+ else
+ $device = 0;
+
+ // Browser
+ if($browserDetect['browser'] == 'Default Browser')
+ $browser = $lang['srv_para_graph_other'];
+ else
+ $browser = $browserDetect['browser'].' '.$browserDetect['version'];
+
+ // OS
+ if($browserDetect['platform'] == 'unknown')
+ $os = $lang['srv_para_graph_other'];
+ else
+ $os = $browserDetect['platform'];
+
+ $sqlu2 = sisplet_query("UPDATE srv_user SET device='$device', browser='$browser', os='$os' WHERE ank_id='".$this->anketa."' AND id='$rowu[id]'");
+ if (!$sqlu2)
+ echo mysqli_error($GLOBALS['connect_db']);
+
+ $cnt++;
+ }
+
+ echo '<div style="float:right; margin:-10px 20px 0 0;">Posodobljenih je bilo '.$cnt.' starih vnosov.</div>';
+ }
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyPostProcess.php b/admin/survey/classes/class.SurveyPostProcess.php
new file mode 100644
index 0000000..4b79ae5
--- /dev/null
+++ b/admin/survey/classes/class.SurveyPostProcess.php
@@ -0,0 +1,1070 @@
+<?php
+
+/**
+*
+* V tem classu so funkcije, ki se ticejo postprocessinga podatkov
+* ala compute, recode, code ...
+*
+*/
+
+class SurveyPostProcess {
+
+ private $anketa;
+ private $spremenljivka;
+
+ private $db_table = '';
+
+ private $SDF = null;
+
+ /**
+ * post procesiranje podatkov ankete
+ *
+ * @param int $anketa ID ankete
+ */
+ function __construct ($anketa) {
+
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->anketa);
+ }
+
+ /**
+ * izris taba za kalkulacijo
+ *
+ */
+ function displayTab () {
+ global $lang;
+
+ echo '<fieldset><legend>'.$lang['srv_compute'].'</legend>';
+ echo '<script>__vnosi=1;</script>';
+
+ $b = new Branching($this->anketa);
+
+ $sql = sisplet_query("SELECT s.id, s.naslov, s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.tip='22'");
+ if (mysqli_num_rows($sql) > 0) {
+
+ echo '<p>'.$lang['srv_compute_list'].'</p>';
+
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<p>'.$row['naslov'].': <a href="" onclick="calculation_editing(\'-'.$row['id'].'\'); return false;"><b> '.$row['variable'].'= '.$b->calculations_display(-$row['id'], 1).'</b></a></p>';
+ }
+ }
+
+ echo '<p><a href="" onclick="spremenljivka_new(0, 0, 1, 0, 22); return false;">'.$lang['srv_add_compute'].'</a></p>';
+
+ if (mysqli_num_rows($sql) > 0) {
+ echo '<span class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="postprocess_start_calculation(); return false;">'.$lang['srv_compute_start'].'</a></span>';
+ }
+
+ echo '</legend>';
+ }
+
+ /**
+ * prikaze link za dodat novo kalkulacijo za post process
+ * dodamo kar obicno kalkulacijo, pri zapiranju (detektiramo v JS) pa se poklice ajax_calculation_postprocess_save, ki gre cez celo bazo
+ *
+ */
+ function displayLink () {
+ global $lang;
+
+ echo '<div style="float:right; margin-right:10px">';
+ echo '<a href="" onclick="spremenljivka_new(0, 0, 1, 0, 22); return false;">'.$lang['srv_add_compute'].'</a>';
+ echo '</div>';
+
+ }
+
+ /**
+ * zavihek za avtomatsko rekodiranje
+ *
+ */
+ function displayCodingAuto () {
+ global $lang;
+
+ echo '<fieldset><legend>'.$lang['srv_auto_coding'].'</legend>';
+
+ SurveyAnalysis::Init($this->anketa);
+ $freq = SurveyAnalysis::getFrequencys();
+
+ $ok = false;
+
+ echo '<p id="ok">'.$lang['srv_mass_coding'].': ';
+ echo '<select name="spr_id" id="mass_coding_spr_id" style="width:250px">';
+
+ foreach (SurveyAnalysis::$_HEADERS AS $key => $h) {
+
+ $spr = explode('_', $key);
+
+ if ( is_numeric( $spr['0'] ) ) {
+
+ foreach ($h['grids'] AS $grids_k => $grids_v) {
+
+ foreach ($grids_v['variables'] AS $variables_k => $variables_v) {
+
+ if ($variables_v['text'] == '1'/* || $h['tip'] == 19*/) {
+ $ok = true;
+ echo '<option value="'.$variables_v['sequence'].'-'.$spr[0].'">('.$h['variable'].') '.$h['naslov'].($variables_v['naslov']!=''?' - '.$variables_v['naslov']:'').'</option>';
+ }
+ }
+ }
+ }
+ }
+
+ echo '</select> ';
+
+ echo '<select name="coding_type" id="coding_type">';
+ echo '<option value="1">'.$lang['srv_coding_one'].'</option>';
+ echo '<option value="2">'.$lang['srv_coding_multi'].'</option>';
+ echo '</select> ';
+
+ echo '<input type="submit" value="'.$lang['srv_save_and_run_profile'].'" onclick="$(this).prop(\'disabled\', true); mass_coding($(\'#mass_coding_spr_id\').val(), $(\'#coding_type\').val()); return false;"></p>';
+
+
+ if (!$ok) {
+ ?><script> $('#ok').hide(); </script><?
+ echo '<p>'.$lang['srv_mass_coding_no_vars'].'</p>';
+ }
+
+ echo '<p>'.$lang['srv_mass_coding_txt'].'</p>';
+
+ echo '</fieldset>';
+ }
+
+ /**
+ * zavihek za rocno rekodiranje
+ *
+ */
+ function displayCoding () {
+ global $lang;
+
+ //$this->updateTracking($this->anketa, 4);
+ echo '<fieldset><legend>'.$lang['srv_hand_coding'].'</legend>';
+ echo '<div id="analiza_data">';
+ Timer::StartTimer($lang['srv_collectData']);
+ SurveyDataDisplay::Init($this->anketa);
+
+ echo '<div id="div_analiza_filtri_right" class="analiza" style="left:auto"><a href="#" onclick="$(\'#filters\').slideToggle(); $(this).find(\'span\').toggleClass(\'plus\').toggleClass(\'minus\'); return false"><span class="faicon plus"></span> '.$lang['srv_advanced'].'</a></div>';
+
+ echo '<div id="filters" style="display:none; height:80px; margin-top:10px">';
+ SurveyDataDisplay::displayFilters();
+ echo '</div>';
+
+ SurveyAnalysis::Init($this->anketa);
+ $freq = SurveyAnalysis::getFrequencys();
+
+ echo '<p class="coding-refresh"><a href="index.php?anketa='.$this->anketa.'&a=data&m=coding">'.$lang['src_coding_refresh'].'</a></p>';
+
+
+ SurveyVariablesProfiles::Init($this->anketa, $global_user_id);
+ $variables = SurveyVariablesProfiles::getProfileVariables(-1);
+ if (SurveyVariablesProfiles::getCurentProfileId() != -1)
+ $variables = array();
+
+ echo '<p>'.$lang['srv_hand_coding_text'] . '</p>';
+
+ echo '<p><label id="link_variable_profile_remove" onclick="removeVariableProfile();"><input type="radio" name="filter" '.(count($variables)==0?'checked':'').'> '.$lang['srv_coding_spr_1'].'</label></p>';
+
+ echo '<p><label onclick="coding_filter($(\'#mass_coding_spr_id\').val());"><input type="radio" name="filter" '.(count($variables)>0?'checked':'').' onclick="return false;"> '.$lang['srv_coding_spr'].':</label> ';
+ echo '<select name="spr_id" id="mass_coding_spr_id" style="width:200px" onchange="coding_filter($(\'#mass_coding_spr_id\').val()); return false;">';
+
+ SurveyAnalysis::Init($this->anketa);
+ $freq = SurveyAnalysis::getFrequencys();
+
+ foreach (SurveyAnalysis::$_HEADERS AS $key => $h) {
+
+ $spr = explode('_', $key);
+
+ if ( is_numeric( $spr['0'] ) ) {
+
+ foreach ($h['grids'] AS $grids_k => $grids_v) {
+
+ foreach ($grids_v['variables'] AS $variables_k => $variables_v) {
+
+ if ($variables_v['text'] == '1'/* || $h['tip'] == 19*/) {
+
+ echo '<option value="'.$variables_v['sequence'].'-'.$spr[0].'" '.(in_array($spr[0].'_0', $variables)?'selected':'').'>('.$h['variable'].') '.$h['naslov'].($variables_v['naslov']!=''?' - '.$variables_v['naslov']:'').'</option>';
+ }
+ }
+ }
+ }
+ }
+
+ echo '</select> ';
+ //echo '<input type="submit" value="'.$lang['srv_coding_filter'].'" onclick="$(this).prop(\'disabled\', true); coding_filter($(\'#mass_coding_spr_id\').val()); return false;"> ('.$lang['srv_coding_spr2'].')</p>';
+ if ( count($variables)>0 )
+ echo '('.$lang['srv_coding_spr2'].')';
+ echo '</p>';
+
+
+ SurveyDataDisplay::displayVnosiHTML();
+ echo '</div>'; // div_analiza_data
+ Timer::GetTimer($lang['srv_collectData']);
+
+
+ // div za popup editiranje
+ echo '<div id="coding"></div>';
+ echo '</fieldset>';
+ }
+
+ function ajax() {
+
+ $this->anketa = $_REQUEST['anketa'];
+ $this->spremenljivka = $_REQUEST['spremenljivka'];
+
+ if ($_GET['a'] == 'postprocess_start_calculation') {
+ $this->ajax_postprocess_start_calculation();
+
+ } elseif ($_GET['a'] == 'edit_data_question') {
+ $this->ajax_edit_data_question();
+
+ } elseif ($_GET['a'] == 'edit_data_question_save') {
+ $this->ajax_edit_data_question_save(0);
+
+ } elseif ($_GET['a'] == 'edit_data_question_upload_delete') {
+ $this->ajax_edit_data_question_upload_delete();
+
+ } elseif ($_GET['a'] == 'get_inline_edit') {
+ $this->ajax_get_inline_edit();
+
+ } elseif ($_GET['a'] == 'get_inline_edit_all') {
+ $this->ajax_get_inline_edit_all();
+
+ } elseif ($_GET['a'] == 'coding') {
+ $this->ajax_coding();
+
+ } elseif ($_GET['a'] == 'coding_save') {
+ $this->ajax_coding_save();
+
+ } elseif ($_GET['a'] == 'vrednost_new') {
+ $this->ajax_vrednost_new();
+
+ } elseif ($_GET['a'] == 'spremenljivka_new') {
+ $this->ajax_spremenljivka_new();
+
+ } elseif ($_GET['a'] == 'tip') {
+ $this->ajax_tip();
+
+ } elseif ($_GET['a'] == 'mass_coding') {
+ $this->ajax_mass_coding();
+
+ } elseif ($_GET['a'] == 'coding_merge') {
+ $this->ajax_coding_merge();
+
+ } elseif ($_GET['a'] == 'coding_filter') {
+ $this->ajax_coding_filter();
+ }
+ }
+
+ /**
+ * pozene racunanje kalkulacij na celotni anketi
+ *
+ */
+ function ajax_postprocess_start_calculation () {
+ Common::updateEditStamp();
+
+ $sql = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.tip='22'");
+ if (!$sql) echo 'err34234'.mysqli_error($GLOBALS['connect_db']);
+
+ $spremenljivk = mysqli_num_rows($sql);
+
+ $i = 0;
+ while ($row = mysqli_fetch_array($sql)) {
+ $this->calculate_spremenljivka($row['id']);
+ }
+
+ self::forceRefreshData($this->anketa);
+
+ // redirect
+ echo 'index.php?anketa='.$this->anketa.'&a=data';
+ }
+
+ /**
+ * za spremenljivko (tipa 22 - kalkulacija) gre cez celo bazo (beremo iz tekstovne datoteke) in preracuna vrednosti
+ *
+ */
+ function calculate_spremenljivka ($spremenljivka = 0) {
+
+ require('definition.php');
+
+ if ($spremenljivka != 0)
+ $this->spremenljivka = $spremenljivka;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ if ($row['tip'] != 22) return;
+
+ $_fileStatus = $this->SDF->getStatus() ;
+
+ # če imamo data datoteko (novo=1 in staro=0)
+ if ($_fileStatus == FILE_STATUS_OK || $_fileStatus == FILE_STATUS_OLD) {
+ $_dataFileName = $this->SDF->getDataFileName();
+
+ $missing = $this->generateCalculationMissing(-$this->spremenljivka);
+ $calculation = $this->generateCalculationAWK(-$this->spremenljivka);
+
+ // for(i=1;i<=NF;i++) if ($i < 0) $i=0; // nastavi vse <0 na 0
+
+ if (IS_WINDOWS) {
+ $cmd = 'awk -F"|" "{{OFS=\"\"} {ORS=\"\"}} { if ( '.$missing.' ) calc=-1; else calc = '.$calculation.' ; print \"('.$this->spremenljivka.',\",calc,\",\",$1,\"),\"}" '.$_dataFileName;
+ } else {
+ $cmd = 'awk -F"|" \'{{OFS=""} {ORS=""}} { if ( '.$missing.' ) calc=-1; else calc = '.$calculation.' ; print "('.$this->spremenljivka.',",calc,",",$1,"),"}\' '.$_dataFileName;
+ }
+
+ $out = shell_exec($cmd);
+
+ // rezultat lahko vrne nan - spremenimo na -1
+ $out = str_replace('-nan', '-1', $out);
+ $out = str_replace('nan', '-1', $out);
+
+ // pobrisemo zadnjo vejico
+ $values = substr($out, 0, strrpos($out, ",") );
+
+ // Zaokrozimo na doloceno stevilo decimalk
+ $decimals = $row['decimalna'];
+ $calc_val_array = explode(',', $values);
+ for($i=1; $i<count($calc_val_array); $i+=3){
+ $calc_val_array[$i] = round(floatval($calc_val_array[$i]), $decimals);
+ }
+ $values = implode(',', $calc_val_array);
+
+ $sql = sisplet_query("DELETE FROM srv_data_text".$this->db_table." WHERE spr_id='".$this->spremenljivka."'");
+ if (!$sql) echo 'err3324'.mysqli_error($GLOBALS['connect_db']);
+
+ if ($values != '') {
+
+ $sql_query = "INSERT INTO srv_data_text".$this->db_table." (spr_id, text, usr_id) VALUES " . $values . "";
+
+ $sql = sisplet_query($sql_query);
+ if (!$sql) echo 'err766567'.' '.$sql_query.' '.mysqli_error($GLOBALS['connect_db']);
+
+ }
+
+ $sql = sisplet_query("UPDATE srv_anketa SET edit_time = NOW() WHERE id = '$this->anketa'");
+ if (!$sql) echo 'err6563'.sisplet_query($sql);
+
+ } else {
+ //echo 'filestatus' . $_fileStatus;
+ }
+
+ }
+
+ /**
+ * vrne vrstni red stolpca v datoteki s podatki za podano spremenljivko
+ *
+ * @param mixed $spr_id
+ * @param mixed $vre_id
+ * @return mixed
+ */
+ function getSequence ($spr_id, $vre_id = null, $grd_id = null) {
+
+ $header = $this->SDF->getHeaderVariable($spr_id.'_0');
+
+ switch ($header['tip']) {
+ case 1 : // radio
+ case 3 : // dropdown
+ case 4 : // text -??
+ case 21: // beseilo?
+ case 22: // compute
+ case 25: // kvota
+ return $header['grids']['0']['variables']['0']['sequence'];
+ break;
+ case 7: // number
+ return $header['grids']['0']['variables'][$grd_id]['sequence'];
+ case 16: // multicheckbox
+ case 20: // multinumber
+ foreach ($header['grids'] AS $grids) {
+ foreach ($grids['variables'] AS $variables) {
+ if ($variables['vr_id'] == $vre_id && $variables['gr_id'] == $grd_id)
+ return ($variables['sequence']);
+ }
+ }
+ case 17: // razvrscanje
+ case 18: // vsota
+ default : // multigrid, checkbox
+ foreach ($header['grids'] AS $grids) {
+ foreach ($grids['variables'] AS $variables) {
+ if ($variables['vr_id'] == $vre_id)
+ return ($variables['sequence']);
+ }
+ }
+ return ;
+ break;
+ }
+ }
+
+ /**
+ * @desc zgenerira kalkulacijo za vstavitev v awk
+ */
+ function generateCalculationAWK ($condition) {
+
+ $sql = sisplet_query("SELECT * FROM srv_calculation WHERE cnd_id = '$condition' ORDER BY vrstni_red ASC");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i = 0;
+ $expression = '';
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $row1 = Cache::srv_spremenljivka($row['spr_id']);
+
+ if ($i++ != 0)
+ if ($row['operator'] == 0)
+ $expression .= ' + ';
+ elseif ($row['operator'] == 1)
+ $expression .= ' - ';
+ elseif ($row['operator'] == 2)
+ $expression .= ' * ';
+ elseif ($row['operator'] == 3)
+ $expression .= ' / ';
+
+ for ($i=1; $i<=$row['left_bracket']; $i++)
+ $expression .= ' ( ';
+
+ // spremenljivke
+ if ($row['spr_id'] > 0) {
+
+ $seq = $this->getSequence($row['spr_id'], $row['vre_id'], $row['grd_id']);
+ if ($seq > 0)
+ $expression .= ' $'.$seq.' ';
+ else
+ $expression .= ' 0 ';
+
+ // konstante
+ } elseif ($row['spr_id'] == -1) {
+
+ $expression .= $row['number'];
+
+ }
+
+ for ($i=1; $i<=$row['right_bracket']; $i++)
+ $expression .= ' ) ';
+
+ }
+
+ return '('.$expression.')';
+ }
+
+ /**
+ * @desc zgenerira pogoj, ki preveri, ce je kateri od odgovorov missing - potem je tudi kalkulacija missing
+ */
+ function generateCalculationMissing ($condition) {
+
+ $sql = sisplet_query("SELECT * FROM srv_calculation WHERE cnd_id = '$condition' ORDER BY vrstni_red ASC");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i = 0;
+ $expression = '';
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $row1 = Cache::srv_spremenljivka($row['spr_id']);
+
+ // spremenljivke
+ if ($row['spr_id'] > 0) {
+
+ $seq = $this->getSequence($row['spr_id'], $row['vre_id'], $row['grd_id']);
+ if ($seq > 0) {
+ if ($expression != '') $expression .= ' || ';
+ $expression .= ' $'.$seq.' < 0 ';
+ }
+
+ }
+
+ }
+
+ if ($expression == '') $expression = 'false';
+ return $expression;
+ }
+
+ function ajax_edit_data_question() {
+ global $lang;
+
+ /*?>
+ <link rel="stylesheet" href="http://localhost/fdv/cms2/main/survey/skins/Modern.css" type="text/css" media="screen" />
+ <?*/
+
+ $spr_id = $_POST['spr_id'];
+ $usr_id = $_POST['usr_id'];
+
+ // preverimo, ce gre za multiple tabelo
+ $sql = sisplet_query("SELECT parent FROM srv_grid_multiple WHERE spr_id='$spr_id' AND ank_id='$this->anketa'");
+ $row = mysqli_fetch_array($sql);
+ if (mysqli_num_rows($sql) > 0)
+ $spr_id = $row['parent'];
+
+ echo '<div id="preview_spremenljivka">';
+ echo '<div id="spremenljivka_preview">';
+
+ echo '<div class="popup_close"><a href="#" onClick="edit_data_close(); return false;">✕</a></div>';
+
+ echo '<form name="edit_data" method="post" action="ajax.php?t=postprocess&a=edit_data_question_save&anketa='.$this->anketa.'" onsubmit="edit_data_question_save(); return false;">';
+ echo '<input type="submit" id="submit" style="display:none" />'; // workaround, ker se drugace ne poklice onsubmit
+ echo '<input type="hidden" name="spr_id" value="'.$spr_id.'" />';
+ echo '<input type="hidden" name="usr_id" value="'.$usr_id.'" />';
+
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+ save('anketa', $this->anketa);
+ save('forceShowSpremenljivka', true);
+ save('question_edit', true);
+ \App\Controllers\Vprasanja\VprasanjaController::getInstance()->displaySpremenljivka($spr_id);
+
+ echo '<div class="buttons_holder">';
+ echo '<span class="floatRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="javascript:$(\'#submit\').click(); return false;"><span>'.$lang['srv_potrdi'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="javascript:edit_data_close();"><span>'.$lang['srv_cancel'].'</span></a></div></span>';
+ echo '</div>';
+
+ echo '</form>';
+
+ /*echo '<div class="clr"></div>';*/
+
+ echo '</div>';
+ echo '</div>';
+
+ }
+
+ function ajax_edit_data_question_save ($refresh = 1) {
+ Common::updateEditStamp();
+
+ // Preverimo ce gre za prvo popravljanje podatkov in avtomatskoustvarimo arhiv podatkov ce je potrebno
+ $sas = new SurveyAdminSettings();
+ $sas->checkFirstDataChange();
+
+ $spr_id = $_POST['spr_id'];
+ $usr_id = $_POST['usr_id'];
+
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+ save('anketa', $this->anketa);
+ save('forceShowSpremenljivka', true);
+ save('usr_id', $usr_id);
+ \App\Models\SaveSurvey::getInstance()->posted(0, $spr_id);
+
+ /*if ($refresh == 1)
+ header("Location: index.php?anketa=".$this->anketa."&a=data&m=edit");*/
+ }
+
+ // Pobrisemo upload datoteke v urejanju podatkov
+ function ajax_edit_data_question_upload_delete () {
+ Common::updateEditStamp();
+
+ $spr_id = $_POST['spr_id'];
+ $usr_id = $_POST['usr_id'];
+ $code = $_POST['code'];
+
+ $s = sisplet_query("DELETE FROM srv_data_upload WHERE ank_id='".$this->anketa."' AND usr_id='".$usr_id."' AND code='".$code."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $s2 = sisplet_query("DELETE FROM srv_data_text".$this->db_table." WHERE spr_id='".$spr_id."' AND usr_id='".$usr_id."'");
+ if (!$s2) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->ajax_edit_data_question();
+
+ self::forceRefreshData($this->anketa);
+ }
+
+ function ajax_get_inline_edit () {
+
+ $spr_id = $_POST['spr_id'];
+
+ echo '<form action="ajax.php?t=postprocess&a=edit_data_question_save&anketa='.$this->anketa.'">';
+ echo '<input type="hidden" name="spr_id" value="'.$spr_id.'" />';
+ echo '<input type="hidden" name="visible_'.$spr_id.'" value="1" />';
+
+ echo '<select name="vrednost_'.$spr_id.'" onchange="edit_data_inline_edit_save(this.parentNode.getAttribute(\'name\'));">';
+ $sql = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$spr_id' ORDER BY vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<option value="'.$row['id'].'" variable="'.$row['variable'].'" class="'.$row['variable'].'">'.$row['naslov'].'</option>';
+ }
+
+ echo '</select>';
+ echo '</form>';
+ }
+
+ function ajax_get_inline_edit_all () {
+
+ $spr = $_POST['spr'];
+
+ $response = array();
+
+ foreach ($spr AS $spr_id) {
+
+ $output = array();
+
+ $output['spr'] = $spr_id;
+ $output['html'] = '';
+
+ $output['html'] .= '<form action="ajax.php?t=postprocess&a=edit_data_question_save&anketa='.$this->anketa.'">';
+ $output['html'] .= '<input type="hidden" name="spr_id" value="'.$spr_id.'" />';
+ $output['html'] .= '<input type="hidden" name="visible_'.$spr_id.'" value="1" />';
+
+ $output['html'] .= '<select name="vrednost_'.$spr_id.'" onchange="edit_data_inline_edit_save(this.parentNode.getAttribute(\'name\'));">';
+
+ $sql = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$spr_id' ORDER BY naslov ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $output['html'] .= '<option value="'.$row['id'].'" variable="'.$row['variable'].'" class="'.$row['variable'].'">'.$row['naslov'].'</option>';
+ }
+
+ $output['html'] .= '</select>';
+ $output['html'] .= '</form>';
+
+ $response[] = $output;
+ }
+
+ echo json_encode($response);
+ }
+
+ function ajax_coding ($editing = false) {
+ global $lang;
+
+ $usr_id = $_POST['usr_id'];
+ $spr_id = $_POST['spr_id'];
+
+ $row = Cache::srv_spremenljivka($spr_id);
+ if ($row['coding'] > 0) {
+ $coding_id = $row['coding'];
+ } else {
+ $coding_id = $spr_id;
+ }
+ echo '<h3 style="margin: 7px 10px">'.$lang['srv_hand_coding'].'</h3>';
+ echo '<form id="coding_'.$usr_id.'">';
+
+ echo '<input type="hidden" value="'.$usr_id.'" name="usr_id">';
+ echo '<input type="hidden" value="'.$this->anketa.'" name="anketa">';
+
+ $sql = sisplet_query("SELECT s.* FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.coding='$coding_id' ORDER BY g.vrstni_red, s.vrstni_red");
+ if (mysqli_num_rows($sql) > 0) {
+
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<fieldset style="position: relative">';
+
+ echo '<p style="float:left; min-height:20px"><strong>'.skrajsaj(strip_tags($row['naslov']), 20).'</strong> <a href="" onclick="$(\'.edit_'.$row['id'].'\').toggle(); return false;" title="'.$lang['edit2'].'"><span class="faicon edit"></span></a></p>';
+ echo '<p class="edit_'.$row['id'].'" style="display:none; float:left; margin-left:10px">'.$lang['srv_tip'].': ';
+ echo '<select name="tip" onchange="if (confirm(\''.$lang['srv_change_q_tip'].'\')) {coding_tip(\''.$row['id'].'\', \''.$usr_id.'\', $(this).val());} return false;"><option value="1" '.($row['tip']==1?'selected':'').'>'.$lang['srv_vprasanje_tip_1'].'</option><option value="2" '.($row['tip']==2?'selected':'').'>'.$lang['srv_vprasanje_tip_2'].'</option><option value="3" '.($row['tip']==3?'selected':'').'>'.$lang['srv_vprasanje_tip_3'].'</option></select>';
+ //echo '<a href="#" onclick="if (confirm(\''.$lang['srv_change_q_tip'].'\')) {coding_tip(\''.$row['id'].'\', \''.$usr_id.'\', \''.($row['tip']==1?'2':'1').'\');} return false;" title="'.$lang['srv_change_q_tip'].'">'.($row['tip']==1?$lang['srv_vprasanje_tip_1']:$lang['srv_vprasanje_tip_2']).'</a>';
+ echo ' <a href="index.php?anketa='.$this->anketa.'&spr_id='.$row['id'].'#branching_'.$row['id'].'">'.$lang['srv_napredno_urejanje'].'</a> <a href="" onclick="brisi_spremenljivko(\''.$row['id'].'\'); return false;" title="'.$lang['srv_brisispremenljivko'].'"><span class="faicon delete icon-grey_dark_link"></span></a></p>';
+
+ echo '<input id="visible_'.$row['row'].'" type="hidden" value="1" name="visible_'.$row['id'].'">';
+
+ //echo '<input type="hidden" value="'.$row['id'].'" name="spr_id">';
+
+ echo '<p style="clear:both">';
+ if ($row['tip'] == 3) {
+ echo '<select name="vrednost_'.$row['id'].'">';
+ }
+ $sql1 = sisplet_query("SELECT id, naslov FROM srv_vrednost WHERE spr_id='$row[id]' ORDER BY vrstni_red ASC");
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ $sql2 = sisplet_query("SELECT * FROM srv_data_vrednost".$this->db_table." WHERE spr_id='$row[id]' AND vre_id='$row1[id]' AND usr_id='$usr_id'");
+ if (mysqli_num_rows($sql2) > 0)
+ $checked = 'checked="checked"'; else $checked = '';
+
+ if ($row['tip'] == 1) {
+ echo '<input type="radio" name="vrednost_'.$row['id'].'" id="spremenljivka_'.$row['id'].'_vrednost_'.$row1['id'].'" value="'.$row1['id'].'" '.$checked.' /><label for="spremenljivka_'.$row['id'].'_vrednost_'.$row1['id'].'"> '.$row1['naslov'].'</label>';
+ } elseif ($row['tip'] == 2) {
+ echo '<input type="checkbox" name="vrednost_'.$row['id'].'[]" id="spremenljivka_'.$row['id'].'_vrednost_'.$row1['id'].'" value="'.$row1['id'].'" '.$checked.' /><label for="spremenljivka_'.$row['id'].'_vrednost_'.$row1['id'].'"> '.$row1['naslov'].'</label>';
+ } elseif ($row['tip'] == 3) {
+ echo '<option value="'.$row1['id'].'" '.($checked!=''?'selected':'').'>'.$row1['naslov'].'</option>';
+ }
+
+ if ($row['tip'] == 1 || $row['tip'] == 2) {
+ echo '<span style="display:none; color:gray; float:right" class="edit_'.$row['id'].'"><select onchange="coding_merge(\''.$row['id'].'\', \''.$row1['id'].'\', \''.$usr_id.'\', this.value)" style="width:150px">';
+ echo '<option value="0">'.$lang['srv_coding_merge'].':</option>';
+
+ $sql2 = sisplet_query("SELECT id, naslov FROM srv_vrednost WHERE spr_id='$row[id]' AND id != '$row1[id]' ORDER BY vrstni_red ASC");
+ while ($row2 = mysqli_fetch_array($sql2))
+ echo '<option value="'.$row2['id'].'">'.$row2['naslov'].'</option>';
+
+ echo '</select></span><br />';
+ }
+
+ }
+ if ($row['tip'] == 3) {
+ echo '</select>';
+ }
+ echo '<input type="text" name="vrednost_new_'.$row['id'].'" value="" placeholder="'.$lang['srv_novavrednost'].'" style="margin-left:23px; width: 80px" /> <a href="#" onclick="coding_vrednost_new(\''.$row['id'].'\', \''.$usr_id.'\', $(\'input[name=vrednost_new_'.$row['id'].']\').val()); return false;"><span class="faicon add small icon-as_link" title="'.$lang['add'].'"></span></a>';
+ echo '</p>';
+ echo '</fieldset>';
+ }
+ } else {
+ echo '<fieldset>';
+ echo '<p>'.$lang['srv_coding_no_spr'].'</p>';
+ echo '</fieldset>';
+ }
+
+ echo '<div class="new-spr">';
+ echo '<a href="#" onclick="'.(true?' $(\'#coding_spr_new\').toggle();':'').' return false;">'.$lang['srv_coding_new'].'</a>';
+ echo '<div id="coding_spr_new" '.(true?' style="display:none"':'').'>';
+ echo '<p>'.$lang['name'].': <input type="text" name="spremenljivka_new" value="" style="width: 123px" /> <a href="#" onclick="coding_spremenljivka_new(\''.$coding_id.'\', \''.$usr_id.'\', $(\'input[name=spremenljivka_new]\').val()); return false;">'.$lang['add'].'</a></p>';
+ echo '</div>';
+ echo '</div>';
+
+
+
+ echo '<p style="margin:20px 10px 10px 10px">';
+
+ if (mysqli_num_rows($sql) > 0) {
+ //echo '<input type="submit" value="'.$lang['srv_close_profile'].'" onclick="coding_save(\''.$usr_id.'\'); return false;"> ';
+ }
+ echo '<a href="#" onclick="coding_save(\''.$usr_id.'\'); return false;">'.$lang['srv_close_profile'].'</a>';
+ echo '</p>';
+
+ echo '</form>';
+
+ if ($editing !== false) {
+ echo '<script> $(\'.edit_'.$editing.'\').show(); </script>';
+ }
+
+ }
+
+ function ajax_coding_save () {
+ Common::updateEditStamp();
+
+ $usr_id = $_POST['usr_id'];
+
+ foreach ($_POST AS $key => $val) {
+
+ if ( substr($key, 0, 8) == 'visible_' ) {
+
+ $spr_id = substr($key, 8);
+
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+ save('anketa', $this->anketa);
+ save('forceShowSpremenljivka', true);
+ save('usr_id', $usr_id);
+ \App\Models\SaveSurvey::getInstance()->posted(0, $spr_id);
+
+ }
+ }
+
+ self::forceRefreshData($this->anketa);
+
+ }
+
+ function ajax_vrednost_new () {
+ Common::updateEditStamp();
+
+ $usr_id = $_POST['usr_id'];
+
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $_POST['spr_id'];
+
+ $v->vrednost_new($_POST['naslov']);
+
+ $this->ajax_coding();
+
+ self::forceRefreshData($this->anketa);
+
+ }
+
+ function ajax_spremenljivka_new () {
+ Common::updateEditStamp();
+ global $global_user_id;
+
+ $usr_id = $_POST['usr_id'];
+ $spr_id = $_POST['spr_id'];
+
+ ob_start();
+ $ba = new BranchingAjax($this->anketa);
+ $ba->ajax_spremenljivka_new($spr_id, 0, 0, 0, 2, 0);
+ $spr_new = $ba->spremenljivka;
+ ob_clean();
+
+ SurveyVariablesProfiles::Init($this->anketa, $global_user_id);
+ $variables = SurveyVariablesProfiles::getProfileVariables(0);
+ if ( count($variables['variables']) > 0 ) {
+ SurveyVariablesProfiles::setProfileVariables(0, implode(',', $variables['variables']).','.$spr_new.'_0');
+ SurveyVariablesProfiles::setDefaultProfile(0);
+ }
+
+ // spremenimo ime, coding
+ $s = sisplet_query("UPDATE srv_spremenljivka SET variable_custom='1' WHERE id='$spr_id'");
+
+ $var = Cache::get_spremenljivka($spr_id, 'variable');
+ $i = 1;
+ do {
+ $variable = $var.'_coding_'.$i++;
+ $sql = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE variable='$variable' AND s.gru_id=g.id AND g.ank_id='".$this->anketa."'");
+ } while (mysqli_num_rows($sql) > 0);
+
+ if ($_POST['naslov'] != '')
+ $naslov = $_POST['naslov'];
+ else
+ $naslov = $variable;
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET coding='$spr_id', visible='0', naslov='".$naslov."', variable='".$variable."', variable_custom='1', size='0' WHERE id='$spr_new'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$spr_new'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id = '$spr_new'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->ajax_coding();
+
+ self::forceRefreshData($this->anketa);
+
+ }
+
+
+ function ajax_tip () {
+ Common::updateEditStamp();
+
+ $spr_id = $_POST['spr_id'];
+ $tip = $_POST['tip'];
+
+ $v = new Vprasanje($this->anketa);
+ $v->change_tip($spr_id, $tip);
+
+ Common::prestevilci($spr_id);
+
+ $this->ajax_coding();
+
+ self::forceRefreshData($this->anketa);
+
+ }
+
+ function ajax_coding_merge () {
+ Common::updateEditStamp();
+
+ $spr_id = $_POST['spr_id'];
+ $vre_id = $_POST['vre_id'];
+ $merge = $_POST['merge'];
+
+ $s = sisplet_query("UPDATE srv_data_vrednost$this->db_table SET vre_id='$merge' WHERE vre_id='$vre_id' AND spr_id='$spr_id'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE id = '$vre_id'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->ajax_coding($spr_id);
+
+ self::forceRefreshData($this->anketa);
+
+ }
+
+ function ajax_mass_coding () {
+ global $lang;
+
+ $spr_new = $this->mass_coding_auto();
+
+ $link = '<a href="index.php?anketa='.$this->anketa.'&a=data&m=coding&highlight_spr='.$spr_new.'&relevance=0">'.$lang['srv_hand_coding'].'</a>';
+
+ // enajblamo labele
+ session_start();
+ $_SESSION['sid_'.$this->anketa]['dataIcons_labels'] = true;
+
+ echo '<p>';
+
+ printf($lang['srv_auto_coding_end'], $this->mass_coding_auto_vars, $link);
+
+ echo '</p>';
+
+ }
+
+ private $mass_coding_auto_vars = 0;
+
+ function mass_coding_auto () {
+ global $global_user_id;
+ Common::updateEditStamp();
+
+ global $lang;
+
+ $coding_type = $_POST['coding_type'];
+
+ $seq = $_POST['seq'];
+ $seq = explode('-', $seq);
+
+ $spr_id = (int)$seq[1];
+ $sequence = (int)$seq[0];
+
+ // frekvence besed poberemo iz analize
+ SurveyAnalysis::Init($this->anketa);
+ SurveyAnalysis::setUpFilter(1);
+ $freq = SurveyAnalysis::getFrequencys();
+
+ // imamo sekvenco polja (pozicijo v text fajlu)
+ if ($sequence != false) {
+
+ $besede = $freq[$sequence]['valid'];
+ $koreni = array();
+
+ // sestavimo array korenov
+ foreach ($besede AS $beseda => $count) {
+
+ if (strlen( iconv("UTF-8", "ISO-8859-2", $beseda) ) >= 3) { // manjsih od 3 znakov ne upostevamo
+
+ if ($coding_type == 1) {
+
+ $k = iconv("ISO-8859-2", "UTF-8", substr( iconv("UTF-8", "ISO-8859-2", $beseda), 0, round(strlen( iconv("UTF-8", "ISO-8859-2", $beseda) )*0.75) ) );
+
+ if ( array_key_exists($k, $koreni) ) {
+ $koreni[$k] += $count;
+ } else {
+ $koreni[$k] = $count;
+ }
+
+ } elseif ($coding_type == 2) {
+
+ $razbita = explode(",", $beseda);
+ foreach ($razbita AS $part) {
+ $k = iconv("ISO-8859-2", "UTF-8", substr( iconv("UTF-8", "ISO-8859-2", $part), 0, round(strlen( iconv("UTF-8", "ISO-8859-2", $part) )*0.75) ) );
+
+ if ( array_key_exists($k, $koreni) ) {
+ $koreni[$k] += $count;
+ } else {
+ $koreni[$k] = $count;
+ }
+ }
+
+ }
+ }
+ }
+
+ // array obrnemo, da imamo vrstni_red => koren
+ $i = 1;
+ foreach ($koreni AS $key => $val) {
+ $koren[$i++] = $key;
+ }
+
+ if (count($koren) > 0) {
+
+ // naredimo novo spremenljivko
+ ob_start();
+ $ba = new BranchingAjax($this->anketa);
+ $ba->ajax_spremenljivka_new($spr_id, 0, 0, 0, $coding_type, 0);
+ $spr_new = $ba->spremenljivka;
+ ob_clean();
+
+ if ($spr_new > 0) {
+
+ // spremenimo ime, coding
+ $s = sisplet_query("UPDATE srv_spremenljivka SET variable_custom='1' WHERE id='$spr_id'");
+
+ $var = Cache::get_spremenljivka($spr_id, 'variable');
+ $i = 1;
+ do {
+ $variable = $var.'_coding_'.$i++;
+ $sql = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.variable='$variable' AND s.gru_id=g.id AND g.ank_id='".$this->anketa."'");
+ } while (mysqli_num_rows($sql) > 0);
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET coding='$spr_id', visible='0', naslov='".$variable."', variable='".$variable."', variable_custom='1', size='".count($koren)."' WHERE id='$spr_new'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$spr_new'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // napolnimo vrednosti spremenljivke s koreni
+ $koren_new = array();
+ foreach ($koren AS $key => $val) {
+ $val = ucfirst(strtolower( $val ));
+ $s = sisplet_query("INSERT INTO srv_vrednost (id, spr_id, naslov, variable, vrstni_red) VALUES ('', '$spr_new', '$val', '$key', '$key')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $koren_new[strtolower($val)] = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ // gremo cez tekstovne podatke in vnasamo vrednosti
+ $sql = sisplet_query("SELECT usr_id, text FROM srv_data_text".$this->db_table." WHERE spr_id='$spr_id'");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ if ($coding_type == 1) {
+
+ $k = iconv("ISO-8859-2", "UTF-8", substr( iconv("UTF-8", "ISO-8859-2", $row['text']), 0, round(strlen( iconv("UTF-8", "ISO-8859-2", $row['text']) )*0.75) ) );
+ $k = strtolower($k);
+
+ if ( array_key_exists($k, $koren_new) ) {
+
+ $s = sisplet_query("DELETE FROM srv_data_vrednost$this->db_table WHERE spr_id='$spr_new' AND usr_id='$row[usr_id]'"); // ker se zafilajo z -4
+ $s = sisplet_query("INSERT INTO srv_data_vrednost$this->db_table (spr_id, vre_id, usr_id, loop_id) VALUES('$spr_new', '$koren_new[$k]', '$row[usr_id]', NULL)");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->mass_coding_auto_vars++;
+ }
+
+ } elseif ($coding_type == 2) {
+
+ $s = sisplet_query("DELETE FROM srv_data_vrednost$this->db_table WHERE spr_id='$spr_new' AND usr_id='$row[usr_id]'"); // ker se zafilajo z -4
+
+ foreach ($koren_new AS $k => $v) {
+ if ( strpos($row['text'], $k) !== false ) {
+
+ $s = sisplet_query("INSERT INTO srv_data_vrednost$this->db_table (spr_id, vre_id, usr_id, loop_id) VALUES('$spr_new', '$koren_new[$k]', '$row[usr_id]', NULL)");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->mass_coding_auto_vars++;
+
+ }
+
+ }
+
+ }
+
+ }
+
+ $variables = $spr_id.'_0,'.$spr_new.'_0';
+ SurveyVariablesProfiles::Init($this->anketa, $global_user_id);
+ SurveyVariablesProfiles::setProfileVariables(0, $variables);
+ SurveyVariablesProfiles::setDefaultProfile(0);
+
+ self::forceRefreshData($this->anketa);
+
+ return $spr_new;
+
+ }
+
+ }
+
+ }
+
+ return 0;
+
+ }
+
+ function ajax_coding_filter () {
+ global $global_user_id;
+ global $lang;
+
+ $seq = $_POST['seq'];
+ $seq = explode('-', $seq);
+
+ $spr_id = (int)$seq[1];
+ $sequence = (int)$seq[0];
+ $variables = array();
+ $variables[] = $spr_id.'_0';
+
+ $sql = sisplet_query("SELECT id FROM srv_spremenljivka WHERE coding = '$spr_id'");
+ while ($row = mysqli_fetch_array($sql)) {
+ $variables[] = $row['id'].'_0';
+ }
+
+ $variables = serialize($variables);
+
+ SurveyVariablesProfiles::Init($this->anketa, $global_user_id);
+ SurveyVariablesProfiles::setProfileVariables(-1, $variables);
+ SurveyVariablesProfiles::setDefaultProfile(-1);
+ }
+
+ static function forceRefreshData( $anketa ) {
+
+ if ( file_exists( dirname(__FILE__) . '/../surveyData/export_dashboard_'.$anketa.'.html' ) )
+ unlink( dirname(__FILE__) . '/../surveyData/export_dashboard_'.$anketa.'.html' );
+
+ if ( file_exists( dirname(__FILE__) . '/../surveyData/export_data_'.$anketa.'.dat' ) )
+ unlink( dirname(__FILE__) . '/../surveyData/export_data_'.$anketa.'.dat' );
+
+ if ( file_exists( dirname(__FILE__) . '/../surveyData/export_header_'.$anketa.'.dat' ) )
+ unlink( dirname(__FILE__) . '/../surveyData/export_header_'.$anketa.'.dat' );
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyProfileManager.php b/admin/survey/classes/class.SurveyProfileManager.php
new file mode 100644
index 0000000..cf95af6
--- /dev/null
+++ b/admin/survey/classes/class.SurveyProfileManager.php
@@ -0,0 +1,433 @@
+<?php
+/** @author: Gorazd Veselič
+ *
+ * @Desc: za upravljanje s profili
+ *
+ *
+ * @Date: 10.12.2012
+ */
+
+session_start();
+
+DEFINE ('SPM_DEFAULT_PROFILE', -1);
+class SurveyProfileManager {
+ private $uid = null; # id userja
+ private $sid = null; # id ankete
+
+ private $currentProfileId = SPM_DEFAULT_PROFILE; # id trenutno izbranega profila
+ private $ssp = null;
+ private $svp = null;
+ private $scp = null;
+ private $stp = null;
+
+ private $profileVariables = array(0=>'ssp',1=>'svp',2=>'scp',3=>'stp');
+
+ private $profiles = array();
+
+
+ function __construct($anketa = null) {
+ if ((int)$anketa > 0) {
+ $this->sid = $anketa;
+ } else {
+ $this->sid = $_REQUEST['anketa'];
+ }
+
+ global $global_user_id;
+ $this->uid = $global_user_id;;
+
+ #polovimo privzete profile
+ $this->ssp = new SurveyStatusProfiles;
+ $this->ssp -> Init($this->sid);
+ $this->svp = new SurveyVariablesProfiles();
+ $this->svp -> Init($this->sid, $this->uid, true);
+ $this->scp = new SurveyConditionProfiles();
+ $this->scp -> Init($this->sid, $this->uid);
+ $this->stp = new SurveyTimeProfiles();
+ $this->stp -> Init($this->sid, $this->uid);
+
+ SurveyUserSetting :: getInstance()->Init($this->sid, $this->uid);
+ $this -> currentProfileId = (int)SurveyUserSetting :: getInstance()->getSettings('default_profileManager_pid');
+
+ $this->getProfiles();
+ }
+
+ function getCurentProfileId(){
+ return $this->currentProfileId;
+ }
+
+ function ajax() {
+ if (isset($_REQUEST['m']) && trim($_REQUEST['m']) != '') {
+ $this->action($_REQUEST['m']);
+ } else {
+ echo 'Ajax error!';
+ return 'Ajax error!';
+ }
+ }
+
+ function action($action) {
+ if ($action == 'displayProfiles') {
+ $this->DisplayProfiles();
+ } else if ($action == 'save') {
+ $this->SaveProfile();
+ } else if ($action == 'saveNew') {
+ $_POST['pm_name'] = $_POST['newName'];
+ $_POST['asNew'] = 'true';
+ $this->SaveProfile();
+ } else if ($action == 'changeProfile') {
+ $this->ChangeProfile();
+ } else if ($action == 'choose') {
+ $this->ChooseProfile();
+ } else if ($action == 'delete') {
+ $this->DeleteProfile();
+ } else {
+ echo $_REQUEST;
+ }
+ }
+
+ function getProfiles() {
+ global $lang;
+
+ $this->profiles = array();
+ # privzet profil
+ $this->profiles[SPM_DEFAULT_PROFILE] = array (
+ 'id' => SPM_DEFAULT_PROFILE,
+ 'name' => $lang['srv_profileManager_profileName_without'],
+ 'comment' => $lang['srv_profileManager_profileComment_system'],
+ 'ssp' => (int)SurveyStatusProfiles :: getSystemDefaultProfile(),
+ 'svp' => SurveyVariablesProfiles :: getSystemDefaultProfile(),
+ 'scp' => SurveyConditionProfiles :: getSystemDefaultProfile(),
+ 'stp' =>SurveyTimeProfiles :: getSystemDefaultProfile()
+ );
+
+ # trenutne nastavitve
+ $this->profiles[0] = array (
+ 'id' => 0,
+ 'name' => $lang['srv_profileManager_profileName_current'],
+ 'comment' => $lang['srv_profileManager_profileComment_system'],
+ 'ssp' => SurveyStatusProfiles :: getCurentProfileId(),
+ 'svp' => SurveyVariablesProfiles :: getCurentProfileId(),
+ 'scp' => SurveyConditionProfiles :: getCurentProfileId(),
+ 'stp' =>SurveyTimeProfiles :: getCurentProfileId()
+ );
+
+ # polovimo iz baze
+ $str = "SELECT id, name, comment, ssp, svp, scp, stp FROM srv_profile_manager WHERE ank_id = '$this->sid'";
+ $qry = sisplet_query($str);
+ if (mysqli_num_rows($qry) > 0) {
+ while (list($id,$name,$comment,$ssp,$svp,$scp,$stp) = mysqli_fetch_row($qry)) {
+ # preverimo še obstoj posameznega profila
+ $updateProfile=false;
+ if (!$this->ssp->checkProfileExist((int)$ssp))
+ {
+ $ssp = (int)SurveyStatusProfiles::getSystemDefaultProfile();
+ $updateProfile=true;
+ }
+ if (!$this->svp->checkProfileExist((int)$svp))
+ {
+ $svp = (int)SurveyVariablesProfiles::getSystemDefaultProfile();
+ $updateProfile=true;
+ }
+ if (!$this->scp->checkProfileExist((int)$scp))
+ {
+ $scp = (int)SurveyConditionProfiles::getSystemDefaultProfile();
+ $updateProfile=true;
+ }
+ if (!$this->stp->checkProfileExist((int)$stp))
+ {
+ $stp = (int)SurveyTimeProfiles::getSystemDefaultProfile();
+ $updateProfile=true;
+ }
+ $this->profiles[$id] = array (
+ 'id' => $id,
+ 'name' => $name,
+ 'comment' => $comment,
+ 'ssp' => (int)$ssp,
+ 'svp' => (int)$svp,
+ 'scp' => (int)$scp,
+ 'stp' => (int)$stp
+ );
+ #po potrebi updejtamo profil
+ if($updateProfile == true) {
+ $this->updateProfiles($id);
+ }
+ }
+ }
+
+ return $this->profiles;
+ }
+
+ function DisplayLink($hideAdvanced = true, $hideSeperator = false) {
+ global $lang;
+ $css = (
+ (int)$this->currentProfileId == SPM_DEFAULT_PROFILE
+ || (int)$this->currentProfileId == 0
+ ? ' gray'
+ : '');
+ if ($hideAdvanced == false || $izbranStatusProfile != SSP_DEFAULT_PROFILE) {
+ if ($hideSeperator == false) {
+ echo '<li class="space">&nbsp;</li>';
+ }
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" onclick="profileManager_displayProfiles(); return false;" title="' . $lang['srv_profileManager_link'] . '">' . $lang['srv_profileManager_link'] . '</span>';
+ echo '</li>';
+
+ }
+ }
+
+ function DisplayProfiles($pid = null) {
+ global $lang;
+
+ if ($pid === null) {
+ $pid = $this -> currentProfileId;
+ }
+
+ $popUp = new PopUp();
+ $popUp->setId('divProfileManager');
+ $popUp->setHeaderText($lang['srv_profileManager_div_header']);
+
+ #vsebino shranimo v buffer
+ ob_start();
+ echo '<form id="profileManager_form">';
+ echo '<div class="floatLeft spaceRight" style="height:100%;">';
+ echo '<div id="profileManager_holder">';
+ echo '<div id="profileManager_profile" class="select">';
+ foreach ($this->profiles as $key => $value) {
+ echo '<div class="option' . ( $pid == $value['id'] ? ' active' : '') . '" id="profileManager_profile_' . $value['id'] . '" value="'.$value['id'].'">';
+
+ echo $value['name'];
+
+ if($pid > 0 && $pid == $value['id']){
+ echo ' <a href="#" onclick="profileManager_delete(\''.$pid.'\'); return false;" value="'.$lang['srv_delete_profile'].'"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'."\n";
+ }
+
+ echo '</div>';
+ }
+ echo '</div>';
+
+ echo '</div>';
+ echo '</div>';
+ $this->DisplayProfileData($pid);
+ echo '</form>'; # profileManager_form
+
+ // cover Div
+ echo '<div id="profileManagerCoverDiv"></div>';
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfile">'.$lang['srv_missing_profile_name'].': ';
+
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />';
+
+ $button = new PopUpButton($lang['srv_save_profile']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','profileManager_saveNew(\''.$pid.'\'); return false;');
+
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','$(\'#newProfile\').hide(); $(\'#profileManagerCoverDiv\').fadeOut(); return false;');
+
+ echo '</div>';
+
+
+ $content = ob_get_clean();
+
+ #dodamo vsebino
+ $popUp->setContent($content);
+
+ #dodamo gumb izberi profil
+ $button = new PopUpButton($lang['srv_choose_profile']);
+ $button -> setFloat('right')
+ -> setButtonColor('orange')
+ -> addAction('onClick','profileManager_choose(\''.$pid.'\'); return false;');
+ $popUp->addButton($button);
+
+
+ #dodamo gumb nov profil
+ $button = new PopUpButton($lang['srv_new_profile_name']);
+ $button -> setFloat('right')
+ -> addAction('onClick','profileManager_newName(\''.$pid.'\'); return false;');
+
+ $popUp->addButton($button);
+
+ if ($pid > 0) {
+
+ # dodamo gumb shrani
+ $button = new PopUpButton($lang['srv_save_profile']);
+ $button -> setFloat('right')
+ -> addAction('onClick','profileManager_save(\''.$pid.'\',\'false\'); return false;');
+ $popUp->addButton($button);
+
+ # dodamo gumb izbriši
+ /*$button = new PopUpButton($lang['srv_delete_profile']);
+ $button -> setFloat('right')
+ -> addAction('onClick','profileManager_delete(\''.$pid.'\'); return false;');
+ $popUp->addButton($button);*/
+ }
+
+ # dodamo gumb Prekliči
+ $button = new PopUpCancelButton();
+ $button -> setFloat('right');
+ $popUp->addButton($button);
+
+ echo $popUp;
+ }
+
+ function getPidData($pid = null) {
+ if ($pid === null) {
+ $pid = $this -> currentProfileId;
+ }
+
+ $result = $this->profiles[$pid];
+ # pridobimo imena profilov
+ foreach ($this->profileVariables AS $pvKey => $profileVariable) {
+ $sub_pid = $this->profiles[$pid][$profileVariable];
+
+ $subName = $this->{$profileVariable}->getProfileName($sub_pid);
+ $result[$profileVariable] = array('id'=>$sub_pid, 'name'=>$subName);
+ }
+
+ return $result;
+ }
+
+ function SaveProfile() {
+ global $lang;
+ $pid = (int)$_POST['pid'];
+ $name = isset($_POST['pm_name']) && trim($_POST['pm_name']) != '' ? $_POST['pm_name'] : $lang['srv_profileManager_profileName_new'];
+
+ $comment = $_POST['pm_comment'];
+ $asNew = $_POST['asNew'] == 'true' ? true : false;
+
+ $data_fields = array();
+ $data_variables = array();
+ foreach ($this->profileVariables AS $pvKey => $profileVariable) {
+ $data[] = $_POST['pm_profile_'.$profileVariable];
+ if (isset($_POST['pm_profile_'.$profileVariable])) {
+ $data_fields[] = $profileVariable;
+ $data_variables[] = $_POST['pm_profile_'.$profileVariable];
+ }
+ }
+
+ # ali updejtamo obstoječ profil
+ if ($asNew == false) {
+ # preverimo ali profil s tem ID-jem že obstaja ali ga samo shranmimo
+ $str = "SELECT count(*) FROM srv_profile_manager WHERE id = '$pid'";
+ $qry = sisplet_query($str);
+ list($count) = mysqli_fetch_row($qry);
+ if ($count > 0) {
+ # popravimo star profil
+ $strUpdate = "UPDATE srv_profile_manager SET name='$name', comment='$comment' WHERE id='$pid'";
+ $qryUpdate = sisplet_query($strUpdate);
+ sisplet_query('COMMIT');
+ $this->profiles = $this->getProfiles();
+ $this->DisplayProfiles($pid);
+ return;
+ }
+ }
+
+ # v nov profil
+ if (count($data_fields) > 0 && count($data_variables) > 0) {
+ $str = "INSERT INTO srv_profile_manager (id,ank_id,name,comment,"
+ .implode(',',$data_fields)
+ .") VALUES (NULL,'$this->sid','$name','$comment',"
+ .implode(',',$data_variables)
+ . ")";
+ $qry = sisplet_query($str);
+ $new_id = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query('COMMIT');
+ $this->profiles = $this->getProfiles();
+ $this->DisplayProfiles($new_id);
+ }
+ }
+
+ /** updejtamo izbrane podprofile pri posameznem glevnem profilu
+ *
+ * @param (int) $pid
+ */
+ function updateProfiles($pid) {
+ # popravimo star profil
+ $strUpdate = "UPDATE srv_profile_manager SET"
+ . " ssp = '".$this->profiles[$pid]['ssp']."'"
+ . ", svp = '".$this->profiles[$pid]['svp']."'"
+ . ", scp = '".$this->profiles[$pid]['scp']."'"
+ . ", stp = '".$this->profiles[$pid]['stp']."'"
+ . " WHERE id='$pid'";
+ $qryUpdate = sisplet_query($strUpdate);
+ sisplet_query('COMMIT');
+ }
+
+ function ChangeProfile() {
+ $pid = (int)$_REQUEST['pid'];
+ $this->DisplayProfiles($pid);
+ }
+
+ function DisplayProfileData($pid=null) {
+ global $lang;
+
+ if ($pid === null) {
+ $pid = $this -> currentProfileId;
+ }
+
+ echo '<div style="background-color:#EFF2F7; padding: 5px; float:right; height:160px;">';
+
+ echo '<div class="floatRight">';
+ $pidData = $this->getPidData($pid);
+ echo '<table id="tbl_profileManager_pdofileData">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_profileManager_profileChoosen'].'</th>';
+ echo '<th>'.$lang['srv_profileManager_profileChoosen_name'].'</th>';
+ echo '</tr>';
+ foreach ($this->profileVariables AS $pvKey => $profileVariable) {
+ $pvProfile = $pidData[$profileVariable];
+ echo '<tr>';
+ echo '<td>'.$lang['srv_profileManager_profileName_'.$profileVariable].'</td>';
+ echo '<td><input type="hidden" name="pm_profile_'.$profileVariable.'" value="'.$pvProfile['id'].'">'.$pvProfile['name'].'</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '</div>';
+
+ echo '<div class="floatRight spaceRight">';
+ echo '<table><tr>';
+ echo '<td style="vertical-align:top;"><label>'.$lang['srv_profileManager_name'].'</label></td>';
+ if (trim($pidData['name']) == '') {
+ $placeholder = ' placeholder="'.$lang['srv_profileManager_profileName_new'].'"';
+ }
+ if ($pid <= 0) {
+ $disabled = ' disabled="disabled"';
+ }
+ echo '<td style="vertical-align:top;">';
+ echo '<input type="text" style="width:250px;" name="pm_name"'.$placeholder.$disabled.' value="'.$pidData['name'].'"/>';
+ echo '</td>';
+ echo '</tr><tr>';
+ echo '<td style="vertical-align:top;"><label>'.$lang['srv_profileManager_comment'].'</label></td>';
+ echo '<td style="vertical-align:top;"><textarea name="pm_comment"'.$disabled.' style="width:250px; height:80px;">'.$pidData['comment'].'</textarea></td>';
+ echo '</tr></table>';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function DeleteProfile() {
+ $pid = (int)$_REQUEST['pid'];
+ if ($pid > 0) {
+ # popravimo star profil
+ $strUpdate = "DELETE FROM srv_profile_manager WHERE id='$pid' AND ank_id='$this->sid'";
+ $qryUpdate = sisplet_query($strUpdate);
+ sisplet_query('COMMIT');
+ $this->profiles = $this->getProfiles();
+ }
+ $this->DisplayProfiles((int)SPM_DEFAULT_PROFILE);
+ }
+
+ function ChooseProfile() {
+ $pid = (int)$_REQUEST['pid'];
+
+ #zloopamo skozi profile in ponastavimo nastavitve
+ foreach ($this->profileVariables AS $pvKey => $profileVariable) {
+ $sub_pid = $this->profiles[$pid][$profileVariable];
+ $this->{$profileVariable}->setDefaultProfileId($sub_pid);
+ }
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', $pid);
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyQuotas.php b/admin/survey/classes/class.SurveyQuotas.php
new file mode 100644
index 0000000..7f71e73
--- /dev/null
+++ b/admin/survey/classes/class.SurveyQuotas.php
@@ -0,0 +1,816 @@
+<?php
+/**
+* @author Peter Hrvatin
+* @date December 2015
+*
+*/
+
+
+class SurveyQuotas {
+
+ private $anketa; # id ankete
+ private $spremenljivka; # id spremenljivke
+
+
+ /**
+ * Konstruktor
+ */
+ public function __construct( $anketa = null ) {
+ global $global_user_id, $site_path;
+
+ // če je podan anketa ID
+ if ((int)$anketa > 0) {
+
+ $this->anketa = $anketa;
+ }
+ else {
+ die("Napaka!");
+ }
+ }
+
+
+ public function quota_display($condition, $long_alert=0) {
+ global $lang;
+
+ $echo = '';
+ $echo .= '<span class="quota_display">';
+
+ if ($condition < 0) {
+ $rowC = Cache::srv_spremenljivka($condition < 0 ? -$condition : $condition);
+ $echo .= $rowC['variable'].' = ';
+ }
+
+ $sql = sisplet_query("SELECT * FROM srv_quota WHERE cnd_id = '$condition' ORDER BY vrstni_red ASC");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $bracket = 0;
+ $i = 0;
+ while ($row = mysqli_fetch_array($sql)) {
+
+ if ($i++ != 0)
+ if ($row['operator'] == 0)
+ $echo .= ' <span class="conjunction">+</span> ';
+ elseif ($row['operator'] == 1)
+ $echo .= ' <span class="conjunction">-</span> ';
+ elseif ($row['operator'] == 2)
+ $echo .= ' <span class="conjunction">*</span> ';
+ elseif ($row['operator'] == 3)
+ $echo .= ' <span class="conjunction">/</span> ';
+
+ for ($i=1; $i<=$row['left_bracket']; $i++)
+ if ($long_alert == 1)
+ $echo .= ' <span class="bracket'.(($bracket++)%12).'">(</span> ';
+ else
+ $echo .= ' ( ';
+
+ // Pri kvotah imamo vedno count
+ $echo .= $lang['srv_quota'].' (';
+
+ // spremenljivke
+ if ($row['spr_id'] > 0) {
+
+ // obicne spremenljivke
+ if ($row['vre_id'] == 0) {
+ $row1 = Cache::srv_spremenljivka($row['spr_id']);
+ if ($row1['tip'] != 7) {
+ $variable = $row1['variable'];
+ }
+ // number
+ else {
+ $variable = $row1['variable'].'['.($row['grd_id']+1).']';
+ }
+ }
+ // multigrid, checkbox, radio
+ elseif ($row['grd_id'] == 0) {
+ $sql1 = sisplet_query("SELECT variable FROM srv_vrednost WHERE id = '$row[vre_id]'");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+ $row1 = mysqli_fetch_array($sql1);
+
+ $rowS = Cache::srv_spremenljivka($row['spr_id']);
+ if ($rowS['tip'] != 1) {
+ $variable = $row1['variable'];
+ }
+ else{
+ $variable = $rowS['variable'].'_'.$row1['variable'];
+ }
+ }
+ // multichecckbox, multinumber
+ elseif ($row['grd_id'] > 0) {
+ $sql1 = sisplet_query("SELECT variable FROM srv_vrednost WHERE id = '$row[vre_id]'");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+ $row1 = mysqli_fetch_array($sql1);
+ $sql1g = sisplet_query("SELECT variable FROM srv_grid WHERE id = '$row[grd_id]'");
+ if (!$sql1g) echo mysqli_error($GLOBALS['connect_db']);
+ $row1g = mysqli_fetch_array($sql1g);
+ $variable = $row1['variable'].'['.$row1g['variable'].']';
+ }
+
+ if ($long_alert) $echo .= '<strong>';
+ $echo .= $variable;
+ if ($long_alert) $echo .= '</strong>';
+
+ // konstante
+ } elseif ($row['spr_id'] < 0) {
+
+ $echo .= $lang['srv_quota_status_'.(-1*$row['spr_id'])];
+
+ }
+
+ // Pri kvotah imamo vedno count
+ $echo .= ')';
+
+ for ($i=1; $i<=$row['right_bracket']; $i++)
+ if ($long_alert == 1)
+ $echo .= ' <span class="bracket'.((--$bracket)%12).'">)</span> ';
+ else
+ $echo .= ' ) ';
+
+ }
+
+ $echo .= '</span>';
+
+ if ($long_alert) {
+ $quota_check = $this->quota_check($condition);
+
+ if ( $quota_check != 0) {
+
+ if ($quota_check == 1)
+ $echo .= '<br /><span class="faicon warning icon-orange"></span> <span class="red">'.$lang['srv_error_spremenljivka'].'</span>';
+ elseif ($quota_check == 2)
+ $echo .= '<br /><span class="faicon warning icon-orange"></span> <span class="red">'.$lang['srv_error_spremenljivka'].'</span>';
+ elseif ($quota_check == 3)
+ $echo .= '<br /><span class="faicon warning icon-orange"></span> <span class="red">'.$lang['srv_error_oklepaji'].'</span>';
+
+ }
+ }
+
+ return $echo;
+ }
+
+
+ // Izpise urejanje kvote
+ private function quota_editing ($condition, $vrednost=0) {
+ global $lang;
+
+ echo '<div class="popup_close"><a href="#" onClick="quota_editing_close(\''.$condition.'\', \''.$vrednost.'\'); return false;">✕</a></div>';
+
+ echo '<div id="quota_editing_inner">';
+ $this->quota_editing_inner($condition, $vrednost);
+ echo '</div>';
+
+ echo '<div id="bottom_space">';
+
+ $row = Cache::srv_spremenljivka(-$condition);
+ if ($condition < 0) {
+ echo '<p style="float:left; padding:0; margin:0; margin-left:20px">'.$lang['srv_variable'].': <input type="text" id="variable_'.(-$condition).'" value="'.$row['variable'].'" onkeyup="quota_edit_variable(\''.-$condition.'\');" style="width:60px" /></p>';
+ }
+
+
+ echo '<div id="condition_editing_close">';
+
+ // kvota kot spremenljivka (lahko jo zbrisemo)
+ if ($condition < 0) {
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="brisi_spremenljivko(\''.(-$condition).'\'); return false;"><span>'.$lang['srv_anketadelete_txt'].'</span></a>';
+ echo '</span>';
+ }
+
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="quota_editing_close(\''.$condition.'\', \''.$vrednost.'\'); return false;"><span>'.$lang['srv_zapri'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="quota_editing_close(\''.$condition.'\', \''.$vrednost.'\'); return false;"><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+
+ echo '</div>';
+ echo '</div>';
+ }
+
+ private function quota_editing_inner ($condition, $vrednost=0) {
+ global $lang;
+
+ echo '<div class="quota_editing_preview">';
+
+ echo '<h2>'.$lang['srv_quota'].'</h2>';
+ echo '<div id="quota_editing_calculations">';
+ echo $this->quota_display($condition, 1);
+ echo '</div>';
+ echo '</div>';
+
+ echo '<div class="condition_editing_body">';
+ echo '<h2>'.$lang['srv_edit_quota'].'</h2>';
+ echo '</div>';
+
+ // Vrednost kvote
+ /*$rowS = Cache::srv_spremenljivka(-$condition);
+ echo '<div id="quota_value_holder">';
+ echo $lang['srv_quota_value'].': ';
+ echo ' <input type="text" name="value" id="quota_value" value="'.$rowS['vsota_limit'].'" style="width:50px" onkeypress="checkNumber(this, 6, 0);" onkeyup="checkNumber(this, 9, 0);" onBlur="quota_value_edit(\''.$rowS['id'].'\');">';
+ echo '</div>';*/
+
+ $sql = sisplet_query("SELECT id FROM srv_quota WHERE cnd_id = '$condition' ORDER BY vrstni_red");
+ if (mysqli_num_rows($sql) == 0) {
+ sisplet_query("INSERT INTO srv_quota (id, cnd_id, vrstni_red) VALUES ('', '$condition', '1')");
+ $sql = sisplet_query("SELECT id FROM srv_quota WHERE cnd_id = '$condition' ORDER BY vrstni_red");
+ }
+ while ($row = mysqli_fetch_array($sql)) {
+ $this->quota_edit($row['id'], $vrednost);
+ }
+
+ echo '<p id="quota_editing_operators" style="margin-left:62px">'.$lang['srv_add_cond'].':
+ <a href="#" onclick="quota_add(\''.$condition.'\', \'0\', \''.$vrednost.'\'); return false;"><strong style="font-size:18px">&nbsp;+&nbsp;</strong></a>,
+ <a href="#" onclick="quota_add(\''.$condition.'\', \'1\', \''.$vrednost.'\'); return false;"><strong style="font-size:18px">&nbsp;-&nbsp;</strong></a>,
+ <a href="#" onclick="quota_add(\''.$condition.'\', \'2\', \''.$vrednost.'\'); return false;"><strong style="font-size:18px">&nbsp;*&nbsp;</strong></a>,
+ <a href="#" onclick="quota_add(\''.$condition.'\', \'3\', \''.$vrednost.'\'); return false;"><strong style="font-size:18px">&nbsp;/&nbsp;</strong></a>
+ </p>';
+ }
+
+ /**
+ * @desc vrstica v urejanju kvot
+ */
+ private function quota_edit ($quota, $vrednost=0) {
+ global $lang;
+
+ $b = new Branching($this->anketa);
+
+ $sql = sisplet_query("SELECT * FROM srv_quota WHERE id = '$quota'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $row = mysqli_fetch_array($sql);
+
+ $sql1 = sisplet_query("SELECT if_id FROM srv_condition WHERE id = '{$row['cnd_id']}'");
+ $row1 = mysqli_fetch_array($sql1);
+
+ if ($row['cnd_id'] > 0) { // kalkulacija znotraj pogoja
+ $vrstni_red = $b->vrstni_red($b->find_before_if($row1['if_id']));
+ } else { // kalkulacija kot spremenljivka
+ $vrstni_red = $b->vrstni_red(-$row['cnd_id']) - 1; // -1 je da ne prikaze se trenutne kalkulacije
+ }
+
+ $sql_count = sisplet_query("SELECT COUNT(*) AS count FROM srv_quota WHERE cnd_id='$row[cnd_id]'");
+ if (!$sql_count) die();
+ $row_count = mysqli_fetch_array($sql_count);
+
+ if ($row['vrstni_red'] == 1 && $row_count['count'] > 1) {
+ echo '<table class="tbl_condition_editing">';
+ echo '<tr>';
+ echo '<th style="text-align:center; width:50px">'.$lang['srv_oklepaji'].'</th>'; // gumbi oklepaji
+ echo '<th style="width:70px">&nbsp;</th>'; // logicni operatorji
+ echo '<th style="width:50px">&nbsp;</th>'; // oklepaji
+ echo '<th >&nbsp;</th>';
+ echo '<th style="text-align:center; width:50px;">'.$lang['srv_zaklepaji'].'</th>'; // gumbi zaklepaji
+ echo '<th style="text-align:center; width:60px">'.$lang['edit2'].'</th>'; // move
+ echo '</tr>';
+ echo '</table>';
+
+ } elseif ($row['vrstni_red'] == 1) {
+ echo '<table class="tbl_condition_editing"><tr><th>&nbsp;</th></tr></table>';
+ }
+
+ // form
+ echo '<form name="quota_'.$quota.'" id="quota_'.$quota.'" action="" method="post" onsubmit="quota_edit(\''.$quota.'\'); return false;">'."\n\r";
+
+ echo '<table class="tbl_condition_editing" style="margin-bottom:10px; padding-bottom:10px; background-color:white">';
+ echo '<tr>';
+
+
+ // left_bracket
+ if ($row_count['count'] != 1 || $row['left_bracket']>0 || $row['right_bracket']>0) {
+ echo '<td class="tbl_ce_lol white" style="width:50px; text-align:center;" >';
+ echo '<a href="#" onclick="javascript:quota_bracket_edit_new(\''.$quota.'\', \''.$vrednost.'\', \'left\', \'plus\' ); return false;" title="'.$lang['srv_oklepaj_add'].'"><span class="faicon add small"></span></a>';
+ if ($row['left_bracket'] > 0)
+ echo '<a href="#" onclick="javascript:quota_bracket_edit_new(\''.$quota.'\', \''.$vrednost.'\', \'left\', \'minus\'); return false;" title="'.$lang['srv_oklepaj_rem'].'"><span class="faicon add small"></span></a>';
+ else
+ echo '<span class="faicon delete_circle icon-grey_normal"></span>';
+ }
+ else {
+ echo '<td class="tbl_ce_lol white" style="width:50px; text-align:center;" >';
+ }
+ echo '</td>';
+
+ // operator
+ echo '<td class="tbl_ce_tb white" style="width:77px; text-align:center">';
+
+ if ($row['vrstni_red'] == 1) {
+ // nimamo nic..
+ } else {
+
+ if ($row['operator']==0)
+ echo '<a href="#" onclick="quota_operator_edit(\''.$quota.'\', \'1\'); return false;" style="font-weight:bold; font-size:18px" title="'.$lang['srv_edit_condition_conjunction'].'">&nbsp;+&nbsp;</a>';
+ if ($row['operator']==1)
+ echo '<a href="#" onclick="quota_operator_edit(\''.$quota.'\', \'2\'); return false;" style="font-weight:bold; font-size:18px" title="'.$lang['srv_edit_condition_conjunction'].'">&nbsp;-&nbsp;</a>';
+ if ($row['operator']==2)
+ echo '<a href="#" onclick="quota_operator_edit(\''.$quota.'\', \'3\'); return false;" style="font-weight:bold; font-size:18px" title="'.$lang['srv_edit_condition_conjunction'].'">&nbsp;*&nbsp;</a>';
+ if ($row['operator']==3)
+ echo '<a href="#" onclick="quota_operator_edit(\''.$quota.'\', \'0\'); return false;" style="font-weight:bold; font-size:18px" title="'.$lang['srv_edit_condition_conjunction'].'">&nbsp;/&nbsp;</a>';
+ }
+
+ echo '</td>';
+
+
+ // left_bracket
+ echo '<td class="tbl_ce_tb white" style="width:40px; text-align:center">';
+ for ($i=$row['left_bracket']; $i>0; $i--) {
+ echo ' ( '; }
+ echo '</td>';
+
+ // spremenljivka
+ echo '<td class="tbl_ce_tb white" style="width:auto">';
+ if ($row['spr_id']==0) echo '<span class="red">'.$lang['srv_select_spr'].'!</span>';
+ echo '<br />';
+ echo '<select name="quota_spremenljivka_'.$quota.'" id="quota_spremenljivka_'.$quota.'" size="1" style="width:150px" onchange="javascript:quota_edit(\''.$quota.'\', \''.$vrednost.'\');">'."\n\r";
+
+ echo '<option value="0"></option>';
+
+ // Kvote po statusu
+ echo '<option value="-1"'. ($row['spr_id']==-1 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_1'].'</option>';
+ echo '<option value="-2"'. ($row['spr_id']==-2 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_2'].'</option>';
+ echo '<option value="-3"'. ($row['spr_id']==-3 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_3'].'</option>';
+ echo '<option value="-4"'. ($row['spr_id']==-4 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_4'].'</option>';
+ echo '<option value="-5"'. ($row['spr_id']==-5 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_5'].'</option>';
+ echo '<option value="-6"'. ($row['spr_id']==-6 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_6'].'</option>';
+ // Kvota po ustreznih odgovorih
+ echo '<option value="-7"'. ($row['spr_id']==-7 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_7'].'</option>';
+ // Kvota po vseh odgovorih
+ echo '<option value="-8"'. ($row['spr_id']==-8 ?' selected="selected"':'').' style="color: blue">&nbsp;&nbsp;&nbsp; '.$lang['srv_quota_status_8'].'</option>';
+
+ $sql1 = sisplet_query("SELECT s.id, s.gru_id, s.naslov, s.variable, s.tip, g.naslov AS grupa_naslov
+ FROM srv_spremenljivka s, srv_grupa g
+ WHERE g.ank_id='$this->anketa' AND s.gru_id=g.id AND s.tip IN (1, 2, 3, 6, 7, 22, 16, 20, 17, 18)
+ ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+
+ if(!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+
+ $prev_grupa = 0;
+
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ if ($b->vrstni_red($row1['id']) <= $vrstni_red) {
+
+ if ($row1['gru_id'] != $prev_grupa) {
+ echo '<option value="0" disabled style="font-style: italic;">'.$row1['grupa_naslov'].'</option>';
+ $prev_grupa = $row1['gru_id'];
+ }
+
+
+ // radio, select, checkbox
+ if ($row1['tip'] == 1 || $row1['tip'] == 2 || $row1['tip'] == 3) {
+
+ echo '<option value="0" disabled>&nbsp;&nbsp;&nbsp; ('.$row1['variable'].') '.$row1['naslov'].'</option>';
+
+ $sql2 = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$row1[id]' ORDER BY vrstni_red ASC");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+
+ if ($row2['id'] == $row['vre_id'] && $row['grd_id'] == 0)
+ $selected = ' selected="selected"';
+ else
+ $selected = '';
+
+ echo '<option value="vre_'.$row2['id'].'"'.$selected.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - ('.($row1['tip'] == 1 ? $row1['variable'].'_' : '').''.$row2['variable'].') '.$row2['naslov'].'</option>'."\n\r";
+ }
+ }
+ // multigrid, multichecbox
+ elseif ($row1['tip'] == 6 || $row1['tip'] == 16) {
+
+ echo '<option value="0" disabled>&nbsp;&nbsp;&nbsp; ('.$row1['variable'].') '.$row1['naslov'].'</option>';
+
+ $sql2 = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$row1[id]' ORDER BY vrstni_red ASC");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+
+ echo '<option value="0" disabled>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - ('.$row2['variable'].') '.$row2['naslov'].'</option>'."\n\r";
+
+ $sql3 = sisplet_query("SELECT id, naslov, variable FROM srv_grid WHERE spr_id='$row1[id]' ORDER BY vrstni_red ASC");
+ while ($row3 = mysqli_fetch_array($sql3)) {
+
+ if ($row1['id']==$row['spr_id'] && $row2['id']==$row['vre_id'] && $row3['id']==$row['grd_id'])
+ $selected = ' selected="selected"';
+ else
+ $selected = '';
+
+ echo '<option value="mlti_'.$row1['id'].'_'.$row2['id'].'_'.$row3['id'].'"'.$selected.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ('.$row3['variable'].') '.$row3['naslov'].'</option>'."\n\r";
+ }
+ }
+ }
+ // multinumber
+ elseif ($row1['tip'] == 20) {
+
+ /*echo '<option value="0" disabled>&nbsp;&nbsp;&nbsp; ('.$row1['variable'].') '.$row1['naslov'].'</option>';
+
+ $sql2 = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id='$row1[id]' ORDER BY vrstni_red ASC");
+ while ($row2 = mysqli_fetch_array($sql2)) {
+
+ echo '<option value="0" disabled>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - ('.$row2['variable'].') '.$row2['naslov'].'</option>'."\n\r";
+
+ $sql3 = sisplet_query("SELECT * FROM srv_grid WHERE spr_id='$row1[id]' ORDER BY vrstni_red ASC");
+ while ($row3 = mysqli_fetch_array($sql3)) {
+
+ if ($row1['id']==$row['spr_id'] && $row2['id']==$row['vre_id'] && $row3['id']==$row['grd_id'])
+ $selected = ' selected="selected"';
+ else
+ $selected = '';
+
+ echo '<option value="mlti_'.$row1['id'].'_'.$row2['id'].'_'.$row3['id'].'"'.$selected.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ('.$row3['variable'].') '.$row3['naslov'].'</option>'."\n\r";
+ }
+ }*/
+ }
+ // number
+ elseif ($row1['tip'] == 7) {
+
+ /*echo '<option value="0" disabled>&nbsp;&nbsp;&nbsp; ('.$row1['variable'].') '.$row1['naslov'].'</option>'."\n\r";
+
+ // number ima lahko dva polja
+ for ($i=0; $i<$row1['size']; $i++) {
+
+ if ($row1['id'] == $row['spr_id'] && $i == $row['grd_id'])
+ $selected = ' selected="selected"';
+ else
+ $selected = '';
+
+ echo '<option value="num_'.$row1['id'].'_'.$i.'"'.$selected.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - ('.($i+1).') '.($i+1).'. '.$lang['srv_field'].'</option>'."\n\r";
+ }*/
+ }
+ // vsi ostali (numericni)
+ else {
+ /*if ($row1['id'] == $row['spr_id'])
+ $selected = ' selected="selected"';
+ else
+ $selected = '';
+
+ echo '<option value="'.$row1['id'].'"'.$selected.'>&nbsp;&nbsp;&nbsp; ('.$row1['variable'].') '.$row1['naslov'].'</option>'."\n\r";*/
+ }
+ }
+ }
+
+ echo '</select>';
+
+
+ // Vrednost kvote
+ /*echo ' <input type="text" name="value" id="quota_value_'.$quota.'" value="'.$row['value'].'" style="width:40px" >';
+ echo '<script type="text/javascript">'; // shranimo ko zapustmo input polje
+ echo '$(document).ready(function() {' .
+ ' $("input#quota_value_'.$quota.'").bind("blur", {}, function(e) {' .
+ ' quota_edit(\''.$quota.'\', \''.$vrednost.'\'); return false; ' .
+ ' });' .
+ '});';
+ echo '</script>';*/
+
+
+ echo '<br />&nbsp;'."\n\r";
+ echo '</td>';
+
+
+ // right_bracket
+ echo '<td class="tbl_ce_tb white" style="width:40px; text-align:center">';
+ for ($i=$row['right_bracket']; $i>0; $i--) {
+ echo ' ) ';
+ }
+ echo '</td>';
+
+
+ // right_bracket buttons
+ if ($row_count['count'] != 1 || $row['right_bracket']>0 || $row['left_bracket']>0) {
+ echo '<td class="tbl_ce_lor" style="width:50px; text-align:center" nowrap>';
+ if ($row['right_bracket'] > 0)
+ echo '<a href="#" onclick="javascript:quota_bracket_edit_new(\''.$quota.'\', \''.$vrednost.'\', \'right\', \'minus\'); return false;" title="'.$lang['srv_zaklepaj_rem'].'"><span class="faicon delete_circle"></span></a>';
+ else
+ echo '<span class="faicon delete_circle icon-grey_normal"></span>';
+
+ echo '<a href="#" onclick="javascript:quota_bracket_edit_new(\''.$quota.'\', \''.$vrednost.'\', \'right\', \'plus\' ); return false;" title="'.$lang['srv_zaklepaj_add'].'"><span class="faicon add small"></span></a>';
+ }
+ else {
+ echo '<td class="tbl_ce_lor white" style="width:50px; text-align:center" nowrap>';
+ }
+ echo '</td>';
+
+ // move
+ echo '<td class="tbl_ce_bck_blue white" style="text-align:right; width:30px">';
+ if ($row_count['count'] != 1 )
+ echo '<img src="img_0/move_updown.png" class="move" title="'.$lang['srv_move'].'" />';
+ echo '</td>';
+
+ // remove
+ echo '<td class="tbl_ce_bck_blue white" style="text-align:left; width:30px">';
+ $sql3 = sisplet_query("SELECT id FROM srv_quota WHERE cnd_id='$row[cnd_id]'");
+ if (mysqli_num_rows($sql3) != 1 )
+ echo ' <a href="#" onclick="quota_remove(\''.$row['cnd_id'].'\', \''.$quota.'\', \''.$vrednost.'\'); return false;" title="'.$lang['srv_if_rem'].'"><span class="faicon delete icon-grey_dark_link delte-if-block"></span></a>'."\n\r";
+ echo '</td>';
+
+
+ echo '</tr>';
+ echo '</table>';
+
+ echo '</form>'."\n\r";
+ }
+
+ /**
+ * @desc preveri ali so oklepaji pravilno postavljeni v kalkulacijah (presteje predoklepaje in zaklepaje)
+ * in pa ce je izbrana spremenljivka
+ */
+ private function quota_check ($condition) {
+
+ $sql = sisplet_query("SELECT spr_id, left_bracket, right_bracket FROM srv_quota WHERE cnd_id='$condition' ORDER BY vrstni_red");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ if (mysqli_num_rows($sql) == 0) return 1; // ni sploh se izbrana spremenljivka (ker ni quota sploh se inicializiran z default vrstico)
+
+ $bracket = 0;
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['spr_id'] == 0) // ce ni izbrana spremenljivka v eni od vrstic
+ return 2;
+
+ $bracket = $bracket + $row['left_bracket'] - $row['right_bracket'];
+ if ($bracket < 0)
+ return 3; // oklepaj
+ }
+
+ if ($bracket == 0)
+ return 0; // vse ok
+ else
+ return 3; // zaklepaj
+ }
+
+
+
+ public function ajax() {
+ global $global_user_id;
+ global $lang;
+ global $site_path;
+
+ if (isset($_POST['anketa'])) $this->anketa = $_POST['anketa'];
+ if (isset($_POST['spremenljivka'])) $this->spremenljivka = $_POST['spremenljivka'];
+
+ $ajax = 'ajax_' . $_GET['a'];
+
+ if ( method_exists('SurveyQuotas', $ajax) )
+ $this->$ajax();
+ else
+ echo 'method '.$ajax.' does not exist';
+ }
+
+ private function ajax_quota_editing () {
+ if ($_POST['noupdate'] != 1) {
+ Common::updateEditStamp();
+ }
+
+ $condition = $_POST['condition'];
+ $vrednost = $_POST['vrednost'];
+
+ $sql = sisplet_query("SELECT vre_id FROM srv_condition WHERE id = '$condition'");
+ $row = mysqli_fetch_array($sql);
+
+ $quota = $this->quota_editing($condition, $vrednost);
+
+ if ($row['vre_id'] == 0) {
+ $s = sisplet_query("UPDATE srv_condition SET vre_id='$quota' WHERE id='$condition'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ private function ajax_quota_editing_close () {
+
+ $condition = $_POST['condition'];
+ $vrednost = $_POST['vrednost'];
+
+ $sql = sisplet_query("SELECT if_id FROM srv_condition WHERE id = '$condition'");
+ $row = mysqli_fetch_array($sql);
+
+ $b = new Branching($this->anketa);
+ if ($condition >= 0)
+ $b->condition_editing($row['if_id'], $vrednost);
+ else {
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+ if ($row['expanded'] == 1) {
+ $b->vprasanje(-$condition);
+ } else {
+ $b->spremenljivka_name(-$condition);
+ }
+ }
+ }
+
+ private function ajax_quota_save () {
+ if ($_POST['noupdate'] != 1) {
+ Common::updateEditStamp();
+ }
+
+ $quota = $_POST['quota'];
+ $expression = $_POST['expression'];
+
+ sisplet_query("UPDATE srv_quota SET expression='$expression' WHERE id = '$quota'");
+ }
+
+ private function ajax_quota_add () {
+ if ($_POST['noupdate'] != 1) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+ }
+
+ $condition = $_POST['condition'];
+ $operator = $_POST['operator'];
+ $vrednost = $_POST['vrednost'];
+
+ $sql = sisplet_query("SELECT MAX(vrstni_red) AS max FROM srv_quota WHERE cnd_id = '$condition'");
+ $row = mysqli_fetch_array($sql);
+ $vrstni_red = $row['max'] + 1;
+
+ $s = sisplet_query("INSERT INTO srv_quota (id, cnd_id, operator, vrstni_red) VALUES ('', '$condition', '$operator', '$vrstni_red')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $this->quota_editing_inner($condition, $vrednost);
+ }
+
+ private function ajax_quota_operator_edit () {
+ if ($_POST['noupdate'] != 1) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+ }
+
+ $quota = $_POST['quota'];
+ $operator = $_POST['operator'];
+
+ sisplet_query("UPDATE srv_quota SET operator='$operator' WHERE id = '$quota'");
+
+ $sql = sisplet_query("SELECT cnd_id FROM srv_quota WHERE id = '$quota'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $row = mysqli_fetch_array($sql);
+
+ $this->quota_editing_inner($row['cnd_id'], $_POST['vrednost']);
+ }
+
+ private function ajax_quota_edit () {
+ if ($_POST['noupdate'] != 1) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+ }
+
+ $spremenljivka = $_POST['spremenljivka'];
+ $quota = $_POST['quota'];
+ $value = $_POST['value'];
+ $vrednost = $_POST['vrednost'];
+ $grd_id = 0;
+
+ // obicna spremenljivka
+ if (is_numeric($spremenljivka)) {
+ $spr_id = $spremenljivka;
+ $vre_id = 0;
+
+ // checkbox, multigrid
+ } elseif ( strpos($spremenljivka, 'vre_') !== false ) {
+ $e = explode('_', $spremenljivka);
+ list( , $vre_id, $grd_id) = $e;
+ $sql2 = sisplet_query("SELECT spr_id FROM srv_vrednost WHERE id = '$vre_id'");
+ $row2 = mysqli_fetch_array($sql2);
+ $spr_id = $row2['spr_id'];
+
+ // number
+ } elseif ( strpos($spremenljivka, 'num_') !== false ) {
+
+ $e = explode('_', $spremenljivka);
+ list( , $spr_id, $grd_id) = $e;
+ $vre_id = 0;
+
+ // multicheckbox, multinumber
+ } else {
+ $e = explode('_', $spremenljivka);
+ list( , $spr_id, $vre_id, $grd_id) = $e;
+ }
+
+ if (!is_numeric($value)) $value = 0;
+
+ $s = sisplet_query("UPDATE srv_quota SET spr_id='$spr_id', vre_id='$vre_id', grd_id='$grd_id', value='$value' WHERE id = '$quota'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $sql = sisplet_query("SELECT cnd_id FROM srv_quota WHERE id = '$quota'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $row = mysqli_fetch_array($sql);
+
+ $this->quota_editing_inner($row['cnd_id'], $vrednost);
+ }
+
+ private function ajax_quota_value_edit (){
+
+ if ($_POST['noupdate'] != 1) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+ }
+
+ if(isset($_POST['spremenljivka']) && $_POST['spremenljivka'] > 0){
+ $spremenljivka = $_POST['spremenljivka'];
+ $value = $_POST['value'];
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET vsota_limit='$value' WHERE id = '$spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ private function ajax_quota_remove () {
+ if ($_POST['noupdate'] != 1) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+ }
+
+ $quota = $_POST['quota'];
+ $vrednost = $_POST['vrednost'];
+
+ sisplet_query("DELETE FROM srv_quota WHERE id='$quota'");
+
+ $b = new Branching($this->anketa);
+ $b->repare_calculation($_POST['condition']);
+
+ $this->quota_editing_inner($_POST['condition'], $vrednost);
+ }
+
+ private function ajax_quota_bracket_edit_new () {
+ if ($_POST['noupdate'] != 1) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+ }
+
+ $who = $_POST['who'];
+ $what = $_POST['what'];
+ $left_bracket = $_POST['left_bracket'];
+ $quota = $_POST['quota'];
+
+ if ($who == 'left')
+ if ($what == 'plus')
+ $bracket = 'left_bracket=left_bracket+1';
+ else
+ $bracket = 'left_bracket=left_bracket-1';
+ else
+ if ($what == 'plus')
+ $bracket = 'right_bracket=right_bracket+1';
+ else
+ $bracket = 'right_bracket=right_bracket-1';
+
+
+ sisplet_query("UPDATE srv_quota SET $bracket WHERE id = '$quota'");
+
+ $sql = sisplet_query("SELECT cnd_id FROM srv_quota WHERE id = '$quota'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $row = mysqli_fetch_array($sql);
+
+ $this->quota_editing_inner($row['cnd_id'], $_POST['vrednost']);
+ }
+
+ private function ajax_quota_sort() {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $condition = $_POST['condition'];
+ $sortable = $_POST['sortable'];
+ $sortable = explode('&', $sortable);
+
+ $i=1;
+ foreach ($sortable AS $calc) {
+ $quota = explode('=', $calc);
+ $quota = $quota[1];
+
+ $s = sisplet_query("UPDATE srv_quota SET vrstni_red='{$i}' WHERE id='{$quota}'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i++;
+ }
+
+ $b = new Branching($this->anketa);
+ $b->repare_condition($if);
+ $this->quota_editing_inner($condition);
+ }
+
+ private function ajax_quota_edit_variable () {
+ Common::updateEditStamp();
+
+ if(isset($_POST['spremenljivka']) && $_POST['spremenljivka'] > 0){
+ $spremenljivka = $_POST['spremenljivka'];
+ $variable = $_POST['variable'];
+
+ // preverimo, da ni se kje drugje v anekti tako ime spremenljivke
+ $sqlv = sisplet_query("SELECT s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa'");
+ $ok = true;
+ while ($rowv = mysqli_fetch_array($sqlv)) {
+ if ($rowv['variable'] == $variable)
+ $ok = false;
+ }
+
+ // Ce se ime ze pojavi v anketi mu dodamo stevilko
+ if(!$ok){
+ $ok = false;
+ $i = 2;
+ while(!$ok){
+ $ok = true;
+ $variable = $_POST['variable'].'_'.$i;
+
+ $sqlv = sisplet_query("SELECT s.variable, s.id as id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa'");
+ while ($rowv = mysqli_fetch_array($sqlv)) {
+ if ($rowv['variable'] == $variable && $spremenljivka != $rowv['id']){
+ $ok = false;
+ $i++;
+ }
+ }
+ }
+ }
+
+ sisplet_query("UPDATE srv_spremenljivka SET variable='$variable', variable_custom='1' WHERE id = '$spremenljivka'");
+ }
+ }
+
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyRecoding.php b/admin/survey/classes/class.SurveyRecoding.php
new file mode 100644
index 0000000..53f789e
--- /dev/null
+++ b/admin/survey/classes/class.SurveyRecoding.php
@@ -0,0 +1,627 @@
+<?php
+
+class SurveyRecoding
+{
+ private $anketa; # id ankete
+ private $db_table; # katere tabele uporabljamo
+
+ function __construct($anketa) {
+ $this->anketa = $anketa;
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+
+ $this->db_table = '_active';
+
+ }
+
+ function Ajax() {
+
+ switch ($_GET['a']) {
+ case 'showQuestionRecode':
+ $this->showQuestionRecode();
+ break;
+ case 'saveQuestionRecode':
+ $this->saveQuestionRecode();
+ break;
+ case 'removeQuestionRecode':
+ $this->removeQuestionRecode();
+ break;
+ case 'add_new_numeric':
+ $this->addNewNumeric();
+ break;
+ case 'changeRecodeType':
+ $this->changeRecodeType();
+ break;
+ case 'recodeSpremenljivkaNew':
+ $this->recodeSpremenljivkaNew();
+ break;
+ case 'recodeVrednostNew':
+ $this->recodeVrednostNew();
+ break;
+ case 'runRecodeVredonosti':
+ $this->runRecodeVredonosti();
+ break;
+ case 'removeSpremenljivka':
+ $this->removeSpremenljivka();
+ break;
+ case 'enableRecodeVariable':
+ $this->enableRecodeVariable();
+ break;
+ case 'visibleRecodeVariable':
+ $this->visibleRecodeVariable();
+ break;
+
+ default:
+ print_r("<pre>Class:SurveyRecoding");
+ print_r($_POST);
+ print_r($_GET);
+ exit();
+ break;
+ }
+ }
+
+ function DisplaySettings() {
+ global $lang;
+ echo '<fieldset><legend>'.$lang['srv_data_subnavigation_recode'].'</legend>';
+ echo $lang['srv_recode_note'].'<br/><br/>';
+ echo $lang['srv_recode_note_text'].'<br/><br/>';
+ #poiščemo spremenljivke ki so morda rekodirane v drugo spremenljivko
+ /*
+ $qry_str = "select distinct spr1, spr2 from srv_recode_vrednost WHERE ank_id = '$this->anketa'";
+ $sql = sisplet_query($qry_str);
+ $recodedFrom = array();
+ $recodedMaping = array();
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $recodedFrom[] = $row['spr1'];
+ $recodedMaping[$row['spr1']] = $row['spr2'];
+ }
+ */
+ $recodedFrom = array();
+ $recodedMaping = array();
+ # za barvanje celic
+ $cnt_even_odd = 0;
+ $qry_str = "select spr_id, enabled, to_spr_id from srv_recode_spremenljivka WHERE ank_id = '$this->anketa'";
+ $sql = sisplet_query($qry_str);
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $recodedFrom[] = $row['spr_id'];
+ $recodedMaping[$row['spr_id']] = $row['to_spr_id'];
+ }
+
+
+ $recodedSpremenljivkaEnabled = array();
+ #polovimo enabled za rekodiranje v novo spremenljivko
+ $qry_str = "select spr_id, enabled, to_spr_id from srv_recode_spremenljivka WHERE ank_id = '$this->anketa' AND enabled='1'";
+ $sql = sisplet_query($qry_str);
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $recodedSpremenljivkaEnabled[$row['spr_id']] = (int)$row['enabled'];
+ }
+ # polovimo enabled še za normalno rekodiranje
+ $qry_str = "select DISTINCT spr_id, enabled from srv_recode WHERE ank_id = '$this->anketa' AND enabled='1'";
+ $sql = sisplet_query($qry_str);
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $recodedSpremenljivkaEnabled[$row['spr_id']] = (int)$row['enabled'];
+ }
+
+ SurveyAnalysis::Init($this->anketa);
+ SurveyAnalysis::$setUpJSAnaliza = false;
+ /*kategorialne: 1,2,3,6,16,17
+ * number: 7,18,20,22,25
+ */
+ $qry_str = "SELECT s.id, s.variable, s.naslov FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.tip IN (1,2,3,6,16,17,7,18,20,22,25)ORDER BY g.vrstni_red ASC, s.vrstni_red ASC";
+ $sql = sisplet_query($qry_str);
+ if (mysqli_num_rows($sql)) {
+ echo '<table id="recode_table">';
+ echo '<thead><tr>';
+ echo '<th colspan="4">'.$lang['srv_recode_h_variable'].'</th>';
+ echo '<th colspan="5">'.$lang['srv_recode_h_actions'].Help::display('srv_recode_h_actions').'</th>';
+ echo '</tr></thead>';
+ while (list($spr_id, $variable, $naslov) = mysqli_fetch_row($sql)) {
+ $vmv = new RecodeValues($this->anketa,$spr_id);
+ $hasRecoded = $vmv->hasRecodedValues() || in_array($spr_id,$recodedFrom);
+ $enabled = (isset($recodedSpremenljivkaEnabled[$spr_id]) && $recodedSpremenljivkaEnabled[$spr_id] = 1) ? true : false;
+ $row = Cache::srv_spremenljivka($spr_id);
+ $is_recoded_new = false;
+ if ((int)$hasRecoded > 0) {
+ $css_strong = ' strong';
+ # spremenljivka je rekodirana v drugo
+ $icon1 = $lang['srv_recoded_note_original'];
+ $icon2 = '';
+ if ((int)$vmv->hasRecodedValues() > 0 && (int)in_array($spr_id,$recodedFrom) == 0) {
+ $icon1 = $lang['srv_recoded_note_recoded'];
+ $icon2 = '';
+ }
+ } else {
+ $css_strong = '';
+ $icon1 = '';
+ $icon2 = '';
+ }
+ $key = array_search($spr_id, $recodedMaping);
+ if ($key) {
+ # spremenljivka je rekodirana iz druge variable
+ $icon1 = '';
+ $icon2 = $lang['srv_recoded_note_recoded'];
+ $is_recoded_new = true;
+ }
+ $css_border = ' border_top_lite';
+ if ((int)$key == 0) {
+ $cnt_even_odd++;
+ $css_border = ' border_top';
+ }
+ $css_even_odd = ( ($cnt_even_odd & 1) ? ' odd' : ' even' );
+
+ echo '<tr id="recoding_variable_div_'.$spr_id.'" class="recoding_variable_div'.$css_even_odd.$css_border.'">';
+ echo '<td style="width:auto;">';
+ SurveyAnalysis::showIcons($spr_id.'_0',$row,'desc',array('noReport' => true, 'showChart' => false));
+ echo '</td>';
+ echo '<td style="width:25px; text-align:center;" class="gray">';
+ echo $icon1;
+ echo '</td>';
+ echo '<td>';
+ echo '<span class="gray">'.$icon2.'</span>';
+ echo '<span class="green'.$css_strong.'">';
+
+ echo '<a onclick="showspremenljivkaSingleVarPopup(\''.$spr_id.'_0\'); return false;" href="#">';
+ echo $variable;
+ echo '</a>';
+ echo '</span> - <span class="spaceRight'.$css_strong.'">'.skrajsaj(strip_tags($naslov),40).'</span>';
+
+ if ($key) {
+ $row1 = Cache::srv_spremenljivka($key);
+ echo '<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="italic gray">( '.$lang['srv_recode_ercode_from_spr'].$row1['variable'].' )</span>';
+ }
+
+ echo '</td>';
+
+ echo '<td class="gray" style="padding-right:10px; padding-left:10px;">';
+ $legend = Cache::spremenljivkaLegenda($spr_id);
+ echo '('.$legend['izrazanje'].' - '.$legend['skala'].')';
+ echo '</td>';
+ echo '<td style="width:50px; text-align:center;" >';
+ #dodaj
+ if ($is_recoded_new == true) {
+ echo '<span class="silver">&nbsp;</span>';
+ } else {
+ if ((int)$hasRecoded > 0) {
+ echo '<span class="silver">'.$lang['srv_recode_add'].'</span>';
+ } else {
+ echo '<span class="as_link" onclick="showQuestionRecode(\''.$spr_id.'\');">'.$lang['srv_recode_add'].'</span>';
+ }
+ }
+ echo '</td>';
+
+ echo '<td style="padding-right:10px; padding-left:10px;text-align:center;">';
+ # uredi
+ if ($is_recoded_new == true) {
+ echo '<span class="silver">&nbsp;</span>';
+ } else {
+
+ if ((int)$hasRecoded > 0) {
+ echo '<span class="as_link" onclick="showQuestionRecode(\''.$spr_id.'\');">'.$lang['srv_recode_edit'] .'</span>';
+ } else {
+ echo '<span class="silver">'.$lang['srv_recode_edit'] .'</span>';
+ }
+ }
+ echo '</td>';
+ echo '<td style="padding-right:10px; padding-left:10px; text-align:center;">';
+ # odstrani
+ if ($is_recoded_new == true) {
+ echo '<span class="silver">&nbsp;</span>';
+ } else {
+ if ((int)$hasRecoded > 0) {
+ echo '<span class="as_link" onclick="removeQuestionRecode(\''.$spr_id.'\',\''.$lang['srv_recode_confirm_delete'].'\');">'.$lang['srv_recode_remove'].'</span>';
+ } else {
+ echo '<span class="silver" >'.$lang['srv_recode_remove'].'</span>';
+ }
+ }
+ echo '</td>';
+
+ echo '<td style="padding-right:10px; padding-left:10px;">';
+ if ($is_recoded_new == true) {
+ echo '<span class="silver">&nbsp;</span>';
+ } else {
+ if ($hasRecoded) {
+ echo '<label><span class="as_link" onclick="enableRecodeVariable(\''.$spr_id.'\',this);">'.($enabled ? $lang['srv_recode_enabled'] : $lang['srv_recode_disabled']).'</span></label>';
+ #echo '<label><input type="checkbox" id="recoding_variable_cb_'.$spr_id.'" onchange="enableRecodeVariable(\''.$spr_id.'\',this);"'.($enabled?' checked="checked"':'').' autocomplete="off">'.$lang['srv_recode_enable'].'</label>';
+ } else {
+ echo '<span class="silver">'.$lang['srv_recode_enabled'].'</span>';
+ }
+ }
+ echo '</td>';
+
+ $visible= ((int)$row['visible'] == 1) ? true : false;
+
+ echo '<td style="padding-right:10px; padding-left:10px;">';
+ echo '<label><span class="as_link" onclick="visibleRecodeVariable(\''.$spr_id.'\',this);">'.($visible ? $lang['srv_recode_visible'] : $lang['srv_recode_invisible']).'</span></label>';
+ echo '</td>';
+
+ echo '</tr>';
+ $vmv = null;
+ unset($vmv);
+ }
+ echo '</table>';
+ }
+
+ session_start();
+
+ if ($_SESSION['showRunRecodeButton'][$this->anketa] == true) {
+ echo '<br/><div class="buttonwrapper floatLeft" id="btnRunRecode" title="'.$lang['srv_compute_start'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="runRecodeVredonosti($(\'#question_recode_run_note\'));">'.$lang['srv_compute_start'].'</a></div>';
+ echo '<br /><br />';
+ }
+
+ echo '</fieldset>';
+
+ $this->DisplayDashboard();
+ }
+
+ function showQuestionRecode() {
+ global $lang;
+
+ $spr_id = $_POST['spr_id'];
+
+ if ((int)$spr_id > 0 && (int)$this->anketa > 0) {
+ $qry_str = "SELECT naslov, variable FROM srv_spremenljivka WHERE id = '$spr_id'";
+ $qry = sisplet_query($qry_str);
+ $spr_row = mysqli_fetch_assoc($qry);
+
+ echo '<h2>'.$spr_row['variable'].' - '.strip_tags($spr_row['naslov']).'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="cancelQuestionRecode(); return false;">✕</a></div>';
+
+ #echo '<span id="vprasanje_edit_mv" style="outline:1px solid red;">';
+ $vmv = new RecodeValues($this->anketa,$spr_id);
+ $vmv->DisplayMissingValuesForQuestion();
+ #echo '</span>';
+
+ echo '<div class="recodeButtonHolder buttons_holder">';
+ echo '<span class="floatRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="saveQuestionRecode(); return false;">'.$lang['save'].'</a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="cancelQuestionRecode(); return false;"><span>'.$lang['srv_cancel'].'</span></a></div></span>';
+ echo '<br class="clr"/>';
+ echo '</div>';
+ } else {
+ echo 'Napaka!';
+ }
+ }
+
+ function saveQuestionRecode() {
+ $spr_id = $_REQUEST['spr_id'];
+ if ((int)$spr_id > 0 && (int)$this->anketa > 0) {
+ if (isset($_REQUEST['edit_recode_nsmv']) && (int)$_REQUEST['edit_recode_nsmv'] == 1) {
+ #rekodiramo v novo spremenljivko
+ $vmv = new RecodeValues($this->anketa,$spr_id);
+ $vmv->SetRecodeNewVrednost();
+ } else {
+ # Shranimo zamenjave manjkajočih vrednosti pri posameznem vprašanu za analize
+ if (isset($_REQUEST['edit_recode_mv']) || isset($_REQUEST['edit_recode_number'])) {
+ $vmv = new RecodeValues($this->anketa,$spr_id);
+ if ((int)$_REQUEST['recode_type'] == 0) {
+ $vmv->SetUpMissingValuesForQuestion();
+ } else {
+ # rekodiramo number v novo vrednost
+ $vmv->SetRecodeNumberNewVrednost();
+ }
+ }
+ }
+ }
+ #shranimo sejo da ob naslednjem prikaru (reload) prikažemo gumb za ponovo zaganjanje rekodiranih vrednosti
+ session_start();
+ $_SESSION['showRunRecodeButton'][$this->anketa] = true;
+ session_commit();
+ }
+ function removeQuestionRecode() {
+ global $lang;
+
+ $spr_id = $_REQUEST['spr_id'];
+ $result = array();
+ $result['spr_id'] = 0;
+ if ((int)$spr_id > 0 && (int)$this->anketa > 0) {
+ # odstranimo rekodiranje za anketo
+ $vmv = new RecodeValues($this->anketa,$spr_id);
+ $result['spr_id'] = $vmv->removeRecodeForQuestion();
+ if ((int)$result['spr_id']) {
+ $qry_str = "SELECT variable, naslov FROM srv_spremenljivka s WHERE id = '".(int)$result['spr_id']."'";
+ $sql = sisplet_query($qry_str);
+ (list($variable, $naslov) = mysqli_fetch_row($sql));
+ $result['confirmtext'] = $lang['srv_recode_confirm_delete_sub'].''.$variable.' '.strip_tags($naslov).'?';
+ }
+
+ # vsilimo preračunavanje
+ $this->recalculateRecode();
+
+
+ }
+ echo json_encode($result);
+ }
+
+ function addNewNumeric() {
+ $spremenljivka = $_REQUEST['spremenljivka'];
+ if ((int)$spremenljivka > 0 && (int)$this->anketa > 0) {
+ $vmv = new RecodeValues($this->anketa,$spremenljivka);
+ $vmv->AddNewNumericRecode();
+ }
+ }
+ function changeRecodeType() {
+ $spremenljivka = $_REQUEST['spr_id'];
+
+ if ((int)$spremenljivka > 0 && (int)$this->anketa > 0) {
+ $vmv = new RecodeValues($this->anketa,$spremenljivka);
+ $vmv->changeRecodeType();
+ return;
+ }
+ if ((int)$spremenljivka == 0) {
+ echo 'Missing spr_id!';
+ }
+ }
+
+ function recodeSpremenljivkaNew() {
+ $spremenljivka = $_REQUEST['spr_id'];
+ if ((int)$spremenljivka > 0 && (int)$this->anketa > 0) {
+ if (trim($_POST['spremenljivka_naslov']) != '') {
+
+ Common::updateEditStamp();
+
+ ob_start();
+ $ba = new BranchingAjax($this->anketa);
+ $ba->ajax_spremenljivka_new($spremenljivka, 0, 0, 0, 1, 0);
+ $spr_id = $ba->spremenljivka;
+ ob_clean();
+ global $global_user_id;
+ $insertString = "INSERT INTO srv_recode_spremenljivka (ank_id,spr_id,recode_type,to_spr_id,usr_id,rec_date)".
+ " VALUES ('".$this->anketa."', '".$spremenljivka."', '".(int)$_POST['recode_type']."', '$spr_id','$global_user_id',NOW())".
+ " ON DUPLICATE KEY UPDATE recode_type='".(int)$_POST['recode_type']."',to_spr_id = '$spr_id', usr_id='$global_user_id',rec_date=NOW()";
+ $sqlInsert = sisplet_query($insertString);
+
+ # spremenimo ime, Q1_rec_1
+
+ $var = Cache::get_spremenljivka($spremenljivka, 'variable');
+ $i = 1;
+ do {
+ $variable = $var.'_rec_'.$i++;
+ $sql = sisplet_query("SELECT id FROM srv_spremenljivka WHERE variable='$variable'");
+ } while (mysqli_num_rows($sql) > 0);
+
+ $naslov = "naslov='".$_POST['spremenljivka_naslov']."',";
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET $naslov visible='1', variable_custom='1', variable='".$variable."', size='0' WHERE id = '$spr_id'");
+ if (!$s) echo "x1".mysqli_error($GLOBALS['connect_db']);
+
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id = '$spr_id'");
+ if (!$s) echo "x2".mysqli_error($GLOBALS['connect_db']);
+ } else {
+ echo '<span class="red">Vpišite ime spremenljivke!</span><br/>';
+ }
+ $vmv = new RecodeValues($this->anketa,$spremenljivka);
+ $vmv->displayRecodeType();
+ }
+
+ }
+ function recodeVrednostNew() {
+ $spremenljivka = $_REQUEST['recodeToSpr'];
+ if ((int)$spremenljivka > 0) {
+ if (trim($_POST['vrednost_new']) != '') {
+ Common::updateEditStamp();
+
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $spremenljivka;
+
+ $v->vrednost_new($_POST['vrednost_new']);
+ } else {
+ echo '<span class="red">Vpišite ime kategorije!</span><br/>';
+ }
+ }
+ $vmv = new RecodeValues($this->anketa,$_POST['spr_id']);
+ $vmv->displayRecodeType();
+ }
+ function getProfileString() {
+ global $lang;
+ #preštejemo koliko rekodiranj imamo za anketo
+ $strSelect = "SELECT count(*) FROM srv_recode WHERE ank_id = '".$this->anketa."'";
+ $sqlSelect = sisplet_query($strSelect);
+ list($count) = mysqli_fetch_row($sqlSelect);
+ if ((int)$count > 0) {
+ /*echo '<div id="recodingNote">';
+ echo '<span>'.$lang['srv_data_recoded_note'].'</span>';
+ echo '&nbsp;&nbsp;<a href="index.php?anketa=' . $this->anketa . '&a='.A_COLLECT_DATA.'&m='.M_COLLECT_DATA_RECODING.'">'.$lang['srv_profile_edit'].'</a>';
+ echo '</div>';*/
+ return true;
+ }
+ return false;
+ }
+
+ function removeSpremenljivka() {
+ $spr_id = (int)$_POST['spr_id'];
+ if ($spr_id > 0) {
+ $s = sisplet_query("DELETE FROM srv_spremenljivka WHERE id = '$spr_id'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ function DisplayDashboard() {
+ global $lang;
+
+
+ # zloopamo skozi vse spremenljivke
+ $qry_str = "SELECT s.id, s.tip, s.variable, s.naslov FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC";
+ $sql = sisplet_query($qry_str);
+ $all_recoded = array();
+
+ if (mysqli_num_rows($sql) > 0) {
+
+ while (list($spr_id, $tip, $variable, $naslov) = mysqli_fetch_row($sql)) {
+ # preverimo ali je rekodirana v novo spremenljivko
+ # preverimo ali imamo rekodiranje v novo spremenljivko, če ja, kasneje ponudimo tud izbris psremenljivke
+ $qry = sisplet_query("SELECT to_spr_id, usr_id, rec_date FROM srv_recode_spremenljivka WHERE ank_id = '".$this->anketa."' AND spr_id = '".$spr_id."'");
+ list($to_spr_id,$usr_id,$rec_date) = mysqli_fetch_row($qry);
+ if ((int)$to_spr_id > 0) {
+ $row_to_spr_id = Cache::srv_spremenljivka($to_spr_id);
+ $sel = "select count(*) from srv_recode_vrednost where ank_id = '".$this->anketa."' AND spr1 = '$spr_id' GROUP BY spr1";
+ $qry = sisplet_query($sel);
+ list($cnt1) = mysqli_fetch_row($qry);
+ if ((int)$cnt1 > 0) {
+ $all_recoded[] = array('txt'=>sprintf($lang['srv_recode_summary_new_spr'],$variable, $row_to_spr_id['variable'],strip_tags($row_to_spr_id['naslov']),(int)$cnt1),'usr_id'=>$usr_id,'rec_date'=>$rec_date);
+ }
+ # lahko da je numerična
+ $sel = "select count(*) from srv_recode_number where ank_id = '".$this->anketa."' AND spr_id = '$spr_id'";
+ $qry = sisplet_query($sel);
+ list($cnt1) = mysqli_fetch_row($qry);
+ if ((int)$cnt1 > 0) {
+ $all_recoded[] = array('txt'=>sprintf($lang['srv_recode_summary_new_spr'],$variable, $row_to_spr_id['variable'],strip_tags($row_to_spr_id['naslov']),(int)$cnt1),'usr_id'=>$usr_id,'rec_date'=>$rec_date);
+ }
+
+ } else {
+
+ $strSelect = "SELECT count(*) FROM srv_recode WHERE ank_id = '".$this->anketa."' AND spr_id = '$spr_id' GROUP BY spr_id";
+ $qry = sisplet_query($strSelect);
+ list($cnt2) = mysqli_fetch_row($qry);
+ if ((int)$cnt2 > 0) {
+ $all_recoded[] = array('txt'=>sprintf($lang['srv_recode_summary_same_spr'],$variable,(int)$cnt2),'usr_id'=>$usr_id,'rec_date'=>$rec_date);
+ }
+ }
+
+ }
+
+ }
+ if (count($all_recoded) == 0) {
+ echo $lang['srv_recode_summary_nothing'];
+ } else {
+ #var_dump($all_recoded);#
+ echo '<span id="div_recent_recoding_1" class="as_link" onclick="$(\'#div_recent_recoding, #div_recent_recoding_1, #div_recent_recoding_2\').toggle();">+ '.$lang['srv_recode_summary'].'</span>';
+ echo '<span id="div_recent_recoding_2" class="as_link displayNone" onclick="$(\'#div_recent_recoding, #div_recent_recoding_1, #div_recent_recoding_2\').toggle();">- '.$lang['srv_recode_summary'].'</span>';
+ echo '<div id="div_recent_recoding" class="displayNone">';
+ foreach ($all_recoded AS $msg) {
+ echo $msg['txt']."<br/>";
+ }
+ echo '</div>';
+ }
+
+ }
+
+ function enableRecodeVariable() {
+ global $lang;
+ # updejtamo polje enabled
+ $spr_id = (int)$_POST['spr_id'];
+
+ #polovimo enabled za rekodiranje v novo spremenljivko
+ $enabled = false;
+ $qry_str = "SELECT enabled FROM srv_recode_spremenljivka WHERE ank_id = '$this->anketa' AND spr_id='$spr_id'";
+ $sql = sisplet_query($qry_str);
+ while (list($_enabled) = mysqli_fetch_row($sql)) {
+ if ((int)$_enabled == 1) {
+ $enabled=true;
+ }
+ }
+ # polovimo enabled še za normalno rekodiranje
+ $qry_str = "SELECT enabled FROM srv_recode WHERE ank_id = '$this->anketa' AND spr_id='$spr_id'";
+ $sql = sisplet_query($qry_str);
+ while (list($_enabled) = mysqli_fetch_row($sql)) {
+ if ((int)$_enabled == 1) {
+ $enabled=true;
+ }
+ }
+ # če je bilo prej omogočeno sedaj obrnemo
+ $enabled_str = ($enabled) ? '0' : '1';
+
+ global $global_user_id;
+ #polovimo enabled za rekodiranje v novo spremenljivko
+ $qry_str1 = "UPDATE srv_recode_spremenljivka SET enabled='$enabled_str',usr_id='$global_user_id',rec_date=NOW() WHERE ank_id = '$this->anketa' AND spr_id='$spr_id'";
+ $s1 = sisplet_query($qry_str1);
+ if (!$s1) echo 'e1:'.mysqli_error($GLOBALS['connect_db']);
+ # polovimo enabled še za normalno rekodiranje
+ $qry_str2 = "UPDATE srv_recode SET enabled='$enabled_str' WHERE ank_id = '$this->anketa' AND spr_id='$spr_id'";
+ $s2 = sisplet_query($qry_str2);
+ if (!$s2) echo 'e2:'.mysqli_error($GLOBALS['connect_db']);
+
+ # popravimo timestamp
+ Common::updateEditStamp();
+ echo ($enabled == false) ? $lang['srv_recode_enabled'] : $lang['srv_recode_disabled'];
+ }
+
+ function visibleRecodeVariable() {
+ global $lang;
+ # updejtamo polje visible
+ $spr_id = (int)$_POST['spr_id'];
+ $row = Cache::srv_spremenljivka($spr_id);
+ $visible= ((int)$row['visible'] == 1) ? true : false;
+ #spremenimo vidnost spreenljivke
+ $visible_str = ($visible) ? '0' : '1';
+ $qry_str1 = "UPDATE srv_spremenljivka SET visible='$visible_str' WHERE id='$spr_id'";
+ $s1 = sisplet_query($qry_str1);
+ if (!$s1) echo 'e3:'.mysqli_error($GLOBALS['connect_db']);
+ # popravimo timestamp
+ Common::updateEditStamp();
+ echo ($visible == false) ? $lang['srv_recode_visible'] : $lang['srv_recode_invisible'];
+ }
+
+ function runRecodeVredonosti($showButton=true) {
+ global $lang;
+ $this->recalculateRecode();
+ if ($showButton == true) {
+ echo '<div class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_gray" href="index.php?anketa=' . $this->anketa . '&a='.A_ANALYSIS.'&m='.M_ANALYSIS_SUMMARY.'"><span>'.$lang['srv_analiza'].'</span></a></div>';
+ }
+ echo '<script>$("#btnRunRecode").hide();$("#fullscreen").fadeOut("slow").html("");$("#fade").fadeOut("slow");</script>';
+ }
+
+ function recalculateRecode() {
+
+ # pobrišemo vse obstoječe zamenjane vrednosti ankete
+ #$strDel = "DELETE FROM srv_data_vrednost".$this->db_table." WHERE spr_id IN (SELECT to_spr_id from srv_recode_spremenljivka where ank_id = '".$this->anketa."')";
+ #posodobljen query.. zdaj bi moglo letel :)
+ $strDel = "DELETE sdv.* FROM srv_data_vrednost".$this->db_table." AS sdv INNER JOIN srv_recode_spremenljivka AS srs ON sdv.spr_id = srs.to_spr_id WHERE srs.ank_id = '".$this->anketa."'";
+ $qD = sisplet_query($strDel);
+ if (!$qD) echo mysqli_error($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+
+ # najprej za katagorialne
+ #updejtamo samo tiste katere so omogočene
+ $sel = "select spr1,vre1,spr2,vre2 from srv_recode_vrednost WHERE ank_id = '".$this->anketa."' AND spr2 IN( SELECT to_spr_id from srv_recode_spremenljivka where ank_id = '".$this->anketa."' AND enabled='1' AND recode_type IN ('0','1'))";
+ $qry = sisplet_query($sel);
+ while (list($spr1, $vre1, $spr2, $vre2) = mysqli_fetch_row($qry)) {
+ # podvojimo polja za novo variablo za vse userje in loope z novimi vrednostmi
+ $insert = "INSERT INTO srv_data_vrednost".$this->db_table." (spr_id,vre_id,usr_id,loop_id)"
+ ." (SELECT \"$spr2\",\"$vre2\",usr_id,loop_id FROM srv_data_vrednost".$this->db_table." WHERE spr_id='$spr1' AND vre_id='$vre1')"
+ ." ON DUPLICATE KEY UPDATE vre_id=\"$vre2\"";
+ $qryI = sisplet_query($insert);
+ sisplet_query("COMMIT");
+ }
+
+
+ # potem še za numerične
+ $_operators = array( # operatorji
+ '0'=>'==', # ==
+ '1'=>'<>', # <>
+ '2'=>'<', # <
+ '3'=>'>', # >
+ '4'=>'<=', # <=
+ '5'=>'>=', # >=
+ '6'=>'interval' # interval
+ );
+
+ #updejtamo samo tiste katere so omogočene
+ $sprMapping = array();
+ $selS ="SELECT spr_id, to_spr_id from srv_recode_spremenljivka where ank_id = '".$this->anketa."' AND enabled='1' AND recode_type='1'";
+
+ $qryS = sisplet_query($selS);
+ while ($rowS = mysqli_fetch_assoc($qryS)) {
+ $sprMapping[$rowS['spr_id']] = $rowS['to_spr_id'];
+ }
+ $sel = "select * from srv_recode_number WHERE ank_id = '".$this->anketa."' AND spr_id IN( SELECT spr_id from srv_recode_spremenljivka where ank_id = '".$this->anketa."' AND enabled='1' AND recode_type='1') ORDER BY spr_id, vrstni_red";
+ $qry = sisplet_query($sel);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ if($row['operator'] != '6') {
+ $selU = "SELECT ".$sprMapping[$row['spr_id']].", ".$row['vred_id'].", usr_id, loop_id FROM srv_data_text".$this->db_table." WHERE spr_id='$row[spr_id]' AND vre_id='0' AND text ".$_operators[$row['operator']]." $row[search]";
+ } else {
+ $_search = explode(',',$row['search']);
+ $selU = "SELECT ".$sprMapping[$row['spr_id']].", ".$row['vred_id'].", usr_id, loop_id FROM srv_data_text".$this->db_table." WHERE spr_id='$row[spr_id]' AND vre_id='0' AND text BETWEEN ".(int)$_search[0]." AND ".(int)$_search[1];
+ }
+
+ $insert = "INSERT INTO srv_data_vrednost".$this->db_table." (spr_id,vre_id,usr_id,loop_id) ($selU) ON DUPLICATE KEY UPDATE vre_id='".$row['vred_id']."'";
+ $qryI = sisplet_query($insert);
+ sisplet_query("COMMIT");
+ }
+ unset($_SESSION['showRunRecodeButton'][$this->anketa]);
+ session_commit();
+ Common::updateEditStamp();
+ }
+
+
+}
+?>
diff --git a/admin/survey/classes/class.SurveyReminderTracking.php b/admin/survey/classes/class.SurveyReminderTracking.php
new file mode 100644
index 0000000..e41871b
--- /dev/null
+++ b/admin/survey/classes/class.SurveyReminderTracking.php
@@ -0,0 +1,1380 @@
+<?php
+
+class SurveyReminderTracking{
+
+ private $anketa; # id ankete
+ private $db_table; # katere tabele uporabljamo
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo (zakeširamo)
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ public $_PROFILE_ID_VARIABLE = ''; # filter po statusih, privzeto izvažamo 6 in 5
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ private $_missings = array();
+ private $_unsets = array();
+
+ private $displayEditIconsSettings = false; # ali prikazujemo okno s checkboxi za nastavitve tabele s podatki
+
+ private $cols_with_value = array(); # kateri stolpci imajo vrednosti
+ private $show_with_zero = false; # Ali prikazujemo stolpce z vrednostmi 0
+ private $show_details = false; # Ali prikazujemo stolpce s podrobnimi vrednostmi (-1, -2...)
+ private $show_calculations = false; # Ali prikazujemo stolpce s podrobnimi izracuni (UML, UNL...)
+ private $show_with_other = true; # Ali prikazujemo vrstice "Drugo"
+ private $show_with_text = true; # Ali prikazujemo vrstice tipa "besedilo"
+
+ public $bottom_usable_limit = 50; # Spodnja meja za usable respondente (def. 50%)
+ public $top_usable_limit = 80; # Zgornja meja za usable respondente (def. 80%) - unusable (50-), partially usable (50-80), usable(80+)
+
+ //private $sortField = 'recnum'; # Polje po katerem sortiramo tabelo
+ private $sortField = ''; # Polje po katerem sortiramo tabelo
+ private $sortType = 0; # Nacin sortiranja (narascajoce/padajoce)
+
+
+ function __construct($anketa, $generateDataFile=true){
+ global $lang;
+
+ if ((int)$anketa > 0){
+
+ $this->anketa = $anketa;
+
+ SurveyAnalysisHelper::getInstance()->Init($this->anketa);
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ Common::deletePreviewData($this->anketa);
+
+
+ // Poskrbimo za datoteko s podatki
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->anketa);
+
+ if($generateDataFile)
+ $SDF->prepareFiles();
+
+ $this->headFileName = $SDF->getHeaderFileName();
+ $this->dataFileName = $SDF->getDataFileName();
+ $this->dataFileStatus = $SDF->getStatus();
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_SRV_DELETED) {
+ Common::noDataAlert();
+ exit();
+ }
+
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->anketa);
+ SurveyUserSetting::getInstance()->Init($this->anketa, $global_user_id);
+ SurveyConditionProfiles :: Init($this->anketa, $global_user_id);
+ SurveyTimeProfiles :: Init($this->anketa, $global_user_id);
+ SurveyVariablesProfiles :: Init($this->anketa, $global_user_id);
+ SurveyDataSettingProfiles :: Init($this->anketa);
+
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->anketa);
+ $this->sessionData = SurveyUserSession::getData();
+
+ if(isset($_SESSION['sid_'.$this->anketa]['usabilityIcons_settings']))
+ $this->displayEditIconsSettings = ($_SESSION['sid_'.$this->anketa]['usabilityIcons_settings']);
+
+ if ($this->headFileName !== null && $this->headFileName != ''){
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ # nastavimo filtre uporabnika
+ $this->setUserFilters();
+
+ # nastavimo sortiranje
+ if(isset($_GET['sortField']))
+ $this->sortField = $_GET['sortField'];
+ if(isset($_GET['sortType']))
+ $this->sortType = $_GET['sortType'];
+ }
+ else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+ public function getMissings(){
+ return $this->_missings;
+ }
+
+ public function getUnsets(){
+ return $this->_unsets;
+ }
+
+ public function getColsWithValue(){
+ return $this->cols_with_value;
+ }
+
+ public function showCalculations(){
+ return $this->show_calculations;
+ }
+
+ public function showDetails(){
+ return $this->show_details;
+ }
+
+ public function showWithZero(){
+ return $this->show_with_zero;
+ }
+
+
+
+ function displayTable(){
+ global $lang;
+
+ # ali imamo testne podatke
+ if ($this->_HAS_TEST_DATA){
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml($this->anketa);
+ $SSH -> displayTestDataBar(true);
+ }
+
+ // Izracunamo vse podatke
+ $usability = $this->calculateData(); //podatki po respondentih
+ $userData = $usability['data'];
+
+ $vars = $this->calculateDataVars($userData[1]['usr_id']); //podatki po spremenljivkah
+
+
+ if($_GET['m'] == A_REMINDER_TRACKING_RECNUM){ //ce je prikaz po respondentih
+ $this->sortField = 'recnum';
+ }
+ else if($_GET['m'] == A_REMINDER_TRACKING_VAR){ //ce je prikaz po spremenljivkah
+ $this->sortField = 'vars';
+ }
+
+ // Sortiramo podatke
+ foreach ($userData as $key => $row) {
+ $mid[$key] = $row[$this->sortField];
+ }
+ if($this->sortType == 0)
+ array_multisort($mid, SORT_ASC, $userData);
+ else
+ array_multisort($mid, SORT_DESC, $userData);
+
+
+ # ali odstranimo stolpce kateri imajo same 0
+ if ($this->show_with_zero == false) {
+ # odstranimo missinge brez vrednosti
+ foreach ($this->_missings AS $_key => $_missing) {
+ if (!isset($this->cols_with_value[$_key]) || $this->cols_with_value[$_key] == false) {
+ unset($this->_missings[$_key]);
+ }
+ }
+ # odstranimo neveljavne brez vrednosti
+ foreach ($this->_unsets AS $_key => $_unset) {
+ if (!isset($this->cols_with_value[$_key]) || $this->cols_with_value[$_key] == false) {
+ unset($this->_unsets[$_key]);
+ }
+ }
+ }
+
+
+ if($_GET['m'] == A_REMINDER_TRACKING_RECNUM){ //ce je prikaz po respondentih
+ echo '<h2>'.$lang['srv_reminder_tracking_title_recnum'].'</h2>';
+ $naslovStolpecMoznaOpozorila = $lang['srv_reminder_tracking_possible_errors_resp'];
+ }
+ else if($_GET['m'] == A_REMINDER_TRACKING_VAR){ //ce je prikaz po spremenljivkah
+ echo '<h2>'.$lang['srv_reminder_tracking_title_vars'].'</h2>';
+ $naslovStolpecMoznaOpozorila = $lang['srv_reminder_tracking_possible_errors_var'];
+ }
+
+ echo '<div id="table_reminder_tracking"><table class="reminder_tracking_table" '.($this->show_details==true && $this->show_calculations==true ? '' : ' style="width:100%"').'>';
+
+ // Header row
+ echo '<tr>';
+
+ if($this->sortType == 1){
+ $sortType = 0;
+ $arrow = ' <span class="faicon sort_ascending"></span>';
+ }
+ else{
+ $sortType = 1;
+ $arrow = ' <span class="faicon sort_descending"></span>';
+ }
+
+ if($_GET['m'] == A_REMINDER_TRACKING_RECNUM){ //ce je prikaz po respondentih
+ echo '<th class="recnum" rowspan="2" style="width:60px;"><a href="index.php?anketa='.$this->anketa.'&a=reminder_tracking&m='.A_REMINDER_TRACKING_RECNUM.'&sortField=recnum&sortType='.$sortType.'">Recnum'./*$lang['recnum'].*/($this->sortField=='recnum' ? $arrow : '').'</a></th>';
+ //$qualityRowSpan = count($userData) + 2;
+ $qualityRowSpan = count($userData) + 3;
+ $numOf = count($userData);
+ }
+ else if($_GET['m'] == A_REMINDER_TRACKING_VAR){ //ce je prikaz po spremenljivkah
+ //echo '<th class="vars" rowspan="2" style="width:100px;"><a href="index.php?anketa='.$this->anketa.'&a=reminder_tracking&m='.A_REMINDER_TRACKING_VAR.'&sortField=vars&sortType='.$sortType.'">Spremenljivka'./*$lang['recnum'].*/($this->sortField=='vars' ? $arrow : '').'</a></th>';
+ echo '<th class="vars" rowspan="2" style="width:100px;">Vprašanje</th>';
+ //$qualityRowSpan = count($vars) + 2;
+ $qualityRowSpan = count($vars) + 3;
+ $numOf = count($vars);
+ }
+
+ //echo '<th class="usable" colspan="2">Opozorila obveznih vprašanj</th>';
+ //Obvezna vprasanja
+ echo '<th class="usable" colspan="2">'.$lang['srv_reminder_tracking_question'].'</th>';
+
+ //echo '<th class="data" colspan=2>Num opozorila</th>';
+ //Vnos stevil
+ echo '<th class="data" colspan=2>'.$lang['srv_reminder_tracking_num'].'</th>';
+
+ //echo '<th class="data" colspan=2>Sum opozorila</th>';
+ //Vsota stevil
+ echo '<th class="data" colspan=2>'.$lang['srv_reminder_tracking_sum'].'</th>';
+
+ //echo '<th class="usable" colspan="2">Validacije</th>';
+ //Validacije
+ echo '<th class="usable" colspan="2">'.$lang['srv_reminder_tracking_validation'].'</th>';
+
+ echo '<th class="sprozenaOpozorila" rowspan="2">'.$naslovStolpecMoznaOpozorila.'</th>'; //naslov stolpca "Število možnih opozoril"
+
+ echo '<th class="sprozenaOpozorila" rowspan="2">'.$lang['srv_reminder_tracking_sum_of_errors'].'</th>'; //naslov stolpca "Vsota sprozenih opozoril"
+
+ echo '<th class="sprozenaOpozorilaLine" rowspan="2">'.$lang['srv_reminder_tracking_activated_errors'].'</th>'; //naslov stolpca "Stevilo sprozenih opozoril"
+
+ //$qualityRowSpan = count($userData) + 2;
+
+ echo '<th class="sprozenaOpozorilaLine" rowspan="'.$qualityRowSpan.'">'.$lang['srv_reminder_tracking_quality'].' '.Help::display('srv_reminder_tracking_quality').'</th>';
+
+ echo '</tr>'; // Header row - konec
+
+
+ //Second title row
+ echo '<tr>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_hard'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_soft'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_hard'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_soft'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_hard'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_soft'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_hard'].'</th>';
+ echo '<th class="data">'.$lang['srv_reminder_tracking_soft'].'</th>';
+ echo '</tr>'; //Second title row - konec
+
+
+ if($_GET['m'] == A_REMINDER_TRACKING_RECNUM)
+ { //ce je prikaz po respondentih
+ $sprozenaOpozorilaAll = 0;
+
+ $sumObveznihVprasanjHard = 0;
+ $sumObveznihVprasanjSoft = 0;
+ $sumNumAlertHard = 0;
+ $sumNumAlertSoft = 0;
+ $sumSumAlertHard = 0;
+ $sumSumAlertSoft = 0;
+ $sumValidationHard = 0;
+ $sumValidationSoft = 0;
+
+ // Izpis podatkov vsakega respondenta
+ foreach($userData as $key => $user){
+
+ // Prva vrstica z vrednostmi
+ echo '<tr>';
+
+ echo '<td rowspan="1" class="recnum"><a href="index.php?anketa='.$this->anketa.'&a=data&m=quick_edit&usr_id='.$user['usr_id'].'&quick_view=1">'.$user['recnum'].'</a></td>';
+
+ $sprozenaOpozorila = 0;
+ $steviloVsehMoznihOpozoril= 0;
+
+ // Alerti obveznih vprasanj Hard
+ $this->izrisPodatka($user['rowHardAlert']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowHardAlert'];
+ if($user['rowHardAlert'] != 0){$sprozenaOpozorila++;}
+
+ // Alerti obveznih vprasanj Soft
+ $this->izrisPodatka($user['rowSoftAlert']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowSoftAlert'];
+ if($user['rowSoftAlert'] != 0){$sprozenaOpozorila++;}
+
+ // Num Alerti Hard
+ $this->izrisPodatka($user['rowNumHard']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowNumHard'];
+ if($user['rowNumHard'] != 0){$sprozenaOpozorila++;}
+
+ // Num Alerti Soft
+ $this->izrisPodatka($user['rowNumSoft']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowNumSoft'];
+ if($user['rowNumSoft'] != 0){$sprozenaOpozorila++;}
+
+ // Sum Alerti Hard
+ $this->izrisPodatka($user['rowSumHard']);
+ //$sprozenaOpozorila = $user['rowSumHard'];
+ if($user['rowSumHard'] != 0){$sprozenaOpozorila++;}
+
+ // Sum Alerti Soft
+ $this->izrisPodatka($user['rowSumSoft']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowSumSoft'];
+ if($user['rowSumSoft'] != 0){$sprozenaOpozorila++;}
+
+ // Alerti Hard Validation
+ $this->izrisPodatka($user['rowHardValidation']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowHardValidation'];
+ if($user['rowHardValidation'] != 0){$sprozenaOpozorila++;}
+
+ // Alerti Soft Validation
+ $this->izrisPodatka($user['rowSoftValidation']);
+ //$sprozenaOpozorila = $sprozenaOpozorila + $user['rowSoftValidation'];
+ if($user['rowSoftValidation'] != 0){$sprozenaOpozorila++;}
+
+
+ //Izracun vsote sprozenih opozoril - po stolpcih
+ //Alerti obveznih vprasanj
+ $sumObveznihVprasanjHard = $sumObveznihVprasanjHard + $user['rowHardAlert'];
+ $sumObveznihVprasanjSoft = $sumObveznihVprasanjSoft + $user['rowSoftAlert'];
+ //Num Alerti
+ $sumNumAlertHard = $sumNumAlertHard + $user['rowNumHard'];
+ $sumNumAlertSoft = $sumNumAlertSoft + $user['rowNumSoft'];
+ //Sum Alerti
+ $sumSumAlertHard = $sumSumAlertHard + $user['rowSumHard'];
+ $sumSumAlertSoft = $sumSumAlertSoft + $user['rowSumSoft'];
+ //Alerti validation
+ $sumValidationHard = $sumValidationHard + $user['rowHardValidation'];
+ $sumValidationSoft = $sumValidationSoft + $user['rowSoftValidation'];
+ //Izracun vsote sprozenih opozoril - po stolpcih - konec
+
+ //Izracun stevila vseh moznih opozoril, ki ga potrebujemo za izracun kakovosti
+ $steviloVsehMoznihOpozorilSumHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilSumHard');
+ $steviloVsehMoznihOpozorilSumSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilSumSoft');
+ $steviloVsehMoznihOpozorilNumHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilNumHard');
+ $steviloVsehMoznihOpozorilNumSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilNumSoft');
+ $steviloVsehMoznihOpozorilHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilHard');
+ $steviloVsehMoznihOpozorilSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilSoft');
+ $steviloVsehMoznihOpozorilValHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilValHard');
+ $steviloVsehMoznihOpozorilValSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilValSoft');
+
+ //$steviloVsehMoznihOpozoril = $steviloVsehMoznihOpozorilSumHard + $steviloVsehMoznihOpozorilSumSoft + $steviloVsehMoznihOpozorilNumHard + $steviloVsehMoznihOpozorilNumSoft + $steviloVsehMoznihOpozorilHard + $steviloVsehMoznihOpozorilSoft + $steviloVsehMoznihOpozorilValHard + $steviloVsehMoznihOpozorilValSoft;
+
+ if($steviloVsehMoznihOpozorilSumHard != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilSumSoft != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilNumHard != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilNumSoft != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilHard != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilSoft != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilValHard != 0){$steviloVsehMoznihOpozoril++;}
+ if($steviloVsehMoznihOpozorilValSoft != 0){$steviloVsehMoznihOpozoril++;}
+
+ //Izracun stevila vseh moznih opozoril, ki ga potrebujemo za izracun kakovosti - konec
+
+
+ //Stevilo moznih opozoril
+ $steviloMoznihOpozorilPoResp = $steviloVsehMoznihOpozorilSumHard + $steviloVsehMoznihOpozorilSumSoft + $steviloVsehMoznihOpozorilNumHard + $steviloVsehMoznihOpozorilNumSoft + $steviloVsehMoznihOpozorilHard + $steviloVsehMoznihOpozorilSoft + $steviloVsehMoznihOpozorilValHard + $steviloVsehMoznihOpozorilValSoft;
+
+ $this->izrisPodatka($steviloMoznihOpozorilPoResp, 1);
+
+ //Stevilo moznih opozoril - konec
+
+
+ //Izracun vsote sprozenih opozoril - po vrsticah
+ $vsotaSprozenihOpozoril = $user['rowHardAlert'] +
+ $user['rowSoftAlert'] +
+ $user['rowNumHard'] +
+ $user['rowNumSoft'] +
+ $user['rowSumHard'] +
+ $user['rowSumSoft'] +
+ $user['rowHardValidation'] +
+ $user['rowSoftValidation']
+ ;
+ //Izracun vsote sprozenih opozoril - po vrsticah - konec
+
+ echo '<td class="usable bold">'.$vsotaSprozenihOpozoril; //Vsota sprozenih opozoril
+
+
+ echo '<td class="sprozenaOpozorilaLine">'.$sprozenaOpozorila; //Stevilo sprozenih opozoril
+
+/* //Izracun in prikazovanje kakovosti
+ $kakovost = $this->izracunKakovosti(count($userData), $sprozenaOpozorila, $steviloVsehMoznihOpozoril);
+ $kakovost = SurveyAnalysis::formatNumber($kakovost, 3,'');
+ echo '<td class="sprozenaOpozorila">'.$kakovost;
+ //Izracun in prikazovanje kakovosti - konec
+
+ echo '</td>';*/
+
+ echo '</tr>';
+ $sprozenaOpozorilaAll = $sprozenaOpozorilaAll + $sprozenaOpozorila;
+ }
+ }
+ else if($_GET['m'] == A_REMINDER_TRACKING_VAR)
+ { //ce je prikaz po spremenljivkah
+ $sprozenaOpozorilaAll = 0;
+ $sumObveznihVprasanjHard = 0;
+ $sumObveznihVprasanjSoft = 0;
+ $sumNumAlertHard = 0;
+ $sumNumAlertSoft = 0;
+ $sumSumAlertHard = 0;
+ $sumSumAlertSoft = 0;
+ $sumValidationHard = 0;
+ $sumValidationSoft = 0;
+
+ $varsData = array();
+
+ // Izpis podatkov za vsako spremenljivko
+ foreach($vars as $key => $var){
+ // Prva vrstica z vrednostmi
+ echo '<tr>';
+
+ //echo '<td rowspan="1" class="vars"><a href="index.php?anketa='.$this->anketa.'&a=data&m=quick_edit&spr_id='.$var['spr_id'].'&quick_view=1">'.$var['spr_id'].'</a></td>';
+ echo '<td rowspan="1" class="vars">'.$var['variable'].'</td>';
+ //echo '<td rowspan="1" class="vars">'.$var['variable'].' '.count($vars).'</td>';
+
+ $sprozenaOpozorila = 0;
+ $steviloVsehMoznihOpozoril= 0;
+
+ //Alerti obveznih vprasanj Hard
+ $this->izrisPodatka($var['rowHardAlert']);
+ if($var['rowHardAlert'] != 0){$sprozenaOpozorila++;}
+
+ // Alerti obveznih vprasanj Soft
+ $this->izrisPodatka($var['rowSoftAlert']);
+ if($var['rowSoftAlert'] != 0){$sprozenaOpozorila++;}
+
+ // Num Alerti Hard
+ $this->izrisPodatka($var['rowNumHard']);
+ if($var['rowNumHard'] != 0){$sprozenaOpozorila++;}
+
+ // Num Alerti Soft
+ $this->izrisPodatka($var['rowNumSoft']);
+ if($var['rowNumSoft'] != 0){$sprozenaOpozorila++;}
+
+ // Sum Alerti Hard
+ $this->izrisPodatka($var['rowSumHard']);
+ if($var['rowSumHard'] != 0){$sprozenaOpozorila++;}
+
+ // Sum Alerti Soft
+ $this->izrisPodatka($var['rowSumSoft']);
+ if($var['rowSumSoft'] != 0){$sprozenaOpozorila++;}
+
+ // Alerti Hard Validation
+ $this->izrisPodatka($var['rowHardValidation']);
+ if($var['rowHardValidation'] != 0){$sprozenaOpozorila++;}
+
+ // Alerti Soft Validation
+ $this->izrisPodatka($var['rowSoftValidation']);
+ if($var['rowSoftValidation'] != 0){$sprozenaOpozorila++;}
+
+ //echo '<td class="sprozenaOpozorila">'.$sprozenaOpozorila;
+
+ //echo '</tr>';
+
+ //Izracun vsote sprozenih opozoril - po stolpcih
+ //Alerti obveznih vprasanj
+ $sumObveznihVprasanjHard = $sumObveznihVprasanjHard + $var['rowHardAlert'];
+ $sumObveznihVprasanjSoft = $sumObveznihVprasanjSoft + $var['rowSoftAlert'];
+ //Num Alerti
+ $sumNumAlertHard = $sumNumAlertHard + $var['rowNumHard'];
+ $sumNumAlertSoft = $sumNumAlertSoft + $var['rowNumSoft'];
+ //Sum Alerti
+ $sumSumAlertHard = $sumSumAlertHard + $var['rowSumHard'];
+ $sumSumAlertSoft = $sumSumAlertSoft + $var['rowSumSoft'];
+ //Alerti validation
+ $sumValidationHard = $sumValidationHard + $var['rowHardValidation'];
+ $sumValidationSoft = $sumValidationSoft + $var['rowSoftValidation'];
+ //Izracun vsote sprozenih opozoril - po stolpcih - konec
+
+ //Izracun stevila vseh moznih opozoril, ki ga potrebujemo za izracun kakovosti
+ $steviloVsehMoznihOpozorilSumHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilSumHard');
+ $steviloVsehMoznihOpozorilSumSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilSumSoft');
+ $steviloVsehMoznihOpozorilNumHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilNumHard');
+ $steviloVsehMoznihOpozorilNumSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilNumSoft');
+ $steviloVsehMoznihOpozorilHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilHard');
+ $steviloVsehMoznihOpozorilSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilSoft');
+ $steviloVsehMoznihOpozorilValHard = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilValHard');
+ $steviloVsehMoznihOpozorilValSoft = $this->steviloMoznihOpozoril($vars, 'steviloVsehMoznihOpozorilValSoft');
+
+ if($steviloVsehMoznihOpozorilSumHard != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilSumSoft != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilNumHard != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilNumSoft != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilHard != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilSoft != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilValHard != 0){$steviloVsehMoznihOpozoril++; }
+ if($steviloVsehMoznihOpozorilValSoft != 0){$steviloVsehMoznihOpozoril++; }
+
+ //Izracun stevila vseh moznih opozoril, ki ga potrebujemo za izracun kakovosti - konec
+
+
+ //Izracun stevila moznih opozoril po var
+ //echo '<script>console.log("za spremenljivko je: '.$var['steviloVsehMoznihOpozorilSoft'].' ")</script>';
+ $steviloMoznihOpozorilPoVar =
+ $var['steviloVsehMoznihOpozorilSumHard'] +
+ $var['steviloVsehMoznihOpozorilSumSoft'] +
+ $var['steviloVsehMoznihOpozorilNumHard'] +
+ $var['steviloVsehMoznihOpozorilNumSoft'] +
+ $var['steviloVsehMoznihOpozorilHard'] +
+ $var['steviloVsehMoznihOpozorilSoft'] +
+ $var['steviloVsehMoznihOpozorilValHard'] +
+ $var['steviloVsehMoznihOpozorilValSoft'];
+
+ $this->izrisPodatka($steviloMoznihOpozorilPoVar, 1);
+ //Izracun stevila moznih opozoril po var - konec
+
+
+ //Izracun vsote sprozenih opozoril - po vrsticah
+ $vsotaSprozenihOpozoril = $var['rowHardAlert'] +
+ $var['rowSoftAlert'] +
+ $var['rowNumHard'] +
+ $var['rowNumSoft'] +
+ $var['rowSumHard'] +
+ $var['rowSumSoft'] +
+ $var['rowHardValidation'] +
+ $var['rowSoftValidation']
+ ;
+ //Izracun vsote sprozenih opozoril - po vrsticah - konec
+
+ echo '<td class="usable bold">'.$vsotaSprozenihOpozoril; //Vsota sprozenih opozoril
+
+ echo '<td class="sprozenaOpozorilaLine">'.$sprozenaOpozorila; //Stevilo sprozenih opozoril
+
+ echo '</tr>';
+
+ $sprozenaOpozorilaAll = $sprozenaOpozorilaAll + $sprozenaOpozorila;
+ }
+ }
+
+
+ //predzadnja vrstica preglednice, ki prikazuje sprozenih opozoril po stolpcih
+ echo '<tr class="sum">';
+ //echo '<td> Možnih opozoril za celotno anketo</td>';
+ //stevilo moznih opozoril po stolpih
+ echo '<td>'.$lang['srv_reminder_tracking_sum_of_errors'].'</td>';
+ //echo '<td> '.$this->anketa.'</td>';
+
+ //1. stolpec - Vsota obveznih vprasanj Hard
+ echo '<td> '.$sumObveznihVprasanjHard.'</td>';
+ //1. stolpec - Vsota obveznih vprasanj Hard - konec
+
+ //2. stolpec - Vsota obveznih vprasanj Soft
+ echo '<td> '.$sumObveznihVprasanjSoft.'</td>';
+ //2. stolpec - Vsota obveznih vprasanj Soft - konec
+
+ //3. stolpec - Vsota Num opozorila Hard
+ echo '<td> '.$sumNumAlertHard.'</td>';
+ //3. stolpec - Vsota Num opozorila Hard - konec
+
+ //4. stolpec - Vsota Num opozorila Soft
+ echo '<td> '.$sumNumAlertSoft.'</td>';
+ //4. stolpec - Vsota Num opozorila Soft - konec
+
+ //5. stolpec - Vsota Sum opozorila Hard
+ echo '<td> '.$sumSumAlertHard.'</td>';
+ //5. stolpec - Vsota Sum opozorila Hard - konec
+
+ //6. stolpec - Vsota Sum opozorila Soft
+ echo '<td> '.$sumSumAlertSoft.'</td>';
+ //6. stolpec - Vsota Sum opozorila Soft - konec
+
+ //7. stolpec - Vsota Validacije Hard
+ echo '<td> '.$sumValidationHard.'</td>';
+ //7. stolpec - Vsota Validacije Hard - konec
+
+ //8. stolpec - Vsota Validacije Soft
+ echo '<td> '.$sumValidationSoft.'</td>';
+ //8. stolpec - Vsota Validacije Soft - konec
+
+/* //9. stolpec - Vsota vseh moznih opozoril
+ echo '<td> '.$steviloVsehMoznihOpozoril.'</td>';
+ //9. stolpec - Vsota vseh moznih opozoril - konec */
+
+ //9. stolpec - Stevilo moznih opozoril po vrsticah
+ //echo '<td> '.$steviloMoznihOpozorilPoVrsticah.'</td>';
+ echo '<td> </td>';
+ //9. stolpec - Stevilo moznih opozoril po vrsticah - konec */
+
+ //10. stolpec - Stevilo moznih opozoril po vrsticah
+ //echo '<td> '.$steviloMoznihOpozorilPoVrsticah.'</td>';
+ echo '<td> </td>';
+ //10. stolpec - Stevilo moznih opozoril po vrsticah - konec */
+
+ //11. stolpec - Prikaz stevila vseh sprozenih opozoril in vseh moznih opozoril
+ echo '<td class="sprozenaOpozorilaLine"> </td>';
+ //11. stolpec - Prikaz stevila vseh sprozenih opozoril in vseh moznih opozoril - konec
+
+ echo '</tr>';
+ //predzadnja vrstica preglednice, ki prikazuje sprozenih opozoril po stolpcih - konec
+
+ //zadnja vrstica preglednice, ki prikazuje stevilo vseh moznih opozoril
+ echo '<tr class="sumSprozenih">';
+ //echo '<td> Možnih opozoril za celotno anketo</td>';
+ //stevilo moznih opozoril po stolpih
+ echo '<td>'.$lang['srv_reminder_tracking_possible_errors'].'</td>';
+ //echo '<td> '.$this->anketa.'</td>';
+
+ //1. stolpec - Opozorila obveznih vprasanj Hard
+ echo '<td> '.$steviloVsehMoznihOpozorilHard.'</td>';
+ //1. stolpec - Opozorila obveznih vprasanj Hard - konec
+
+ //2. stolpec - Opozorila obveznih vprasanj Soft
+ echo '<td> '.$steviloVsehMoznihOpozorilSoft.'</td>';
+ //2. stolpec - Opozorila obveznih vprasanj Soft - konec
+
+ //3. stolpec - Num opozorila Hard
+ echo '<td> '.$steviloVsehMoznihOpozorilNumHard.'</td>';
+ //3. stolpec - Num opozorila Hard - konec
+
+ //4. stolpec - Num opozorila Soft
+ echo '<td> '.$steviloVsehMoznihOpozorilNumSoft.'</td>';
+ //4. stolpec - Num opozorila Soft - konec
+
+ //5. stolpec - Sum opozorila Hard
+ echo '<td> '.$steviloVsehMoznihOpozorilSumHard.'</td>';
+ //5. stolpec - Sum opozorila Hard - konec
+
+ //6. stolpec - Sum opozorila Soft
+ echo '<td> '.$steviloVsehMoznihOpozorilSumSoft.'</td>';
+ //6. stolpec - Sum opozorila Soft - konec
+
+ //7. stolpec - Validacije Hard
+ echo '<td> '.$steviloVsehMoznihOpozorilValHard.'</td>';
+ //7. stolpec - Validacije Hard - konec
+
+ //8. stolpec - Validacije Soft
+ echo '<td> '.$steviloVsehMoznihOpozorilValSoft.'</td>';
+ //8. stolpec - Validacije Soft - konec
+
+/* //9. stolpec - Vsota vseh moznih opozoril
+ echo '<td> '.$steviloVsehMoznihOpozoril.'</td>';
+ //9. stolpec - Vsota vseh moznih opozoril - konec */
+
+ //9. stolpec - Stevilo moznih opozoril po vrsticah
+ //echo '<td> '.$steviloMoznihOpozorilPoVrsticah.'</td>';
+ echo '<td> </td>';
+ //9. stolpec - Stevilo moznih opozoril po vrsticah - konec */
+
+ //10. stolpec - Vsota sprozenih
+ echo '<td> </td>';
+ //10. stolpec - Vsota sprozenih - konec
+
+ //11. stolpec - Prikaz stevila vseh sprozenih opozoril in vseh moznih opozoril
+ echo '<td > '.$sprozenaOpozorilaAll.'/'.$steviloVsehMoznihOpozoril.'</td>';
+ //11. stolpec - Prikaz stevila vseh sprozenih opozoril in vseh moznih opozoril - konec
+
+ //Izracun in prikazovanje kakovosti
+ //$kakovost = $this->izracunKakovosti(count($userData), $sprozenaOpozorilaAll, $steviloVsehMoznihOpozoril);
+ $kakovost = $this->izracunKakovosti($numOf, $sprozenaOpozorilaAll, $steviloVsehMoznihOpozoril);
+ $kakovost = SurveyAnalysis::formatNumber($kakovost, 3,'');
+ echo '<td class="sprozenaOpozorilaLine">'.$kakovost;
+ echo '</td>';
+ //Izracun in prikazovanje kakovosti - konec
+
+ echo '</tr>';
+ //zadnja vrstica preglednice, ki prikazuje stevilo vseh moznih opozoril - konec
+ echo '</table>';
+
+
+ echo '</div>';
+ }
+
+ //metoda, ki skrbi za izbiro sloga podatka v preglednici
+ private function izrisPodatka($podatek, $stolpec1=0){
+ if ($podatek != 0){ //ce je podatek razlicen od 0
+ if($stolpec1){
+ $redBg = '';
+ }else{
+ $redBg = ' redCell';
+ }
+ //$slog = 'data sum bold'; //naj bo slog bold
+ //$slog = 'data sum bold red'; //naj bo slog bold in stevilke rdece barve
+ $slog = 'data bold'.$redBg; //naj bo slog bold in ozadje celice rdece barve, ce niso celice zadnjega stolpca
+ }else{
+ $slog = 'data';
+ }
+ echo '<td class="'.$slog.'">'.$podatek.'</td>';
+ }
+
+ function displayUsableSettings(){
+ global $lang;
+
+ // Div z nastavitvami ki se razpre
+ echo '<div id="dataSettingsCheckboxes" '.($this->displayEditIconsSettings ? '' : ' style="display:none;"').'>';
+ echo '<div id="toggleDataCheckboxes2" onClick="toggleDataCheckboxes(\'usability\');"><span class="faicon close icon-orange" style="padding-bottom:2px;"></span> '.$lang['srv_data_settings_checkboxes2'].'</div>';
+
+
+ echo '<div id="usable_respondents_settings">';
+
+ echo $lang['srv_usableResp_limit'].': ';
+
+ echo '<span class="spaceLeft spaceRight">'.$lang['srv_usableResp_bottom_limit'].': <input type="text" id="bottom_usable_limit" size="2" onblur="changeUsableRespSetting(this);" value="'.$this->bottom_usable_limit.'" />%</span>';
+ echo '<span class="spaceLeft spaceRight">'.$lang['srv_usableResp_top_limit'].': <input type="text" id="top_usable_limit" size="2" onblur="changeUsableRespSetting(this);" value="'.$this->top_usable_limit.'" />%</span>';
+
+ echo '<br />';
+
+ echo '<div style="margin-top:10px;">';
+ echo $lang['srv_usableResp_show'].': ';
+
+ // Prikaz neničelnih stolpcev
+ echo '<label class="spaceLeft spaceRight">';
+ echo '<input type="checkbox" id="show_with_zero" onclick="changeUsableRespSetting(this);" '.($this->show_with_zero == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_usableResp_showZero'];
+ echo '</label>';
+
+ // Prikaz podrobnosti
+ echo '<label class="spaceLeft spaceRight">';
+ echo '<input type="checkbox" id="show_details" onclick="changeUsableRespSetting(this);" '.($this->show_details == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_usableResp_showDetails'];
+ echo '</label>';
+
+ // Prikaz podrobnih izracunov
+ echo '<label class="spaceLeft">';
+ echo '<input type="checkbox" id="show_calculations" onclick="changeUsableRespSetting(this);" '.($this->show_calculations == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_usableResp_showCalc'];
+ echo '</label>';
+ echo '</div>';
+
+ echo '</div>';
+
+
+ echo '</div>';
+ }
+
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter(){
+ /*if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED)
+ {
+ return false;
+ }*/
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ || ($_time_profile_awk != "" && $_time_profile_awk != null))
+ {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null)
+ {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD)
+ {
+ if (isset($this->_HEADERS['testdata']))
+ {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+
+ $smv = new SurveyMissingValues($this->anketa);
+ $smv -> Init();
+
+ $smv_array = $smv->GetSurveyMissingValues($this->anketa);
+ if (!empty($smv_array[1])){
+ foreach ($smv_array[1] AS $_survey_missings)
+ {
+ $this->_missings[$_survey_missings['value']] = $_survey_missings['text'];
+
+ }
+ }
+ if (!empty($smv_array[2])){
+ foreach ($smv_array[2] AS $_survey_unsets)
+ {
+ $this->_unsets[$_survey_unsets['value']] = $_survey_unsets['text'];
+ }
+ }
+ }
+
+ private function setUserFilters(){
+ # Nastavimo filtre variabel
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+ if ($dvp != $_currentVariableProfile) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', $_currentVariableProfile);
+ }
+ $this->_PROFILE_ID_VARIABLE = $_currentVariableProfile;
+
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['usable_resp']['show_with_zero'])) {
+ $this->show_with_zero = $this->sessionData['usable_resp']['show_with_zero'];
+ }
+
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['usable_resp']['show_details'])) {
+ $this->show_details = $this->sessionData['usable_resp']['show_details'];
+ }
+
+ # ali prikazujemo tudi stolpce z izracuni
+ if (isset($this->sessionData['usable_resp']['show_calculations'])) {
+ $this->show_calculations = $this->sessionData['usable_resp']['show_calculations'];
+ }
+
+ # ali prikazujemo vrstice "Drugo"
+ $this->show_with_other = true;
+ if (isset($this->sessionData['usable_resp']['show_with_other'])) {
+ $this->show_with_other = $this->sessionData['usable_resp']['show_with_other'];
+ }
+
+ # ali prikazujemo vrstice tipa "besedilo"
+ $this->show_with_text = true;
+ if (isset($this->sessionData['usable_resp']['show_with_text'])) {
+ $this->show_with_text = $this->sessionData['usable_resp']['show_with_text'];
+ }
+
+ # Spodnja in zgornja meja za usable
+ if (isset($this->sessionData['usable_resp']['bottom_usable_limit'])) {
+ $this->bottom_usable_limit = $this->sessionData['usable_resp']['bottom_usable_limit'];
+ }
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['usable_resp']['top_usable_limit'])) {
+ $this->top_usable_limit = $this->sessionData['usable_resp']['top_usable_limit'];
+ }
+ }
+
+
+ // Zgeneriramo datoteko in izracunamo frekvence (stevilo 1, -1, -2...) za vsako enoto
+ private function collectData(){
+ global $site_path;
+
+ # polovimo frekvence statusov odgovorov za posameznega respondenta (stevilo -1, -2...)
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ #array za imeni tmp fajlov, ki jih nato izbrišemo
+ $tmp_file = $folder.'tmp_export_'.$this->anketa.'_reminder_tracking_recnum.php';
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ # s katero sekvenco se začnejo podatki, da ne delamo po nepotrebnem za ostala polja
+ $start_sequence = $this->_HEADERS['_settings']['dataSequence'];
+ # s katero sekvenco se končajo podatki da ne delamo po nepotrebnem za ostala polja
+ $end_sequence = $this->_HEADERS['_settings']['metaSequence']-1;
+ # sekvenca recnuma
+ $recnum_sequence = $this->_HEADERS['recnum']['sequences'];
+
+ # naredimo datoteko z frekvencami
+ # za windows sisteme in za linux sisteme
+
+ if (IS_WINDOWS ) {
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" "{{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} {{for (n in arr) {delete arr[n]}}} {delete arr} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[$i]++}} '.$status_filter.' {{for (n in arr) { print NR,$'.$recnum_sequence.',$1,n,arr[n]}}}" '.$this->dataFileName;
+ $command .= ' | sed "s*\x27*`*g" ';
+ $command .= ' | awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} { print \"$frequency[\",$1,\"]\",\"[\x27\",$4,\"\x27]\",\"=\",$5,\";\"} { print \"$frequency[\",$1,\"]\",\"[usr_id]\",\"=\",$3,\";\"} { print \"$frequency[\",$1,\"]\",\"[recnum]\",\"=\",$2,\";\"}" >> '.$tmp_file;
+ }
+
+ else {
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" \' {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} {{for (n in arr) {delete arr[n]}}} {delete arr} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[$i]++}} '.$status_filter.' {{for (n in arr) { print NR,$'.$recnum_sequence.',$1,n,arr[n]}}}\' '.$this->dataFileName;
+ $command .= ' | sed \'s*\x27*`*g\' ';
+ $command .= ' | awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} { print "$frequency[",$1,"]","[\x27",$4,"\x27]","=\x27",$5,"\x27;"} { print "$frequency[",$1,"]","[usr_id]","=\x27",$3,"\x27;"} { print "$frequency[",$1,"]","[recnum]","=\x27",$2,"\x27;"}\' >> '.$tmp_file;
+ }
+
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+
+ $out = shell_exec($command);
+
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ // Loop cez podatke da vidimo kateri stolpci so prazni
+ foreach ($frequency AS $seq => $freqData) {
+
+ if (empty($freqData)) {
+ continue;
+ }
+
+ foreach ($freqData AS $key => $cnt){
+ if (is_numeric($key) && (isset($this->_missings[(int)$key]) || isset($this->_unsets[(int)$key])))
+ $this->cols_with_value[(int)$key] += $cnt;
+ elseif($key != 'recnum')
+ $this->cols_with_value['valid'] += $cnt;
+ }
+ }
+
+ return $frequency;
+ }
+
+ // Gremo cez enote in izracunamo uporabne vrednosti (uporabnost, breakoff...)
+ public function calculateData(){
+
+ // Preko datoteke preberemo frekvence za posamezne userje (1, -1, -2...)
+ $data = $this->collectData();
+ $ank_id = $this->anketa;
+ $css = '';
+ $usability = array();
+
+ // Loop cez vse responente
+ $counter = 1;
+ foreach($data as $key1 => $frequencies){
+
+ // Prestejemo vse in veljavne
+ $all = 0;
+ $valid = 0;
+ $usable = 0; // valid + nonsubstantive
+ $nonsubstantive = 0; // -97,-98...
+ $nonresponse = 0; // -1
+ $preskok = 0; // -2
+ $breakoff = 0; // -3
+ $naknadno = 0; // -4
+ $status = 0; // 0->unusable, 1->part. usable, 2->usable
+ foreach($frequencies as $key => $cnt){
+
+ if(!array_key_exists($key, $this->_missings) && !array_key_exists($key, $this->_unsets) && $key!==''){
+ $valid += $cnt;
+ $usable += $cnt;
+ }
+
+ if(array_key_exists($key, $this->_unsets)){
+ $nonsubstantive += $cnt;
+ $usable += $cnt;
+ }
+
+ if($key == -1)
+ $nonresponse += $cnt;
+
+ if($key == -3)
+ $breakoff+= $cnt;
+
+ if($key == -2)
+ $preskok+= $cnt;
+
+ if($key == -4)
+ $naknadno+= $cnt;
+
+ $all += $cnt;
+ }
+
+ // odstejemo polje recnum
+ $all -= $frequencies['recnum'];
+ $valid -= $frequencies['recnum'];
+ $usable -= $frequencies['recnum'];
+
+ // odstejemo polje usr_id
+ $all -= $frequencies['usr_id'];
+ $valid -= $frequencies['usr_id'];
+ $usable -= $frequencies['usr_id'];
+
+
+/* echo '
+ <script>
+ console.log('.$frequencies['usr_id'].');
+ </script>
+ '; */
+ //*************************** Pobiranje in stetje alertov po respondentih *****************************************************
+ $user = $frequencies['usr_id'];
+ //poberi stevilo hard in soft alertov za vsoto
+ $sqlSumHard = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfSumHard FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND (a.type LIKE '%hard%' AND a.trigger_type = 'sum')");
+ $sqlSumSoft = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfSumSoft FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND (a.type LIKE '%soft%' AND a.trigger_type = 'sum')");
+
+ //poberi stevilo hard in soft alertov za stevilo
+ $sqlNumHard = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfNumHard FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND (a.type LIKE '%hard%' AND a.trigger_type = 'num')");
+ $sqlNumSoft = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfNumSoft FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND (a.type LIKE '%soft%' AND a.trigger_type = 'num')");
+
+ //poberi stevilo hard in soft alertov
+ $sqlHardAlert = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfHardAlert FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND trigger_type = 'har'");
+ $sqlSoftAlert = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfSoftAlert FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND trigger_type = 'sof'");
+
+ //poberi stevilo hard in soft validacij
+ $sqlHardValidation = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfHardValidation FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND (a.type LIKE '%hard%' AND a.trigger_type = 'val')");
+ $sqlSoftValidation = sisplet_query("SELECT COUNT(d.usr_id) AS NumberOfSoftValidation FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE d.usr_id = '$user' AND d.ank_id='$ank_id' AND (a.type LIKE '%soft%' AND a.trigger_type = 'val')");
+
+ $rowSumHard = mysqli_fetch_assoc($sqlSumHard);
+ $rowSumSoft = mysqli_fetch_assoc($sqlSumSoft);
+
+ $rowNumHard = mysqli_fetch_assoc($sqlNumHard);
+ $rowNumSoft = mysqli_fetch_assoc($sqlNumSoft);
+
+ $rowHardAlert = mysqli_fetch_assoc($sqlHardAlert);
+ $rowSoftAlert = mysqli_fetch_assoc($sqlSoftAlert);
+
+ $rowHardValidation = mysqli_fetch_assoc($sqlHardValidation);
+ $rowSoftValidation = mysqli_fetch_assoc($sqlSoftValidation);
+
+ //************************************************************************************************************* po respondentih - konec
+
+ //$validPercent = ($all > 0) ? ($valid / $all * 100) : 0;
+ //$nonsubstantivePercent = ($valid + $nonsubstantive > 0) ? ($nonsubstantive / ($valid + $nonsubstantive) * 100) : 0;
+ //$nonresponsePercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($nonresponse / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+ $validPercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($valid / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+ $nonsubstantivePercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($nonsubstantive / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+ $nonresponsePercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($nonresponse / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+
+ //$breakoffPercent = ($valid + $nonsubstantive + $nonresponse + $breakoff > 0) ? ($breakoff / ($valid + $nonsubstantive + $nonresponse + $breakoff) * 100) : 0;
+ $breakoffPercent = $breakoff / $all * 100;
+
+ //$usablePercent = ($valid + $nonsubstantive + $nonresponse + $breakoff > 0) ? ($usable / ($valid + $nonsubstantive + $nonresponse + $breakoff) * 100) : 0;
+
+ // Posebni izracuni
+ $UNL = (($valid + $nonsubstantive + $nonresponse) > 0) ? $nonresponse / ($valid + $nonsubstantive + $nonresponse) : 0; // Delez neodgovorov
+ $UBL = ($all > 0) ? $breakoff / $all : 0; // Delez prekinitev
+ $UML = $UBL + (1 - $UBL) * $UNL;
+ $UCL = 1 - $UML; // Uporabnost
+ $UIL = (($valid + $nonsubstantive + $nonresponse + $preskok) > 0) ? $preskok /($valid + $nonsubstantive + $nonresponse + $preskok) : 0; // Delez preskokov
+ $UAQ = ($all > 0) ? $naknadno / $all : 0; // Delez naknadnih
+
+ // Ce nimamo veljavnih in nevsebinskih je UCL vedno 0
+ $UCL = ($valid + $nonsubstantive == 0) ? 0 : $UCL;
+
+ $usablePercent = $UCL * 100;
+
+ if($usablePercent < (int)$this->bottom_usable_limit){
+ $css_usable = 'unusable';
+ $status = 0;
+ $usability['unusable']++;
+ }
+ elseif($usablePercent >= (int)$this->bottom_usable_limit && $usablePercent < (int)$this->top_usable_limit){
+ $css_usable = 'partusable';
+ $status = 1;
+ $usability['partusable']++;
+ }
+ else{
+ $css_usable = 'usable';
+ $status = 2;
+ $usability['usable']++;
+ }
+ $usability['all']++;
+
+ // Nastavimo izracunane podatke za respondenta
+ $usability['data'][$counter]['recnum'] = $frequencies['recnum'];
+ $usability['data'][$counter]['usr_id'] = $frequencies['usr_id'];
+ $usability['data'][$counter]['css'] = $css;
+ $usability['data'][$counter]['status'] = $status;
+ $usability['data'][$counter]['all'] = $all;
+ $usability['data'][$counter]['valid'] = $valid;
+ $usability['data'][$counter]['nonsubstantive'] = $nonsubstantive;
+ $usability['data'][$counter]['nonresponse'] = $nonresponse;
+ $usability['data'][$counter]['breakoff'] = $breakoff;
+ $usability['data'][$counter]['usable'] = $usable;
+ $usability['data'][$counter]['validPercent'] = $validPercent;
+ $usability['data'][$counter]['usablePercent'] = $usablePercent;
+ $usability['data'][$counter]['nonsubstantivePercent'] = $nonsubstantivePercent;
+ $usability['data'][$counter]['nonresponsePercent'] = $nonresponsePercent;
+ $usability['data'][$counter]['breakoffPercent'] = $breakoffPercent;
+ $usability['data'][$counter]['UNL'] = $UNL;
+ $usability['data'][$counter]['UML'] = $UML;
+ $usability['data'][$counter]['UCL'] = $UCL;
+ $usability['data'][$counter]['UIL'] = $UIL;
+ $usability['data'][$counter]['UAQ'] = $UAQ;
+
+ //************ Za alerte ************
+ $usability['data'][$counter]['rowSumHard'] = $rowSumHard['NumberOfSumHard'];
+ $usability['data'][$counter]['rowSumSoft'] = $rowSumSoft['NumberOfSumSoft'];
+ $usability['data'][$counter]['rowNumHard'] = $rowNumHard['NumberOfNumHard'];
+ $usability['data'][$counter]['rowNumSoft'] = $rowNumSoft['NumberOfNumSoft'];
+ $usability['data'][$counter]['rowHardAlert'] = $rowHardAlert['NumberOfHardAlert'];
+ $usability['data'][$counter]['rowSoftAlert'] = $rowSoftAlert['NumberOfSoftAlert'];
+ $usability['data'][$counter]['rowHardValidation'] = $rowHardValidation['NumberOfHardValidation'];
+ $usability['data'][$counter]['rowSoftValidation'] = $rowSoftValidation['NumberOfSoftValidation'];
+ //***********************************
+
+ // ali odstranimo vse stolpce s podrobnimi vrednostmi (-1, -2...)
+ foreach ($this->_missings AS $value => $text){
+ $usability['data'][$counter][$value] = (isset($frequencies[$value]) ? $frequencies[$value] : '0');
+ }
+ foreach ($this->_unsets AS $value => $text){
+ $usability['data'][$counter][$value] = (isset($frequencies[$value]) ? $frequencies[$value] : '0');
+ }
+
+
+ $css = ($css == 'colored') ? '' : 'colored';
+ $counter++;
+ }
+
+ return $usability;
+ }
+
+
+ private function calculateDataVars($usr_id){
+ global $site_path;
+ $usability_vars = array();
+
+ //*************************** Pobiranje in stetje alertov po spremenljivkah *****************************************************
+
+ $defaultProfile = SurveyStatusProfiles::getDefaultProfile(); //ce je 1, imamo "Vse enota", ce je 2, imamo "Ustrezne" enote
+ $ank_id = $this->anketa;
+
+
+ $counter = 0;
+
+ if($defaultProfile == 2){ //ce imamo "Ustrezne", najdi ne respondente
+ $sql_lurkers_hard_alert = sisplet_query("SELECT id FROM srv_user WHERE ank_id = '$ank_id' and lurker = 1");//poberi podatki o lurker oz. ne respondentov
+ while($row_lurkers_hard_alert = mysqli_fetch_array($sql_lurkers_hard_alert)){
+/* echo'
+ <script>
+ console.log('.$row_lurkers_hard_alert['id'].');
+ </script>
+ '; */
+ $lurkers = $lurkers.' and usr_id !='.$row_lurkers_hard_alert['id'];
+ }
+/* echo'
+ <script>
+ console.log(\''.$lurkers.'\');
+ </script>
+ '; */
+ }
+
+ $sql_spr_id = sisplet_query("SELECT element_spr FROM srv_branching WHERE ank_id = ".$ank_id); //poberi id spremenljivk
+ while($row_spr_id = mysqli_fetch_array($sql_spr_id)){
+
+ $spr_id = $row_spr_id['element_spr'];
+
+ if($spr_id){ //ce $spr_id ni nula
+
+ $sql_spr_variable = sisplet_query("SELECT variable FROM srv_spremenljivka WHERE id=$spr_id");//poberi id spremenljivk
+ $row_spr_variable = mysqli_fetch_assoc($sql_spr_variable);
+ $usability_vars[$counter]['variable'] = $row_spr_variable['variable'];
+
+ //Hard alerts**************************
+ $query_variable_hard_alert = "SELECT COUNT(a.trigger_id) AS NumOfHardAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND a.trigger_type='har' ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_hard_alert = $query_variable_hard_alert.''.$lurkers;
+ }
+ $sql_variable_hard_alert = sisplet_query($query_variable_hard_alert);
+ $row_variable_hard_alert = mysqli_fetch_assoc($sql_variable_hard_alert);
+ $usability_vars[$counter]['rowHardAlert'] = $row_variable_hard_alert['NumOfHardAlerts'];
+
+ $query_steviloVsehMoznihOpozorilHard = "SELECT COUNT(id) AS steviloVsehMoznihOpozorilHard FROM `srv_spremenljivka` WHERE id = '$spr_id' AND reminder = 2";
+ $sql_steviloVsehMoznihOpozorilHard = sisplet_query($query_steviloVsehMoznihOpozorilHard);
+ $row_steviloVsehMoznihOpozorilHard = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilHard);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilHard'] = $row_steviloVsehMoznihOpozorilHard['steviloVsehMoznihOpozorilHard'];
+
+ //Hard alerts - konec**************************
+
+ //Soft alerts**************************
+ $query_variable_soft_alert = "SELECT COUNT(a.trigger_id) AS NumOfSoftAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND a.trigger_type='sof' ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_soft_alert = $query_variable_soft_alert.''.$lurkers;
+ }
+ $sql_variable_soft_alert = sisplet_query($query_variable_soft_alert);
+ $row_variable_soft_alert = mysqli_fetch_assoc($sql_variable_soft_alert);
+ $usability_vars[$counter]['rowSoftAlert'] = $row_variable_soft_alert['NumOfSoftAlerts'];
+
+ $query_steviloVsehMoznihOpozorilSoft = "SELECT COUNT(id) AS steviloVsehMoznihOpozorilSoft FROM `srv_spremenljivka` WHERE id = '$spr_id' AND reminder = 1";
+ $sql_steviloVsehMoznihOpozorilSoft = sisplet_query($query_steviloVsehMoznihOpozorilSoft);
+ $row_steviloVsehMoznihOpozorilSoft = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilSoft);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilSoft'] = $row_steviloVsehMoznihOpozorilSoft['steviloVsehMoznihOpozorilSoft'];
+ //Soft alerts - konec**************************
+
+ //Num Hard alerts**************************
+ $query_variable_num_hard_alert = "SELECT COUNT(a.trigger_id) AS NumOfNumHardAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND (a.type LIKE '%hard%' AND a.trigger_type = 'num') ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_num_hard_alert = $query_variable_num_hard_alert.''.$lurkers;
+ }
+ $sql_variable_num_hard_alert = sisplet_query($query_variable_num_hard_alert);
+ $row_variable_num_hard_alert = mysqli_fetch_assoc($sql_variable_num_hard_alert);
+ $usability_vars[$counter]['rowNumHard'] = $row_variable_num_hard_alert['NumOfNumHardAlerts'];
+
+ $query_steviloVsehMoznihOpozorilNumHard = "SELECT COUNT(id) AS steviloVsehMoznihOpozorilNumHard FROM `srv_spremenljivka` WHERE id = '$spr_id' AND vsota_reminder = 2 AND tip = 7";
+ $sql_steviloVsehMoznihOpozorilNumHard = sisplet_query($query_steviloVsehMoznihOpozorilNumHard);
+ $row_steviloVsehMoznihOpozorilNumHard = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilNumHard);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilNumHard'] = $row_steviloVsehMoznihOpozorilNumHard['steviloVsehMoznihOpozorilNumHard'];
+ //Num Hard alerts - konec**************************
+
+ //Num Soft alerts**************************
+ $query_variable_num_soft_alert = "SELECT COUNT(a.trigger_id) AS NumOfNumSoftAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND (a.type LIKE '%soft%' AND a.trigger_type = 'num') ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_num_soft_alert = $query_variable_num_soft_alert.''.$lurkers;
+ }
+ $sql_variable_num_soft_alert = sisplet_query($query_variable_num_soft_alert);
+ $row_variable_num_soft_alert = mysqli_fetch_assoc($sql_variable_num_soft_alert);
+ $usability_vars[$counter]['rowNumSoft'] = $row_variable_num_soft_alert['NumOfNumSoftAlerts'];
+
+ $query_steviloVsehMoznihOpozorilNumSoft = "SELECT COUNT(id) AS steviloVsehMoznihOpozorilNumSoft FROM `srv_spremenljivka` WHERE id = '$spr_id' AND vsota_reminder = 1 AND tip = 7";
+ $sql_steviloVsehMoznihOpozorilNumSoft = sisplet_query($query_steviloVsehMoznihOpozorilNumSoft);
+ $row_steviloVsehMoznihOpozorilNumSoft = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilNumSoft);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilNumSoft'] = $row_steviloVsehMoznihOpozorilNumSoft['steviloVsehMoznihOpozorilNumSoft'];
+ //Num Soft alerts - konec**************************
+
+ //Sum Hard alerts**************************
+ $query_variable_sum_hard_alert = "SELECT COUNT(a.trigger_id) AS NumOfSumHardAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND (a.type LIKE '%hard%' AND a.trigger_type = 'sum') ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_sum_hard_alert = $query_variable_sum_hard_alert.''.$lurkers;
+ }
+ $sql_variable_sum_hard_alert = sisplet_query($query_variable_sum_hard_alert);
+ $row_variable_sum_hard_alert = mysqli_fetch_assoc($sql_variable_sum_hard_alert);
+ $usability_vars[$counter]['rowSumHard'] = $row_variable_sum_hard_alert['NumOfSumHardAlerts'];
+
+ $query_steviloVsehMoznihOpozorilSumHard = "SELECT COUNT(id) AS steviloVsehMoznihOpozorilSumHard FROM `srv_spremenljivka` WHERE id = '$spr_id' AND vsota_reminder = 2 AND tip = 18";
+ $sql_steviloVsehMoznihOpozorilSumHard = sisplet_query($query_steviloVsehMoznihOpozorilSumHard);
+ $row_steviloVsehMoznihOpozorilSumHard = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilSumHard);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilSumHard'] = $row_steviloVsehMoznihOpozorilSumHard['steviloVsehMoznihOpozorilSumHard'];
+ //Sum Hard alerts - konec**************************
+
+ //Sum Soft alerts**************************
+ $query_variable_sum_soft_alert = "SELECT COUNT(a.trigger_id) AS NumOfSumSoftAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND (a.type LIKE '%soft%' AND a.trigger_type = 'sum') ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_sum_soft_alert = $query_variable_sum_soft_alert.''.$lurkers;
+ }
+ $sql_variable_sum_soft_alert = sisplet_query($query_variable_sum_soft_alert);
+ $row_variable_sum_soft_alert = mysqli_fetch_assoc($sql_variable_sum_soft_alert);
+ $usability_vars[$counter]['rowSumSoft'] = $row_variable_sum_soft_alert['NumOfSumSoftAlerts'];
+
+ $query_steviloVsehMoznihOpozorilSumSoft = "SELECT COUNT(id) AS steviloVsehMoznihOpozorilSumSoft FROM `srv_spremenljivka` WHERE id = '$spr_id' AND vsota_reminder = 1 AND tip = 18";
+ $sql_steviloVsehMoznihOpozorilSumSoft = sisplet_query($query_steviloVsehMoznihOpozorilSumSoft);
+ $row_steviloVsehMoznihOpozorilSumSoft = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilSumSoft);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilSumSoft'] = $row_steviloVsehMoznihOpozorilSumSoft['steviloVsehMoznihOpozorilSumSoft'];
+ //Sum Soft alerts - konec**************************
+
+ //Val Hard alerts**************************
+ $query_variable_val_hard_alert = "SELECT COUNT(a.trigger_id) AS NumOfValHardAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND (a.type LIKE '%hard%' AND a.trigger_type = 'val') ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_val_hard_alert = $query_variable_val_hard_alert.''.$lurkers;
+ }
+ $sql_variable_val_hard_alert = sisplet_query($query_variable_val_hard_alert);
+ $row_variable_val_hard_alert = mysqli_fetch_assoc($sql_variable_val_hard_alert);
+ $usability_vars[$counter]['rowHardValidation'] = $row_variable_val_hard_alert['NumOfValHardAlerts'];
+
+ $query_steviloVsehMoznihOpozorilValHard = "SELECT COUNT(reminder) AS steviloVsehMoznihOpozorilValHard FROM `srv_validation` WHERE spr_id = '$spr_id' AND reminder = '2'";
+ $sql_steviloVsehMoznihOpozorilValHard = sisplet_query($query_steviloVsehMoznihOpozorilValHard);
+ $row_steviloVsehMoznihOpozorilValHard = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilValHard);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilValHard'] = $row_steviloVsehMoznihOpozorilValHard['steviloVsehMoznihOpozorilValHard'];
+ //Val Hard alerts - konec**************************
+
+ //Val Soft alerts**************************
+ $query_variable_val_soft_alert = "SELECT COUNT(a.trigger_id) AS NumOfValSoftAlerts FROM srv_advanced_paradata_alert a INNER JOIN srv_advanced_paradata_page d ON a.page_id=d.id WHERE a.trigger_id = '$spr_id' AND d.ank_id='$ank_id' AND (a.type LIKE '%soft%' AND a.trigger_type = 'val') ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_val_soft_alert = $query_variable_val_soft_alert.''.$lurkers;
+ }
+ $sql_variable_val_soft_alert = sisplet_query($query_variable_val_soft_alert);
+ $row_variable_val_soft_alert = mysqli_fetch_assoc($sql_variable_val_soft_alert);
+ $usability_vars[$counter]['rowSoftValidation'] = $row_variable_val_soft_alert['NumOfValSoftAlerts'];
+
+ $query_steviloVsehMoznihOpozorilValSoft = "SELECT COUNT(reminder) AS steviloVsehMoznihOpozorilValSoft FROM `srv_validation` WHERE spr_id = '$spr_id' AND reminder = '1'";
+ $sql_steviloVsehMoznihOpozorilValSoft = sisplet_query($query_steviloVsehMoznihOpozorilValSoft);
+ $row_steviloVsehMoznihOpozorilValSoft = mysqli_fetch_assoc($sql_steviloVsehMoznihOpozorilValSoft);
+ $usability_vars[$counter]['steviloVsehMoznihOpozorilValSoft'] = $row_steviloVsehMoznihOpozorilValSoft['steviloVsehMoznihOpozorilValSoft'];
+ //Val Soft alerts - konec**************************
+
+
+ /* //Hard alerts
+ $query_variable_hard_alert = "SELECT COUNT(spr_id_variable) AS NumOfHardAlerts FROM `srv_parapodatki` WHERE spr_id_variable = '$spr_id' AND what = 'hard alert' ";
+ if($defaultProfile == 2){ //ce imamo "Ustrezne"
+ $query_variable_hard_alert = $query_variable_hard_alert.''.$lurkers;
+ }
+ $sql_variable_hard_alert = sisplet_query($query_variable_hard_alert);
+ $row_variable_hard_alert = mysqli_fetch_assoc($sql_variable_hard_alert);
+ $usability_vars[$counter]['rowHardAlert'] = $row_variable_hard_alert['NumOfHardAlerts'];
+ //Hard alerts - konec */
+
+ //za ureditev stevila vseh moznih opozoril
+ //$query_steviloVsehmoznihOpozoril = "SELECT COUNT(spr_id_variable) AS NumOfHardAlerts FROM `srv_parapodatki` WHERE spr_id_variable = '$spr_id' AND what = 'hard alert' ";
+
+ //za ureditev stevila vseh moznih opozoril - konec
+
+
+ /* echo'
+ <script>
+ console.log('.$usability_vars[$counter]['steviloVsehMoznihOpozorilHard'].');
+ </script>
+ '; */
+
+ $counter = $counter + 1;
+ }
+ }
+ //************************************************************************************************************* po spremenljivkah - konec
+ //******belezenje stevila moznih oziroma narejenih opozoril iz strani urejevalca ankete
+
+
+ //******belezenje stevila moznih oziroma narejenih opozoril iz strani urejevalca ankete - konec
+
+ return $usability_vars;
+ }
+
+ // Ali imamo zgenerirano datoteko ali ne
+ public function hasDataFile(){
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED)
+ return false;
+ else
+ return true;
+ }
+
+ public function setStatusFilter($status=''){
+
+ $this->_CURRENT_STATUS_FILTER = $status;
+ }
+
+ function ajax(){
+
+ $action = $_GET['a'];
+
+ switch ($action){
+ case 'changeSetting' :
+ $this->ajax_change_settings();
+ break;
+ }
+ }
+ private function ajax_change_settings(){
+
+ $value = $_POST['value'];
+ $what = $_POST['what'];
+
+ if($value == 'true')
+ $value = true;
+ elseif($value == 'false')
+ $value = false;
+
+ $this->sessionData['reminder_tracking'][$what] = $value;
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ private function steviloMoznihOpozoril($vars, $what){
+ $steviloMoznihOpozoril = 0;
+ foreach($vars as $key => $var){
+ $steviloMoznihOpozoril = $steviloMoznihOpozoril + $var[$what];
+ }
+ return $steviloMoznihOpozoril;
+ }
+
+ //skrbi za racunanje kakovosti
+ private function izracunKakovosti($steviloRespondentov, $sprozenaOpozorila, $steviloVsehMoznihOpozoril){
+
+ $kakovost = 1 - ($sprozenaOpozorila/$steviloVsehMoznihOpozoril)/$steviloRespondentov;
+
+ return $kakovost;
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyRespondents.php b/admin/survey/classes/class.SurveyRespondents.php
new file mode 100644
index 0000000..07dac48
--- /dev/null
+++ b/admin/survey/classes/class.SurveyRespondents.php
@@ -0,0 +1,816 @@
+<?php
+/**
+ * Created on 11.12.2009
+ *
+ * @author: Gorazd Veselič
+ */
+
+session_start();
+
+global $site_path;
+
+
+class SurveyRespondents {
+
+ static private $instance;
+
+ static private $surveyId = null;
+ static private $uId = null;
+
+ static private $messages = null;
+ static private $errors = null;
+
+ static private $currentProfileId = null; // trenutno izbrana lista
+ static private $profiles = array(); // seznam vseh list uporannika
+
+ static private $systemVariables = null;
+ /* naredimo v konstruktu
+ static private $systemVariables = array(
+ 'email' => array('naslov'=>$lang['srv_system_variables_email']),
+ 'ime' => array('naslov'=>$lang['srv_system_variables_name']),
+ 'priimek' => array('naslov'=>$lang['srv_system_variables_surname']),
+ 'telefon' => array('naslov'=>$lang['srv_system_variables_phone']),
+ 'naziv' => array('naslov'=>$lang['srv_system_variables_title']));
+ */
+
+ protected function __construct() {
+ global $lang;
+ self::$systemVariables = array(
+ 'email' => array('naslov'=>$lang['srv_system_variables_email']),
+ 'pass' => array('naslov'=>$lang['password']),
+ 'ime' => array('naslov'=>$lang['srv_system_variables_name']),
+ 'priimek' => array('naslov'=>$lang['srv_system_variables_surname']),
+ 'telefon' => array('naslov'=>$lang['srv_system_variables_phone']),
+ 'naziv' => array('naslov'=>$lang['srv_system_variables_title']),
+ 'drugo' => array('naslov'=>$lang['srv_system_variables_custom']),
+ 'odnos' => array('naslov'=>$lang['srv_system_variables_relation']));
+ }
+
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveyRespondents();
+ }
+ return self::$instance;
+ }
+
+ /** napolnimo podatke
+ *
+ */
+ static function Init($_surveyId)
+ {
+ global $global_user_id;
+
+ if ($_surveyId && $global_user_id)
+ {
+ self::$surveyId = $_surveyId;
+ self::$uId = $global_user_id;
+ // inicializiramo datoteko z nastavitvami
+ SurveyUserSetting :: getInstance()->Init(self::$surveyId, self::$uId);
+ // polovimo uporabnikovo privzeto listo
+ self::getProfileId();
+ self::getProfiles();
+ self::getSistemVariables();
+ } else {
+ die("Mandatory data missing in SurveyRespondents class!");
+ }
+ }
+
+ static function getSurveyId() { return self::$surveyId; }
+ static function getGlobalUserId() { return self::$uId; }
+ static function getCurentProfileId() { return self::$currentProfileId; }
+
+ static function getProfileId() {
+ // preverimo ali obstaja nastavitev
+ // poiščemo kateri profil variabel imamo
+ $drl = SurveyUserSetting :: getInstance()->getSettings('default_respondent_profile');
+
+
+ if ($drl == null || $drl < 1) {
+ $drl = self::checkDefaultProfile();
+ if ($drl > 0)
+ SurveyUserSetting :: getInstance()->saveSettings('default_respondent_profile', $drl);
+
+ }
+ self::$currentProfileId = $drl;
+ return self::$currentProfileId;
+ }
+
+ static function checkDefaultProfile() {
+ global $lang;
+
+ # če smo v telefonski anketi skreiramo začasen prazen profil,
+ if ($_GET['a'] == A_PHONE || $_POST['profile_from'] == A_PHONE) {
+
+ // najprej preverimo ali obstaja seja začasin profil
+ if ( isset($_SESSION['respondent_profile']) ) {
+ # preverimo ali obstaja variabla telefon, potem je bil provil pravilno skreiran
+ if (strpos($_SESSION['respondent_profile']['variables'],'telefon')) {
+ // vrnemo id iz seje
+ return $_SESSION['respondent_profile']['id'];
+ }
+ }
+ # če profil ne obstaja skreiramo nov zacasni prodil v obliki seje
+
+ $_SESSION['respondent_profile'] = array( 'id' => 0,
+ 'uid' => self::getGlobalUserId(),
+ 'variables' => 'telefon',
+ 'lines' => array());
+ if (!isset($_SESSION['respondent_profile']['name'])) {
+ $_SESSION['respondent_profile']['name'] = $lang['srv_temp_profile_author'];
+ }
+ return 0; # vrnemo id = 0, pravkar skreiranega profila
+ }
+ # če pa smo v e-mail anketi pa skreiramo prazen e-mail profil
+ if ($_GET['a'] == A_EMAIL || $_POST['profile_from'] == A_EMAIL) {
+
+ // najprej preverimo ali obstaja seja začasin profil
+ if ( isset($_SESSION['respondent_profile']) ) {
+ # preverimo ali obstaja variabla email, potem je bil provil pravilno skreiran
+ if (strpos($_SESSION['respondent_profile']['variables'],'email')) {
+ // vrnemo id iz seje
+ return $_SESSION['respondent_profile']['id'];
+ }
+ }
+ # če profil ne obstaja skreiramo nov zacasni prodil v obliki seje
+ # in dodamo listo z avtorjevim e-mailom
+ $qryEmail = sisplet_query("SELECT email FROM users WHERE id = '".self::getGlobalUserId()."'");
+ $rowEmail = mysqli_fetch_assoc($qryEmail);
+
+ $_SESSION['respondent_profile'] = array( 'id' => 0,
+ 'uid' => self::getGlobalUserId(),
+ 'variables' => 'email',
+ 'lines' => array($rowEmail['email']));
+ if (!isset($_SESSION['respondent_profile']['name'])) {
+ $_SESSION['respondent_profile']['name'] = $lang['srv_temp_profile_author'];
+ }
+ return 0; # vrnemo id = 0, pravkar skreiranega profila
+ }
+
+ # če smo tukaj je napaka !
+ return 0;
+ }
+
+ /** Pridobimo seznam vseh list uporabnika
+ * v obliki arraya
+ */
+ static function getProfiles() {
+
+ self::$profiles = array();
+ // dodamo profil iz seje , če obstaja
+ if ( isset($_SESSION['respondent_profile']) ) {
+ self::$profiles[$_SESSION['respondent_profile']['id']] = $_SESSION['respondent_profile'];
+ }
+
+ // dodamo še ostale profile iz baze
+ $stringSelect = "SELECT * FROM srv_respondent_profiles WHERE uid = '".self::getGlobalUserId()."' ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ }
+ return self::$profiles;
+ }
+
+ static function getProfileData($pid = null) {
+ $result = array();
+ if($pid == null) {
+ $pid = self::$currentProfileId;
+ }
+ if (isset($_SESSION['respondent_profile']['id']) && $pid == $_SESSION['respondent_profile']['id']) {
+ $result[$_SESSION['respondent_profile']['id']] = array('pid'=> $_SESSION['respondent_profile']['id'], 'lines'=>$_SESSION['respondent_profile']['lines']);
+ return $result;
+ }
+
+ // cene dodamo podatke iz baze
+
+ $selectString = "SELECT * FROM srv_respondents WHERE pid = '".$pid."'";
+ $querySelect = sisplet_query($selectString);
+ $_lines = array();
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ){
+ $_lines[] = $rowSelect['line'];
+ }
+ $result[$pid] = array('pid'=> $pid, 'lines'=>$_lines);
+
+ return $result;
+ }
+
+ static function getSistemVariables() {
+ // osnovnm sistemskim variablam dodamo tiste iz ankete
+ $sqlSistemske = sisplet_query("SELECT s.id, s.naslov, s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".self::getSurveyId()."' ORDER BY g.vrstni_red, s.vrstni_red");
+ if (mysqli_num_rows($sqlSistemske) > 0) {
+ while ($rowSistemske = mysqli_fetch_assoc($sqlSistemske)) {
+ if (!isset(self::$systemVariables[$rowSistemske['variable']])) {
+ self::$systemVariables[$rowSistemske['variable']] = array('naslov'=>$rowSistemske['naslov']);
+ }
+ }
+
+ }
+ return self::$systemVariables;
+ }
+
+ static function displayProfiles() {
+ global $admin_type;
+ global $lang;
+
+ ?>
+ <div class="respondent_profile_holder">
+ <div id="respondent_profiles" class="select">
+ <input type="hidden" id="profile_from" value="<?php
+
+ echo isset($_POST['profile_from']) ? $_POST['profile_from'] : $_GET['a']; ?>" />
+ <?php
+ foreach ( self::$profiles as $key => $profile ) {
+ echo '<div class="option' . ($profile['id'] == self::$currentProfileId ? ' active' : '') . '" value="' . $profile['id'] . '">' . $profile['name'] . '</div>';
+ }
+ ?>
+ </div>
+ <div class="clr"></div>
+ <div class="respondent_profiles_links link_no_decoration">
+ <a href="#" onclick="showDeleteRespondentProfile(); return false;"><?=$lang['srv_delete_profile'];?></a><br/>
+ <?php
+ //zacasnega profila ne moremo preimenovat
+ if (self::$currentProfileId != 0)
+ echo ' <a href="#" onclick="showRenameRespondentProfile(); return false;">'.$lang['srv_rename_profile'].'</a>'."\n";
+ ?>
+ </div>
+ </div>
+ <div id="respondent_profile_values" ><?=self::displayProfileData(self::$currentProfileId);?></div>
+ <div id="respondent_profile_right" >
+ <?php
+ if (!($admin_type <= 1)) {
+ ?>
+ <?=$lang['srv_user_base_user_note20']?></p><?
+ }
+ ?>
+ <div id="respondent_profile_notes" ><?=$lang['srv_mailing_add_help'];?></div>
+ <div id="respondent_profile_upload" >
+ <form id="resp_uploader" name="resp_uploader" method="post" enctype="multipart/form-data" action="index.php?anketa=<?=self::getSurveyId();?>&a=email&m=uploadRespondents">
+ <input type="hidden" name="posted" value="1" /><?=$lang['srv_mailing_upload_list'];?>:<input type="file" name="ul" id="ul" size="42"onChange="submit();" />
+ </form>
+ </div>
+ </div>
+ <div class="clr"></div>
+ <script type="text/javascript">
+ $(document).ready(function() {
+ $("#respondent_profiles .option").click(function() {
+ $("#respondent_profiles .option").each(function () {
+ $(this).removeClass("active"); });
+ $(this).addClass("active");
+ change_respondent_profile($(this).attr('value'));
+ });
+ });
+ </script>
+ <!-- dialog za skrani kot nov -->
+ <div id="respondent_new_dialog"><?=$lang['srv_respondent_profile_name']?>:
+ <input id="newProfileName" name="newProfileName" type="text" value="" size="45" />
+ <input id="newProfileId" type="hidden" />
+ <span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$('#respondent_new_dialog, #fade').hide(); return false;"><span><?=$lang['srv_close_profile'];?></span></a></span></span>
+ <span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="respondent_saveNewProfile(); return false;"><span><?=$lang['srv_save_profile_yes'];?></span></a></span></span>
+ </div>
+
+ <!-- dialog za preimenuj -->
+ <div id="respondent_rename_dialog"><?=$lang['srv_respondent_profile_name'];?>:
+ <input id="renameProfileName" name="renameProfileName" type="text" value="<?=self::$profiles[self::$currentProfileId]['name'];?>" size="45" />
+ <input id="renameProfileId" type="hidden" />
+ <span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$('#respondent_rename_dialog, #fade').hide(); return false;"><span><?=$lang['srv_close_profile'];?></span></a></span></span>
+ <span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="respondent_renameProfile(); return false;"><span><?=$lang['srv_rename_profile_yes'];?></span></a></span></span>
+ </div>
+
+ <!-- div za brisanje -->
+ <div id="respondent_delete_dialog"><?=$lang['srv_missing_profile_delete_confirm'];?>: <b><?=self::$profiles[self::$currentProfileId]['name']?></b>?
+ <input id="deleteProfileId" type="hidden" value="<?=self::$currentProfileId?>" />
+ <span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$('#respondent_delete_dialog, #fade').hide(); return false;"><span><?=$lang['srv_close_profile'];?></span></a></span></span>
+ <span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="respondent_deleteProfile(); return false;"><span><?=$lang['srv_delete_profile_yes'];?></span></a></span></span>
+ </div>
+ <?php
+
+
+ }
+ static function displayProfileData($pid) {
+
+ global $lang;
+
+ $pd = self::getProfileData($pid);
+
+ $data = implode("\n",$pd[$pid]['lines']);
+
+ echo '<p> <span class="labelSpanWide" >'.$lang['srv_respondents_variables'].':</span>';
+ echo '<div id="respondent_profile_variables_box">';
+ foreach (self::$systemVariables as $sysKey =>$sysVar) {
+ echo '<input type="checkbox" value="'.$sysKey.'" name="resp_check"',((strpos(self::$profiles[$pid]['variables'],$sysKey) === false) ? '' : ' checked="checked"'),
+ ' onChange="respondent_change_variable(\''.$sysKey.'\');" />',$sysVar['naslov'];
+
+
+ }
+ echo '</div>';
+ echo '<div class="clr"></div>';
+ echo '<span class="labelSpanWide" >&nbsp;</span>';
+ echo '<input type="text" id="respondent_profile_variables" value="' . self::$profiles[$pid]['variables'] . '" /></p>';
+ echo '<p> <span class="labelSpanWide" >'.$lang['srv_respondents_respondents'].':</span>';
+ echo '<textarea id="respondent_profile_value_text" >'.$data.'</textarea>';
+ echo '<div class="">';
+
+ echo ' <span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="respondent_run(\''.$pid.'\'); return false;"><span>'.$lang['srv_respondents_add'].'</span></a></div></span>';
+ echo ' <span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="respondent_save(\''.$pid.'\'); return false;"><span>'.$lang['srv_respondents_save'].'</span></a></div></span>';
+ echo ' <span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="respondent_save_new(\''.$pid.'\'); return false;"><span>'.$lang['srv_respondents_save_as_new'].'</span></a></div></span>';
+
+ echo ' <div class="clr"></div>';
+
+ echo '</div>';
+ }
+
+
+ static function CheckUploadedFile() {
+ global $lang;
+ $error = array();
+
+ $fileName = $_FILES['ul']['name'];
+ $tmpName = $_FILES['ul']['tmp_name'];
+ $fileSize = $_FILES['ul']['size'];
+ $fileType = $_FILES['ul']['type'];
+
+
+ $okFileType = ( $fileType == 'text/plain' || $fileType == 'application/vnd.ms-excel' );
+ $okFileEnd = (pathinfo($fileName, PATHINFO_EXTENSION) != 'txt' || pathinfo($fileName, PATHINFO_EXTENSION) != 'csv');
+ // preverimo tip:
+ if ( $okFileType = false ) {
+ $error[] = $lang['srv_respondents_invalid_file_type'];
+ }
+ // prevermio še končnico (.txt)
+ else if ($okFileEnd = false)
+ $error[] = $lang['srv_respondents_invalid_file_type'];
+
+ // preverimo velikost
+ if ( $fileSize == 0 )
+ $error[] = $lang['srv_respondents_invalid_file_size'];
+
+ // ce je do tu vse ok pregledamo vsebino
+ $respondents = array();
+ $fh = @fopen($tmpName, "rb");
+
+ if ($fh) {
+ //$data = fread($fh, 4096); // zakaj je ta limit?
+ $data = fread($fh, filesize($tmpName));
+ fclose($fh);
+
+ // počistimo prazne vrstice in kakšno zlonamerno kodo
+ $data = strip_tags(str_replace(array("\n\r","\n"),array("\n","\n"),$data));
+ $respondents = explode("\n",$data);
+ $respondents = array_values(array_filter($respondents));
+
+ } else {
+ $error[] = 'file read';
+ }
+
+ // ce ni napak in ce imamo zapise kreiramo nov zacasni profil v seji
+ if (count($error) == 0 && count($respondents) > 0) {
+
+ $_SESSION['respondent_profile'] = array( 'id' => 0,
+ 'uid' => self::getGlobalUserId(),
+ 'variables' => 'email',
+ 'lines' => $respondents);
+ $_SESSION['respondent_profile']['name'] = $lang['srv_respondents_temp_profile'];
+ // nastavimo profil
+ self::$currentProfileId = 0;
+
+ } else {
+ echo $lang['error'].'<br/>';
+ foreach ( $error as $value ) {
+ echo $value,"<br/>";
+ }
+ }
+ // prikazemo vrednosti
+ self::getProfiles();
+ self::displayProfiles();
+ }
+
+ static function checkSystemVariables($variables, $setUserbase=true) {
+ $user_base = 0;
+ global $site_path;
+
+ $sqlb = sisplet_query("SELECT branching, user_base FROM srv_anketa WHERE id = '".self::getSurveyId()."'");
+ $rowb = mysqli_fetch_array($sqlb);
+
+ $ba = new BranchingAjax(self::getSurveyId());
+
+ if (count($variables) > 0) {
+ // zakaj je bi ta reverse???
+ //$variables = array_reverse($variables,true);
+ foreach ($variables as $variable) {
+
+ $sqlVariable = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.variable='".$variable."' AND s.gru_id=g.id AND g.ank_id='".self::getSurveyId()."'");
+ if (mysqli_num_rows($sqlVariable) == 0 && $variable!='pass') { // če varabla še ne obstaja jo kreiramo
+ // za polje pass - Geslo ne kreiramo sistemske variable
+
+ if ($variable != 'language') $user_base = 1;
+
+ // dodamo novo spremenljivko na konec, tip je 21
+ ob_start();
+ $ba->ajax_spremenljivka_new(0, 0, 1, 0, 21);
+ $spr_id = $ba->spremenljivka;
+ ob_clean();
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET variable='".$variable."', variable_custom='1', naslov='".((isset($allowed[$variable]['naslov']) ? $allowed[$variable]['naslov'] : $variable))."', sistem='1', visible='0' WHERE id='$spr_id'");
+ if (!$s) echo 'err435'.mysqli_error($GLOBALS['connect_db']);
+
+ }
+ }
+ }
+ // če je potreben updejt (ampak najbrž je itak na 1 zaradi e-mail)
+ if ($setUserbase == true && $user_base > 0 && $user_base != $rowb['user_base']) {
+ $sql = sisplet_query("UPDATE srv_anketa SET user_base='$user_base' WHERE id='" . self::getSurveyId() . "'");
+ SurveyInfo :: getInstance()->resetSurveyData();
+ }
+
+ }
+ static function displayAddedUsers() {
+ global $site_path, $site_url, $lang;
+
+ SurveyInfo::getInstance()->SurveyInit(self::getSurveyId());
+ $db_table = (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) ? '_active' : '';
+
+ echo '<span>'.$lang['srv_respondents_added_respondents'].':</span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="' . $site_url . 'admin/survey/index.php?anketa='.self::getSurveyId().'&a=email&m=usermailing_setting" ><span>'.$lang['forward'].'</span></a></span></span>';
+ echo '<br class="clr"/>';
+ echo '<br/>';
+
+ $temp_user_data = array();
+ $data = array();
+ $header = array();
+
+ // poiščemo sistemske spremenljivke ki so navedene za spremenlivko
+ $sprList = "";
+ $prefix="";
+
+ $sql = sisplet_query("SELECT s.id, s.variable, s.naslov FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".self::getSurveyId()."' ORDER BY g.vrstni_red, s.vrstni_red ASC");
+ while($row = mysqli_fetch_assoc($sql)) {
+ $sprList .= $prefix.$row['id'];
+ $prefix=",";
+ $header[$row['id']] = $row['naslov'];
+ }
+
+ // dodamo sistemske podatke
+ $header_sys = array('pass'=>$lang['srv_respondents_cookie'],
+ 'status'=>$lang['srv_respondents_status'],
+ 'datetime'=>$lang['srv_respondents_datetime'],
+ 'admin_id'=>$lang['srv_respondents_admin']);
+
+ $str_qry_users = "SELECT u.id AS usr_id, u.cookie, u.pass, u.unsubscribed, IF(u.last_status = '-1','null',u.last_status) as status FROM srv_user as u WHERE u.ank_id = '".self::getSurveyId()."' AND u.preview = '0' ";
+
+ $qry_users = sisplet_query($str_qry_users);
+ while ( $row_users = mysqli_fetch_assoc($qry_users)) {
+ // polovimo podatke sistemskih spremenljivk od userja
+ if ($sprList != "") {
+ $sqlSprData = sisplet_query("SELECT spr_id,text FROM srv_data_text".$db_table." WHERE usr_id='".$row_users['usr_id']."' AND spr_id IN (".$sprList.")");
+
+ while ($rowSprData = mysqli_fetch_assoc($sqlSprData)) {
+ $data[$row_users['usr_id']][$rowSprData['spr_id']] = $rowSprData['text'];
+ }
+ }
+ // uporabniku dodamo podatke o kookiju in statusu
+ $data[$row_users['usr_id']]['pass'] = $row_users['pass'];
+ $data[$row_users['usr_id']]['status'] = $row_users['status'] . ' - ' .$lang['srv_userstatus_'.$row_users['status']];
+
+ if ($row_users['unsubscribed'] == 1) $data[$row_users['usr_id']]['status'] .= ', '.$lang['srv_unsubscribed'];
+
+ // polovimo podatke iz userbase
+// $str_ub = "SELECT ub.*, usr.name, usr.surname, usr.email FROM srv_userbase AS ub LEFT JOIN (SELECT usr.* FROM users as usr) as usr ON usr.id = ub.admin_id WHERE ub.usr_id = '".$row_users['usr_id']."' ORDER BY ub.tip ASC LIMIT 1";
+ $str_ub = "SELECT ub.* FROM srv_userbase AS ub WHERE ub.usr_id = '".$row_users['usr_id']."' ORDER BY ub.tip ASC LIMIT 1";
+ $qry_ub = sisplet_query($str_ub);
+ $row_ub = mysqli_fetch_assoc($qry_ub);
+
+ $data[$row_users['usr_id']]['datetime'] = $row_ub['datetime'];
+
+ // user insert data
+ if (!isset($temp_user_data[$row_ub['admin_id']])) {
+ $str_user = "SELECT usr.name, usr.surname, usr.email FROM users as usr WHERE usr.id = '".$row_ub['admin_id']."'";
+ $qry_user = sisplet_query($str_user);
+ $row_user = mysqli_fetch_assoc($qry_user);
+ $data[$row_users['usr_id']]['admin_id'] = $row_user['name']." ".$row_user['surname'];
+ $temp_user_data[$row_ub['admin_id']] = $row_user['name']." ".$row_user['surname'];
+ } else
+ $data[$row_users['usr_id']]['admin_id'] = $temp_user_data[$row_ub['admin_id']];
+
+ }
+ echo '<table id="respondentTable" class="anl_tbl anl_bt anl_bl anl_br anl_bb" style="padding:0px; margin:0px; border-collapse: collapse;">' . "\n";
+ // naslovna vrstica
+ echo '<tr>';
+ echo '<th class="anl_br anl_al anl_bck anl_bb anl_w50">'.$lang['srv_anketadelete_txt'].'</th>';
+ echo '<th class="anl_br anl_al anl_bck anl_bb anl_w50">'.$lang['srv_unsubscribe_1'].'</th>';
+ foreach ($header as $header_key => $headerTitle) {
+ echo '<th class="anl_br anl_al anl_bb anl_bck">'. $headerTitle .'</th>';
+ }
+ foreach ($header_sys as $header_key => $headerTitle) {
+ echo '<th class="anl_br anl_al anl_bb anl_bck">'. $headerTitle .'</th>';
+ }
+
+ echo '</tr>'."\n";
+ foreach ( $data as $user_id => $user_data ) {
+
+ echo '<tr id="respondent_id_'.$user_id.'">';
+ echo '<td class="anl_br anl_ac"><a href="#" onclick="respondent_data_delete(\''.$user_id.'\', \''.$lang['srv_ask_delete'].'\'); return false;"><img src="img_0/delete_red.png" alt="' . $lang['srv_delete_respondent'] . '" title="' . $lang['srv_delete_respondent'] . '" /></a></td>';
+ echo '<td class="anl_br anl_ac"><a href="#" onclick="$.post(\'unsubscribe.php?anketa='.self::getSurveyId().'&code='.$user_data['pass'].'\', {}, function() { window.location.reload(); }); return false;"><img src="img_0/email_delete.png" alt="' . $lang['srv_unsubscribe_2'] . '" title="' . $lang['srv_unsubscribe_2'] . '" /></a></td>';
+ // držimo se vrstnega reda header polij
+ foreach ($header as $header_key => $headerTitle) {
+ echo '<td class="anl_br anl_ac">'.($data[$user_id][$header_key] != null && $data[$user_id][$header_key] != "" ? $data[$user_id][$header_key] : '&nbsp;').'</td>';
+ }
+ foreach ($header_sys as $header_key => $headerTitle) {
+ echo '<td class="anl_br anl_ac">'.($data[$user_id][$header_key] != null && $data[$user_id][$header_key] != "" ? $data[$user_id][$header_key] : '&nbsp;').'</td>';
+ }
+ echo '</tr>'."\n";
+ }
+ echo '</table>'. "\n";
+
+ }
+
+ static function Ajax($action) {
+ switch ( $action ) {
+ case 'save_new_respondent_profile':
+ // shranimo podatek
+ self::ajaxSaveNewProfile();
+ // osvezimo
+ self::getProfileId();
+ self::getProfiles();
+ self::displayProfiles();
+ break;
+
+ case 'change_respondent_profile':
+ // osvezimo
+ $pid = (isset($_POST['pid']) ? $_POST['pid'] : SurveyUserSetting :: getInstance()->getSettings('default_respondent_profile') );
+// if ($pid > 0) // če ni seja, shranimo kot privzeti
+ SurveyUserSetting :: getInstance()->saveSettings('default_respondent_profile', $pid);
+ self::$currentProfileId = $pid;
+ self::getProfileId();
+ self::getProfiles();
+ self::displayProfiles();
+// self::displayProfileData($pid);
+ break;
+ case 'save_respondent_profile':
+ // shranimo podatek
+ self::ajaxSaveProfile();
+ self::getProfileId();
+ self::getProfiles();
+ self::displayProfiles();
+ break;
+ case 'run_respondent_profile':
+ // shranimo podatek
+ self::ajaxRunProfile();
+ // osvežimo
+ # odvisno ali smo v telefonu ali e-mail vabilih
+ if ($_POST['profile_from'] == A_PHONE) {
+ # če smo telefon
+ echo 'index.php?anketa=',self::getSurveyId(),'&a='.A_PHONE.'&m=start';
+ } else {
+ # če smo e-mail
+ echo 'index.php?anketa=',self::getSurveyId(),'&a=email&m=respondenti_view';
+ }
+ break;
+ case 'rename_respondent_profile':
+ // shranimo podatek
+ self::ajaxRenameProfile();
+ // osvežimo
+ self::getProfileId();
+ self::getProfiles();
+ self::displayProfiles();
+ break;
+ case 'delete_respondent_profile':
+ // pobrišemo
+ self::ajaxDeleteProfile();
+ // osvežimo
+ self::getProfileId();
+ self::getProfiles();
+ self::displayProfiles();
+ break;
+
+
+ default:
+ self::displayProfiles();
+ break;
+ }
+ }
+
+ static function ajaxSaveNewProfile() {
+ global $lang;
+ if ( isset($_POST['name']) && isset($_POST['pid']) ) {
+
+ if ( !isset($_POST['variables']) )
+ self::$messages[] = 'Manjka podatek spremenljivke!';
+ if ( !isset($_POST['data']) )
+ self::$messages[] = 'Polje respondenti je prazno!';
+
+ // shranimo vrednosti
+ $new_name = $_POST['name'];
+ $variables = $_POST['variables'];
+ $stringInsert = "INSERT INTO srv_respondent_profiles (uid, name, variables) VALUES ('".self::getGlobalUserId()."', '".$new_name."', '".$variables."')";
+ $queryInsert = sisplet_query($stringInsert) or die(mysqli_error($GLOBALS['connect_db']));
+ $newId = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($newId > 0) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_respondent_profile', $newId);
+ self::$currentProfileId = $newId;
+
+ // dodamo še podatke (najprej pobrišemo stare če obstajajo)
+ $lines = explode("\n",$_POST['data']);
+ if (count($lines)) {
+ foreach ( $lines as $line ) {
+ $stringInsert = "INSERT INTO srv_respondents (pid, line) VALUES ('".$newId."', '".$line."')";
+ $queryInsert = sisplet_query($stringInsert) or die(mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ } else {
+ self::$errors[] = $lang['srv_respondents_error_create'];
+ }
+ } else {
+ self::$errors[] = $lang['srv_respondents_error_data'];
+ }
+ // posodobimo podatke
+ }
+
+ static function ajaxSaveProfile() {
+
+ if (isset($_POST['pid'])) {
+ $pid = $_POST['pid'];
+ if ($pid == 0) { // imamo profil iz seje
+ //popravimo podatke v seji
+
+ $lines = explode("\n",$_POST['data']);
+ $_SESSION['respondent_profile']['lines'] = $lines;
+
+ $_SESSION['respondent_profile']['variables'] = $_POST['variables'];
+
+ } else {
+ // popravimo podatek za variables v bazi
+ $stringUpdate = "UPDATE srv_respondent_profiles SET variables = '".$_POST['variables']."' WHERE id = '".$pid."'";
+ sisplet_query($stringUpdate);
+
+ // pobrisemo stare zapise (podatke)
+ $stringDelete = "DELETE FROM srv_respondents WHERE pid = '".$pid."'";
+ sisplet_query($stringDelete);
+ // dodamo še podatke
+ $lines = explode("\n",$_POST['data']);
+ if (count($lines)) {
+ foreach ( $lines as $line ) {
+ $stringInsert = "INSERT INTO srv_respondents (pid, line) VALUES ('".$pid."', '".$line."')";
+ $queryInsert = sisplet_query($stringInsert) or die(mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ }
+ }
+ }
+
+ static function ajaxRunProfile() {
+ global $admin_type;
+
+ SurveyInfo::getInstance()->SurveyInit(self::getSurveyId());
+ $db_table = (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) ? '_active' : '';
+
+ // preverimo potrebne sistemske variable
+ // tu je lahko vejica
+ $variables = explode(",",$_POST['variables']);
+ self::checkSystemVariables($variables);
+
+ // poskrbeti moramo za pravilni vrstni red shranjevanja (vrstni red in id-je spremenljivk)
+ $cnt=0;
+ $spremenlivke = array(); // array kam po vrstnem redu shranimo id-je spremenlivk
+ $vrednosti = array(); // poleg IDja spremenljivk potrebujemo tudi ID vrednosti (ker za tip 21 imamo lahko vec text fieldov)
+ foreach ($variables as $variabla) {
+ // za vsako variablo dobimo id spremenlivke
+ if ($variabla != 'pass') {
+ $sqlSpremenlivka = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.variable = '".$variabla."' AND s.gru_id=g.id AND g.ank_id='".self::$surveyId."' ORDER BY g.vrstni_red, s.vrstni_red");
+ $rowSpremenlivka = mysqli_fetch_assoc($sqlSpremenlivka);
+ $spremenlivke[$cnt] = $rowSpremenlivka['id'];
+ $sqlVrednost = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = '$rowSpremenlivka[id]' ORDER BY vrstni_red ASC LIMIT 1");
+ $rowVrednost = mysqli_fetch_array($sqlVrednost);
+ $vrednosti[$cnt] = $rowVrednost['id'];
+ } else {
+ $spremenlivke[$cnt] = -1;
+ $vrednosti[$cnt] = -1;
+ }
+ $cnt++;
+ }
+ $delimiter = $_POST['recipientsDelimiter'];
+
+ $users = mysql_real_unescape_string($_POST['data']);
+ // najprej razdelimo vrstice
+ $vrstice = explode("\n", $users);
+
+ // navadni userji lahko dodajo najvec 20 respondentov
+ if ($admin_type <= 1) {
+ $count = null;
+ } else {
+ $sql = sisplet_query("SELECT COUNT(*) AS count FROM srv_user WHERE ank_id='".self::$surveyId."' AND preview='0'");
+ $row = mysqli_fetch_array($sql);
+ $count = $row['count'];
+ }
+
+ // shranjujemo v session za progress bar
+ session_start();
+ $_SESSION['progressBar'][self::$surveyId]['status'] = 'ok';
+ $_SESSION['progressBar'][self::$surveyId]['total'] = (int)count($vrstice);
+ $_SESSION['progressBar'][self::$surveyId]['current'] = (int)0;
+ session_commit();
+
+ $progressCounter = 0;
+
+ foreach ($vrstice AS $vrstica) {
+
+ if ($count === null || $count < 20) {
+ if ($vrstica != '') {
+
+ // izberemo random hash, ki se ni v bazi
+ do {
+ $rand = md5(mt_rand(1, mt_getrandmax()) . '@' . $_SERVER['REMOTE_ADDR']);
+ $sql = sisplet_query("SELECT id FROM srv_user WHERE SUBSTRING(cookie, 1, 6) = SUBSTRING('".$rand."', 1, 6)");
+ } while (mysqli_num_rows($sql) > 0);
+
+ sisplet_query("INSERT INTO srv_user (ank_id, cookie, pass, last_status, time_insert) VALUES ('".self::$surveyId."', '".$rand."', '".substr($rand, 0, 6)."', '0', NOW())");
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ sisplet_query("INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ('".$usr_id."', '0', NOW(), '" . self::$uId . "')");
+ sisplet_query("INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ('".$usr_id."', '0', '0', NOW())");
+
+ // vrstico razbijemo v data, v $i pa mamo stevec in dodajamo po vrsti v while zanki
+ // pa smo spet pri vejicah ipd.
+
+ $data = explode($delimiter, $vrstica);
+
+ $i = 0;
+ if (count($data) > 0) {
+ foreach ( $data as $value ) {
+ $value = trim($value);
+ if (isset($spremenlivke[$i])) {
+ if ($spremenlivke[$i] > 0) { // sistemska
+ if (!isset($value) || $value == "")
+ $value = -1;
+ sisplet_query("INSERT INTO srv_data_text".$db_table." (spr_id, vre_id, text, usr_id) VALUES ('".$spremenlivke[$i]."', '".$vrednosti[$i]."', '" . trim($value) . "', '".$usr_id."')");
+ } elseif ($spremenlivke[$i] == -1) { // pass - Geslo
+ sisplet_query("UPDATE srv_user SET pass='".strtolower($value)."' WHERE id='$usr_id'");
+ }
+ }
+ $i++;
+ }
+ }
+
+ session_start();
+ $_SESSION['progressBar'][self::$surveyId]['current'] = (int)++$progressCounter;
+ session_commit();
+
+ }
+ }
+ if ($count !== null) $count++;
+ }
+
+ session_start();
+ $_SESSION['progressBar'][self::$surveyId]['status'] = 'end';
+ session_commit();
+
+ }
+
+ static function ajaxRenameProfile() {
+
+ $pid = $_POST['pid'];
+ $name = $_POST['name'];
+
+ if (isset($pid) && $pid > 0 && isset($name) && $name != "") {
+ // popravimo podatek za variables
+ $stringUpdate = "UPDATE srv_respondent_profiles SET name = '".$name."' WHERE id = '".$pid."'";
+ sisplet_query($stringUpdate);
+
+ } else {
+ global $lang;
+ die($lang['srv_respondents_error_data']);
+ }
+ }
+ static function ajaxDeleteProfile() {
+ $pid = $_POST['pid'];
+ if ($pid == 0) {
+ // brišemo session (to lahko samo če imamo še druge profile)
+ unset( $_SESSION['respondent_profile'] );
+ } else if (isset($pid) && $pid > 0) {
+ // pobrišemo vrednosti
+ $stringDelete = "DELETE FROM srv_respondents WHERE pid = '".$pid."'";
+ sisplet_query($stringDelete);
+
+ // pobrišemo profil
+ $stringDelete = "DELETE FROM srv_respondent_profiles WHERE id = '".$pid."'";
+ sisplet_query($stringDelete);
+
+ // nastavimo nov privzet profil
+ $stringSelect = "SELECT id FROM srv_respondent_profiles WHERE uid = '".self::getGlobalUserId()."' ORDER BY id LIMIT 1";
+ $querySelect = sisplet_query($stringSelect);
+ $rowSelect = mysqli_fetch_assoc($querySelect);
+ if ($rowSelect['id'])
+ SurveyUserSetting :: getInstance()->saveSettings('default_respondent_profile', $rowSelect['id']);
+ else
+ SurveyUserSetting :: getInstance()->saveSettings('default_respondent_profile', 0);
+ }
+ }
+}
+?>
diff --git a/admin/survey/classes/class.SurveySession.php b/admin/survey/classes/class.SurveySession.php
new file mode 100644
index 0000000..390c0e2
--- /dev/null
+++ b/admin/survey/classes/class.SurveySession.php
@@ -0,0 +1,180 @@
+<?php
+/** Shranjujemo nastavitve ankete. Za vsako anketo unikatno.
+ *
+ * @author veselicg
+ *
+ */
+
+/** Ker za statičen klas ne moremo narediti destructor funkcije,
+ * si pomagamo s lastno destruktor instanco,
+ * katera pokliče destruct funkcijo našega statičnega razreda
+ *
+ * @author veselicg
+ *
+ */
+class SurveySessionDestructor
+{
+ /** pokličemo destruktor funkcijo
+ *
+ */
+ public function __destruct()
+ {
+ SurveySession::destruct();
+ }
+}
+
+class SurveySession {
+
+ private static $destructorInstance;
+ private static $anketa = null;
+ private static $data = array();
+ private static $updated = false;
+
+
+ static function sessionStart($anketa = null) {
+ if (null === self::$destructorInstance)
+ self::$destructorInstance = new SurveySessionDestructor();
+
+ if ($anketa == null || (int)$anketa == 0 || !is_numeric($anketa))
+ {
+ throw new Exception('Survey ID is mandatory for SurveySession!');
+ }
+ self::$anketa = $anketa;
+
+ # preberemo vse nastavitve za to anketo
+ $sql = sisplet_query("SELECT what,value FROM srv_survey_session WHERE ank_id='".self::$anketa."'");
+ while (list($what,$value) = mysqli_fetch_row($sql))
+ {
+ self::$data[$what] = unserialize($value);
+ }
+ }
+
+ static function get($what=null) {
+ if (self::$anketa == null)
+ {
+ throw new Exception('Survey ID is mandatory for SurveySession!');
+ return null;
+ }
+
+ if ($what == null)
+ {
+ return self::$data;
+ }
+ else if (isset(self::$data[$what]))
+ {
+ return self::$data[$what];
+ }
+ else
+ {
+ return null;
+ }
+ return null;
+ }
+
+ static function set($what,$value) {
+ if (self::$anketa == null)
+ {
+ throw new Exception('Survey ID is mandatory for SurveySession!');
+ return null;
+ }
+ if ($what == null)
+ {
+ throw new Exception('Variable \'what\' is mandatory for SurveySession!');
+ return null;
+ }
+ if (!is_string($what))
+ {
+ throw new Exception('Variable \'what\' must be string!');
+ return null;
+ }
+
+ # če je vse ok setiramo vrednost
+ self::$data[$what] = $value;
+ self::$updated = true;
+
+ return true;
+ }
+
+ static public function remove($what)
+ {
+ if (self::$anketa == null)
+ {
+ throw new Exception('Survey ID is mandatory for SurveySession!');
+ return null;
+ }
+ if ($what == null)
+ {
+ throw new Exception('Variable \'what\' is mandatory for remove()!');
+ return null;
+ }
+ if (!is_string($what))
+ {
+ throw new Exception('Variable \'what\' must be string!');
+ return null;
+ }
+
+ if (isset(self::$data[$what])) {
+ unset (self::$data[$what]);
+
+ #pobrišemo še iz baze
+ $deleteString = "DELETE FROM srv_survey_session WHERE ank_id = '".self::$anketa."' AND what='$what'";
+ $query = sisplet_query($deleteString);
+ self::$updated = true;
+ }
+ return null;
+ }
+
+ /** ob ukinitvi klassa shranimo vse vrednosti
+ *
+ */
+ static public function destruct()
+ {
+ if (self::$anketa == null)
+ {
+ throw new Exception('Survey ID is mandatory for SurveySession!');
+ return null;
+ }
+
+ // v destructu več nimamo connect_db resoursa
+ global $connect_db;
+ if ($connect_db == null) {
+ // poizkusimo še 1x
+ global $mysql_server, $mysql_username, $mysql_password, $mysql_database_name;
+ if (!$connect_db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database_name)) {
+ die ('Please try again later [ERR: DB])');
+ }
+ }
+
+ # pripravimo string za shranjevanje
+ if (count(self::$data) > 0 && self::$updated) {
+ $insertStringArray = array();
+ foreach (self::$data AS $what => $value) {
+ $insertStringArray[] = "('".self::$anketa."', '".$what."', '".serialize($value)."')";
+ }
+ $insertString = "INSERT INTO srv_survey_session (ank_id,what,value) VALUES ".implode(', ',$insertStringArray);
+ $insertString .=" ON DUPLICATE KEY UPDATE value = VALUES(value)";
+ $query = sisplet_query($insertString, $connect_db);
+ }
+ }
+
+ static function append($where,$what,$value)
+ {
+ if (self::$anketa == null)
+ {
+ throw new Exception('Survey ID is mandatory for SurveySession!');
+ return null;
+ }
+ if ($what == null)
+ {
+ throw new Exception('Variable \'what\' is mandatory for remove()!');
+ return null;
+ }
+ if (!is_string($what))
+ {
+ throw new Exception('Variable \'what\' must be string!');
+ return null;
+ }
+ self::$updated = true;
+ self::$data[$where][$what] = $value;
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveySetting.php b/admin/survey/classes/class.SurveySetting.php
new file mode 100644
index 0000000..21198aa
--- /dev/null
+++ b/admin/survey/classes/class.SurveySetting.php
@@ -0,0 +1,132 @@
+<?php
+/*
+ * Created on 2.6.2009
+ *
+ */
+
+class SurveySetting
+{
+ static private $instance;
+
+
+ // SurveyId
+ static private $sid = null;
+
+ static private $mySqlResult = null;
+ static private $mySqlErrNo = null;
+
+ // konstrutor
+ protected function __construct() {}
+ // kloniranje
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveySetting();
+ }
+ return self::$instance;
+ }
+
+ /** inicializacija */
+
+ static function Init( $_surveyId = null)
+ {
+ if ( $_surveyId )
+ { self::$sid = $_surveyId; }
+ }
+
+ // nastavimo nov Survey Id
+ static function setSID( $_surveyId = null )
+ {
+ if ( $_surveyId )
+ { self::$sid = $_surveyId; }
+ }
+
+
+ /**
+ * @desc polovimo nastavitev za posamezno anketo če obstaja,
+ * če ne uporabimo nastavitev sistema
+ */
+ private $getSurveyMiscSetting = array();
+ function getSurveyMiscSetting($what=null)
+ {
+ # če že imamo polovljene nastavitve iz baze jih vrnemo direkt
+ if (isset($this->getSurveyMiscSetting[$what])) {
+ return $this->getSurveyMiscSetting[$what];
+ }
+
+ if (is_string($what))
+ {
+ $stringSelect = "SELECT value FROM srv_survey_misc WHERE sid='".self::$sid ."' AND what = '".$what."'";
+ $sqlSelect = sisplet_query($stringSelect);
+ if (mysqli_num_rows($sqlSelect) > 0)
+ {
+ $rowSelect = mysqli_fetch_assoc($sqlSelect);
+ $result = $rowSelect['value'];
+ }
+ else
+ {
+ global $site_path;
+ //require_once($site_path.'admin/survey/classes/class.Setting.php');
+ Setting::getInstance()->Init();
+ $result = Setting::getInstance()->getSysMiscSetting($what);
+ }
+ }
+
+ $this->getSurveyMiscSetting[$what] = $result;
+ return $this->getSurveyMiscSetting[$what];
+ }
+ /**
+ * @desc shranimo nastavitev survey sistema
+ */
+ function setSurveyMiscSetting($what=null, $value=null)
+ {
+ if (self::$sid ) // rabimo sid
+ {
+ if ( $what ) // pustimo, da je value 0 ali prazen
+ {
+ if ( is_string($what) )
+ {
+ $stringInsert = "INSERT INTO srv_survey_misc (sid, what, value) VALUES ('".self::$sid."', '".$what."', '".$value."') ON DUPLICATE KEY UPDATE value = '".$value."'";
+ $sqlInsert = sisplet_query($stringInsert);
+ sisplet_query("COMMIT");
+ return mysqli_affected_rows($GLOBALS['connect_db']);
+ }
+ else
+ return false;
+ }
+ else
+ return false;
+
+ }
+ else
+ return false;
+ }
+
+ function removeSurveyMiscSetting ($what = null) {
+
+ if (self::$sid) { // rabimo sid
+
+ if ( $what ) { // pustimo, da je value 0 ali prazen
+
+ if ( is_string($what) ) {
+
+ $stringInsert = "DELETE FROM srv_survey_misc WHERE sid = '".self::$sid."' AND what = '".$what."'";
+ $sqlInsert = sisplet_query($stringInsert);
+ return mysqli_affected_rows($GLOBALS['connect_db']);
+
+ }
+ }
+ }
+
+ return false;
+
+ }
+}
+
+?>
diff --git a/admin/survey/classes/class.SurveySkupine.php b/admin/survey/classes/class.SurveySkupine.php
new file mode 100644
index 0000000..b559adc
--- /dev/null
+++ b/admin/survey/classes/class.SurveySkupine.php
@@ -0,0 +1,462 @@
+<?php
+/**
+* @author Peter Hrvatin
+* @date November 2013
+*
+*/
+
+
+class SurveySkupine {
+
+ public $anketa; # id ankete
+ public $folder = ''; # pot do folderja
+
+ public $uid; # id userja
+
+
+ /**
+ * Konstruktor
+ *
+ * @param int $anketa
+ */
+ function __construct( $anketa = null ) {
+ global $global_user_id, $site_path;
+
+ $this->folder = $site_path . EXPORT_FOLDER.'/';
+
+ // če je podan anketa ID
+ if ((int)$anketa > 0) {
+
+ $this->anketa = $anketa;
+ }
+ else {
+ die("Napaka!");
+ }
+
+ if ( SurveyInfo::getInstance()->SurveyInit($this->anketa)) {
+ $this->uid = $global_user_id;
+ SurveyUserSetting::getInstance()->Init($this->anketa, $this->uid);
+ }
+ }
+
+ function displayEdit(){
+ global $global_user_id;
+ global $lang;
+ global $site_url;
+
+ // Ce je vklopljen evoli team meter se ne sme tukaj urejat skupin (ker se belezijo v dodatno bazo srv_evoli_teammeter z dodatnimi parametri)
+ if(SurveyInfo::getInstance()->checkSurveyModule('evoli_teammeter')
+ || SurveyInfo::getInstance()->checkSurveyModule('evoli_quality_climate')
+ || SurveyInfo::getInstance()->checkSurveyModule('evoli_teamship_meter')
+ || SurveyInfo::getInstance()->checkSurveyModule('evoli_organizational_employeeship_meter')
+ ){
+
+ echo '<fieldset><legend>'.$lang['srv_skupine'].'</legend>';
+ echo '<p class="bold red">Urejanje skupin ni mogoče, ker je vklopljen modul za Evoli!</p>';
+ echo '</fieldset>';
+
+ return;
+ }
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $spr_id = $this->hasSkupine();
+ echo '<input type="hidden" id="skupine_spr_id" value="'.$spr_id.'"></input>';
+
+ echo '<fieldset><legend>'.$lang['srv_skupine'].'</legend>';
+ echo '<div id="skupine">';
+
+ echo '<br />'.$lang['srv_skupine_insert'].' '.Help::display('srv_skupine');
+
+ if($spr_id != 0){
+
+ // dodajanje skupin za anketo
+ $vrednosti = $this->getVrednosti($spr_id);
+ foreach($vrednosti as $vrednost){
+ echo '<p>';
+
+ echo '<strong>'.$vrednost['naslov'].'</strong>';
+
+ $link = $vrednost['url'];
+ if(isset($vrednost['nice_url']))
+ $link = $vrednost['nice_url'];
+ echo ' (<a href="'.$link.'" target="_blank" title="URL skupine '.$vrednost['naslov'].'">'.$link.'</a>)';
+
+ echo '<span class="faicon delete_circle icon-orange_link spaceLeft" style="margin-bottom:1px;" onclick="delete_skupina(\'1\', \''.$vrednost['id'].'\', \''.$vrednost['naslov'].'\');"></span>';
+
+ echo '</p>';
+ }
+ }
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik - ce ni ni gumba za dodajanje skupin
+ if(!$userAccess->checkUserAccess($what='skupine')){
+ echo '<br />';
+ $userAccess->displayNoAccess($what='skupine');
+ }
+ else{
+ echo '<p class="add_skupina_button"><input type="text" name="skupina" autocomplete="off" onKeyUp="add_skupina_enter(\'1\', event);" /> <input type="button" value="'.$lang['add'].'" onclick="add_skupina(\'1\');" /></p>';
+ }
+
+ echo '</div>';
+ echo '</fieldset>';
+ }
+
+ /*
+ * Vrne id spremenljivke ce obstaja skupina
+ * param $skupine -> 1 navadne skupine, 2 -> password skupine
+ */
+ function hasSkupine($skupine=1){
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT s.id AS id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa' AND s.skupine='$skupine'");
+
+ if(mysqli_num_rows($sql) > 0){
+ $row = mysqli_fetch_array($sql);
+ return $row['id'];
+ }
+ else
+ return 0;
+ }
+
+ function getVrednosti($spr_id){
+ global $global_user_id;
+ global $site_url;
+
+ $link = SurveyInfo::getSurveyLink();
+ $vrednosti = array();
+
+ $sqlS = sisplet_query("SELECT variable FROM srv_spremenljivka WHERE id='$spr_id'");
+ $rowS = mysqli_fetch_array($sqlS);
+ $variable = $rowS['variable'];
+
+ // Preverimo ce imamo lep url
+ $sql2 = sisplet_query("SELECT id FROM srv_nice_links WHERE ank_id='$this->anketa'");
+
+ $sql = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id='$spr_id'");
+ if(mysqli_num_rows($sql) > 0){
+
+ $cnt = 0;
+ while($row = mysqli_fetch_array($sql)){
+ $vrednosti[$cnt] = $row;
+ $vrednosti[$cnt]['url'] = $link.'?'.$variable.'='.$row['id'];
+
+ // Ce imamo nice url za skupine ga tudi shranimo
+ if(mysqli_num_rows($sql2) > 0){
+
+ $sql3 = sisplet_query("SELECT link fROM srv_nice_links_skupine WHERE ank_id='$this->anketa' AND vre_id='$row[id]'");
+ if(mysqli_num_rows($sql3) > 0){
+ $row3 = mysqli_fetch_array($sql3);
+ $vrednosti[$cnt]['nice_url'] = $site_url.$row3['link'];
+ }
+ }
+
+ $cnt++;
+ }
+
+ return $vrednosti;
+ }
+ else
+ return 0;
+ }
+
+ // Vrnemo url za doloceno skupino
+ function getUrl($spr_id, $vre_id){
+ global $global_user_id;
+ global $site_url;
+
+ $link = SurveyInfo::getSurveyLink();
+
+ $sqlS = sisplet_query("SELECT variable FROM srv_spremenljivka WHERE id='$spr_id'");
+ $rowS = mysqli_fetch_array($sqlS);
+ $variable = $rowS['variable'];
+
+ $sql = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id='$spr_id' AND id='$vre_id'");
+ if(mysqli_num_rows($sql) > 0){
+
+ $row = mysqli_fetch_array($sql);
+ $url = $link.'?'.$variable.'='.$row['id'];
+
+ // Ce imamo nice url za skupine ga tudi shranimo
+ $sql2 = sisplet_query("SELECT id FROM srv_nice_links WHERE ank_id='$this->anketa'");
+ if(mysqli_num_rows($sql2) > 0){
+
+ $sql3 = sisplet_query("SELECT link fROM srv_nice_links_skupine WHERE ank_id='$this->anketa' AND vre_id='$row[id]'");
+ if(mysqli_num_rows($sql3) > 0){
+ $row3 = mysqli_fetch_array($sql3);
+ $url = $site_url.$row3['link'];
+ }
+ }
+
+ return $url;
+ }
+ else
+ return '';
+ }
+
+
+ /** Funkcije ki skrbijo za ajax del
+ *
+ */
+ public function ajax() {
+ global $global_user_id;
+ global $lang;
+ global $site_path;
+
+ if (isset ($_POST['anketa'])) {
+ $anketa = $_POST['anketa'];
+ $this->anketa = $_POST['anketa'];
+ }
+
+ $spr_id = (isset($_POST['spr_id'])) ? $_POST['spr_id'] : 0;
+
+
+ if ($_GET['a'] == 'add_skupina') {
+
+ $skupine = (isset($_POST['skupine'])) ? $_POST['skupine'] : 1;
+ $variable = ($skupine == 2) ? 'password' : strtolower($lang['srv_skupina']);
+ $naslov = ($skupine == 2) ? 'Password' : $lang['srv_skupina'];
+ $naslov_vrednost = (isset($_POST['text'])) ? $_POST['text'] : '';
+
+ if($naslov_vrednost != ''){
+
+ // Dodatno preverimo ce sigurno nimamo skupine
+ if($spr_id == 0){
+ $spr_id = $this->hasSkupine($skupine);
+ }
+
+ // Na zacetku moramo ustvarit najprej vprasanje
+ if($spr_id == 0){
+
+ $sqlG = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='$this->anketa' AND vrstni_red='1'");
+ $rowG = mysqli_fetch_array($sqlG);
+ $gru_id = $rowG['id'];
+
+ $b = new Branching($this->anketa);
+ $spr_id = $b->nova_spremenljivka($grupa=$gru_id, $grupa_vrstni_red=1, $vrstni_red=0);
+
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET naslov='$naslov', variable='$variable', variable_custom='1', skupine='$skupine', sistem='1', visible='0', size='0' WHERE id='$spr_id'");
+
+ Vprasanje::change_tip($spr_id, 1);
+ }
+
+
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $spr_id;
+ $vre_id = $v->vrednost_new($naslov_vrednost);
+
+
+ // Ce gre za password ga dodamo
+ if($skupine == 2){
+ $s = sisplet_query("REPLACE INTO srv_password (ank_id, password) VALUES ('$this->anketa', '$naslov_vrednost')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+
+ // Preverimo ce imamo nice URL -> dodamo dodatnega za skupine
+ $sql = sisplet_query("SELECT id, link FROM srv_nice_links WHERE ank_id='$this->anketa'");
+ if($skupine == 1 && mysqli_num_rows($sql) > 0){
+
+ Common::updateEditStamp();
+
+ $row = mysqli_fetch_array($sql);
+
+ $add = false;
+
+ $anketa = $this->anketa;
+ $nice_url = $row['link'];
+
+ $sql2 = sisplet_query("SELECT vrstni_red FROM srv_vrednost WHERE id='$vre_id'");
+ $row2 = mysqli_fetch_array($sql2);
+ $nice_url .= '_'.$row2['vrstni_red'];
+
+ $f = @fopen($site_path.'.htaccess', 'rb');
+ if ($f !== false) {
+ $add = true;
+ while (!feof($f)) {
+ $r = fgets($f);
+ if (strpos($r, "^".$nice_url.'\b') !== false) { // preverimo, da ni tak redirect ze dodan
+ $add = false;
+ }
+ }
+ fclose($f);
+ }
+
+ if (strlen($nice_url) < 3) $add = false;
+
+ if (SurveyInfo::getInstance()->checkSurveyModule('uporabnost'))
+ $link = 'main/survey/uporabnost.php?anketa='.$anketa.'&skupina='.$vre_id;
+ else
+ $link = 'main/survey/index.php?anketa='.$anketa.'&skupina='.$vre_id;
+
+ if ($add) {
+ $f = @fopen($site_path.'.htaccess', 'a');
+ if ($f !== false) {
+ fwrite($f, "\nRewriteRule ^".$nice_url.'\b(.*) '.$link."&foo=\$1&%{QUERY_STRING}");
+ fclose($f);
+
+ $sqlI = sisplet_query("INSERT INTO srv_nice_links_skupine (id,ank_id,nice_link_id,vre_id,link) VALUES ('','$this->anketa','$row[id]','$vre_id','$nice_url')");
+ }
+ }
+ }
+
+
+ // Vrnemo novo geslo, ki ga vstavimo v html
+ echo '<p>';
+
+ echo '<strong>'.$naslov_vrednost.'</strong>';
+ if($skupine == 1){
+ $link = $this->getUrl($spr_id, $vre_id);
+ echo ' (<a href="'.$link.'" target="_blank" title="URL skupine '.$naslov_vrednost.'">'.$link.'</a>)';
+ }
+
+ echo '<span class="faicon delete_circle icon-orange_link spaceLeft" style="margin-bottom:1px;" onclick="delete_skupina(\''.$skupine.'\', \''.$vre_id.'\', \''.$naslov_vrednost.'\');"></span>';
+
+ echo '</p>';
+ }
+ }
+
+ if ($_GET['a'] == 'delete_skupina') {
+
+ $skupine = (isset($_POST['skupine'])) ? $_POST['skupine'] : 1;
+ $vre_id = (isset($_POST['vre_id'])) ? $_POST['vre_id'] : 0;
+ $naslov = (isset($_POST['text'])) ? $_POST['text'] : '';
+
+ $sql2 = sisplet_query("SELECT vrstni_red FROM srv_vrednost WHERE id='$vre_id'");
+ $row2 = mysqli_fetch_array($sql2);
+ $index = $row2['vrstni_red'];
+
+ if($spr_id > 0){
+ $sql = sisplet_query("DELETE FROM srv_vrednost WHERE id='$vre_id' AND spr_id='$spr_id'");
+
+ // Ce smo pobrisali zadnjo vrednost pobrisemo tudi spremenljivko
+ $sql2 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$spr_id'");
+ if(mysqli_num_rows($sql2) == 0){
+ $sql3 = sisplet_query("DELETE FROM srv_spremenljivka WHERE id='$spr_id'");
+ }
+ }
+
+ // Ce gre za password ga zbrisemo
+ if($skupine == 2){
+ $password = $_POST['text'];
+ if ($password != '') {
+ $s = sisplet_query("DELETE FROM srv_password WHERE ank_id='$this->anketa' AND password = '$password'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ // Preverimo ce imamo nice URL -> pobrisemo dodatnega za skupine
+ $sql = sisplet_query("SELECT id, link FROM srv_nice_links WHERE ank_id='$this->anketa'");
+ if($skupine == 1 && mysqli_num_rows($sql) > 0){
+
+ Common::updateEditStamp();
+
+ $row = mysqli_fetch_array($sql);
+
+ $anketa = $this->anketa;
+ $nice_url = $row['link'].'_'.$index;
+
+ $f = fopen($site_path.'.htaccess', 'rb');
+ if ($f !== false) {
+ $output = array();
+ while (!feof($f)) {
+ $r = fgets($f);
+ if (strpos($r, "^".$nice_url.'\b(.*) ') !== false && strpos($r, "?anketa=".$anketa."&skupina=".$vre_id."") !== false) {
+ // kao pobrisemo vrstico in vnos v bazi
+ $sqlD = sisplet_query("DELETE FROM srv_nice_links_skupine WHERE ank_id='$anketa' AND nice_link_id='$row[id]' AND vre_id='$vre_id'");
+ }
+ else {
+ $output[] = $r;
+ }
+ }
+ fclose($f);
+ }
+
+ if (count($output) > 0) {
+
+ $f = fopen($site_path.'.htaccess', 'w');
+ if ($f !== false) {
+ foreach ($output AS $line) {
+ fwrite($f, $line);
+ }
+ fclose($f);
+ }
+ }
+ }
+ }
+
+
+ // Popup za masovno dodajanje gesel
+ if ($_GET['a'] == 'show_add_password_mass') {
+
+ // Naslov
+ echo '<h2>' . $lang['srv_password_add_mass'] . '</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="popupImportAnketaFromText_close();">✕</a></div>';
+
+ echo '<p class="bold">' . $lang['srv_password_add_mass_instructions'] . '</p>';
+ //echo '<span class="italic">' . $lang['srv_password_add_mass_sample'] . '</span></p>';
+
+ echo '<textarea id="add_passwords_mass" name="add_passwords_mass" style="width:99%; height:300px; box-sizing:border-box; padding:5px;"></textarea>';
+
+ echo '<br /><br />';
+
+ echo '<span class="buttonwrapper floatRight"><a class="ovalbutton ovalbutton_orange" href="#" onClick="execute_add_passwords_mass();">'.$lang['srv_password_add_mass_execute'].'</a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight"><a class="ovalbutton ovalbutton_gray" href="#" onClick="popupImportAnketaFromText_close();">'.$lang['srv_zapri'].'</a></span>';
+ }
+
+ // Masovno dodajanje gesel
+ if ($_GET['a'] == 'add_password_mass') {
+
+ $skupine = 2;
+ $variable = 'password';
+ $naslov = 'Password';
+
+ $passwords = (isset($_POST['passwords'])) ? $_POST['passwords'] : '';
+
+ if($passwords != ''){
+
+ // Dodatno preverimo ce sigurno nimamo skupine
+ if($spr_id == 0){
+ $spr_id = $this->hasSkupine($skupine);
+ }
+
+ // Na zacetku moramo ustvarit najprej vprasanje
+ if($spr_id == 0){
+
+ $sqlG = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='$this->anketa' AND vrstni_red='1'");
+ $rowG = mysqli_fetch_array($sqlG);
+ $gru_id = $rowG['id'];
+
+ $b = new Branching($this->anketa);
+ $spr_id = $b->nova_spremenljivka($grupa=$gru_id, $grupa_vrstni_red=1, $vrstni_red=0);
+
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET naslov='$naslov', variable='$variable', variable_custom='1', skupine='$skupine', sistem='1', visible='0', size='0' WHERE id='$spr_id'");
+
+ Vprasanje::change_tip($spr_id, 1);
+ }
+
+
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $spr_id;
+
+
+ // Loop cez vsa gesla po vrsticah in jih dodamo
+ $passwords_array = explode("\\n", $passwords);
+ foreach($passwords_array as $password){
+
+ // Pocistimo vec presledkov in line breakov
+ $password = trim($password);
+ $password = preg_replace('/\s+/', ' ', $password);
+
+ if($password != ''){
+ $vre_id = $v->vrednost_new($password);
+
+ $s = sisplet_query("REPLACE INTO srv_password (ank_id, password) VALUES ('$this->anketa', '$password')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyStaticHtml.php b/admin/survey/classes/class.SurveyStaticHtml.php
new file mode 100644
index 0000000..744d81f
--- /dev/null
+++ b/admin/survey/classes/class.SurveyStaticHtml.php
@@ -0,0 +1,1247 @@
+<?php
+
+/** Pomožen class
+ *
+ * Enter description here ...
+ * @author veselicg
+ *
+ */
+class SurveyStaticHtml
+{
+ private $sid = null;
+
+
+ public function __construct($anketa){
+ global $global_user_id;
+
+ $this->sid = $anketa;
+
+ SurveyUserSetting:: getInstance()->Init($anketa, $global_user_id);
+ }
+
+
+ # Nastavitve multicrosstab tabele
+ public function displayMulticrosstabSettings(){
+ global $lang;
+ global $global_user_id;
+
+ $this->table_id = SurveyUserSetting:: getInstance()->getSettings('default_mc_table');
+
+ if (isset($this->table_id) && $this->table_id != '')
+ $sql = sisplet_query("SELECT name FROM srv_mc_table WHERE id='$this->table_id' AND ank_id='$this->sid' AND usr_id='$global_user_id'");
+ else
+ $sql = sisplet_query("SELECT name FROM srv_mc_table WHERE ank_id='$this->sid' AND usr_id='$global_user_id' ORDER BY time_created ASC");
+ $row = mysqli_fetch_array($sql);
+
+ echo '<div class="mc_settings_links">';
+ echo '<ul>';
+
+ // Izbiro tabele (popup) in dodajanje
+ echo '<li>';
+ echo '<span onClick="show_mc_tables();">' . $lang['srv_table'] . ': <span class="bold">' . $row['name'] . '</span></span>';
+ echo '<span id="mc_tables_plus" class="pointer spaceLeft faicon add icon-blue" title="' . $lang['srv_multicrosstabs_tables_add'] . '"></span></span>';
+ echo '</li>';
+
+ echo '<li class="space">&nbsp;</li>';
+
+ // Nastavitve tabele (popup)
+ echo '<li>';
+ echo '<span class="gray" onClick="showMCSettings();">' . $lang['srv_multicrosstabs_settings'] . '</span>';
+ echo '</li>';
+
+ echo '</ul>';
+ echo '</div>';
+ }
+
+ function displayAnalizaPreview()
+ {
+ global $lang;
+ echo '<div id="srv_analiza_preview_div" class="displayNone;">';
+ echo '<div class="top-left"></div>';
+ echo '<div class="top-right"></div>';
+ echo '<div class="inside">';
+
+ echo '<div id="srv_analiza_preview_sub_1" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_1'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledSumarnik.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_1
+
+ echo '<div id="srv_analiza_preview_sub_2" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_2'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledOpisne.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_2
+
+ echo '<div id="srv_analiza_preview_sub_3" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_3'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledFrekvence.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_3
+
+ echo '<div id="srv_analiza_preview_sub_4" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_4'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledTabele.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_4
+
+ echo '<div id="srv_analiza_preview_sub_5" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_5'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledPovprecja.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_5
+
+
+ echo '<div id="srv_analiza_preview_sub_6" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_6'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledTTest.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_6
+
+ echo '<div id="srv_analiza_preview_sub_7" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_7'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledRazbitje.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_7
+
+ echo '<div id="srv_analiza_preview_sub_8" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_8'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledMultitabele.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_8
+
+ echo '<div id="srv_analiza_preview_sub_9" class="srv_analiza_preview_sub hidden">';
+ echo '<span class="red">' . $lang['srv_analize_preview_sample_choose'] . '</span><br/>';
+ echo '<div id="srv_preview_analiza">';
+ echo '<span class="large">' . $lang['srv_analize_preview_sample'] . '</span>';
+ echo '<span class="large">' . $lang['srv_analize_preview_9'] . '</span>';
+ echo $lang['srv_analysys_perview_sample'];
+ include 'staticHtml/AnalizaPredogledNeodgovori.html';
+ echo '</div>'; //srv_preview_analiza
+ echo '</div>'; //srv_analiza_preview_sub_9
+
+ echo '</div>'; // inside
+ echo '<div class="bottom-left"></div>';
+ echo '<div class="bottom-right"></div>';
+ echo '</div>'; // srv_analiza_preview_div
+ }
+
+ public function displayArchiveNavigation($showDiv = true)
+ {
+ global $lang, $admin_type, $global_user_id;
+
+ $d = new Dostop();
+
+ $sa = new SurveyAdmin();
+ $this->survey_type = $sa->getSurvey_type($this->sid);
+
+ echo '<div id="globalSetingsLinks" class="archive">';
+ echo '<ul class="">';
+
+ # arhivi vprasalnika
+ if ($d->checkDostopSub('edit')) {
+ echo '<li' . ($_GET['a'] == A_ARHIVI && $_GET['m'] != 'data' && $_GET['m'] != 'changes' && $_GET['m'] != 'survey' && $_GET['m'] != 'survey_data' && $_GET['m'] != 'testdata' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . $_js_links[1] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ARHIVI . '" title="' . $lang['srv_questionnaire_archives'] . '"><span>' . $lang['srv_questionnaire_archives'] . '</span></a>';
+ echo '</li>';
+ }
+
+ # arhivi podatkov
+ if ($d->checkDostopSub('edit') && $this->survey_type > 0) {
+ echo '<li' . ($_GET['a'] == A_ARHIVI && $_GET['m'] == 'data' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . $_js_links[1] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ARHIVI . '&m=data" title="' . $lang['srv_arhiv_data'] . '"><span>' . $lang['srv_arhiv_data'] . '</span></a>';
+ echo '</li>';
+ }
+
+ # arhivi objave
+ if ($d->checkDostopSub('publish')) {
+ echo '<li' . ($_GET['a'] == A_INVITATIONS && $_GET['m'] == 'view_archive' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . $_js_links[2] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_INVITATIONS . '&m=view_archive' . '" title="' . $lang['srv_archive_invitation'] . '"><span>' . $lang['srv_archive_invitation'] . '</span></a>';
+ echo '</li>';
+ }
+
+ # arhivi analiz
+ if ($d->checkDostopSub('analyse')) {
+ echo '<li' . ($_GET['a'] == A_ANALYSIS && $_GET['m'] == M_ANALYSIS_ARCHIVE ? ' class="highlightLineTab"' : ' class="nonhighlight"') . $_js_links[3] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_ARCHIVE . '" title="' . $lang['srv_archive_analysis'] . '"><span>' . $lang['srv_archive_analysis'] . '</span></a>';
+ echo '</li>';
+ }
+
+ # uvoz/izvoz ankete ali ankete s podatki
+ if ($d->checkDostopSub('edit')) {
+ echo '<li' . ($_GET['a'] == A_ARHIVI && ($_GET['m'] == 'survey' || $_GET['m'] == 'survey_data') ? ' class="navi_tracking highlightLineTab"' : ' class="navi_tracking nonhighlight"') . $_js_links[1] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ARHIVI . '&m=survey" title="' . $lang['srv_survey_archives'] . '"><span>' . $lang['srv_survey_archives'] . '</span></a>';
+ echo '</li>';
+
+ if ($_GET['a'] == A_ARHIVI && ($_GET['m'] == 'survey' || $_GET['m'] == 'survey_data')) {
+ echo '<ul id="sub_navi_tracking">';
+
+ // Uvoz/izvoz ankete
+ echo '<li ' . ($_GET['a'] == A_ARHIVI && $_GET['m'] == 'survey' && $_GET['appendMerge'] != '1' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ARHIVI . '&m=survey" title="' . $lang['srv_survey_archives_ie'] . '"><span>' . $lang['srv_survey_archives_ie'] . '</span></a>';
+ echo '</li>';
+
+ // Uvoz/izvoz ankete in podatkov
+ echo '<li ' . ($_GET['a'] == A_ARHIVI && $_GET['m'] == 'survey_data' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ARHIVI . '&m=survey_data" title="' . $lang['srv_survey_archives_ie_data'] . '"><span>' . $lang['srv_survey_archives_ie_data'] . '</span></a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+ }
+
+ # arhivi testnih vnosov
+ if ($this->survey_type > 1) {
+ $str_testdata = "SELECT count(*) FROM srv_user WHERE ank_id='" . $this->sid . "' AND (testdata='1' OR testdata='2') AND deleted='0'";
+ $query_testdata = sisplet_query($str_testdata);
+ list($testdata) = mysqli_fetch_row($query_testdata);
+ if ((int)$testdata > 0) {
+ echo '<li' . ($_GET['a'] == A_ARHIVI && $_GET['m'] == 'testdata' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ARHIVI . '&m=testdata" title="' . $lang['srv_arhiv_testdata'] . '"><span>' . $lang['srv_arhiv_testdata'] . '</span></a>';
+ echo '</li>';
+ }
+ }
+
+ # arhivi sprememb
+ if ($d->checkDostopSub('edit')) {
+ echo '<li' . ($_GET['a'] == A_TRACKING || $_GET['a'] == A_TRACKING_HIERARHIJA ? ' class="navi_tracking highlightLineTab"' : ' class="navi_tracking nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_TRACKING . '" title="' . $lang['srv_survey_archives_tracking'] . '"><span>' . $lang['srv_survey_archives_tracking'] . '</span></a>';
+ echo '</li>';
+
+ if ($_GET['a'] == A_TRACKING || $_GET['a'] == A_TRACKING_HIERARHIJA) {
+ echo '<ul id="sub_navi_tracking">';
+
+ // Vse spremembe ankete
+ echo '<li ' . ($_GET['a'] == A_TRACKING && $_GET['m'] != 'tracking_data' && $_GET['appendMerge'] != '1' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_TRACKING . '" title="' . $lang['srv_survey_archives_tracking_survey'] . '"><span>' . $lang['srv_survey_archives_tracking_survey'] . '</span></a>';
+ echo '</li>';
+
+ $hierarhija = false;
+ if (SurveyInfo::getInstance()->checkSurveyModule('hierarhija')) {
+ $uporabnik = sisplet_query("SELECT type FROM srv_hierarhija_users WHERE anketa_id='".$this->sid."' AND user_id='".$global_user_id."'", "obj");
+ if (!empty($uporabnik) && $uporabnik->type == 1)
+ $hierarhija = true;
+ }
+
+ if ($hierarhija) {
+
+ // Vsi podatki o gradnji hierarhije, šifrantov in ostalega
+ echo '<li ' . ($_GET['a'] == A_TRACKING_HIERARHIJA && $_GET['m'] == 'hierarhija' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_TRACKING_HIERARHIJA. '&m=hierarhija" title="' . $lang['srv_survey_archives_tracking_hierarchy_structure'] . '"><span>' . $lang['srv_survey_archives_tracking_hierarchy_structure'] . '</span></a>';
+ echo '</li>';
+
+ // Vse spremembe pri dodajanju udeležencev
+ echo '<li ' . ($_GET['a'] == A_TRACKING_HIERARHIJA && $_GET['m'] == 'udelezenci' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_TRACKING_HIERARHIJA . '&m=udelezenci" title="' . $lang['srv_survey_archives_tracking_hierarchy_users'] . '"><span>' . $lang['srv_survey_archives_tracking_hierarchy_users'] . '</span></a>';
+ echo '</li>';
+ }
+
+ // Spremembe na podatkih
+ echo '<li ' . ($_GET['a'] == A_TRACKING && $_GET['m'] == 'tracking_data' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_TRACKING . '&m=tracking_data" title="' . $lang['srv_survey_archives_tracking_data'] . '"><span>' . $lang['srv_survey_archives_tracking_data'] . '</span></a>';
+ echo '</li>';
+
+ // Append/Merge (uvozi)
+ echo '<li ' . ($_GET['a'] == A_TRACKING && $_GET['appendMerge'] == '1' ? ' class="highlightLineTab"' : ' class="nonhighlight"') . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_TRACKING . '&appendMerge=1" title="' . $lang['srv_survey_archives_tracking_append'] . '"><span>' . $lang['srv_survey_archives_tracking_append'] . '</span></a>';
+ echo '</li>';
+
+ echo '</ul>';
+ }
+ }
+
+
+
+ echo '</ul>';
+ echo '</div>';
+ }
+
+ public function displayTestDataBar($showAnalizeCheckbox = false)
+ {
+ global $lang;
+
+
+ $str_testdata = "SELECT count(*) FROM srv_user WHERE ank_id='" . $this->sid . "' AND (testdata='1' OR testdata='2') AND deleted='0'";
+ $query_testdata = sisplet_query($str_testdata);
+ list($testdata) = mysqli_fetch_row($query_testdata);
+
+ $str_autogen_testdata = "SELECT count(*) FROM srv_user WHERE ank_id='" . $this->sid . "' AND testdata='2' AND deleted='0'";
+ $query_autogen_testdata = sisplet_query($str_autogen_testdata);
+ list($autogen_testdata) = mysqli_fetch_row($query_autogen_testdata);
+
+ echo '<div class="display_data_test_data_note"><span class="faicon warning icon-orange spaceRight"></span> ';
+
+ echo $lang['srv_testni_podatki_alert'] . ' <a href="#" onClick="delete_test_data();">' . $lang['srv_delete_testdata'] . '</a>';
+ echo ' (' . $testdata . '). ';
+ if ($autogen_testdata > 0) {
+ echo $lang['srv_autogen_testni_podatki_alert'] . ' <a href="index.php?anketa=' . $this->sid . '&a=testiranje&m=testnipodatki&delete_autogen_testdata=1">' . $lang['srv_delete_autogen_testdata'] . '</a>';
+ echo ' (' . $autogen_testdata . '). ';
+ }
+
+ if ($showAnalizeCheckbox == true && false) {
+ # print_r("<pre>");
+ # print_r($_SESSION);
+ session_start();
+ $checked = (isset($_SESSION['testData'][$this->sid]['includeTestData']) && $_SESSION['testData'][$this->sid]['includeTestData'] == 'false') ? '' : ' checked="checked"';
+ echo '&nbsp;<label><input id="cnx_include_test_data" type="checkbox"' . $checked . ' onchange="surveyAnalisysIncludeTestData();" autocomplete="off">V analizah upoštevaj tudi testne vnose.';
+ echo '</label>';
+ session_commit();
+ }
+ echo '</div>';
+ }
+
+
+ /* Nastavitve na vrhu pri analizah in podatkih - NOVO
+ * Podstrani: data, export, quick_edit, variables
+ sumarnik, descriptor, frequency, crosstabs, ttest, means, nonresponses,
+ charts,
+ analysis_creport, analysis_links
+ ocena_trajanja, dejanski_casi,
+ komentarji, komentarji_anketa,
+ status,
+ tema, theme_editor
+ */
+ public function displayTopSettings($podstran){
+ global $lang, $admin_type, $site_url, $global_user_id;
+
+ // Ce nimamo podatkov ponekod tega potem ne prikazujemo
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->sid);
+ $data_file_status = $SDF->getStatus();
+
+ if( in_array($data_file_status, array(FILE_STATUS_SRV_DELETED, FILE_STATUS_NO_DATA))
+ && in_array($podstran, array(
+ 'para_analysis_graph', 'para_graph', 'usable_resp',
+ 'data', 'quick_edit', 'variables', 'export',
+ 'sumarnik', 'descriptor', 'frequency', 'crosstabs', 'ttest', 'means', 'break', 'multicrosstabs', 'charts', 'analysis_links'
+ )) ){
+
+ return;
+ }
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+
+ echo '<div id="topSettingsHolder" class="'.$podstran.'">';
+
+ $analiza = false;
+ if (in_array($podstran, array('sumarnik', 'descriptor', 'frequency', 'crosstabs', 'ttest', 'means', 'break', 'multicrosstabs', 'nonresponses'))) {
+ $analiza = true;
+ }
+
+ $borderLeft = '';
+
+ // Navigacija analiz - ANALIZE
+ if ($analiza) {
+ echo '<div id="analizaSubNav">';
+ $this->displayAnalizaSubNavigation();
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+
+
+ // Preklop med porocilom po meri in navadnimi porocili
+ if ($podstran == 'analysis_creport' || $podstran == 'analysis_links') {
+ echo '<div id="additional_navigation">';
+
+ // Link na navadna porocila
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=analysis&m=analysis_links"><span ' . ($podstran == 'analysis_links' ? ' class="active"' : '') . '>' . $lang['srv_standard_report'] . '</span></a>';
+
+ // Link na porocilo po meri
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=analysis&m=analysis_creport"><span ' . ($podstran == 'analysis_creport' ? ' class="active"' : '') . '>' . $lang['srv_custom_report'] . '</span></a>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+ // Preklop na vpogled, hitri seznam, spremenljivke (podatki)
+ elseif ($podstran == 'data') {
+ echo '<div id="additional_navigation">';
+
+ // Link na vpogled
+ echo '<a href="' . $site_url . 'admin/survey/index.php?anketa=' . $this->sid . '&a=' . A_COLLECT_DATA . '&m=quick_edit&quick_view=1"><span>' . $lang['srv_lnk_vpogled'] . '</span></a>';
+
+ // Link na spremenljivke
+ echo '<a href="' . $site_url . 'admin/survey/index.php?anketa=' . $this->sid . '&a=' . A_COLLECT_DATA . '&m=' . M_COLLECT_DATA_VARIABLE_VIEW . '"><span>' . $lang['srv_lnk_pregled_variabel'] . '</span></a>';
+
+ // Link na hitri seznam
+ echo '<a href="#" onClick="displayDataPrintPreview();"><span style="padding-right:0px !important;">' . $lang['srv_data_print_preview_link'] . '</span></a>';
+ echo '<span style="margin-right:40px;">' . Help:: display('srv_data_print_preview') . '</span>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+ // Link nazaj na podatke - vpogled
+ elseif ($podstran == 'quick_edit') {
+ echo '<div id="additional_navigation">';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_COLLECT_DATA . '"><span class="faicon arrow_back" title="' . $lang['srv_lnk_back_to_data'] . '"></span></a>';
+ echo '<a href="#"><span class="active">' . $lang['srv_data_title_quick_view'] . '</span></a>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+ // Link nazaj na podatke - Spremenljivke
+ elseif ($podstran == 'variables') {
+ echo '<div id="additional_navigation">';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_COLLECT_DATA . '"><span class="faicon arrow_back" title="' . $lang['srv_lnk_back_to_data'] . '"></span></a>';
+ echo '<a href="#"><span class="active">' . $lang['srv_data_title_variable_view'] . '</span></a>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+ // Link nazaj na diagnostiko - Ocenjevanje trajanja
+ elseif ($podstran == 'ocena_trajanja') {
+ echo '<div id="additional_navigation">';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=' . A_TESTIRANJE . '&amp;m=' . M_TESTIRANJE_PREDVIDENI . '" title="' . $lang['srv_testiranje_diagnostika_base'] . '"><span class="active">' . $lang['srv_testiranje_predvidenicas'] . '</span></a>';
+ echo '<a href="#"></a>';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=' . A_TESTIRANJE . '&amp;m=' . M_TESTIRANJE_CAS . '" title="' . $lang['srv_testiranje_diagnostika_base'] . '"><span>' . $lang['srv_testiranje_cas'] . '</span></a>';
+ echo '<a href="#"></a>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+ // Link nazaj na diagnostiko - Dejanski casi
+ elseif ($podstran == 'dejanski_casi') {
+ echo '<div id="additional_navigation">';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=' . A_TESTIRANJE . '&amp;m=' . M_TESTIRANJE_PREDVIDENI . '" title="' . $lang['srv_testiranje_predvidenicas'] . '"><span>' . $lang['srv_testiranje_predvidenicas'] . '</span></a>';
+ echo '<a href="#"></a>';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=' . A_TESTIRANJE . '&amp;m=' . M_TESTIRANJE_CAS . '" title="' . $lang['srv_testiranje_cas'] . '"><span class="active">' . $lang['srv_testiranje_cas'] . '</span></a>';
+ echo '<a href="#"></a>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+ // Link nazaj na komentarje
+ elseif ($podstran == 'komentarji' || $podstran == 'komentarji_anketa') {
+
+ // Prestejemo komentarje (nereseni/vsi)
+ $sas = new SurveyAdminSettings();
+ $comment_count = $sas->testiranje_komentarji_count();
+
+ echo '<div id="additional_navigation">';
+
+ //Komentarji na vprasanja
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=' . A_KOMENTARJI_ANKETA . '" title="' . $lang['srv_testiranje_komentarji_anketa_title'] . '">';
+ echo '<span ' . ($_GET['a'] == A_KOMENTARJI_ANKETA ? 'class="active"' : '') . '>';
+ echo $lang['srv_testiranje_komentarji_anketa_title'];
+ echo '</span>';
+ echo '</a>';
+
+ echo '<span class="bold" style="margin-right: 50px;"> (';
+ if ($comment_count['survey_resp']['unresolved'] + $comment_count['survey_admin']['unresolved'] > 0)
+ echo '<span class="orange">';
+ echo($comment_count['survey_resp']['unresolved'] + $comment_count['survey_admin']['unresolved']);
+ if ($comment_count['survey_resp']['unresolved'] + $comment_count['survey_admin']['unresolved'] > 0)
+ echo '</span>';
+ echo '/' . ($comment_count['survey_resp']['all'] + $comment_count['survey_admin']['all']);
+ echo ')</span>';
+
+ // Komentarji na anketo
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=' . A_KOMENTARJI . '" title="' . $lang['srv_testiranje_komentarji_title'] . '">';
+ echo '<span ' . ($_GET['a'] == A_KOMENTARJI ? ' class="active"' : '') . '>';
+ echo $lang['srv_testiranje_komentarji_title'];
+ echo '</span>';
+ echo '</a>';
+
+ echo '<span class="bold"> (';
+ if ($comment_count['question']['unresolved'] > 0)
+ echo '<span class="orange">';
+ echo $comment_count['question']['unresolved'];
+ if ($comment_count['question']['unresolved'] > 0)
+ echo '</span>';
+ echo '/' . $comment_count['question']['all'];
+ echo ')</span>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ } elseif ($podstran == 'theme-editor') {
+ echo '<div id="additional_navigation">';
+
+ $mobile = (isset($_GET['mobile']) && $_GET['mobile'] == '1') ? '&mobile=1' : '';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=tema'.$mobile.'" title="' . $lang['srv_themes_select'] . '"><span class="faicon arrow_back"></span></a>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=theme-editor&profile='. $_GET['profile'] . $mobile.'" title="' . $lang['srv_themes_mod'] . '"><span ' . ($_GET['a'] == 'theme-editor' && $_GET['t'] != 'css' && $_GET['t'] != 'upload' ? ' class="active"' : '') . '>' . $lang['srv_themes_mod'] . '</span></a>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=theme-editor&t=css&profile='. $_GET['profile'] . $mobile.'" title="' . $lang['srv_themes_edit'] . '"><span ' . ($_GET['a'] == 'theme-editor' && $_GET['t'] == 'css' ? ' class="active"' : '') . '>' . $lang['srv_themes_edit'] . '</span></a>';
+
+ // Za mobilno temo zaenkrat nimamo uploada css-ja
+ if($mobile == '')
+ echo '<a href="index.php?anketa=' . $this->sid . '&amp;a=theme-editor&t=upload&profile='. $_GET['profile'] . $mobile.'" title="' . $lang['srv_themes_upload_css'] . '"><span ' . ($_GET['a'] == 'theme-editor' && $_GET['t'] == 'upload' ? ' class="active"' : '') . '>' . $lang['srv_themes_upload_css'] . '</span></a>';
+
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ } // Link nazaj na podatke - Spremenljivke
+ elseif ($podstran == 'para_analysis_graph') {
+
+ // Info o neodgovorih
+ echo '<div id="nonresponse_info">';
+ echo $lang['srv_para_graph_text2'];
+ echo '</div>';
+ $borderLeft = ' class="borderLeft"';
+
+ echo '<div id="additional_navigation" ' . $borderLeft . ' style="padding-left: 40px;">';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_NONRESPONSE_GRAPH . '"><span ' . (!isset($_GET['m']) || $_GET['m'] == '' ? 'class="active"' : '') . '>' . $lang['srv_para_label_variables'] . '</span></a>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_NONRESPONSE_GRAPH . '&m=breaks"><span ' . ($_GET['m'] === 'breaks' ? 'class="active"' : '') . '>' . $lang['srv_para_label_breaks'] . '</span></a>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_NONRESPONSE_GRAPH . '&m=advanced"><span ' . ($_GET['m'] === 'advanced' ? 'class="active"' : '') . '>' . $lang['srv_para_label_details'] . '</span></a>';
+ echo '</div>';
+ $borderLeft = ' class="borderLeft"';
+ }
+ elseif ($podstran == 'aapor') {
+ echo '<div id="additional_navigation">';
+
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . NAVI_AAPOR . '&m=aapor1"><span>' . $lang['srv_lnk_AAPOR1'] . '</span></a>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . NAVI_AAPOR . '&m=aapor2"><span>' . $lang['srv_lnk_AAPOR2'] . '</span></a>';
+ echo '</div>';
+ }
+ elseif ($podstran == 'diagnostics') {
+ echo '<div id="additional_navigation">';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . NAVI_AAPOR . '&m=aapor1"><span>' . $lang['srv_lnk_AAPOR1'] . '</span></a>';
+ echo '<div id="toggleDataCheckboxes" ' . $borderLeft . ' onClick="toggleDataCheckboxes(\'paraAnalysisGraph\');"><span class="faicon ' . ($arrow == 1 ? ' dropup_blue' : 'dropdown_blue') . '"></span> ' . $lang['srv_data_settings_checkboxes'] . '</div>';
+ echo '</div>';
+
+ }
+
+ // Nastavitve tabele (checkboxi) - PODATKI
+ if ($podstran == 'para_analysis_graph') {
+ $arrow = (isset($_SESSION['sid_' . $this->sid]['paraAnalysisGraph_settings'])) ? $_SESSION['sid_' . $this->sid]['paraAnalysisGraph_settings'] : 0;
+ echo '<div id="toggleDataCheckboxes" ' . $borderLeft . ' onClick="toggleDataCheckboxes(\'paraAnalysisGraph\');"><span class="faicon ' . ($arrow == 1 ? ' dropup_blue' : 'dropdown_blue') . '"></span> ' . $lang['srv_data_settings_checkboxes'] . '</div>';
+ }
+
+ // Info o uporabnih enotah
+ if ($podstran == 'usable_resp') {
+ echo '<div id="usable_info">';
+ echo $lang['srv_usableResp_text'];
+ echo '</div>';
+
+ $borderLeft = ' class="borderLeft"';
+ }
+
+ // Nastavitve tabele za UPORABNOST
+ if ($podstran == 'usable_resp') {
+ $arrow = (isset($_SESSION['sid_' . $this->sid]['usabilityIcons_settings'])) ? $_SESSION['sid_' . $this->sid]['usabilityIcons_settings'] : 0;
+ echo '<div id="toggleDataCheckboxes" ' . $borderLeft . ' onClick="toggleDataCheckboxes(\'usability\');"><span class="faicon ' . ($arrow == 1 ? ' dropup_blue' : 'dropdown_blue') . '"></span> ' . $lang['srv_data_settings_checkboxes'] . '</div>';
+ }
+
+ // Radio status (vsi, ustrezni...)
+ if ($analiza || in_array($podstran, array('data', 'export', 'charts', 'analysis_creport', 'analysis_links', 'para_graph', 'reminder_tracking', 'heatmap'))) {
+ echo '<div id="dataOnlyValid" ' . $borderLeft . '>';
+ SurveyStatusProfiles::displayOnlyValidCheckbox();
+ echo '</div>';
+ }
+
+ if ($podstran == 'reminder_tracking') {
+ echo '<div id="additional_navigation">';
+
+ // Link na porocila z recnum
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=reminder_tracking&m=recnum"><span>' . $lang['srv_reminder_tracking_report_recnum'] . '</span></a>';
+
+ // Link na porocila s spremenljivkami
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=reminder_tracking&m=vars"><span>' . $lang['srv_reminder_tracking_report_vprasanja'] . '</span></a>';
+
+ echo '</div>';
+ }
+
+ // Nastavitve na desni
+ if ($analiza || in_array($podstran, array('data', 'export', 'charts', 'analysis_creport', 'analysis_links', 'dejanski_casi', 'para_analysis_graph', 'heatmap'))) {
+
+ $active_filter = $this->filteredData($podstran);
+
+ echo '<div id="analiza_right_options_holder">';
+
+ if ($analiza || in_array($podstran, array('charts'))) {
+
+ // Nastavitev stevila odgovorov (odprtih) - po novem prestavljeno ven
+ echo '<div id="analiza_right_options3" class="spaceRight">';
+ echo $lang['srv_analiza_defAnsCnt_short'] . ': ';
+ echo '<select id="numOpenAnswers" name="numOpenAnswers" autocomplete="off" onChange="saveSingleProfileSetting(\'' . SurveyDataSettingProfiles::getCurentProfileId() . '\', \'numOpenAnswers\', this.value); return false;">';
+ $lastElement = end(SurveyDataSettingProfiles::$textAnswersMore);
+ $cp = SurveyDataSettingProfiles::GetCurentProfileData();
+ foreach (SurveyDataSettingProfiles::$textAnswersMore AS $key => $values) {
+ echo '<option' . ((int)$cp['numOpenAnswers'] == $values ? ' selected="selected"' : '') . ' value="' . $values . '">';
+ if ($values != $lastElement) {
+ echo $values;
+ } else {
+ echo $lang['srv_all'];
+ }
+ echo '</option>';
+ }
+ echo '</select>';
+ echo '</div>';
+
+ // Nastavitve za filtre (po spr, zoom, statusi...)
+ echo '<div title="' . $lang['settings'] . '" id="analiza_right_options2" class="spaceRight spaceLeft">';
+ echo '<span id="filters_span2" class="faicon wheel_32 pointer icon-as_link"></span>';
+ $this->displayAnalizaRightOptions2($podstran);
+ echo '</div>';
+ }
+ elseif ($podstran == 'data' || $podstran == 'export') {
+ // Ikona za ponovno generiranje datoteke
+ echo '<span title="' . $lang['srv_deleteSurveyDataFile_link'] . '" class="faicon refresh icon-as_link pointer spaceRight spaceLeft" onClick="changeColectDataStatus(); return false;"></span>';
+ }
+
+ echo '<div title="' . $lang['filters'] . '" id="analiza_right_options" '.(!$userAccess->checkUserAccess($what='filters') ? 'class="user_access_locked"' : '').'>';
+ echo '<span id="filters_span" class="faicon filter pointer"></span>';
+ $this->displayAnalizaRightOptions($podstran);
+ echo '</div>';
+ echo Help::display('srv_data_filter');
+
+ echo '</div>';
+ }
+ // Link na nastavitve komentarjev
+ elseif ($podstran == 'komentarji' || $podstran == 'komentarji_anketa') {
+
+ $d = new Dostop();
+
+ # nastavitve komentarjev
+ if ($d->checkDostopSub('edit')) {
+ echo '<div id="analiza_right_options_holder">';
+ echo '<div title="' . $lang['settings'] . '" id="analiza_right_options">';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=urejanje" title="' . $lang['srv_settings_komentarji1'] . '">';
+ echo '<span class="faicon wheel_32 pointer icon-as_link"></span>';
+ //echo '<span id="filters_span" class="bold pointer">'.$lang['settings'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+ }
+ }
+ // Nastavitve statusa
+ elseif ($podstran == 'status') {
+
+ $ss = new SurveyStatistic();
+ $ss->Init($this->sid);
+
+ echo '<div id="div_status_filtri_right" class="floatRight">';
+
+ echo '<div id="dashboardEmailInvitationFilter" style="position:absolute; right:20px; top:46px;">';
+ echo $ss->emailInvitationFilter($this->emailInvitation);
+ echo '</div>';
+
+ echo '<ul>';
+ # če imamo vabila
+ $row = SurveyInfo::getSurveyRow();
+
+ if ($row['email'] || $row['user_base']) {
+ if ($ss->cnt_all == $ss->cnt_email) {
+ echo '<li>';
+ # filter za emaile
+ echo $lang['srv_statistic_email_invitation'];
+ echo '<select id="filter_email_status" name="filter_email_status" onchange="statisticRefreshAllBoxes(\'invitation\'); return false;" >';
+ echo '<option value="0" disabled="disabled">' . $lang['srv_statistic_email_invitation_all'] . '</option>';
+ echo '<option value="1" selected="selected">' . $lang['srv_statistic_email_invitation_only_email'] . '</option>';
+ echo '<option value="2" disabled="disabled">' . $lang['srv_statistic_email_invitation_no_email'] . '</option>';
+ echo '</select>';
+ echo '</li>';
+ } else {
+ echo '<li>';
+ # filter za emaile
+ echo $lang['srv_statistic_email_invitation'];
+ echo '<select id="filter_email_status" name="filter_email_status" onchange="statisticRefreshAllBoxes(\'invitation\'); return false;" >';
+ echo '<option value="0"' . ($ss->emailInvitation == 0 ? ' selected="selected"' : '') . '>' . $lang['srv_statistic_email_invitation_all'] . '</option>';
+ echo '<option value="1"' . ($ss->emailInvitation == 1 ? ' selected="selected"' : '') . '>' . $lang['srv_statistic_email_invitation_only_email'] . '</option>';
+ echo '<option value="2"' . ($ss->emailInvitation == 2 ? ' selected="selected"' : '') . '>' . $lang['srv_statistic_email_invitation_no_email'] . '</option>';
+ echo '</select>';
+ echo '</li>';
+ }
+ }
+ echo '<li>';
+ # filter za čase
+ $TimeProfileData = SurveyTimeProfiles:: GetDates();
+ $separator = ($row['email'] || $row['user_base']) ? true : false;
+ SurveyTimeProfiles::DisplayLink(false, $separator);
+ echo '</li>';
+ echo '</ul>';
+
+ echo '</div>';
+ }
+
+
+ echo '</div>';
+ }
+
+ public function displayAnalizaSubNavigation($showDiv = true)
+ {
+ global $lang, $admin_type, $global_user_id;
+
+ $_js_links = array();
+
+ UserSetting:: getInstance()->Init($global_user_id);
+ $show_analiza_preview = (int)UserSetting:: getInstance()->getUserSetting('showAnalizaPreview') == 1 ? true : false;
+ if ($show_analiza_preview == true) {
+ for ($i = 1; $i <= 9; $i++) {
+ $_js_links[$i] = ' onmouseover="show_anl_prev(' . $i . '); return false;" onmouseout="hide_anl_prev(); return false"';
+ }
+
+ }
+ if ($_GET['m'] != M_ANALYSIS_CHARTS && $_GET['m'] != M_ANALYSIS_LINKS && $_GET['m'] != M_ANALYSIS_CREPORT) {
+ if (true) {
+ echo '<span class="srv_statistic_menu">' . $lang['srv_statistic_menu'] . Help::display('srv_menu_statistic') . '&nbsp;</span>';
+ echo '<div id="globalSetingsLinks" class="analiza">';
+ }
+ if (SurveyInfo::getInstance()->checkSurveyModule('hierarhija')) {
+ echo '<ul class="analizaSubNavigation">';
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_MEANS_HIERARHY ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[5] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_MEANS_HIERARHY . '" title="' . $lang['srv_means'] . '"><span>' . $lang['srv_means'] . '</span></a>';
+ echo '</li>';
+ echo '</ul>';
+
+ } else {
+ echo '<ul class="analizaSubNavigation">';
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_SUMMARY ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[1] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_SUMMARY . '" title="' . $lang['srv_sumarnik'] . '"><span>' . $lang['srv_sumarnik'] . '</span></a>';
+ echo '</li>';
+ # opisne
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_DESCRIPTOR ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[2] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_DESCRIPTOR . '" title="' . $lang['srv_descriptor'] . '"><span>' . $lang['srv_descriptor_short'] . '</span></a>';
+ echo '</li>';
+ # frekvence
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_FREQUENCY ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[3] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_FREQUENCY . '" title="' . $lang['srv_frequency'] . '"><span>' . $lang['srv_frequency'] . '</span></a>';
+ echo '</li>';
+ # crostabs
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_CROSSTAB ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[4] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_CROSSTAB . '" title="' . $lang['srv_crosstabs'] . '"><span>' . $lang['srv_crosstabs'] . '</span></a>';
+ echo '</li>';
+ # multicrostabs
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_MULTICROSSTABS ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[8] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_MULTICROSSTABS . '" title="' . $lang['srv_multicrosstabs'] . '"><span>' . $lang['srv_multicrosstabs'] . '</span></a>';
+ echo '</li>';
+ # povprečaj
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_MEANS ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[5] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_MEANS . '" title="' . $lang['srv_means'] . '"><span>' . $lang['srv_means'] . '</span></a>';
+ echo '</li>';
+ # ttest
+ if ($admin_type == 0) {
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_TTEST ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[6] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_TTEST . '" title="' . $lang['srv_ttest'] . '"><span>' . $lang['srv_ttest'] . '</span></a>';
+ echo '</li>';
+ }
+ # break
+ echo '<li' . ($_GET['m'] == M_ANALYSIS_BREAK ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"') . $_js_links[7] . '>';
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=' . A_ANALYSIS . '&m=' . M_ANALYSIS_BREAK . '" title="' . $lang['srv_break'] . '"><span>' . $lang['srv_break'] . '</span></a>';
+ echo '</li>';
+ # para statistike - so pod status??
+ /*if ($admin_type === '0') {
+
+ echo '<li'.($_GET['m']==M_ANALYSIS_PARA ? ' class="highlightLineTab"' : ' class="nonhighlight displayNone"').$_js_links[9].'>';
+ echo '<a href="index.php?anketa='.$this->sid.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_PARA.'" title="'.$lang['srv_para_neodgovori'].'"><span>'.$lang['srv_para_neodgovori'].'</span></a>';
+ echo '</li>';
+ } */
+ # predogled
+ echo '<li class="previewCheck displayNone">';
+ echo '<label><input type="checkbox" id="cbx_shoq_analiza_preview" onchange="change_analiza_preview();"' . ($show_analiza_preview == true ? ' checked=checked' : '') . '>' . $lang['srv_preview'] . '</label>';
+ echo '</li>';
+ echo '</ul>';
+ }
+ if ($showDiv) {
+ echo '</div>';
+ }
+ ?>
+ <script>
+ function show_anl_prev(tip) {
+ $("#srv_analiza_preview_div").show();
+ //var tip = parseInt($(event.target).parent().attr('anl_prv'));
+
+
+ if (tip > 0) {
+ // skrijemo ostale previev-e
+ $('.srv_analiza_preview_sub').addClass('hidden');
+ // prikažemo ustrezen predogled
+ $('#srv_analiza_preview_sub_' + tip).removeClass('hidden');
+ }
+ }
+ function hide_anl_prev() {
+ $("#srv_analiza_preview_div").hide();
+ }
+ // mousever preview vprasanja
+ //$('#globalSetingsLinks ul li a').bind('mouseover', function (event) {
+
+ //}).bind('mouseout', function (event) {
+
+ //});
+ </script>
+ <?php
+
+ }
+ $this->displayAnalizaPreview();
+ }
+
+ public function displayAnalizaRightOptions($podstran, $onlyLinks = false){
+ global $lang, $admin_type, $global_user_id;
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $allowShow = array();
+
+ #dovoljenja za prikaz določenih nastavitev
+ $allowShow[M_ANALYSIS_SUMMARY] =
+ $allowShow[M_ANALYSIS_DESCRIPTOR] =
+ $allowShow[M_ANALYSIS_FREQUENCY] =
+ $allowShow[M_ANALYSIS_CHARTS] =
+ $allowShow[M_ANALYSIS_LINKS] =
+ $allowShow[M_ANALYSIS_CREPORT] = array(
+ 'AS_SETTINGS',
+ 'AS_SEGMENTS',
+ 'AS_ZOOM',
+ 'AS_LOOPS',
+ 'AS_BREAK',
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+
+ $allowShow[M_ANALYSIS_CROSSTAB] =
+ $allowShow[M_ANALYSIS_MULTICROSSTABS] =
+ $allowShow[M_ANALYSIS_MEANS_HIERARHY] =
+ $allowShow[M_ANALYSIS_MEANS] = array(
+ 'AS_SETTINGS',
+ 'AS_ZOOM',
+ 'AS_LOOPS',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+ $allowShow[M_ANALYSIS_TTEST] = array(
+ 'AS_SETTINGS',
+ 'AS_CONDITIONS',
+ 'AS_TIME',
+ 'AS_STATUS');
+ $allowShow[M_ANALYSIS_BREAK] = array(
+ 'AS_SETTINGS',
+ 'AS_ZOOM',
+ 'AS_LOOPS',
+ 'AS_BREAK',
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+
+ $allowShow[M_ANALYSIS_NONRESPONSES] =
+ $allowShow[M_ANALYSIS_PARA] = array(
+ 'AS_SETTINGS',
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+
+ $allowShow['para_analysis_graph'] = array(
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ );
+
+ session_start();
+ $hideAdvanced = (isset($_SESSION['AnalysisAdvancedLinks'][$this->sid]) && $_SESSION['AnalysisAdvancedLinks'][$this->sid] == true) ? true : false;
+
+ if ($podstran == 'data' || $podstran == 'export' || $podstran == 'quick_edit') {
+ echo '<div id="div_analiza_filtri_right" class="floatRight">';
+ echo '<ul>';
+
+ if ($podstran == 'export') {
+ echo '<li>';
+ echo '<span class="as_link" id="link_export_setting" onClick="$(\'#fade\').fadeTo(\'slow\', 1);$(\'#div_export_setting_show\').fadeIn(\'slow\'); return false;" title="' . $lang['srv_dsp_link'] . '">' . $lang['srv_dsp_link'] . '</span>';
+ echo '</li>';
+ }
+
+ # filter za nastavitve
+ # div za filtre statusov
+ SurveyStatusProfiles:: DisplayLink(false, false);
+
+ # filter za spremenljivke - variable
+ SurveyVariablesProfiles::DisplayLink(false, false);
+ #filter za ife - pogoje
+ SurveyConditionProfiles::DisplayLink(false);
+ # filter za čase
+ SurveyTimeProfiles::DisplayLink(false);
+ # generiranje datoteke s podatki - dodana lastna ikona za generiranje datoteke
+ //SurveyStatusProfiles :: FileGeneratingSetting(false);
+
+ echo '</ul>';
+ echo '</div>'; # id="div_analiza_filtri_right" class="floatRight"
+ }
+ elseif ($podstran == 'dejanski_casi') {
+ echo '<div id="div_analiza_filtri_right">';
+
+ SurveyStatusCasi:: Init($this->sid);
+
+ SurveyUserSetting:: getInstance()->Init($this->sid, $global_user_id);
+
+ // nastavitve iz popupa
+ $rezanje = SurveyUserSetting::getInstance()->getSettings('rezanje');
+ if ($rezanje == '') $rezanje = 1;
+ $rezanje_meja_sp = SurveyUserSetting::getInstance()->getSettings('rezanje_meja_sp');
+ if ($rezanje_meja_sp == '') $rezanje_meja_sp = 5;
+ $rezanje_meja_zg = SurveyUserSetting::getInstance()->getSettings('rezanje_meja_zg');
+ if ($rezanje_meja_zg == '') $rezanje_meja_zg = 5;
+ $rezanje_predvidena_sp = SurveyUserSetting::getInstance()->getSettings('rezanje_predvidena_sp');
+ if ($rezanje_predvidena_sp == '') $rezanje_predvidena_sp = 10;
+ $rezanje_predvidena_zg = SurveyUserSetting::getInstance()->getSettings('rezanje_predvidena_zg');
+ if ($rezanje_predvidena_zg == '') $rezanje_predvidena_zg = 200;
+
+ // profili rezanja
+ $statusCasi = SurveyStatusCasi:: getProfiles();
+ echo '<div>' . "\n";
+ echo '<a href="#" onclick="vnosi_show_rezanje_casi(); return false;" id="link_rezanje_casi" title="' . $lang['srv_rezanje'] . '">' . $lang['srv_rezanje'] . '</a><br/>';
+
+ echo '<span id="div_vnosi_status_profile_dropdownd" style="font-size:10px">';
+
+ if ($rezanje == 0) {
+ echo '(' . $lang['srv_rezanje_meja_sp'] . ': ' . $rezanje_meja_sp . '%, ' . $lang['srv_rezanje_meja_zg'] . ': ' . $rezanje_meja_zg . '%)';
+
+ } else {
+ echo '(' . $rezanje_predvidena_sp . '% ' . $lang['srv_and'] . ' ' . $rezanje_predvidena_zg . '% ' . $lang['srv_rezanje_predvidenega'] . ')';
+ }
+
+ echo '</span>';
+ echo '</div>';
+
+ // profili statusov
+ $statusCasi = SurveyStatusCasi:: getProfiles();
+ echo '<div style="margin-top: 15px;">';
+ echo '<span class="as_link" id="link_status_casi" title="' . $lang['srv_statusi'] . '">' . $lang['srv_statusi'] . ': </span>';
+ echo '<span id="div_vnosi_status_profile_dropdown">';
+ echo '<select id="vnosi_current_status_casi" name="vnosi_current_status_casi" onchange="statusCasiAction(\'change\'); return false;" >';
+ foreach ($statusCasi as $key => $value) {
+ echo ' <option' . ($izbranStatusCasi == $value['id'] ? ' selected="selected"' : '') . ' value="' . $value['id'] . '">' . $value['name'] . '</option>';
+ }
+ echo '</select>';
+ echo '</span>';
+ echo '</div>';
+
+ echo '</div>';
+ }
+ else {
+ if ($onlyLinks == false) {
+ echo '<div id="div_analiza_filtri_right" class="analiza">';
+ }
+
+ echo '<ul>';
+
+ if (in_array('AS_SEGMENTS', $allowShow[$podstran])) {
+ # zoom
+ SurveyZoom::DisplayLink($hideAdvanced);
+ }
+ if (in_array('AS_ZOOM', $allowShow[$podstran])) {
+ # inspect
+ $SI = new SurveyInspect($this->sid);
+ $SI->DisplayLink($hideAdvanced);
+ }
+ if (in_array('AS_LOOPS', $allowShow[$podstran])) {
+ # filter za zanke
+ SurveyZankaProfiles::DisplayLink($hideAdvanced);
+ }
+ if (in_array('AS_VARIABLES', $allowShow[$podstran])) {
+ # div za profile variabel
+ SurveyVariablesProfiles::DisplayLink(true, $hideAdvanced);
+ }
+ if (in_array('AS_CONDITIONS', $allowShow[$podstran])) {
+ # filter za pogoje - ifi
+ SurveyConditionProfiles::DisplayLink($hideAdvanced);
+ }
+ if (in_array('AS_MISSINGS', $allowShow[$podstran])) {
+ # profili missingov
+ SurveyMissingProfiles::DisplayLink($hideAdvanced);
+ }
+ if (in_array('AS_TIME', $allowShow[$podstran])) {
+ # filter za čase
+ SurveyTimeProfiles::DisplayLink($hideAdvanced);
+ }
+ if (in_array('AS_STATUS', $allowShow[$podstran])) {
+ # div za filtre statusov
+ SurveyStatusProfiles::DisplayLink($hideAdvanced);
+ }
+ echo '</ul>';
+
+ if ($onlyLinks == false) {
+ echo '</div>';
+ }
+ }
+
+ // Javascript s katerim povozimo urlje za izvoze, ki niso na voljo v paketu
+ $userAccess = UserAccess::getInstance($global_user_id);
+ if(!$userAccess->checkUserAccess($what='filters')){
+ echo '<script> userAccessFilters(); </script>';
+ }
+ }
+
+ public function displayAnalizaRightOptions2($podstran, $onlyLinks = false)
+ {
+ global $lang, $admin_type, $global_user_id;
+
+ $allowShow = array();
+
+ #dovoljenja za prikaz določenih nastavitev
+ $allowShow[M_ANALYSIS_SUMMARY] =
+ $allowShow[M_ANALYSIS_DESCRIPTOR] =
+ $allowShow[M_ANALYSIS_FREQUENCY] =
+ $allowShow[M_ANALYSIS_CHARTS] =
+ $allowShow[M_ANALYSIS_LINKS] =
+ $allowShow[M_ANALYSIS_CREPORT] = array(
+ 'AS_SETTINGS',
+ 'AS_SEGMENTS',
+ 'AS_ZOOM',
+ 'AS_LOOPS',
+ 'AS_BREAK',
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+
+ $allowShow[M_ANALYSIS_CROSSTAB] =
+ $allowShow[M_ANALYSIS_MULTICROSSTABS] =
+ $allowShow[M_ANALYSIS_MEANS_HIERARHY] =
+ $allowShow[M_ANALYSIS_MEANS] = array(
+ 'AS_SETTINGS',
+ 'AS_ZOOM',
+ 'AS_LOOPS',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+ $allowShow[M_ANALYSIS_TTEST] = array(
+ 'AS_SETTINGS',
+ 'AS_CONDITIONS',
+ 'AS_TIME',
+ 'AS_STATUS');
+ $allowShow[M_ANALYSIS_BREAK] = array(
+ 'AS_SETTINGS',
+ 'AS_ZOOM',
+ 'AS_LOOPS',
+ 'AS_BREAK',
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+
+ $allowShow[M_ANALYSIS_NONRESPONSES] =
+ $allowShow[M_ANALYSIS_PARA] = array(
+ 'AS_SETTINGS',
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ 'AS_TIME',
+ 'AS_STATUS');
+
+ $allowShow['para_analysis_graph'] = array(
+ 'AS_VARIABLES',
+ 'AS_CONDITIONS',
+ 'AS_MISSINGS',
+ );
+
+ session_start();
+ $hideAdvanced = (isset($_SESSION['AnalysisAdvancedLinks'][$this->sid]) && $_SESSION['AnalysisAdvancedLinks'][$this->sid] == true) ? true : false;
+
+ if ($onlyLinks == false) {
+ echo '<div id="div_analiza_filtri_right2" class="analiza">';
+ }
+
+ echo '<ul>';
+
+ if ($podstran == 'charts') {
+ // nastavitve za grafe (hq, barva)
+ $this->displayChartOptions();
+ }
+
+ if (in_array('AS_SETTINGS', $allowShow[$podstran])) {
+
+ # filter za nastavitve
+ SurveyDataSettingProfiles::DisplayLink($hideAdvanced);
+ }
+
+ echo '</ul>';
+
+ if ($onlyLinks == false) {
+ echo '</div>';
+ }
+ }
+
+ public function displayChartOptions()
+ {
+ global $lang, $admin_type;
+
+ // Nastavitev HQ grafov
+ echo '<li><label>';
+ echo $lang['srv_chart_hq'] . ': ';
+ echo '<input type="checkbox" name="chart_hq" id="chart_hq" onClick="changeChartHq(this)" ' . (SurveyChart::$quality == 3 ? ' checked="checked"' : '') . '>';
+ echo '</label></li>';
+
+
+ // Nastavitev skina grafov
+ $skin = SurveyUserSetting:: getInstance()->getSettings('default_chart_profile_skin');
+ $skin = isset($skin) ? $skin : '1ka';
+
+ // ce je custom skin
+ if (is_numeric($skin)) {
+ $skin = SurveyChart::getCustomSkin($skin);
+ $name = $skin['name'];
+ } else {
+ switch ($skin) {
+ // 1ka skin
+ case '1ka':
+ $name = $lang['srv_chart_skin_1ka'];
+ break;
+
+ // zivahen skin
+ case 'lively':
+ $name = $lang['srv_chart_skin_0'];
+ break;
+
+ // blag skin
+ case 'mild':
+ $name = $lang['srv_chart_skin_1'];
+ break;
+
+ // Office skin
+ case 'office':
+ $name = $lang['srv_chart_skin_6'];
+ break;
+
+ // Pastel skin
+ case 'pastel':
+ $name = $lang['srv_chart_skin_7'];
+ break;
+
+ // zelen skin
+ case 'green':
+ $name = $lang['srv_chart_skin_2'];
+ break;
+
+ // moder skin
+ case 'blue':
+ $name = $lang['srv_chart_skin_3'];
+ break;
+
+ // rdeč skin
+ case 'red':
+ $name = $lang['srv_chart_skin_4'];
+ break;
+
+ // skin za vec kot 5 moznosti
+ case 'multi':
+ $name = $lang['srv_chart_skin_5'];
+ break;
+ }
+ }
+
+ if ($hideAdvanced == false) {
+
+ echo '<li>';
+ echo '<span class="as_link" id="link_chart_color" title="' . $lang['srv_chart_skin'] . '">' . $lang['srv_chart_skin'] . ': <span style="font-weight: 500;">' . $name . '</span></span>';
+ echo '</li>';
+ }
+
+ // Separator
+ /*echo '<li style="border-bottom:1px #0C377A dashed;">';
+ echo '</li>';
+ echo '<li>';
+ echo '</li>';*/
+ }
+
+
+ // Ugotovimo ce so podatki kako filtrirani
+ function filteredData($podstran)
+ {
+
+ if ($podstran == 'status') {
+
+ if (SurveyTimeProfiles::getCurentProfileId() != STP_DEFAULT_PROFILE)
+ return true;
+ } else if (in_array($podstran, array('sumarnik', 'descriptor', 'frequency', 'crosstabs', 'ttest', 'means', 'break', 'multicrosstabs', 'nonresponses'))) {
+
+ if (SurveyDataSettingProfiles::getCurentProfileId() != SDS_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyZoom::getCurentProfileId() != 0 && $podstran != 'status')
+ return true;
+
+ $SI = new SurveyInspect($this->sid);
+ if ($SI->isInspectEnabled() && $podstran != 'status')
+ return true;
+
+ if (SurveyVariablesProfiles::getCurentProfileId() != SVP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyConditionProfiles::getCurentProfileId() != SCP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyMissingProfiles::getCurentProfileId() != SMP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyTimeProfiles::getCurentProfileId() != STP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyStatusProfiles::getCurentProfileId() != SSP_DEFAULT_PROFILE)
+ return true;
+ } else if (in_array($podstran, array('data', 'export', 'quick_edit'))) {
+
+ $SPM = new SurveyProfileManager($this->sid);
+ if ($SPM->getCurentProfileId() != SSP_DEFAULT_PROFILE && (int)$SPM->getCurentProfileId() != 0 && (int)$SPM->getCurentProfileId() != -1)
+ return true;
+
+ if (SurveyVariablesProfiles::getCurentProfileId() != SVP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyConditionProfiles::getCurentProfileId() != SCP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyTimeProfiles::getCurentProfileId() != STP_DEFAULT_PROFILE)
+ return true;
+
+ if (SurveyStatusProfiles::getCurentProfileId() != SSP_DEFAULT_PROFILE)
+ return true;
+ }
+
+ return false;
+ }
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyStatistic.php b/admin/survey/classes/class.SurveyStatistic.php
new file mode 100644
index 0000000..89910fe
--- /dev/null
+++ b/admin/survey/classes/class.SurveyStatistic.php
@@ -0,0 +1,2482 @@
+<?php
+/*
+ * Created on 28.01.2010
+ *
+ */
+if(session_id() == '') {session_start();}
+
+define('TYPE_ALL', 'all'); # čisto vsi statusi
+define('TYPE_APPROPRIATE', 'appropriate'); # ustrezni statusi 6,5 brez lurkerjev
+define('TYPE_STATUS_6', 'status_6'); # ustrezni statusi 6 brez lurkerjev
+define('TYPE_STATUS_5', 'status_5'); # ustrezni statusi 5 brez lurkerjev
+define('TYPE_INAPPROPRIATE', 'inappropriate'); # neustrezni statusi 6l,5l,4,3,2,1,0,-1
+define('TYPE_STATUS_6l', 'status_6l'); # neustrezni statusi 6l
+define('TYPE_STATUS_5l', 'status_5l'); # neustrezni statusi 5l
+define('TYPE_STATUS_4', 'status_4'); # neustrezni statusi 4
+define('TYPE_STATUS_3', 'status_3'); # neustrezni statusi 3
+define('TYPE_STATUS_2', 'status_2'); # neustrezni statusi 2
+define('TYPE_STATUS_1', 'status_1'); # neustrezni statusi 1
+define('TYPE_STATUS_0', 'status_0'); # neustrezni statusi 0
+# končal anketo => 6
+define('TYPE_STATUS_KUMULATIVE_6', 'status_kum_6'); # kumulativni statusi 6 brez lurkerjev
+# začel izpolnjevat => 5 = 6 + 5 (brez L)
+define('TYPE_STATUS_KUMULATIVE_5', 'status_kum_5'); # kumulativni statusi 6 in 5 brez lurkerjev
+define('TYPE_STATUS_KUMULATIVE_5ll', 'status_kum_5ll'); # kumulativni statusi 5ll
+define('TYPE_STATUS_KUMULATIVE_4ll', 'status_kum_4ll'); # kumulativni statusi 4ll
+define('TYPE_STATUS_KUMULATIVE_3ll', 'status_kum_3ll'); # kumulativni statusi 3ll
+
+define('TYPE_STATUS_NULL', 'status_null'); # neustrezni statusi NULL <=> -1
+define('TYPE_PAGES', 'pages');
+define('TYPE_ANALYSIS', 'analysis');
+define('DATE_FORMAT', 'Y-m-d');
+define('DATE_FORMAT_SHORT', 'j.n.y');
+define('TIME_FORMAT_SHORT', 'G:i');
+
+define('PERIOD_MONTH_PERIOD', 'month_period'); # meseci v obdobju
+define('PERIOD_WEEK_PERIOD', 'week_period'); # tedni v obdobju
+define('PERIOD_DAY_PERIOD', 'day_period'); # dnevi v mesecu v obdobju(izpis po datumih - dnevi)
+define('PERIOD_HOUR_PERIOD', 'hour_period'); # ure v obdobju ( 0 - 23 ) za vsak dan posebej
+define('PERIOD_MONTH_YEAR', 'month_year'); # meseci v letu v obdobju (1-12)
+define('PERIOD_WEEK_YEAR', 'week_year'); # tedni v letu v obdobju (1-52)
+define('PERIOD_DAY_YEAR', 'day_year'); # dnevi v letu v obdobju (1-366)
+define('PERIOD_DAY_MONTH', 'day_month'); # dnevi v mesecu v obdobju (1-31)
+define('PERIOD_DAY_WEEK', 'day_week'); # dnevi v tednu ( 1 - 7 ) (pon-ned)
+define('PERIOD_HOUR_DAY', 'hour_day'); # ure v dnevu ( 0 - 23 )
+
+define('GRAPH_REDUCE', '1.22'); # količnik za koliko zmanjšamo širino grafa da ne prebije
+
+define('REFRESH_USER_COUNT', 1000); # Koliko userejv je meja da delamo refresh na 15 minut
+define('REFRESH_USER_TIME', 15); # Na koliko minut delamo update za veliko bazo
+
+
+class SurveyStatistic {
+ public $inited=false; // inicializacija
+ public $surveyId = null; // id ankete
+
+ public $doCache = false; // ali keširamo dashboard
+
+ public $startDate = null; // datum zacetka statistik
+ public $endDate = null; // datum konca statistik
+ public $type = TYPE_STATUS_KUMULATIVE_3ll;
+ public $period = PERIOD_DAY_PERIOD;
+ public $periods = array (PERIOD_MONTH_PERIOD,PERIOD_WEEK_PERIOD,PERIOD_DAY_PERIOD,PERIOD_HOUR_PERIOD,PERIOD_MONTH_YEAR,PERIOD_WEEK_YEAR,PERIOD_DAY_YEAR,PERIOD_DAY_MONTH,PERIOD_DAY_WEEK,PERIOD_HOUR_DAY); // možni tipi statistike
+ public $hideNullValues_dates = true; // ali prikazujemo nicelne vrednosti pri statistiki referalov
+ public $hideNullValues_status = true; // ali skrivamo nicelne vrednosti pri statisti statusov
+ public $filter_email_status = 0; // vsi userji
+
+ public $timelineDropDownType = 1; // 0 - končni statusi, 1 - kumulativni statusi
+
+ public $isDefaultFilters = false; // ali imampo privzete filtre
+
+ public $range = null;
+ public $arrayRange = null; // za datumsko porazdelitev koikov
+ public $allRecordCount = null; // koliko je vseh zapisov v bazi (neglede na datumsko obdobje)
+ public $maxValue = 0;
+
+ public $isInterval = false; // ali je uporabnik izbral datum iz intervala
+ public $stat_interval = null; // obdobje intervala
+
+
+ /*
+ "srv_userstatus_0" => "Email &#154;e ni bil poslan",
+ "srv_userstatus_1" => "Email poslan",
+ "srv_userstatus_2" => "Napaka pri po&#154;iljanju emaila",
+ "srv_userstatus_3" => "Klik na anketo",
+ "srv_userstatus_4" => "Klik na prvo stran",
+ "srv_userstatus_5" => "Za&#269;el izpolnjevati",
+ "srv_userstatus_6" => "Kon&#269;al anketo",
+ */
+ public $userByStatus = array('valid'=>array(6=>0,5=>0),
+ 'nonvalid'=>array('6l'=>0,'5l'=>0,4=>0,3=>0,-1=>0),
+ 'invitation'=>array(2=>0,1=>0,0=>0)); // za porazdelitev userjev po statusu
+ public $testDataCount = 0;
+ public $appropriateStatus = array(6,5); // Statusi anket katere štejemo kot ustrezne
+ public $unAppropriateStatus = array('6l','5l',4,3,-1); // Statusi anket katere štejemo kot neustrezne, 5l, 6l - lurkerji
+ public $invitationStatus = array(2,1,0); // Statusi anket katere štejemo kot neustrezne, 5l, 6l - lurkerji
+
+ public $emailInvitation = 0; # vsi respondenti (email in normalni)
+ public $cntUserByStatus = array('valid'=>0, 'nonvalid'=>0, 'invitation'=>0); // Štejemo userej po statusu
+ public $emailStatus = array(0,1,2); // Statusi povezani z emaili, se upoštevajo v statistiki neglede na datu (timeinsert)
+
+ public $cntValidRedirections = 0; // Stejemo vlejavne referale (ki vsebujejo tekst)
+ public $cntNonValidRedirections = 0; // Stejemo neveljavne referale (ki ne vsebujejo teksta)
+ public $userRedirections = array(3=>0,4=>0,5=>0,6=>0,'valid' => array('email'=>0),'email'=>0,'direct'=>0, 'cntAll'=>0); // za porazdelitev redirekcij na anketo
+ public $maxRedirection = 0; // koliko je maksimalno število klikov (za primerno širino diva)
+ public $maxCharRedirection = 0; // max stevilo znakovv v "host" (za lepsi izpis redirekcij)
+
+ public $realUsersByStatus_all = 0; // skupaj frekvenc
+ public $realUsersByStatus = array(); // frekvenca po posameznem statusu (uposeteva da ce je kdo koncal anketo jo je tudi zacel)
+ public $respondentLangArray = array(); # grupiranje po jezikih
+
+ public $realUsersByStatus_base = '3ll'; # kateri status nam predstavlja osnovo (100%) v oknu stopnje odgovorov
+
+ public $pageUsersByStatus_base = '3ll'; # kateri status nam predstavlja osnovo (100%) v oknu potek po straneh
+
+ public $ip_list = array();
+
+ public $db_table = "";
+
+ public $fileTimestamp = null; # timestamp ki ga dodelimo datoteki če shranimo dashboard v fajl
+
+ public $comments = array(); # za komentarej ankete
+
+ public $cnt_all = 0;
+ public $cnt_email = 0;
+
+
+ /** Inicializacija
+ *
+ */
+ function Init($sid, $forceDefaultFilter = false) {
+ global $global_user_id;
+ # nastavimo sid
+ $this->surveyId = $sid;
+ $this->setSurveyId($sid);
+
+ Common::deletePreviewData($sid);
+
+ # inicializiramo časovne porfile
+ SurveyTimeProfiles :: Init($this->getSurveyId(), $global_user_id);
+
+ # poiščemo aktivno anketo
+ SurveyInfo :: getInstance()->SurveyInit($this->getSurveyId());
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ # nastavimo spremenljivko ali imamo vse default vrednosti
+ $this->isDefaultFilters = true;
+
+ # resetiramo timestamp
+ $this->fileTimestamp = null;
+
+ # osvezimo datume zacetka in konca iz profila
+ $this->RefreshDates($forceDefaultFilter);
+
+
+ # če se število respondentov z emaili in brez razlikuje ponudimo filter
+ $str1 = "SELECT count(*) FROM srv_user WHERE ank_id = '".$this->getSurveyId()."' AND preview = '0' AND deleted='0' AND (time_insert BETWEEN '".$this->startDate."' AND '".$this->endDate."' + INTERVAL 1 DAY)";
+ list($cnt_all) = mysqli_fetch_row(sisplet_query($str1));
+ $str2 = "SELECT count(*) FROM srv_user WHERE ank_id = '".$this->getSurveyId()."' AND preview = '0' AND deleted='0' AND inv_res_id is NOT NULL AND (time_insert BETWEEN '".$this->startDate."' AND '".$this->endDate."' + INTERVAL 1 DAY)";
+ list($cnt_email) = mysqli_fetch_row(sisplet_query($str2));
+ $this->cnt_all = (int)$cnt_all;
+ $this->cnt_email = (int)$cnt_email;
+
+
+ # ali gledamo vse/samo emaile/brez emailov
+ if ( isset($_REQUEST['filter_email_status']) && $_REQUEST['filter_email_status'] != "") {
+ $this->emailInvitation = (int)$_REQUEST['filter_email_status'];
+ } else if ( $this->cnt_all == $this->cnt_email && $this->cnt_all > 0 ) {
+ $this->emailInvitation = 1;
+ }
+ # tip statistike, strani, analize, uporabniki
+ #privzet tip:
+ $this->type = TYPE_STATUS_KUMULATIVE_3ll;
+ $this->isDefaultFilters = true;
+ if ( isset($_REQUEST['type']) && $_REQUEST['type'] != "") {
+ $this->type = $_REQUEST['type'];
+ $this->isDefaultFilters = false;
+ }
+
+ # Ali skrivamo vrednosti ki so 0 za datumski prikaz
+ if ( isset($_REQUEST['hideNullValues_dates']) && $_REQUEST['hideNullValues_dates'] != "") {
+ $this->hideNullValues_dates = ($_REQUEST['hideNullValues_dates'] == 'true');
+ $this->isDefaultFilters = false;
+ }
+
+ # Ali skrivamo vrednosti ki so 0 pri statusih
+ if ( isset($_REQUEST['hideNullValues_status']) && $_REQUEST['hideNullValues_status'] != "") {
+ $this->hideNullValues_status = ($_REQUEST['hideNullValues_status'] == 'true');
+ $this->isDefaultFilters = false;
+ }
+
+ # Kateri dropdown prikažemo. ali z končnimi statusi, ali pa z kumulativnmi statusi
+ if ( isset($_REQUEST['timelineDropDownType']) && $_REQUEST['timelineDropDownType'] == 'false') {
+ $this->timelineDropDownType = 0;
+ $this->isDefaultFilters = false;
+ # če nimamo pravega tipa
+ } else {
+ if (!in_array($this->type, array(TYPE_STATUS_KUMULATIVE_3ll, TYPE_STATUS_KUMULATIVE_4ll, TYPE_STATUS_KUMULATIVE_5ll, TYPE_STATUS_KUMULATIVE_5, TYPE_STATUS_KUMULATIVE_6))) {
+ $this->type = TYPE_STATUS_KUMULATIVE_3ll;
+ }
+
+ }
+
+
+ # Time filter
+ if ( (int)SurveyTimeProfiles ::getCurentProfileId() !== (int)SurveyTimeProfiles ::getSystemDefaultProfile())
+ {
+ $this->isDefaultFilters = false;
+ }
+
+
+ # obdobje prikaza
+ if ( isset($_REQUEST['period']) && $_REQUEST['period'] != "") {
+ $this->period = $_REQUEST['period'];
+ $this->isDefaultFilters = false;
+ }
+ # osnova za stopnje odgovorov (dropdown)
+ # če smo preklopli na email vabila in če imamo samo vabila je osnova email
+ if ($this->emailInvitation === 1 && $_REQUEST['inviation_dropdown'] === 'true') {
+ $this->realUsersByStatus_base = 'email';
+ } else if ( isset($_REQUEST['userStatusBase']) && $_REQUEST['userStatusBase'] != "") {
+ if ($this->emailInvitation !== 1 && $_REQUEST['userStatusBase'] == 'email') {
+ $_REQUEST['userStatusBase'] = '3ll';
+ }
+ $this->realUsersByStatus_base = $_REQUEST['userStatusBase'];
+ $this->isDefaultFilters = false;
+ }
+
+ // Osnova za odgovore po straneh
+ if (isset($_REQUEST['pageUserStatusBase']) && $_REQUEST['pageUserStatusBase'] != "") {
+ if ($this->emailInvitation !== 1 && $_REQUEST['pageUserStatusBase'] == 'email') {
+ $_REQUEST['pageUserStatusBase'] = '3ll';
+ }
+ $this->pageUsersByStatus_base = $_REQUEST['pageUserStatusBase'];
+ $this->isDefaultFilters = false;
+ }
+
+ if ((int)$sid > 0) {
+ $this->inited = true;
+ }
+ }
+
+ function ajax() {
+ global $lang;
+ }
+
+ // GETTERS & SETTERS
+ function getSurveyId() { return $this->surveyId; }
+ function setSurveyId($sid) { $this->surveyId = $sid; }
+ function getStartDate() { return $this->startDate; }
+ function setStartDate($sd) { $this->startDate = $sd; }
+ function getEndDate() { return $this->endDate; }
+ function setEndDate($ed) { $this->endDate = $ed; }
+ function getUserByStatus() { return $this->userByStatus; }
+ function getCntUserByStatus() { return $this->cntUserByStatus; }
+ function setPeriod($period) { $this->period = $period; }
+ function getArrayRange() { return $this->arrayRange; }//dobi range po datumih
+ function getUserRedirections() { return $this->userRedirections; }//dobi preusmeritve
+
+
+ function RefreshDates($forceDefaultFilter = false) {
+ # iz profila preberemo začetni datum in končni datum
+ $dates = SurveyTimeProfiles :: GetDates($forceDefaultFilter);
+ $this->startDate = $dates['start_date'];
+ $this->endDate = $dates['end_date'];
+ if ($dates['is_default_dates'] == false) {
+ $this->isDefaultFilters = false;
+ }
+ }
+
+ /** Pripravi osnovne podatke ce niso podani drugace
+ *
+ */
+ function PrepareDateView() {
+ switch ($this->type) {
+ case TYPE_ALL :
+ case TYPE_APPROPRIATE :
+ case TYPE_STATUS_6 :
+ case TYPE_STATUS_5 :
+ case TYPE_INAPPROPRIATE :
+ case TYPE_STATUS_6l :
+ case TYPE_STATUS_5l :
+ case TYPE_STATUS_4 :
+ case TYPE_STATUS_3 :
+ case TYPE_STATUS_2 :
+ case TYPE_STATUS_1 :
+ case TYPE_STATUS_0 :
+ case TYPE_STATUS_NULL :
+ #še kumulativni statusi
+ case TYPE_STATUS_KUMULATIVE_6:
+ case TYPE_STATUS_KUMULATIVE_5:
+ case TYPE_STATUS_KUMULATIVE_5ll:
+ case TYPE_STATUS_KUMULATIVE_4ll:
+ case TYPE_STATUS_KUMULATIVE_3ll:
+ $time_edit = 'srv_user.time_insert';
+ break;
+ case TYPE_PAGES :
+ $time_edit = 'grupa.time_edit';
+ break;
+ case TYPE_ANALYSIS :
+ $time_edit = 'srv_tracking'.$this->db_table.'.datetime';
+ break;
+ }
+
+ switch ($this->period) {
+ case PERIOD_MONTH_PERIOD :
+ // vzamemo prvi dan v izbranem mesecu
+ $intervalFormat = "DATE_FORMAT($time_edit,'%Y-%m') AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = $this->createDateRangeArray($this->startDate, $this->endDate, "Y-m", 'm');
+ break;
+ case PERIOD_WEEK_PERIOD :
+ // vzamemo prvi dan v izbranem mesecu
+ $intervalFormat = "YEARWEEK($time_edit) AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = $this->createDateRangeArray($this->startDate, $this->endDate, "YW", 'W');
+ break;
+
+ case PERIOD_MONTH_YEAR :
+ $intervalFormat = "MONTH($time_edit) AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = (($this->startDate <= $this->endDate) ? array_fill(1, 12, 0) : array ());
+ break;
+ case PERIOD_WEEK_YEAR :
+ $intervalFormat = "WEEKOFYEAR($time_edit) AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = (($this->startDate <= $this->endDate) ? array_fill(1, 52, 0) : array ());
+ break;
+ case PERIOD_DAY_YEAR :
+ $intervalFormat = "DAYOFYEAR($time_edit) AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = (($this->startDate <= $this->endDate) ? array_fill(1, 366, 0) : array ());
+ break;
+ case PERIOD_DAY_MONTH :
+ $intervalFormat = "DAYOFMONTH($time_edit) AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = (($this->startDate <= $this->endDate) ? array_fill(1, 31, 0) : array ());
+ break;
+
+ case PERIOD_DAY_PERIOD :
+ $intervalFormat = "DATE_FORMAT($time_edit,'%Y-%m-%d') AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = $this->createDateRangeArray($this->startDate, $this->endDate, DATE_FORMAT);
+ break;
+ case PERIOD_DAY_WEEK :
+ $intervalFormat = "WEEKDAY($time_edit) AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = (($this->startDate <= $this->endDate) ? array_fill(0, 7, 0) : array ());
+ break;
+ case PERIOD_HOUR_DAY :
+ $intervalFormat = "DATE_FORMAT($time_edit,'%H') AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) // da ne delamo po neporebnem
+ $this->arrayRange = (($this->startDate <= $this->endDate) ? $this->createDateRangeArray(null,null,null,'H') : array ());
+ break;
+ case PERIOD_HOUR_PERIOD :
+ $intervalFormat = "DATE_FORMAT($time_edit,'%Y-%m-%d %H') AS formatdate ";
+ $groupBy = "GROUP BY formatdate ";
+ if (!$this->hideNullValues_dates) {// da ne delamo po neporebnem
+ // pripravimo data array
+ //$this->arrayRange = $this->createPeriodDateRangeArray(PERIOD_HOUR_PERIOD, $this->startDate, $this->endDate);
+ $this->arrayRange = $this->createDateRangeArray($this->startDate, $this->endDate, "Y-m-d H", 'h');
+ }
+ break;
+ }
+
+ $email_filter_string = null;
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ } else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ // Tega ne rabimo? Drugace je pri kopirani arivski anketi vse prazno
+ //$intervalLimit = "AND $time_edit BETWEEN '".$this->startDate."' AND '".$this->endDate."' + INTERVAL 1 DAY ";
+ $intervalLimit = "";
+
+ switch ($this->type) {
+ # VSI
+ case TYPE_ALL :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' " . $email_filter_string . $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' ".$email_filter_string; // vsi statusi
+ break;
+
+ # USTREZNI BREZ LURKERJEV
+ case TYPE_APPROPRIATE : # 6,5 brez lurkerjev
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' " . " AND last_status IN (6,5) AND lurker = '0' ".$email_filter_string . $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status IN (6,5) AND lurker = '0' ".$email_filter_string; // samo veljavne statuse
+ break;
+
+ # USTREZNI 6 BREZ LURKERJEV
+ case TYPE_STATUS_6 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string . $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string;
+ break;
+
+ # USTREZNI 5 BREZ LURKERJEV
+ case TYPE_STATUS_5 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '5' AND lurker = '0' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '5' AND lurker = '0' ".$email_filter_string;
+ break;
+
+ # NEUSTREZNI
+ case TYPE_INAPPROPRIATE :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND ( last_status NOT IN (6,5) OR lurker = '1') ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status NOT IN (6,5) OR lurker = '1' ".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 6L lurkerji
+ case TYPE_STATUS_6l :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '1' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '1' ".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 5L lurkerji
+ case TYPE_STATUS_5l :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '5' AND lurker = '1' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '1' ".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 4
+ case TYPE_STATUS_4 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '4' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '4' ".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 3
+ case TYPE_STATUS_3 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '3' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '3'".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 2
+ case TYPE_STATUS_2 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '2' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '2'".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 1
+ case TYPE_STATUS_1 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '1' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '1'".$email_filter_string;
+ break;
+
+ # NEUSTREZNI 0
+ case TYPE_STATUS_0 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '0' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '0'".$email_filter_string;
+ break;
+
+ # NEUSTREZNI NULL
+ case TYPE_STATUS_NULL :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '-1' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '-1'.$email_filter_string";
+ break;
+
+ # kumuativni statusi
+ # KUMULATIVNI 6 BREZ LURKERJEV
+ case TYPE_STATUS_KUMULATIVE_6 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string;
+ break;
+ # KUMULATIVNI 5 = 6 in 5 BREZ LURKERJEV
+ case TYPE_STATUS_KUMULATIVE_5 :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status IN ('6','5') AND lurker = '0' ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string;
+ break;
+
+ # KUMULATIVNI 5LL = 6 in 5 z lurkerji
+ case TYPE_STATUS_KUMULATIVE_5ll :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status IN ('6','5') ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string;
+ break;
+
+ # KUMULATIVNI 4LL = 6 in 5 z lurkerji in 4
+ case TYPE_STATUS_KUMULATIVE_4ll :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status IN ('6','5','4') ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string;
+ break;
+
+ # KUMULATIVNI 3LL = 6 in 5 z lurkerji in 4 in 3
+ case TYPE_STATUS_KUMULATIVE_3ll :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status IN ('6','5','4','3') ".$email_filter_string. $intervalLimit . $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user WHERE ank_id = '" . $this->getSurveyId() . "' AND preview = '0' AND deleted='0' AND last_status = '6' AND lurker = '0' ".$email_filter_string;
+ break;
+
+ case TYPE_PAGES :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_user_grupa".$this->db_table." AS grupa, srv_grupa WHERE" .
+ " grupa.gru_id = srv_grupa.id AND srv_grupa.ank_id = '".$this->getSurveyId()."'" . $intervalLimit . " ". $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_user_grupa".$this->db_table." AS grupa, srv_grupa WHERE" .
+ " grupa.gru_id = srv_grupa.id AND srv_grupa.ank_id = '".$this->getSurveyId()."'";
+
+ break;
+ case TYPE_ANALYSIS :
+ $sqlString = "SELECT " . $intervalFormat . ", count(*) as cnt FROM srv_tracking".$this->db_table." WHERE" .
+ " `get` LIKE '%analiza%' AND srv_tracking".$this->db_table.".ank_id = '".$this->getSurveyId()."'" . $intervalLimit . " ". $groupBy;
+ $sqlStringAll = "SELECT count(*) as cnt FROM srv_tracking".$this->db_table." WHERE" .
+ " `get` LIKE '%analiza%' AND srv_tracking".$this->db_table.".ank_id = '".$this->getSurveyId()."'";
+ break;
+ }
+ // napolnomo array z damumi med intervali
+ $sql = sisplet_query($sqlString) ;
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $this->range[$row['formatdate']] = $row['cnt'];
+ }
+
+ // preštejemo vse neodvisno od datuma
+ $sqlAll = sisplet_query($sqlStringAll) ;
+ $rowAll = mysqli_fetch_assoc($sqlAll);
+ $this->allRecordCount = $rowAll['cnt'];
+
+ if ($this->hideNullValues_dates)
+ $this->arrayRange = array(); // naredimo prazen array in nato dodamo samo vrednosti > 0
+
+ // kjer imamo zapise popravimo pre"stete vrednosti
+ if ($this->range)
+ foreach ($this->range as $key => $value) {
+
+
+ $this->arrayRange[$key] = $value;
+ $this->maxValue = max($this->maxValue, $value);
+ }
+
+ }
+
+ /** Funkcija pripravi podatke za vse panele razen za panel DIsplayData
+ *
+ */
+ function prepareStatusView() {
+
+ $email_filter_string = null;
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ }
+ else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ // Tukaj ne vem zakaj filtriramo po datumu? Itak rabimo vse
+ $qry = sisplet_query("SELECT id, last_status, lurker, testdata, inv_res_id, referer, language
+ FROM srv_user
+ WHERE ank_id = '".$this->getSurveyId()."' AND preview='0' AND deleted='0'"
+ .$email_filter_string
+ );
+ if (mysqli_num_rows($qry) > 0) {
+
+ $user_id_to_check_link = array(); # id-ji uporabnikov pri katerih imamo direkten klik. naknadno ugotavljamo ali je slučajno e-mail vabilo
+
+ while ($row = mysqli_fetch_assoc($qry)) {
+
+ if ($this->emailInvitation == 1 && $row['inv_res_id'] != null){
+ $this->userByStatus['valid']['email'] += 1;
+ }
+
+ if ((int)$row['testdata'] > 0) {
+ $this->testDataCount++;
+ }
+
+ // dodamo statuse
+ if (in_array($row['last_status'], $this->appropriateStatus)){
+
+ # če ni lurker je ok
+ if ($row['lurker'] == 0){
+ $this->userByStatus['valid'][$row['last_status']] += 1;
+ $this->cntUserByStatus['valid'] += 1;
+ }
+ else{
+ # če je lurker ga dodamo k neveljavnim
+ $this->userByStatus['nonvalid'][$row['last_status'].'l'] += 1;
+ $this->cntUserByStatus['nonvalid'] += 1;
+ }
+ }
+ # neveljavne enote
+ else if (in_array($row['last_status'], $this->unAppropriateStatus)){
+ $this->userByStatus['nonvalid'][$row['last_status']] += 1;
+ $this->cntUserByStatus['nonvalid'] += 1;
+ }
+ # emaili
+ else if (in_array($row['last_status'], $this->invitationStatus)){
+ $this->userByStatus['invitation'][$row['last_status']] += 1;
+ $this->cntUserByStatus['invitation'] += 1;
+ }
+
+ #polovimo redirekte
+ if (in_array((int)$row['last_status'], $this->invitationStatus)){
+ # email vabila ... ne lovimo redirektov
+ # podatek o referalu je prazen lahko da email ni bil poslan, ali pa gre za direkten link
+ #$this->cntNonValidRedirections += 1;
+ #$this->userRedirections[(int)$row['last_status']] += 1;
+ }
+ else {
+ # če so vabila
+ if ($row['inv_res_id'] != null ){
+ $this->cntValidRedirections += 1;
+ $this->userRedirections["valid"]['email'] += 1;
+ //$this->userRedirections["cntAll"] += 1;
+ $this->maxRedirection = max($this->maxRedirection , $this->userRedirections["valid"]['email']);
+ }
+ # če imamo referal
+ else if ($row['referer'] != "" && $row['referer'] != "0"){
+ $parsed = parse_url($row['referer']);
+ $this->cntValidRedirections += 1;
+ $this->userRedirections["valid"][$parsed['host']] += 1;
+ //$this->userRedirections["cntAll"] += 1;
+ $this->maxCharRedirection = max($this->maxCharRedirection , strlen ($parsed['host']) );
+ $this->maxRedirection = max($this->maxRedirection , $this->userRedirections["valid"][$parsed['host']] );
+ }
+ # če ne je najbrž direkten link
+ else{
+ # shranimo id_userjev za katere nato ugotavljamo ali je link res direkten ali obstaja kaksen zapis da je slo preko e-maila
+ $user_id_to_check_link[] = $row['id'];
+ $_tmp_direct +=1;
+
+ $this->cntNonValidRedirections += 1;
+ }
+ }
+
+ #polovimo jezike
+ if (isset($this->respondentLangArray[$row['language']])){
+ $this->respondentLangArray[$row['language']] ++;
+ }
+ else{
+ $this->respondentLangArray[$row['language']] = 1;
+ }
+ }
+
+ }
+
+ # od direktnega klika odštejemo e-mail vabila
+ if (count($user_id_to_check_link)> 0) {
+
+ $qryEmail = sisplet_query("SELECT COUNT(*) as cnt FROM srv_userstatus WHERE usr_id IN (".implode(',', $user_id_to_check_link).") AND status IN (".implode(',', $this->emailStatus).")");
+ $rwsEmail = mysqli_fetch_assoc($qryEmail);
+
+ $this->userRedirections["email"] = (int)$rwsEmail['cnt'];
+
+ $directCnt = (int)$_tmp_direct - (int)$rwsEmail['cnt'];
+
+ $this->userRedirections["direct"] = $directCnt;
+ //$this->userRedirections["cntAll"] += $directCnt;
+ }
+
+ // prestejemo max stevilo klikov za lepsi izris tabele
+ $this->maxRedirection = max($this->maxRedirection , $this->userRedirections["2"], $this->userRedirections["1"], $this->userRedirections["0"],$this->userRedirections["direct"], $this->userRedirections['email']);
+
+ # izracunamo realne frekvence po statusih
+ # Klik na anketo - vsak ki je končal anketo (itd...) je "najbrž" tudi kliknil na anketo..
+ $this->realUsersByStatus_all = $this->userByStatus['valid'][6]
+ + $this->userByStatus['valid'][5]
+ + $this->userByStatus['nonvalid']['5l']
+ + $this->userByStatus['nonvalid']['6l']
+ + $this->userByStatus['nonvalid'][4]
+ + $this->userByStatus['nonvalid'][3]
+ + $this->userByStatus['nonvalid'][-1];
+ // Klik na prvo stran - vsak ki je končal anketo (itd...) je "najbrž" tudi kliknil na anketo..
+ # končal anketo => 6
+ $this->realUsersByStatus[6] = array('cnt'=>$this->userByStatus['valid'][6], 'percent'=>0);
+ # začel izpolnjevat => 5 = 6 + 5
+ $this->realUsersByStatus[5] = array('cnt'=>$this->userByStatus['valid'][5]+$this->realUsersByStatus[6]['cnt'], 'percent'=>0);
+ # Koliko ljudi je dejansko končalo anketo ne glede na to ali so lurkerji 6 + 6l
+ $this->realUsersByStatus['6ll'] = array('cnt'=>$this->userByStatus['nonvalid']['6l']+$this->realUsersByStatus[6]['cnt'], 'percent'=>0);
+ # delno izpolnjena 4ll => 6 + 5 + 6l + 5l
+ $this->realUsersByStatus['5ll'] = array('cnt'=>$this->userByStatus['nonvalid']['6l']+$this->userByStatus['nonvalid']['5l']+$this->realUsersByStatus[5]['cnt'], 'percent'=>0);
+ # klik na prvo stran => 4 = 6 + 6l + 5l + 5 + 4
+ $this->realUsersByStatus['4ll'] = array('cnt'=>$this->userByStatus['nonvalid'][4]+$this->realUsersByStatus['5ll']['cnt'], 'percent'=>0);
+ # klik na anketo => 3 = 6 + 6l + 5l + 5 + 4 + 3
+ $this->realUsersByStatus['3ll'] = array('cnt'=>$this->userByStatus['nonvalid'][3]+$this->userByStatus['nonvalid'][-1]+$this->realUsersByStatus['4ll']['cnt'], 'percent'=>0);
+ //if ($this->emailInvitation == 1)
+ {
+ $this->realUsersByStatus['email']
+ = array('cnt'=>(isset($this->userByStatus['valid']['email'])?$this->userByStatus['valid']['email']:0), 'percent'=>0);
+ }
+ // izracunamo se procente
+ # v odvisnosti od osnove (dropdown) izberemo kaj nam predstavlja 100%
+ $status_100_percent = ($this->realUsersByStatus_base == '3ll')
+ ? $this->realUsersByStatus_all
+ : $this->realUsersByStatus[$this->realUsersByStatus_base]['cnt'];
+
+ foreach ($this->realUsersByStatus as $key => $value) {
+ $this->realUsersByStatus[$key]['percent'] = ($status_100_percent > 0) ? $value['cnt'] / $status_100_percent : 0;
+ }
+
+ # komentarji
+ $SD = new SurveyDiagnostics($this->surveyId);
+ $this->comments = $SD->testComments();
+ }
+
+
+ /** Funkcija klice funkcije za prikaz statistike
+ * DisplayInfoView - prikaze panelo z osnovnimi informacijami
+ * DisplayStatusView - prikaze panelo z kliki po statusih
+ * DisplayReferalsView - prikaze panelo z redirekcijami in referali
+ * DisplayDataView - prikate panelo z kliki po datumih
+ */
+ function Display() {
+ global $lang, $site_url;
+
+ $dashboardHtml = null;
+
+ // Preverjamo ce imamo slucajno izklopljeno shranjevanje datumov odgovorov (potem ni vecine statusov)
+ $paradata_date = SurveySetting::getInstance()->getSurveyMiscSetting('survey_date');
+
+
+ $dashboardCacheFile = $this->CheckDashbordChacheFile();
+
+
+ // Preverimo stanje datoteke s podatki
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->surveyId);
+
+
+ # iz chace preberemo samo za osnovni profil
+ if ($this->doCache && $dashboardCacheFile !== null && $this->isDefaultFilters == true ) {
+
+ #čas updejta iz dashboarda
+ $_sql_string = "SELECT DATE_FORMAT(dashboard_update_time,'%d.%m.%Y %H:%i:%s') FROM srv_data_files WHERE sid = '".$this->surveyId."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ list($dashboard_update_time) = mysqli_fetch_row($_sql_qry);
+ echo '<span id="srv_dashboard_updated">'.$lang['srv_dashboard_updated'].$dashboard_update_time.'</span>';
+
+ #preberemo podatke o datoteki
+ echo $SDF->getDataFileInfo();
+
+ # preberemo cache file in ga zehamo
+ echo $this->ReadCacheFile();
+ }
+ else {
+
+ $dashboard_update_time = date("d.m.Y, H:i:s");
+ echo '<span id="srv_dashboard_updated">'.$lang['srv_dashboard_updated'].$dashboard_update_time.'</span>';
+
+ #preberemo podatke o datoteki
+ echo $SDF->getDataFileInfo();
+
+ // Ce ne zbiramo parapodatkov casov resevanja izpisemo opozorilo
+ if($paradata_date == 1)
+ echo '<br /><br /><span>'.$lang['srv_dashboard_paradata_date_warning'].'</span>';
+
+ // Prikazemo filter na datum ce je vklopljen
+ if (SurveyTimeProfiles::getCurentProfileId() != STP_DEFAULT_PROFILE){
+ echo '<br class="clr" /><br class="clr" />';
+ echo '<div id="displayFilterNotes">';
+ SurveyTimeProfiles :: printIsDefaultProfile();
+ echo '</div>';
+ }
+
+ # Cache file ne obstaja. Če imamo privzete nastavitve vseh filtrov, shranimo prikazan html v datoteko
+ # spodnje ehote shranimo v spremenljivko ki jo popotrebi keširanja shranimo v datoteko.
+
+ ob_start();
+ $email_filter_string = null;
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ } else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ // preverimo ali ima anketa kakšne vnose
+ $str_qry_all_users = "SELECT count(u.id) AS user_count FROM srv_user AS u " . "WHERE u.ank_id = '".$this->getSurveyId()."' AND preview = '0' AND deleted='0' ".$email_filter_string;
+ $qry_all_users = sisplet_query($str_qry_all_users);
+ $row_all_users = mysqli_fetch_assoc($qry_all_users);
+ $allUserCount = $row_all_users['user_count'];
+
+ // nimamo še vnosov
+ if ($allUserCount == 0 || $paradata_date == 1) {
+
+ // zgornji boxi
+ echo '<table class="dashboard dashboard_single">';
+ echo '<tr>';
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_info" id="div_statistic_info" >'."\n";
+ $this -> DisplayInfoView();
+ echo '</div>';
+ echo '</td>';
+ echo '</tr>';
+ echo '</table>';
+ }
+ // imamo vnose, prikažemo statistiko
+ else {
+
+ $this->PrepareDateView();
+ $this->PrepareStatusView();
+
+ echo '<table class="dashboard">';
+ echo '<tr>';
+
+ // zgornji boxi
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_info" id="div_statistic_info" >'."\n";
+ $this -> DisplayInfoView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_status" id="div_statistic_status" >'."\n";
+ $this -> DisplayStatusView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_answer_state" id="div_statistic_answer_state" >'."\n";
+ $this -> DisplayAnswerStateView();
+ echo '</div>';
+ echo '</td>';
+ echo '</tr>';
+
+ // spodnji boxi
+ echo '<tr>';
+ echo '<td>';
+ echo '<div class="dashboard_cell" id="div_statistic_referals">';
+ $this -> DisplayReferalsView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" id="div_statistic_visit">';
+ echo '<span class="dashboard_title">'.$lang['srv_statistic_timeline_title'].'</span>'.Help :: display('srv_statistic_timeline_title');
+ $this -> DisplayFilters();
+ echo '<br/>';
+ echo '<div name="div_statistic_visit_data" id="div_statistic_visit_data" >'."\n";
+ $this -> DisplayDateView();
+ echo '</div>';
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" id="div_statistic_pages_state">';
+ $this -> DisplayPagesStateView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '</tr>';
+ echo '</table>';
+ }
+
+ # HTML zapišemo v spremenljivko
+
+ $dashboardHtml = ob_get_clean();
+ # če imamo default filtre zapišemo v datoteko; Prav tako mora bit izbran osnovni profil intervala z id = 0
+ if ($dashboardHtml != null && $this->isDefaultFilters == true) {
+ # poiščemo čase
+
+ # poiščemo datume sprememb v anketi
+ $str_qry_surveys = "SELECT id, UNIX_TIMESTAMP(GREATEST(insert_time,edit_time)) as time FROM srv_anketa WHERE id = '".$this->surveyId."'";
+ $qry_surveys = sisplet_query($str_qry_surveys);
+ list($id,$time1) = mysqli_fetch_row($qry_surveys);
+
+ # poiščemo datume sprememb v userju
+ $str_qry_users = "SELECT ank_id, UNIX_TIMESTAMP(GREATEST(max(time_insert), max(time_edit))) as time FROM srv_user WHERE ank_id = '".$this->surveyId."' AND preview = '0' AND deleted='0' GROUP BY ank_id";
+ $qry_users = sisplet_query($str_qry_users);
+ list($id,$time2) = mysqli_fetch_row($qry_users);
+
+ $timestamp = (int)$time1 + (int)$time2;
+
+ $this->WriteToCacheFile($dashboardHtml,$timestamp);
+ }
+ # izpišemo HTML v browser
+ echo $dashboardHtml;
+ }
+
+ echo '<div class="clr"></div>';
+ echo '<span >';
+ echo '</span>';
+
+ $dashboardHtml = null;
+ }
+
+ /** Funkcija prikaze osnovnih informacij
+ *
+ */
+ function DisplayInfoView() {
+ global $lang;
+ global $site_url;
+
+ echo '<div class="dashboard_title">'.$lang['srv_statistic_info_title'].Help :: display('srv_statistic_info_title').'</div><br/>';
+ //SurveyInfo::getInstance()->DisplayInfoBox(false);
+ /* zaradi nenehnih sprememb (Vasja) se ne da naredit univerzalno, */
+
+
+ echo '<table style="width:100%;">';
+ echo '<COLGROUP><COL width="90px"><COL width="100px"><COL width="90px"><COL width="100px"></COLGROUP>';
+
+ # ime ankete
+ echo '<tr><td>';
+ echo $lang['srv_info_name'].':';
+ echo '</td><td colspan="3">';
+ echo htmlentities(SurveyInfo::getSurveyTitle(), ENT_QUOTES, "UTF-8");
+ echo '</td>';
+ echo '</tr>';
+ if (SurveyInfo::getSurveyInfo()) {
+ #opomba
+ // prikažemo 30 znakov na mouseover pa kompletno
+ echo '<tr><td>';
+ echo $lang['srv_info_note'].':';
+ echo '</td><td colspan="3" title="' . SurveyInfo::getSurveyInfo() . '">';
+ echo htmlentities($this->limitString(SurveyInfo::getSurveyInfo(),30), ENT_QUOTES, "UTF-8");
+ echo '</td></tr>';
+ }
+
+
+ # katere napredne možnosti so vklopljene
+ $row = SurveyInfo::getSurveyRow();
+ $modules = SurveyInfo::getSurveyModules();
+ $enabled_advanced = null;
+ $prefix = '';
+ if (isset($modules['uporabnost'])) {
+ $enabled_advanced .= $prefix . $lang['srv_vrsta_survey_type_4'];
+ $prefix = ', ';
+ }
+ if ($row['user_from_cms'] == 1) {
+ $enabled_advanced .= $prefix . $lang['srv_vrsta_survey_type_5'];
+ $prefix = ', ';
+ }
+ if (isset($modules['quiz'])) {
+ $enabled_advanced .= $prefix . $lang['srv_vrsta_survey_type_6'];
+ $prefix = ', ';
+ }
+ if (isset($modules['voting'])) {
+ $enabled_advanced .= $prefix . $lang['srv_vrsta_survey_type_18'];
+ $prefix = ', ';
+ }
+ if (isset($modules['phone'])) {
+ $enabled_advanced .= $prefix . $lang['srv_vrsta_survey_type_7'];
+ $prefix = ', ';
+ }
+ if (isset($modules['social_network'])) {
+ $enabled_advanced .= $prefix . $lang['srv_vrsta_survey_type_8'];
+ $prefix = ', ';
+ }
+
+ # tip ankete
+ echo '<tr><td>';
+ echo $lang['srv_info_type'].':';
+ echo '</td><td colspan="3">';
+ echo $lang['srv_vrsta_survey_type_'.(SurveyInfo::getSurveyType()>2 ? 2 : SurveyInfo::getSurveyType())] . ($enabled_advanced != null ? ' ('.$enabled_advanced.')' : '' );
+ echo '</td></tr>';
+ # vprašanj, variabel
+ echo '<tr><td>';
+ echo $lang['srv_info_questions']. ':';
+ echo '</td><td>';
+ echo SurveyInfo::getSurveyQuestionCount();
+ echo '</td><td>';
+ echo $lang['srv_info_variables']. ':';
+ echo '</td><td>';
+ echo SurveyInfo::getSurveyVariableCount();
+ echo '</td></tr>';
+ # stevilo strani
+ echo '<tr><td>';
+ echo $lang['srv_info_pages']. ':';
+ echo '</td><td>';
+ echo SurveyInfo::getSurveyGroupCount();
+ echo '</td></tr>';
+ # uporabnikov, odgovorov
+ echo '<tr><td>';
+ echo $lang['srv_analiza_stUporabnikov']. ':';
+ echo '</td><td>';
+ echo SurveyInfo::getSurveyAnswersCount();
+ echo '</td><td>';
+ echo $lang['srv_info_answers_valid']. ':';
+ echo '</td><td>';
+ echo SurveyInfo::getSurveyApropriateAnswersCount();
+ echo '</td></tr>';
+ # jezik izpolnjevanja
+ echo '<tr><td>';
+ echo $lang['srv_info_language']. ':';
+ echo '</td><td colspan="3" >';
+ echo SurveyInfo::getRespondentLanguage();
+ echo '</td></tr>';
+ # autor
+ echo '<tr><td>';
+ echo $lang['srv_info_creator']. ':';
+ echo '</td><td colspan="3" title="'.SurveyInfo::getSurveyInsertEmail().'">';
+ echo SurveyInfo::getSurveyInsertName();
+ if (SurveyInfo::getSurveyInsertDate() && SurveyInfo::getSurveyInsertDate() != "00.00.0000")
+ echo SurveyInfo::getDateTimeSeperator() . $this->dateFormat(SurveyInfo::getSurveyInsertDate(),DATE_FORMAT_SHORT);
+ if (SurveyInfo::getSurveyInsertTime() && SurveyInfo::getSurveyInsertTime() != "00:00:00")
+ echo SurveyInfo::getDateTimeSeperator() . $this->dateFormat(SurveyInfo::getSurveyInsertTime(),TIME_FORMAT_SHORT);
+ echo '</td></tr>';
+ # spreminjal
+ echo '<tr><td>';
+ echo $lang['srv_info_modify']. ':';
+ echo '</td><td colspan="3" title="'.SurveyInfo::getSurveyEditEmail().'">';
+ echo SurveyInfo::getSurveyEditName();
+ if (SurveyInfo::getSurveyEditDate() && SurveyInfo::getSurveyEditDate() != "00.00.0000")
+ echo SurveyInfo::getDateTimeSeperator() . $this->dateFormat(SurveyInfo::getSurveyEditDate(),DATE_FORMAT_SHORT);
+ if (SurveyInfo::getSurveyEditTime() && SurveyInfo::getSurveyEditTime() != "00:00:00")
+ echo SurveyInfo::getDateTimeSeperator() . $this->dateFormat(SurveyInfo::getSurveyEditTime(),TIME_FORMAT_SHORT);
+ echo '</td></tr>';
+
+ #dostop, Kdo razen avtorja ima dostop
+ $dostop = SurveyInfo::getSurveyAccessUsers();
+ if ($dostop) {
+ echo '<tr><td>';
+ echo $lang['srv_info_access']. ':';
+ echo '</td><td colspan="3">';
+ $prefix='';
+ foreach ( $dostop as $user) {
+ //echo $prefix.'<span style="width:auto;" title="'.$user['email'].'">'.iconv("iso-8859-2", "utf-8",$user['name']).'</span>';
+ echo $prefix.'<span style="width:auto;" title="'.$user['email'].'">'.$user['name'].'</span>';
+ $prefix='; ';
+ }
+ echo '</td></tr>';
+
+ }
+ # aktivnost
+ $activity = SurveyInfo:: getSurveyActivity();
+ $_last_active = end($activity);
+ echo '<tr><td>';
+ echo $lang['srv_displaydata_status']. ':';
+ echo '</td><td colspan="3">';
+ if (SurveyInfo::getSurveyColumn('active') == 1) {
+ echo '<span style="width:auto; color: green;">'.$lang['srv_anketa_active2'].'</span>';
+ } else {
+ # preverimo ali je bila anketa že aktivirana
+ if (!isset($_last_active['starts'])) {
+ # anketa še sploh ni bila aktivirana
+ echo '<span style="width:auto; color:orange;">'.$lang['srv_survey_non_active_notActivated'].'</span>';
+ } else {
+ # anketa je že bila aktivirna ampak je sedaj neaktivna
+ echo '<span style="width:auto; color:orange;">'.$lang['srv_survey_non_active'].'</span>';
+ }
+ }
+
+ echo '</td></tr>';
+ # trajanje: datumi aktivnosti
+ if ( count($activity) > 0 ) {
+ echo '<tr><td>';
+ echo $lang['srv_info_activity']. ':';
+ echo '</td><td colspan="3">';
+ $prefix = '';
+ foreach ($activity as $active) {
+ $_starts = explode('-',$active['starts']);
+ $_expire = explode('-',$active['expire']);
+
+ echo $prefix.$_starts[2].'.'.$_starts[1].'.'.$_starts[0].'-'.$_expire[2].'.'.$_expire[1].'.'.$_expire[0];
+
+ # echo $prefix . $this->dateFormat($active['starts'],DATE_FORMAT_SHORT).'-'.$this->dateFormat($active['expire'],DATE_FORMAT_SHORT);
+ $prefix = '; ';
+ }
+ echo '</td></tr>';
+ }
+
+
+ # predviceni cas trajanja enkete
+ $sas = new SurveyAdminSettings();
+ $skupni_cas = $sas->testiranje_cas(1);
+ $skupni_predvideni_cas = $sas->testiranje_predvidenicas(1);
+
+ $d = new Dostop();
+
+ echo '<tr><td>';
+ echo $lang['srv_info_duration']. ':';
+ echo '</td><td colspan="3">';
+ echo ($skupni_cas!=''?'<a href="index.php?anketa='.$this->surveyId.'&a='.A_REPORTI . '&m='.M_TESTIRANJE_CAS.'">':'').$skupni_cas.($skupni_cas!=''?'</a>, ':'');
+
+ echo ''.$lang['srv_predvideno'].': ';
+ if ($d->checkDostopSub('test'))
+ echo '<a href="index.php?anketa='.$this->surveyId.'&a=testiranje&m=predvidenicas">';
+ echo $skupni_predvideni_cas;
+ if ($d->checkDostopSub('test'))
+ echo '</a>';
+
+ echo '</td></tr>';
+
+
+ //VNOSI - pvi / zadnji vnos
+ $prvi_vnos_date = SurveyInfo::getSurveyFirstEntryDate();
+ $prvi_vnos_time = SurveyInfo::getSurveyFirstEntryTime();
+ $zadnji_vnos_date = SurveyInfo::getSurveyLastEntryDate();
+ $zadnji_vnos_time = SurveyInfo::getSurveyLastEntryTime();
+ if ($prvi_vnos_date != null) {
+ echo '<tr><td>';
+ echo $lang['srv_info_first_entry']. ':';
+ echo '</td><td '.( $zadnji_vnos_date == null ? 'colspan="3"' : '').'>';
+
+ echo $this->dateFormat($prvi_vnos_date,DATE_FORMAT_SHORT);
+ echo $prvi_vnos_time != null ? (SurveyInfo::$dateTimeSeperator .$this->dateFormat($prvi_vnos_time,TIME_FORMAT_SHORT)) : '';
+ echo '</td>';
+ }
+ if ($zadnji_vnos_date != null) {
+ echo '<td>';
+ echo $lang['srv_info_last_entry']. ':';
+ echo '</td><td '.( $prvi_vnos_date == null ? 'colspan="3"' : '').'>';
+ echo $this->dateFormat($zadnji_vnos_date,DATE_FORMAT_SHORT);
+ echo $zadnji_vnos_time != null ? (SurveyInfo::$dateTimeSeperator .$this->dateFormat($zadnji_vnos_time,TIME_FORMAT_SHORT)) : '';
+ echo'</td></tr>';
+ }
+/*
+ #linki - urejanje
+ echo '<tr><td>';
+ echo $lang['srv_stat_edit'] . ':';
+ echo '</td><td colspan="3">';
+ echo '<a href="'.$site_url.'admin/survey/index.php?anketa='.$this->getSurveyId().'">' . $lang['srv_stat_edit_survey'] . '</a>,';
+ echo ' <a href="index.php?anketa='.$this->getSurveyId().'&a=komentarji">'.$lang['comments'].'</a>';
+ echo '</td></tr>';
+
+ #linki - povezave
+
+ */
+
+
+ list($commentsAll,$commentsUnresolved,$commentsQuestionAll,$commentsQuestionUnresolved,$commentsUser,$commentsUserFinished,$commentsUserSurveyAll,$commentsUserSurveyUnresolved) = $this->comments;
+
+ $commentsUserUnresolved = $commentsUser - $commentsUserFinished;
+ if (( (int)$commentsAll
+ +(int)$commentsUnresolved
+ +(int)$commentsQuestionAll
+ +(int)$commentsQuestionUnresolved
+ +(int)$commentsUser
+ +(int)$commentsUserFinished
+ ) > 0 ) {
+ echo '<tr><td>';
+ echo $lang['srv_diagnostic_4_element_0'] . ':';
+ echo '</td><td colspan="3">';
+ echo $lang['srv_diagnostic_4_element_1'];
+ echo ':&nbsp;';
+ echo (int)$commentsUnresolved. ' / '.(int)$commentsAll;
+ echo '</td></tr>';
+ echo '<tr><td>';
+ echo '&nbsp;';
+ echo '</td><td colspan="3">';
+ echo $lang['srv_diagnostic_4_element_1a'];
+ echo ':&nbsp;';
+ echo (int)$commentsUserSurveyUnresolved. ' / '.(int)$commentsUserSurveyAll;
+ echo '</td></tr>';
+ echo '<tr><td>';
+ echo '&nbsp;';
+ echo '</td><td colspan="3">';
+ echo $lang['srv_diagnostic_4_element_6'];
+ echo ':&nbsp;';
+ echo (int)$commentsQuestionUnresolved. ' / '.(int)$commentsQuestionAll;
+ echo '</td></tr>';
+ echo '<tr><td>';
+ echo '&nbsp;';
+ echo '</td><td colspan="3">';
+ echo $lang['srv_diagnostic_4_element_7'];
+ echo ':&nbsp;';
+ echo (int)$commentsUserUnresolved. ' / '.(int)$commentsUser;
+ echo '</td></tr>';
+ }
+
+ echo '</table>';
+ }
+
+ /** Funkcija prikaže statuse odgovorov
+ *
+ */
+ function DisplayAnswerStateView() {
+ global $lang;
+
+ if ($this->emailInvitation == 1) {
+ $order = array('email','3ll','4ll','5ll',5,6);
+ } else {
+ $order = array('3ll','4ll','5ll',5,6);
+ }
+ if(true) {
+ $this->realUsersByStatus[0]['cnt'] = $this->cntUserByStatus['invitation'];
+ }
+ echo '<div class="floatLeft"><span class="dashboard_title">'.$lang['srv_statistic_answer_state_title'].'</span>'.Help :: display('srv_statistic_answer_state_title');
+ echo '</div>';
+ echo '<div class="floatRight">'.$lang['srv_statistic_answer_state_base'].': ';
+ echo '<select id="userStatusBase" onchange="changeUserStatusBase()">';
+ foreach ($order as $key) {
+ echo '<option '.($this->realUsersByStatus_base.'' == $key.'' ? ' selected="selected"' : '').' value="'.$key.'" >'.$lang['srv_userstatus_'.$key].'</option>';
+ }
+ echo '</select>';
+
+ echo '</div>';
+ echo '<br class="clr"/>';
+ echo '<br />';
+
+ echo '<table id="tbl_answ_state">';
+ echo '<tr class="anl_dash_bb "><th><strong>'.$lang['srv_statistic_answer_state_status'].'</strong></th><td><strong>'.$lang['srv_statistic_answer_state_frequency'].'</strong></td><td><strong>'.$lang['srv_statistic_answer_state_percent'].'</strong></td></tr>';
+ foreach ($order as $key) {
+ if ($this->realUsersByStatus_base == $key) {
+ $base_found = true;
+ }
+ echo '<tr><th>'.$lang['srv_userstatus_'.$key].'</th>';
+ #frekvenca
+ echo '<td>'.($this->realUsersByStatus[$key]['cnt'] > 0 ? $this->realUsersByStatus[$key]['cnt'] : '0').'</td>';
+ #procenti
+ ;
+ echo '<td>';
+ #echo ( (float)$this->realUsersByStatus[$key]['percent'] > 1.0)
+ echo ( $base_found == false)
+ ? '--'
+ : $this->formatNumber($this->realUsersByStatus[$key]['percent']*100,NUM_DIGIT_PERCENT,'%');
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+
+
+ echo '<br />';
+
+
+ // Uporabnost respondentov
+ $sur = new SurveyUsableResp($this->surveyId, $generateDatafile=false);
+ if(!$sur->hasDataFile())
+ echo '<br />';
+// echo $lang['srv_dashboard_no_file'].'<br /><br />';
+ else{
+ $usability = $sur->calculateData();
+
+ echo '<table id="tbl_answ_usability">';
+ echo '<tr class="anl_dash_bb "><th><strong>'.$lang['srv_statistic_answer_state_usability'].' ('.$sur->bottom_usable_limit.'%/'.$sur->top_usable_limit.'%)</strong></th><td><strong>'./*$lang['srv_statistic_answer_state_frequency'].*/'</strong></td><td><strong>'./*$lang['srv_statistic_answer_state_percent'].*/'</strong></td></tr>';
+
+ echo '<tr><th>'.$lang['srv_usableResp_usable_unit'].'</th>';
+ echo '<td>'.$usability['usable'].'</td>';
+ if($usability['all'] > 0)
+ echo '<td>'.$this->formatNumber($usability['usable']/$usability['all']*100, NUM_DIGIT_PERCENT, '%').'</td>';
+ else
+ echo '<td>'.$this->formatNumber(0, NUM_DIGIT_PERCENT, '%').'</td>';
+ echo '</tr>';
+
+ echo '<tr><th>'.$lang['srv_usableResp_partusable_unit'].'</th>';
+ echo '<td>'.$usability['partusable'].'</td>';
+ if($usability['all'] > 0)
+ echo '<td>'.$this->formatNumber($usability['partusable']/$usability['all']*100, NUM_DIGIT_PERCENT, '%').'</td>';
+ else
+ echo '<td>'.$this->formatNumber(0, NUM_DIGIT_PERCENT, '%').'</td>';
+ echo '</tr>';
+
+ echo '<tr><th>'.$lang['srv_usableResp_unusable_unit'].'</th>';
+ echo '<td>'.$usability['unusable'].'</td>';
+ if($usability['all'] > 0)
+ echo '<td>'.$this->formatNumber($usability['unusable']/$usability['all']*100, NUM_DIGIT_PERCENT, '%').'</td>';
+ else
+ echo '<td>'.$this->formatNumber(0, NUM_DIGIT_PERCENT, '%').'</td>';
+ echo '</tr>';
+
+ echo '</table>';
+
+ echo '<br />';
+ }
+
+ // Breakoffi
+ $status3 = (isset($this->userByStatus['nonvalid']['3'])) ? $this->userByStatus['nonvalid']['3'] : 0;
+ $status4 = (isset($this->userByStatus['nonvalid']['4'])) ? $this->userByStatus['nonvalid']['4'] : 0;
+ $status5 = (isset($this->userByStatus['valid']['5'])) ? $this->userByStatus['valid']['5'] : 0;
+ $status5l = (isset($this->userByStatus['nonvalid']['5l'])) ? $this->userByStatus['nonvalid']['5l'] : 0;
+ $status6 = (isset($this->userByStatus['valid']['6'])) ? $this->userByStatus['valid']['6'] : 0;
+ $all = (isset($this->realUsersByStatus['3ll']['cnt'])) ? $this->realUsersByStatus['3ll']['cnt'] : 0;
+ if($all > 0){
+ echo '<table id="tbl_answ_breakoff">';
+ echo '<tr class="anl_dash_bb "><th><strong>'.$lang['srv_statistic_answer_state_breakoff'].'</strong></th><td><strong>'./*$lang['srv_statistic_answer_state_frequency'].*/'</strong></td><td><strong>'./*$lang['srv_statistic_answer_state_percent'].*/'</strong></td></tr>';
+
+ $introBreakoff = $status3 + $status4;
+ $introBreakoffPercent = $introBreakoff / $all;
+ echo '<tr><th>'.$lang['srv_statistic_answer_state_breakoff_1'].'</th>';
+ echo '<td>'.$introBreakoff.'</td>';
+ echo '<td>'.$this->formatNumber($introBreakoffPercent*100, NUM_DIGIT_PERCENT, '%').'</td>';
+ echo '</tr>';
+
+ $qBreakoff = $status5 + $status5l;
+ $qBreakoffPercent = $qBreakoff / $all;
+ if(($all - $status3 - $status4) > 0)
+ $qBreakoffNeto = $qBreakoff / ($all - $status3 - $status4);
+ echo '<tr><th>'.$lang['srv_statistic_answer_state_breakoff_2'].'</th>';
+ echo '<td>'.$qBreakoff.'</td>';
+ echo '<td>'.$this->formatNumber($qBreakoffPercent*100, NUM_DIGIT_PERCENT, '%').' (neto '.$this->formatNumber($qBreakoffNeto*100, NUM_DIGIT_PERCENT, '%').')</td>';
+ echo '</tr>';
+
+ $totalBreakoff = $status3 + $status4 + $status5 + $status5l;
+ $totalBreakoffPercent = $totalBreakoff / $all;
+ echo '<tr><th>'.$lang['srv_statistic_answer_state_breakoff_3'].'</th>';
+ echo '<td>'.$totalBreakoff.'</td>';
+ echo '<td>'.$this->formatNumber($totalBreakoffPercent*100, NUM_DIGIT_PERCENT, '%').'</td>';
+ echo '</tr>';
+
+ echo '</table>';
+ }
+ $this->JsonAnswerStateView();
+ }
+
+ /** Funkcija kreira json statuse odgovorov (za API)
+ *
+ */
+ function JsonAnswerStateView() {
+ global $lang;
+
+ if ($this->emailInvitation == 1) {
+ $order = array('email','3ll','4ll','5ll',5,6);
+ } else {
+ $order = array('3ll','4ll','5ll',5,6);
+ }
+ if(true) {
+ $this->realUsersByStatus[0]['cnt'] = $this->cntUserByStatus['invitation'];
+ }
+
+ $json_array = array();
+
+ foreach ($order as $key) {
+ if ($this->realUsersByStatus_base == $key) {
+ $base_found = true;
+ }
+ $json_array['status'][$key] = ['freq' => $this->realUsersByStatus[$key]['cnt'] > 0 ? $this->realUsersByStatus[$key]['cnt'] : '0',
+ 'state' => ( $base_found == false) ? '--'
+ : $this->formatNumber($this->realUsersByStatus[$key]['percent']*100,NUM_DIGIT_PERCENT,'%')];
+ }
+
+ // Uporabnost respondentov
+ $sur = new SurveyUsableResp($this->surveyId, $generateDatafile=false);
+ if($sur->hasDataFile()){
+ $usability = $sur->calculateData();
+
+ $json_array['usability']['unit'] = '('.$sur->bottom_usable_limit.'%/'.$sur->top_usable_limit.'%)';
+
+ if(isset($usability['usable']))
+ $json_array['usability']['usable'] = ['freq' => $usability['usable'],
+ 'state' => $this->formatNumber($usability['usable']/$usability['all']*100, NUM_DIGIT_PERCENT, '%')];
+ else
+ $json_array['usability']['usable'] = ['freq' => 0, 'state' => '0%'];
+
+ if(isset($usability['partusable']))
+ $json_array['usability']['partusable'] = ['freq' => $usability['partusable'],
+ 'state' => $this->formatNumber($usability['partusable']/$usability['all']*100, NUM_DIGIT_PERCENT, '%')];
+ else
+ $json_array['usability']['partusable'] = ['freq' => 0, 'state' => '0%'];
+
+ if(isset($usability['unusable']))
+ $json_array['usability']['unusable'] = ['freq' => $usability['unusable'],
+ 'state' => $this->formatNumber($usability['unusable']/$usability['all']*100, NUM_DIGIT_PERCENT, '%')];
+ else
+ $json_array['usability']['unusable'] = ['freq' => 0, 'state' => '0%'];
+ }
+ else
+ $json_array['usability'] = array();
+
+ // Breakoffi
+ $status3 = (isset($this->userByStatus['nonvalid']['3'])) ? $this->userByStatus['nonvalid']['3'] : 0;
+ $status4 = (isset($this->userByStatus['nonvalid']['4'])) ? $this->userByStatus['nonvalid']['4'] : 0;
+ $status5 = (isset($this->userByStatus['valid']['5'])) ? $this->userByStatus['valid']['5'] : 0;
+ $status5l = (isset($this->userByStatus['nonvalid']['5l'])) ? $this->userByStatus['nonvalid']['5l'] : 0;
+ $status6 = (isset($this->userByStatus['valid']['6'])) ? $this->userByStatus['valid']['6'] : 0;
+ $all = (isset($this->realUsersByStatus['3ll']['cnt'])) ? $this->realUsersByStatus['3ll']['cnt'] : 0;
+ if($all > 0){
+ $introBreakoff = $status3 + $status4;
+ $introBreakoffPercent = $introBreakoff / $all;
+
+ $json_array['breakoffs']['intro'] = ['freq' => $introBreakoff,
+ 'state' => $this->formatNumber($introBreakoffPercent*100, NUM_DIGIT_PERCENT, '%')];
+
+ $qBreakoff = $status5 + $status5l;
+ $qBreakoffPercent = $qBreakoff / $all;
+ if(($all - $status3 - $status4) > 0)
+ $qBreakoffNeto = $qBreakoff / ($all - $status3 - $status4);
+
+ $json_array['breakoffs']['questionnaire'] = ['freq' => $qBreakoff,
+ 'state' => $this->formatNumber($qBreakoffPercent*100, NUM_DIGIT_PERCENT, '%').
+ ' (neto '.$this->formatNumber($qBreakoffNeto*100, NUM_DIGIT_PERCENT, '%').')'];
+
+ $totalBreakoff = $status3 + $status4 + $status5 + $status5l;
+ $totalBreakoffPercent = $totalBreakoff / $all;
+
+ $json_array['breakoffs']['total'] = ['freq' => $totalBreakoff,
+ 'state' => $this->formatNumber($totalBreakoffPercent*100, NUM_DIGIT_PERCENT, '%')];
+ }
+
+ return $json_array;
+ }
+
+ /** Funkcija prikaže statuse
+ * KONČNI STATUSI
+ */
+ function DisplayStatusView() {
+ global $lang;
+
+ echo '<span class="floatLeft dashboard_title">'.$lang['srv_statistic_status_title'].Help :: display('srv_statistic_status_title');
+ echo '</span>';
+
+ echo '<span class="floatRight">';
+ echo $lang['srv_statistic_hide_null'];
+ echo '<input id="hideNullValues_status" name="hideNullValues_status" type="checkbox" onchange="statisticStatusRefresh(); return false;"'.($this->hideNullValues_status ? ' checked="checked"' : '').' autocomplete="off">';
+ echo '</span>';
+
+ echo '<br class="clr"/><br/>';
+
+ $cntValid = 0; // da vemo ali izpisemo skupne
+ $cntNonValid = 0; // da vemo ali izpisemo skupne
+ $cntInvitation = 0; // da vemo ali izpisemo skupne
+ foreach ($this->appropriateStatus as $status) {
+ if (!($this->hideNullValues_status && $this->userByStatus['valid'][$status] == 0)) {// da ne delamo po neporebnem
+ echo '<span class="dashboard_status_span">' . $lang['srv_userstatus_'.$status] . ' ('.$status.') :</span>' . $this->userByStatus['valid'][$status].'<br/>';
+ $cntValid++;
+ }
+ }
+ // vsota vlejavnih
+ if ($cntValid > 0 || !$this->hideNullValues_status) {
+ echo '<div class="anl_dash_bt full strong"><span class="dashboard_status_span">'.$lang['srv_statistic_redirection_sum_valid'].'</span>'.($this->cntUserByStatus['valid']).'<br/></div><br/>';
+ }
+
+ // izpišemo še neveljavne
+ foreach ($this->unAppropriateStatus as $status) {
+ if (!($this->hideNullValues_status && $this->userByStatus['nonvalid'][$status] == 0)) {// da ne delamo po neporebnem
+ echo '<span class="dashboard_status_span">' . $lang['srv_userstatus_'.$status] . ' ('.$status.') :</span>' . $this->userByStatus['nonvalid'][$status]
+ . ( ( $index <= 2 && $this->userByStatus['valid'][$status] > 0 )
+ ? '&nbsp;<a href="#" onclick="survey_statistic_status(\''.$status.'\')">'.$lang['srv_statistic_detail'].'</a>'
+ : '')
+ . '<br/>';
+ $cntNonValid++;
+ }
+ }
+ // se status null (neznan status)
+ /*if (!($this->hideNullValues_status && $this->userByStatus['nonvalid'][-1] == 0)) {// da ne delamo po neporebnem
+ echo '<span class="dashboard_status_span">' . $lang['srv_userstatus_null'] . ' (null) :</span>' . (isset($this->userByStatus['nonvalid'][-1]) ? $this->userByStatus['nonvalid'][-1] : '0') . '<br/>';
+ $cntNonValid++;
+ }*/
+
+ // vsota nevlejavnih
+ if ($cntNonValid > 0 || !$this->hideNullValues_status) {
+ echo '<div class="anl_dash_bt full strong"><span class="dashboard_status_span">'.$lang['srv_statistic_redirection_sum_nonvalid'].'</span>'.($this->cntUserByStatus['nonvalid']).'<br></div><br/>';
+ }
+
+ // Klikov na povezavo
+ SurveySetting::getInstance()->setSID($this->surveyId);
+ $view_count = SurveySetting::getInstance()->getSurveyMiscSetting('view_count');
+ if ($view_count == "") $view_count = 0;
+ if ($view_count > 0 || !$this->hideNullValues_status)
+ echo '<div class="full strong"><span class="dashboard_status_span">'.$lang['srv_statistic_redirection_sum_view'].'</span>'.($view_count).'<br /><br /></div>';
+
+ // Vsota anketiranih
+ echo '<div class="anl_dash_bt full strong "><span class="dashboard_status_span">'.$lang['srv_statistic_redirection_sum_surveyed'].'</span>'.($this->cntUserByStatus['valid']+$this->cntUserByStatus['nonvalid']).'<br></div>';
+ // Testni
+ if ((int)$this->testDataCount > 0) {
+ echo '<div class="full"><span class="dashboard_status_span">('.$lang['srv_statistic_redirection_test'].')</span>'.((int)$this->testDataCount).'<br></div>';
+ }
+
+ echo '<br class="clr"/>';
+
+
+ # preštejemo še neposlana vabila
+ $str = "SELECT count(*) FROM srv_invitations_recipients WHERE ank_id='".$this->getSurveyId()."' AND sent='0' AND deleted='0'";
+
+ $qry = sisplet_query($str);
+ list($cntUnsent) = mysqli_fetch_row($qry);
+ $this->userByStatus['invitation'][0] = (int)$cntUnsent;
+
+ # še email vabila
+ // ker izpade čudno, statusov email neposlan
+ if (count(array_filter($this->userByStatus['invitation'])) > 0 || !$this->hideNullValues_status){
+
+ echo '<span class="floatLeft strong">'.$lang['srv_statistic_nonsurveyed_title'];
+ echo '</span>';
+ echo '<br class="clr"/>';
+
+ foreach ($this->invitationStatus as $status)
+ {
+ if (!($this->hideNullValues_status && $this->userByStatus['invitation'][$status] == 0)) {// da ne delamo po neporebnem
+ echo '<span class="dashboard_status_span">' . $lang['srv_statistic_email_status_'.$status] . ' ('.$status.') :</span>' . $this->userByStatus['invitation'][$status]
+ #. ( ( $status <= 2 && $this->userByStatus['invitation'][$status] > 0 )
+ # ? '&nbsp;<a href="#" onclick="survey_statistic_status(\''.$status.'\')">'.$lang['srv_statistic_detail'].'</a>'
+ # : '')
+ . '<br/>';
+ $cntInvitation++;
+ }
+ }
+ }
+
+ // vsota emaili
+ if ($cntInvitation > 0 || !$this->hideNullValues_status) {
+ echo '<div class="anl_dash_bt full strong"><span class="dashboard_status_span">'.$lang['srv_statistic_sum2'].'</span>'.($this->cntUserByStatus['invitation']).'<br/></div><br/>';
+ }
+
+
+ // Vsota vseh
+ echo '<div class="anl_dash_bt full strong"><span class="dashboard_status_span">'.$lang['srv_statistic_sum_all'].'</span>'.($this->cntUserByStatus['valid']+$this->cntUserByStatus['nonvalid']+$this->cntUserByStatus['invitation']).'<br></div>';
+ }
+
+ /** Funkcija za prikaz referalov
+ * #KLIK NA ANKETO#
+ * #PREUSMERITVE#
+ */
+ function DisplayReferalsView() {
+ global $lang;
+ global $admin_type;
+
+ echo '<div><span class="dashboard_title">'.$lang['srv_statistic_redirection_title'].'</span>'.Help :: display('srv_statistic_redirection_title').'</div>';
+
+ // izrisemo graf
+ if ( ( $this->cntValidRedirections + $this->cntNonValidRedirections ) > 0) {
+ $maxValue = $this->maxRedirection * GRAPH_REDUCE;
+ $value_sum = 0;
+
+ echo '<table class="survey_referals_tbl">'."\n";
+ echo '<tr class="anl_dash_bb">'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;"><strong>' . $lang['srv_statistic_redirection_site'] . '</strong></th>'."\n";
+ echo '<td class="anl_ar"><strong>'.$lang['srv_statistic_redirection_click'].'</strong></td>'."\n";
+ echo '</tr>'."\n";
+
+ if (count($this->userRedirections["valid"])) {
+ foreach ($this->userRedirections["valid"] as $key => $value) {
+ if ($key == 'email')
+ {
+ echo '<tr>'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;">' . $lang['srv_statistic_redirection_email'] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+ }
+ else
+ {
+ echo '<tr>'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;">' . $key . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+ }
+ $value_sum += $value;
+ }
+ }
+ // dodamo še direktni link
+ if ($this->userRedirections["direct"] > 0) {
+ $value = $this->userRedirections["direct"];
+ echo '<tr>'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;">' . $lang['srv_statistic_redirection_direct'] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+ $value_sum += $value;
+ }
+ // dodamo še email klik
+ // @Uros to je identicno, kot zgoraj v foreach, na koncu se gleda rezultat iz valid...se to sploh rabi?
+ if ($this->userRedirections["email"] > 0) {
+ $value = $this->userRedirections["email"];
+ echo '<tr>'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;">' . $lang['srv_statistic_redirection_email'] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+ $value_sum += $value;
+ }
+ // dodamo sumo
+ echo '<tr class="anl_dash_bt strong">'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;"><strong>' . $lang['srv_statistic_redirection_sum_clicked'] . '</strong></th>'."\n";
+ echo '<td style="text-align:left">'.$value_sum.'</td>'."\n";
+ echo '</tr>'."\n";
+ echo '<tr class="">'."\n";
+ echo '<th colspan="2">&nbsp;</th>'."\n";
+ echo '</tr>'."\n";
+
+ /*
+ // dodamo se neveljavne
+ $value_sum_nonvalid = 0;
+ for ($key = 2; $key >= 0; $key--) {
+ $value = $this->userRedirections["$key"];
+ if ($value > 0) {
+ echo '<tr>'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;">' . $lang['srv_statistic_redirection_email_'.$key] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_ly" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+ $value_sum_nonvalid += $value;
+ }
+ }
+ // dodamo sumo
+ if ($value_sum_nonvalid > 0 ) {
+ echo '<tr class="anl_dash_bt strong">'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;"><strong>' . $lang['srv_statistic_redirection_sum_nonvalid'] . '</strong></th>'."\n";
+ echo '<td style="text-align:left">'.$value_sum_nonvalid.'</td>'."\n";
+ echo '</tr>'."\n";
+ echo '<tr class="">'."\n";
+ echo '<th colspan="2">&nbsp;</th>'."\n";
+ echo '</tr>'."\n";
+ }
+ */
+ if (!($value_sum_nonvalid == 0 || $value_sum == 0 )) {
+ echo '<tr class="anl_dash_bt strong">'."\n";
+ echo '<th style="width:'.($this->maxCharRedirection+2).'pt;"><strong>' . $lang['srv_statistic_redirection_sum'] . '</strong></th>'."\n";
+ echo '<td style="text-align:left">'.($value_sum+$value_sum_nonvalid).'</td>'."\n";
+ echo '</tr>'."\n";
+ }
+ echo '</table>'."\n";
+
+ echo '<div id="referal_detail"><span class="dashboard_title">'.$lang['srv_statistic_details'].'</span></div>';
+ if ($this->cntValidRedirections > 0) {
+ echo '<div class="spaceLeft"><a href="#" onclick="survey_statistic_referal(this); return false;" value="0" title="'.$lang['srv_statistic_detail_referal'].'">'.$lang['srv_statistic_detail_referal'].'</a></div>';
+ } else {
+ echo '<div class="spaceLeft">'.$lang['srv_statistic_show_no_referals'].'</div>';
+ }
+ echo '<div class="spaceLeft"><a href="#" onclick="ip_list_podrobno(this); return false;" value="0" title="'.$lang['srv_statistic_detail_IP'].'">'.$lang['srv_statistic_detail_IP'].'</a></div>';
+ }
+/*
+ #echo '<div><p><strong>'.$lang['srv_count_ip_list'].': '.count($this->ip_list).'</strong></p></div>';
+ echo '<div><p><strong>'.$lang['srv_detail_ip_list'].': </strong></p></div>';
+ echo '<p>&nbsp;<a href="#" onclick="ip_list_podrobno(this); return false;" value="0">'.$lang['srv_statistic_detail'].'</a></p>';
+*/
+ # skrita div aza podrobnosti
+ echo '<div id="survey_referals" class="displayNone"></div>';
+ echo '<div id="ip_list_podrobno" class="displayNone"></div>';
+ }
+
+ /** Funkcija za prikaz klikov po straneh
+ *
+ */
+ function DisplayPagesStateView() {
+ global $lang;
+
+ # ali lovimo samo strani ki niso bile preskočene
+ $grupa_jump = "AND ug.preskocena = 0 ";
+
+ echo '<span class="dashboard_title">'.$lang['srv_statistic_pages_state_title'].'</span>'.Help :: display('srv_statistic_pages_state_title');
+
+ // Filter po osnovi
+ if ($this->emailInvitation == 1) {
+ $order = array('email','3ll','4ll','5ll',5,6);
+ } else {
+ $order = array('3ll','4ll','5ll',5,6);
+ }
+ echo '<div class="floatRight">'.$lang['srv_statistic_answer_state_base'].': ';
+ echo '<select id="pageUserStatusBase" onchange="changePageUserStatusBase()">';
+ foreach ($order as $key) {
+ echo '<option '.($this->pageUsersByStatus_base.'' == $key.'' ? ' selected="selected"' : '').' value="'.$key.'" >'.$lang['srv_userstatus_'.$key].'</option>';
+ }
+ echo '</select>';
+ echo '</div>';
+
+ $status_filter_string = '';
+ switch($this->pageUsersByStatus_base){
+ case 'email':
+ //$status_filter_string = "AND u.last_status IN ('6','5')";
+ break;
+
+ case '3ll':
+ $status_filter_string = "AND u.last_status IN ('3','4','6','5')";
+ break;
+
+ case '4ll':
+ $status_filter_string = "AND u.last_status IN ('4', '6','5')";
+ break;
+
+ case '5ll':
+ $status_filter_string = "AND u.last_status IN ('6','5')";
+ break;
+
+ case '5':
+ $status_filter_string = "AND u.last_status IN ('6','5') AND u.lurker='0'";
+ break;
+
+ case '6':
+ $status_filter_string = "AND u.last_status='6' AND u.lurker='0'";
+ break;
+ }
+
+ echo '<br class="clr">';
+
+ $pages=array();
+ $maxValue = 0;
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ } else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ # polovimo imena strani in preštejemo klike
+ $sql= "SELECT g.id, g.naslov, g.vrstni_red, COUNT( ug.usr_id ) cnt FROM srv_grupa g LEFT JOIN srv_user_grupa".$this->db_table." ug ON g.id = ug.gru_id"
+ ." JOIN srv_user u ON u.id=ug.usr_id"
+ ." WHERE ug.time_edit BETWEEN '".$this->startDate."' AND '".$this->endDate."' + INTERVAL 1 DAY ".$grupa_jump
+ ." AND g.ank_id = '".$this->getSurveyId()."' AND u.preview='0' AND u.deleted='0' ".$email_filter_string." ".$status_filter_string." GROUP BY g.id ORDER BY g.vrstni_red";
+
+ $qry = sisplet_query($sql);
+ if (!$qry) echo mysqli_error($GLOBALS['connect_db']);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $pages[$row['id']] = array('naslov'=>$row['naslov'],'vrstni_red'=>$row['vrstni_red'],'cnt'=>$row['cnt']);
+ $maxValue = max($maxValue, $row['cnt']);
+ }
+
+ $maxValue = max($maxValue, $this->realUsersByStatus['3ll']['cnt']);
+ $maxValue = $maxValue * GRAPH_REDUCE;
+ echo '<table class="survey_referals_tbl">'."\n";
+ echo '<tr class="anl_dash_bb">'."\n";
+ echo '<th style="width:10pt;"><strong>' . $lang['srv_statistic_answer_state_status'] . '</strong></th>'."\n";
+ echo '<td class="anl_ar"><strong>'.$lang['srv_statistic_redirection_click'].'</strong></td>'."\n";
+ echo '</tr>'."\n";
+
+ # status 3 - "Klik na anketo"
+ $value = $this->realUsersByStatus['3ll']['cnt'];
+ echo '<tr>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_userstatus_3'] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ # status 4 - "Klik na prvo stran"
+ $value = $this->realUsersByStatus['4ll']['cnt'];
+ echo '<tr>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_userstatus_4'] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ # status 5 - "Za&#269;el izpolnjevati",
+ $value = $this->realUsersByStatus[5]['cnt'];
+ echo '<tr>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_userstatus_5'] . '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ #strani
+ echo '<tr class="anl_dash_bb">'."\n";
+ echo '<th style="width:10pt;">' . $lang[''] . '</th>'."\n";
+ echo '<td style="text-align:center">'.$lang[' '].'</td>'."\n";
+ echo '</tr>'."\n";
+
+ foreach ($pages as $key => $page) {
+ $value = $page['cnt'];
+ echo '<tr>'."\n";
+ //echo '<th style="width: 10pt;">' . $page['naslov'] . '</th>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_stran'].' '.$page['vrstni_red']. '</th>'."\n";
+ $width = ($maxValue && $value) ? (round($value / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+ }
+
+ #strani
+ echo '<tr class="anl_dash_bb">'."\n";
+ echo '<th style="width:10pt;">' . $lang[''] . '</th>'."\n";
+ echo '<td style="text-align:center">'.$lang[' '].'</td>'."\n";
+ echo '</tr>'."\n";
+
+ # status 6 - "Koncal",
+ $value6 = $this->realUsersByStatus[6]['cnt'];
+
+ echo '<tr>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_userstatus_6'] . '</th>'."\n";
+ $width = ($maxValue && $value6) ? (round($value6/ $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value6.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ #če imamo lurkerje 6l dodamo skupaj konačal anketo (to je 6 + 6l) in nato še koliko jih je samo s statusom 6 (končal anketo)
+ # status 6l - "Koncal - lurker", izpišemo samo če obstajajo 6l
+ $lurkerjev = $this->realUsersByStatus['6ll']['cnt'] - $value6;
+ if ($lurkerjev > 0) {
+ $valueall = $this->realUsersByStatus['6ll']['cnt'] ;
+
+ # končal s tem da je lurker (6l)
+ echo '<tr>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_userstatus_6l'].'' . '</th>'."\n";
+ $width = ($maxValue && $lurkerjev) ? (round($lurkerjev / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$lurkerjev.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ #črta
+ echo '<tr class="anl_dash_bb">'."\n";
+ echo '<th style="width:10pt;">' . $lang[''] . '</th>'."\n";
+ echo '<td style="text-align:center">'.$lang[' '].'</td>'."\n";
+ echo '</tr>'."\n";
+
+ # končal ne glede na to ali je lurker
+ echo '<tr>'."\n";
+ echo '<th style="width: 10pt;">' . $lang['srv_userstatus_all'] . '</th>'."\n";
+ $width = ($maxValue && $valueall) ? (round($valueall / $maxValue * 100, 0)) : "0";
+ echo '<td><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$valueall.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ }
+
+ echo '</table>'."\n";
+ }
+
+ /** Funkcija za prikaz seznam referalov
+ *
+ */
+ function DisplayReferalsList() {
+ global $lang;
+
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ } else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ echo '<br/><div class="dashboard_title">'.$lang['srv_statistic_referals_list'].Help :: display('srv_statistic_referals_list').'</div>';
+
+ // še podatke o uporabniku
+ $sql_userInfo = sisplet_query("SELECT referer, COUNT(*) as cnt FROM srv_user WHERE ank_id = '".$this->getSurveyId()."' AND preview = '0' AND deleted='0' AND time_insert BETWEEN '".$this->startDate."' AND '".$this->endDate."' + INTERVAL 1 ".$email_filter_string ." DAY GROUP BY referer");
+ if (mysqli_num_rows($sql_userInfo) > 0) {
+
+ echo '<table>';
+ $cnt=0;
+ while ( $row_userInfo = mysqli_fetch_assoc($sql_userInfo) ) {
+ if ($row_userInfo['referer'] != "") {
+ $css_top = $cnt ? ' anl_dash_bt' : '';
+ echo '<tr><td class="anl_dash_br anl_w15'.$css_top.'">'.$row_userInfo['cnt']. '</td><td class="'.$css_top.'">' .$row_userInfo['referer'].'</td></tr>';
+ $cnt++;
+ }
+ }
+ echo '</table>';
+ } else {
+ echo $lang['srv_statistic_show_no_referals'];
+ }
+ }
+
+ /** Funkcija za prikaz seznam IP-jev
+ *
+ */
+ function DisplayIPList() {
+ global $lang;
+
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ } else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ # IP-je lovimo preko ajaxa
+ $string_sql = "SELECT COUNT(id) AS count, ip FROM srv_user WHERE ank_id='".$this->getSurveyId()."' AND preview = '0' AND deleted='0' AND (time_insert BETWEEN '".$this->startDate."' AND '".$this->endDate."' + INTERVAL 1 DAY) ".$email_filter_string." GROUP BY ip ORDER BY count DESC, ip ASC";
+ $sql = sisplet_query($string_sql);
+
+ echo '<br/><div class="dashboard_title">'.$lang['srv_statistic_IP_list'].Help :: display('srv_statistic_IP_list').'</div>';
+ if (mysqli_num_rows($sql) > 0) {
+ #echo '<div class="dashboard_title">'.$lang[''].'</div>';
+ echo '<table>';
+
+ while ($row = mysqli_fetch_array($sql)) {
+ echo '<tr><td class="anl_dash_br">'.$row['ip'].'</td><td>'.$row['count'].'</td></tr>';
+ }
+ echo '</table>';
+ }
+ }
+
+ /** Prikaze userje po posameznem statusu
+ *
+ */
+ function DisplayUserByStatus() {
+ global $lang;
+ $status = $_POST['status'];
+
+ if ($this->emailInvitation > 0) {
+ if ($this->emailInvitation == 1) {
+ $email_filter_string = ' AND inv_res_id is not NULL ';
+ } else if($this->emailInvitation == 2) {
+ $email_filter_string = ' AND inv_res_id is NULL ';
+ }
+ }
+
+ echo '<div id="div_statistic_float_div">';
+ echo '<span>'.$lang['srv_statistic_show_emails'].'</span><br/>';
+ // polovimo e-maile ce obstajajo
+ $sqlUser = sisplet_query("SELECT d.text FROM srv_data_text".$this->db_table." d, srv_spremenljivka s , srv_grupa g WHERE d.spr_id=s.id AND d.usr_id IN ( SELECT id FROM srv_user WHERE ank_id = '".$this->getSurveyId()."' AND preview = '0' AND deleted='0' AND last_status = '".$status."' ) AND s.variable = 'email' AND g.ank_id='" . $this->getSurveyId(). "' AND s.gru_id=g.id ".$email_filter_string);
+ $cnt = 0;
+
+ while($rowUser = mysqli_fetch_assoc($sqlUser)) {
+ if (isset($rowUser['text']) && $rowUser['text'] != "") {
+ echo '<div class="list">'.$rowUser['text'].'</div>';
+ $cnt++;
+ }
+ }
+ if (!$cnt){
+ echo $lang['srv_statistic_show_no_emails'];
+ }
+
+
+ echo '<br/><span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_statistic_float_div(); return false;"><span>';
+ echo $lang['srv_zapri'];
+ echo '</span></a></div></span>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ }
+
+ /** Funkcija prikaze filter
+ *
+ */
+ function DisplayFilters () {
+ global $lang;
+
+ // Kumulativa
+ echo '<span class="floatRight" style="display:inline-block; vertical-align: middle;">';
+ echo $lang['srv_statistic_hide_null'];
+ echo '<input id="hideNullValues_dates" name="hideNullValues_dates" type="checkbox" onclick="statisticFilterDateRefresh();"'.($this->hideNullValues_dates ? ' checked="checked"' : '').' autocomplete="off">';
+ echo '</span>';
+
+ // Skrij 0
+ echo '<span class="floatRight" style="display:inline-block; margin-right:10px; vertical-align: middle;">';
+ echo '<label for="timelineDropDownType" autocomplete="off">'.$lang['srv_statistic_kumulativa'].': </label>';
+ echo '<input type="checkbox" id="timelineDropDownType" name="timelineDropDownType" value="0" '.($this->timelineDropDownType == 1 ? ' checked="checked"' : '').' autocomplete="off" style="margin:0px!important;" onclick="statisticDropdownChange();" >';
+ echo '</span>';
+
+ echo '<br class="clr"/>';
+
+ // Osnova
+ echo '<span id="span_timelineDropDownType" class="floatLeft">';
+ $this->DisplayTimelineDropdowns();
+ echo '</span>';
+
+ // Oblika
+ echo '<span class="floatRight">';
+ echo '<label>'.$lang['srv_statistic_period'].'</label>:'."\n";
+ echo '<select id="period" name="period" size="1" onchange="statisticFilterDateRefresh();" autocomplete="off" >'."\n";
+ foreach ( $this->periods as $key => $_period) {
+ echo '<option value="' . $_period . '" ' . ( $_period == $this->period ? ' selected="selected" ' : '') . '>'.$lang['srv_statistic_period_' . $_period ].'</option>'."\n";
+ }
+ echo '</select>'."\n";
+ echo '</span>';
+ }
+
+ function DisplayTimelineDropdowns() {
+ global $lang;
+
+ echo $lang['srv_statistic_answer_state_base'].': ';
+
+ if ($this->timelineDropDownType == 0) {
+ echo '<select name="type" id="type" onchange="statisticFilterDateRefresh();" autocomplete="off">'."\n";
+
+ echo '<option value="'.TYPE_ALL.'"' . ($this -> type == TYPE_ALL ? ' selected' : '') . ' class="opt_bold">'.$lang['srv_userstatus_total'].'</option>';
+ echo '<option value="'.TYPE_APPROPRIATE.'"' . ($this -> type == TYPE_APPROPRIATE ? ' selected' : '') . ' class="opt_bold">'.$lang['srv_userstatus_appropriate'].'</option>';
+ echo '<option value="'.TYPE_STATUS_6.'"' . ($this -> type == TYPE_STATUS_6 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_6'].' (6)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_5.'"' . ($this -> type == TYPE_STATUS_5 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_5'].' (5)</option>'."\n";
+ echo '<option value="'.TYPE_INAPPROPRIATE.'"' . ($this -> type == TYPE_INAPPROPRIATE ? ' selected' : '') . 'class="opt_bold">'.$lang['srv_userstatus_inappropriate'].'</option>';
+ echo '<option value="'.TYPE_STATUS_6l.'"' . ($this -> type == TYPE_STATUS_6l ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_6l'].' (6l)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_5l.'"' . ($this -> type == TYPE_STATUS_5l ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_5l'].' (5l)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_4.'"' . ($this -> type == TYPE_STATUS_4 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_4'].' (4)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_3.'"' . ($this -> type == TYPE_STATUS_3 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_3'].' (3)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_2.'"' . ($this -> type == TYPE_STATUS_2 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_2'].' (2)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_1.'"' . ($this -> type == TYPE_STATUS_1 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_1'].' (1)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_0.'"' . ($this -> type == TYPE_STATUS_0 ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_0'].' (0)</option>'."\n";
+ echo '<option value="'.TYPE_STATUS_NULL.'"' . ($this -> type == TYPE_STATUS_NULL ? ' selected' : '') . '>&nbsp;&nbsp;'.$lang['srv_userstatus_null'].' (-1)</option>'."\n";
+ echo '<option value="'.TYPE_PAGES.'"' . ($this -> type == TYPE_PAGES ? ' selected' : '') . ' class="opt_bold">'.$lang['srv_diagnostics_strani'].'</option>'."\n";
+ echo '<option value="'.TYPE_ANALYSIS.'"' . ($this -> type == TYPE_ANALYSIS ? ' selected' : '') . ' class="opt_bold">'.$lang['srv_diagnostics_analiza'].'</option>'."\n";
+
+ echo '</select>'."\n";
+ }
+ else {
+ $order = array(
+ '3ll'=>TYPE_STATUS_KUMULATIVE_3ll,
+ '4ll'=>TYPE_STATUS_KUMULATIVE_4ll,
+ '5ll'=>TYPE_STATUS_KUMULATIVE_5ll,
+ 5=>TYPE_STATUS_KUMULATIVE_5,
+ 6=>TYPE_STATUS_KUMULATIVE_6,);
+ echo '<select name="type" id="type" onchange="statisticFilterDateRefresh();" autocomplete="off">'."\n";
+ foreach ($order as $key => $value) {
+ echo '<option value="'.$value.'" '.($this -> type .'' == $value.'' ? ' selected="selected"' : '').' value="'.$value.'" >'.$lang['srv_userstatus_'.$key].'</option>';
+ }
+ echo '</select>';
+ }
+ }
+
+ /** Funkcija prikaze statistike
+ *
+ */
+ function DisplayDateView() {
+ global $lang;
+
+ $this->maxValue *= GRAPH_REDUCE;
+ $cnt=0;
+
+ echo '<table class="survey_referals_tbl">'."\n";
+
+ if ($this->arrayRange) {
+
+ foreach ($this->arrayRange as $key => $value) {
+ $label = $this->formatStatsString($key, $this->period);
+
+ echo '<tr>'."\n";
+ echo '<td style="width:90px;">' . $label . '</td>'."\n";
+ $width = ($this->maxValue && $value) ? (round($value / $this->maxValue * 100, 0)) : "0";
+ echo '<td style=""><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.$value.'</span></td>'."\n";
+ echo '</tr>'."\n";
+
+ $cnt+=$value;
+ }
+
+ // dodamo sumo
+ echo '<tr >'."\n";
+ echo '<th class="anl_dash_bt strong" style="width:'.($this->maxCharRedirection+2).'pt;"><strong>' . $lang['srv_statistic_redirection_sum'] . '</strong></th>'."\n";
+ echo '<td class="anl_dash_bt strong" style="text-align:left">'.$cnt.' </td>'."\n";
+ echo '</tr>'."\n";
+
+ }
+ else {
+ echo '<td style="width:70%"><div style="background-color:#EFF2F7; border-left:1px solid #B9C5D9;">'.$lang['srv_no_data'].'</div></td>'."\n";
+ }
+
+ echo '</table>'."\n";
+ }
+
+ // pomozne funkcije
+ /**
+ * @param $strDateFrom
+ * @param $strDateTo
+ * @param $format
+ * @param $add
+ * [D] - doda en dan (24 ur);
+ * [m] - doda en mesec (št dni * 24 ur);
+ * [h] - doda 1 uro;
+ * @return unknown_type
+ */
+ function createDateRangeArray ($strDateFrom, $strDateTo, $format = DATE_FORMAT, $add = 'D') {
+ // takes two dates formatted as YYYY-MM-DD and creates an
+ // inclusive array of the dates between the from and to dates.
+
+ // could test validity of dates here but I'm already doing
+ // that in the main script
+
+ $aryRange = array ();
+ if ($add == 'H') { // urni interval za dnevno obdobje
+ for ($i = 0; $i <=23; $i++){
+ $aryRange[($i <= 9) ? '0'.$i : $i] = 0; // vrednosti nastavimo na 0
+ }
+ return $aryRange;
+ }
+ if ($add == 'h') { // urni interval za celotno obdobje
+ $iDateFrom = strtotime($strDateFrom.' -1 hour');
+ $iDateTo = strtotime($strDateTo.' + 23 hour');
+ while ($iDateFrom < $iDateTo) {
+ $iDateFrom += 3600; // add 1 hour
+ $aryRange[date($format, $iDateFrom)] = 0; // vrednosti nastavimo na 0
+ }
+ return $aryRange;
+ }
+
+
+ $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
+ $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
+
+ if ($iDateTo >= $iDateFrom) {
+ //NAMESTO: array_push($aryRange,date($format,$iDateFrom)); // first entry
+ $aryRange[date($format, $iDateFrom)] = 0; // vrednosti nastavimo na 0
+ while ($iDateFrom <= $iDateTo) {
+
+ if ($add == 'm') {
+ // ugotovimo koliko dni je v trenutnem mesecu
+ $daysInMonth = date("d", strtotime('-1 second', strtotime('+1 month', strtotime(date("m", $iDateFrom) . '/01/' . date("Y", $iDateFrom) . ' 00:00:00'))));
+ $iDateFrom += 86400 * ($daysInMonth); // add 24 hours * dayInMonth
+ } else { // ($add == 'H')
+ $iDateFrom += 86400; // add 24 hours
+ }
+ if ($iDateFrom <= $iDateTo)
+ $aryRange[date($format, $iDateFrom)] = 0; // vrednosti nastavimo na 0
+ //NAMESTO: array_push($aryRange,date($format,$iDateFrom));
+ }
+ }
+ return $aryRange;
+ }
+
+ function formatStatsString ($txt, $type) {
+ global $months, $months_shortx, $weekdays, $week_short,$months;
+
+ switch ($type) {
+ case PERIOD_MONTH_PERIOD :
+ $result = $months[round(substr($txt, 5, 7), 0)] . ", " . substr($txt, 0, 4);
+ break;
+ case PERIOD_WEEK_PERIOD :
+ $result = substr($txt, 4, 7) . ", " . substr($txt, 0, 4);
+ break;
+ case PERIOD_MONTH_YEAR :
+ $result = $months[$txt];
+ break;
+ case PERIOD_WEEK_YEAR :
+ $result = $txt;
+ break;
+ case PERIOD_DAY_YEAR :
+ $result = $txt;
+ break;
+ case PERIOD_DAY_MONTH :
+ $result = $txt;
+ break;
+ case PERIOD_DAY_PERIOD :
+ $result = $txt;
+ break;
+ case PERIOD_DAY_WEEK :
+ $weekdays['0'] = $weekdays['7'];
+ $nedelja = $weekdays['7'];
+ ksort($weekdays);
+ $weekdays = array_unique($weekdays);
+ $result = $weekdays[round($txt, 0)];
+ break;
+ case PERIOD_HOUR_DAY :
+ $result = $txt.':00 - '.($txt+1).':00';
+ break;
+ case PERIOD_HOUR_PERIOD :
+
+ $result = date('Y-m-d H:00',strtotime($txt.':00')).' - '.date('H:00',strtotime($txt.':00 + 1 hour'));
+ break;
+
+ }
+ return $result;
+ }
+ function dateFormat($input, $format) {
+ if ($input != '..') {
+ return date($format,strtotime($input));
+ } else {
+ return '';
+ }
+ }
+
+ /** Lepo oblikuje number string
+ *
+ * @param float $value
+ * @param int $digit
+ * @param string $sufix
+ * @return string
+ */
+ function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+ $result = number_format($result, $digit, '.', ',') . $sufix;
+
+ return $result;
+ }
+
+ /**
+ * @desc Odreze niz na zadnjem presledkom pred omejitvijo (limit)
+ *
+ * @param $input
+ * @param $limit
+ *
+ * @return $string
+ */
+ function limitString($input, $limit = 100) {
+ // Return early if the string is already shorter than the limit
+ if(strlen($input) < $limit) {return $input;}
+
+ $regex = "/(.{1,$limit})\b/";
+ preg_match($regex, $input, $matches);
+ return $matches[1].'...';
+ }
+
+ /**
+ * perveri ali imamo zakeširan fajl (HTML) če obstaja, ga uporabimo za prikaz dashboarda.
+ */
+ function CheckDashbordChacheFile() {
+ global $site_path;
+ # nastavimo folder
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ # preverimo timestampe
+ $str_qry_surveys = "SELECT id, UNIX_TIMESTAMP(GREATEST(insert_time,edit_time)) as time FROM srv_anketa WHERE id ='".$this->surveyId."'";
+ $qry_surveys = sisplet_query($str_qry_surveys);
+ list($id,$time_survey) = mysqli_fetch_row($qry_surveys);
+
+ $str_qry_users = "SELECT ank_id, UNIX_TIMESTAMP(GREATEST(max(time_insert), max(time_edit))) as time FROM srv_user WHERE ank_id > 0 AND ank_id ='".$this->surveyId."' AND preview = '0' AND deleted='0' GROUP BY ank_id";
+ $qry_users = sisplet_query($str_qry_users);
+ list($id,$time_user) = mysqli_fetch_row($qry_users);
+
+ $dashboard_timestamp = (int)$time_survey + (int)$time_user;
+
+ $fileToUse = $folder . 'export_dashboard_'.$this->surveyId.'.html';
+ # če cache fajla še nimamo kreiramo novega
+ if (!file_exists($fileToUse)) {
+ # cache fajl ne obstaja
+ return null;
+ } else {
+ # cache fajl obstaja
+ #preverimo datum dashboard fajla
+ $_sql_string = "SELECT dashboard_file_time FROM srv_data_files WHERE sid = '".$this->surveyId."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ list($dashboard_file_time) = mysqli_fetch_row($_sql_qry);
+
+ # preverimo ali je file up to date
+ if ($dashboard_timestamp == $dashboard_file_time) {
+ #dashboard file je up to date
+ return $fileToUse;
+ } else {
+ # dashboard fajl ni up to date
+
+ #preštejemo vse userje da lahko za vlke ankete kreiramo cache samo na 15 minut.
+ $str_count = "SELECT count(id) FROM srv_user where ank_id ='".$this->surveyId."' AND deleted='0'"; // zakaj tukaj ni preview???
+ $qry_count = sisplet_query($str_count);
+ list($user_count) = mysqli_fetch_row($qry_count);
+
+ # če imamo dosti uporabnikov refreshamo cache fajl na 15 minut.
+ if ($user_count > REFRESH_USER_COUNT ) {
+ # preverimo ali je potrebno dashboard fajl posodobit, ali uporabimo starega
+ # cache fajl ni up to date, preverimo ali moramo kreirati novega ali lahko uporabimo starega (update time < 15 min)
+ # poiščemo zadnji cache file za to anketo
+ if (file_exists($fileToUse)) {
+ $ctime = filectime($lastFiles);
+ $diff = time() - $ctime;
+ if ($diff > (REFRESH_USER_TIME * 60)) {
+ # pobrišemo star fajl
+ unlink($fileToUse);
+ # updejt je bil pred več kot 15 min. delamo nov fajl
+ return null;
+ } else {
+ return $fileToUse;
+ }
+ }
+ }
+ }
+ }
+
+ unlink($fileToUse);
+ return null;
+ }
+
+ /** Zapišemo html ($data) v html fajl za keširanje
+ *
+ * @param HTML $data
+ */
+ function WriteToCacheFile($data,$timestamp) {
+ global $site_path;
+ if ($this->surveyId !== null && $data !== null && $data !== '') {
+ # če imamo default filtre zapišemo v datoteko; Prav tako mora bit izbran osnovni profil intervala z id = 0
+ if ( $this->isDefaultFilters == true) {
+ # nastavimo folder
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $fileToUse = $folder . 'export_dashboard_'.$this->surveyId.'.html';
+ # pobrišemo morebitne predhodne header datoteke ankete
+ if (file_exists($fileToUse)) {
+ unlink($fileToUse);
+ }
+
+ $df = fopen($fileToUse, 'w') or die("can't open file");
+ fwrite($df, $data);
+ fclose($df);
+
+ $str_qry_exist_files_update = "INSERT INTO srv_data_files (sid, dashboard_file_time, dashboard_update_time) VALUES ('".$this->surveyId."','".$timestamp."',NOW()) ON DUPLICATE KEY UPDATE dashboard_file_time = '".$timestamp."', dashboard_update_time = NOW()";
+ $updated = sisplet_query($str_qry_exist_files_update);
+ }
+ }
+ }
+
+ /** prepebremo zakeširan html fajl
+ *
+ * @param unknown_type $data
+ */
+ function ReadCacheFile() {
+ global $site_path;
+ if ($this->surveyId !== null) {
+ # nastavimo folder
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $dashboardFile = null;
+ # prebermo fajl:
+ foreach (glob($folder . 'export_dashboard_'.$this->surveyId.'.html') as $filesToUse) {
+ if ( $dashboardFile == null) {
+ $dashboardFile = $filesToUse;
+ }
+ }
+
+ $df = fopen($dashboardFile, 'r') or die("can't open file");
+
+ $data = fread($df, filesize($dashboardFile));
+
+ fclose($df);
+ return $data;
+ }
+ return null;
+ }
+
+
+ /** Funkcija klice funkcije za prikaz statistike
+ * DisplayInfoView - prikaze panelo z osnovnimi informacijami
+ * DisplayStatusView - prikaze panelo z kliki po statusih
+ * DisplayReferalsView - prikaze panelo z redirekcijami in referali
+ * DisplayDataView - prikate panelo z kliki po datumih
+ */
+ function WriteDashboardToFile($sid,$timestamp) {
+
+ global $lang, $site_url;
+ if ((int)$sid > 0) {
+
+ # spodnje ehote shranimo v spremenljivko ki jo popotrebi keširanja shranimo v datoteko.
+
+ // preverimo ali ima anketa kakšne vnose
+ $str_qry_all_users = "SELECT count(u.id) AS user_count FROM srv_user AS u " . "WHERE u.ank_id = '".$this->getSurveyId()."' AND preview = '0' AND deleted='0' ";
+ $qry_all_users = sisplet_query($str_qry_all_users);
+ $row_all_users = mysqli_fetch_assoc($qry_all_users);
+ $allUserCount = $row_all_users['user_count'];
+
+ ob_start();
+
+ #echo '<div class="floatLeft" id="updateTime">'.$lang['srv_dashboard_updated'].date("d.m.Y, H:i").'</div>';
+
+ if ($allUserCount == 0) { // nimamo še vnosov
+
+ // zgornji boxi
+ echo '<table class="dashboard dashboard_single">';
+ echo '<tr>';
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_info" id="div_statistic_info" >'."\n";
+ $this -> DisplayInfoView();
+ echo '</div>';
+ echo '</td>';
+ echo '</tr>';
+ echo '</table>';
+
+ // 1) če ankete še nima nobenega klika, naj se pri poročilu ne prikaže nobena od šestih analiza,
+ // ampak naj pise: Anketa nima še nobenega vnosa« zreaven naj bo v SIVEM zavihka UREJANJE
+ // 2) Če nima anketa nobenega klika in ni niti aktivirana, pa napisite:
+ // Anketa še ni aktivvirajna. Zraven naj bo sta siva zavihkja Urejanje vprašalnika in Objave&vabila
+
+
+ } else {
+
+ // imamo vnose, prikažemo statistiko
+ $this->PrepareDateView();
+ $this->PrepareStatusView();
+
+ echo '<table class="dashboard">';
+ echo '<tr>';
+
+ // zgornji boxi
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_info" id="div_statistic_info" >'."\n";
+ $this -> DisplayInfoView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_status" id="div_statistic_status" >'."\n";
+ $this -> DisplayStatusView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_answer_state" id="div_statistic_answer_state" >'."\n";
+ $this -> DisplayAnswerStateView();
+ echo '</div>';
+ echo '</td>';
+ echo '</tr>';
+
+ // spodnji boxi
+ echo '<tr>';
+ echo '<td>';
+ echo '<div class="dashboard_cell" id="div_statistic_referals">';
+ $this -> DisplayReferalsView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" id="div_statistic_visit">';
+ echo '<span class="dashboard_title">'.$lang['srv_statistic_timeline_title'].'</span>'.Help :: display('srv_statistic_timeline_title');
+ echo '<form name="frm_statistic_filter" id="frm_statistic_filter" autocomplete="off">'."\n";
+ // echo '<div name="div_statistic_filter" id="div_statistic_filter" >'."\n";
+ $this -> DisplayFilters();
+ // echo '</div>';
+ echo '</form>';
+ echo '<br/>';
+
+ echo '<div name="div_statistic_visit_data" id="div_statistic_visit_data" >'."\n";
+ $this -> DisplayDateView();
+ echo '</div>';
+ echo '</div>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" id="div_statistic_pages_state">';
+ $this -> DisplayPagesStateView();
+ echo '</div>';
+ echo '</td>';
+
+ echo '</tr>';
+ echo '</table>';
+ }
+
+ # HTML zapišemo v spremenljivko
+ $dashboardHtml = ob_get_clean();
+ $this->WriteToCacheFile($dashboardHtml,$timestamp);
+ }
+ }
+
+ function changeInvitationFilter() {
+ $this->emailInvitationFilter($_POST['filter_email_status']);
+ }
+
+ function emailInvitationFilter($dashboardInvitationType) {
+ global $lang;
+
+ if ($dashboardInvitationType == 1) {
+ echo '<div id="dashboardEmailFilter">';
+ echo $lang[''].'Podatki so filtrirani: ';
+ echo $lang['srv_statistic_email_invitation_only_email'];
+ echo '&nbsp;&nbsp;<span class="as_link space_left" onclick="$(\'#filter_email_status\').val(\'0\').trigger(\'change\');">Odstrani</span>';
+ echo '</div>';
+
+ }
+ if ($dashboardInvitationType == 2) {
+ echo '<div id="dashboardEmailFilter">';
+ echo $lang[''].'Podatki so filtrirani: ';
+ echo $lang['srv_statistic_email_invitation_no_email'];
+ echo '&nbsp;&nbsp;<span class="as_link space_left" onclick="$(\'#filter_email_status\').val(\'0\').trigger(\'change\');">Odstrani</span>';
+ echo '</div>';
+ }
+ }
+
+ function DisplayAaporCalculations() {
+ global $lang;
+
+ $this->PrepareDateView();
+ $this->PrepareStatusView();
+
+ $sa = new SurveyAapor($this->cntUserByStatus,$this->userByStatus,$this->surveyId);
+ }
+
+ function DisplayAaporPriblizek(){
+ $this->PrepareDateView();
+ $this->PrepareStatusView();
+
+ $sa = new SurveyAapor($this->cntUserByStatus,$this->userByStatus,$this->surveyId);
+ $sa->prikaziPriblizek();
+ }
+
+ function DisplayAaporFullCalculation(){
+ $sa = new SurveyAapor($this->cntUserByStatus,$this->userByStatus,$this->surveyId);
+ $sa->calculationForFullAapor();
+ }
+
+ function DisplayLangStatistic() {
+ global $lang;
+
+ $this->PrepareDateView();
+ $this->PrepareStatusView();
+
+
+ echo '<table class="dashboard dashboard_single">';
+ echo '<tr>';
+
+ // zgornji boxi
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_statistic_info" id="div_statistic_info" >'."\n";
+
+ {
+ $lang_array = array();
+ $lang_array[$lang['id']] = $lang['language'];
+
+ $sqll = sisplet_query("SELECT lang_id, language FROM srv_language WHERE ank_id='$this->surveyId' ORDER BY language");
+ while ($rowl = mysqli_fetch_array($sqll)) {
+ $lang_array[$rowl['lang_id']] = $rowl['language'];
+ }
+
+ echo '<span class="dashboard_title">'.$lang['srv_statistic_lang_title'].'</span>';
+ echo '<br/>';
+ echo '<table id="tbl_answ_state">';
+ echo '<tr class="anl_dash_bb "><th><strong>'.$lang['srv_statistic_lang'].'</strong></th><td><strong>'.$lang['srv_statistic_answer_state_frequency'].'</strong></td><td><strong>'.$lang['srv_statistic_answer_state_percent'].'</strong></td></tr>';
+ foreach ($this->respondentLangArray as $key => $cnt) {
+ $allCnt+=$cnt;
+ echo '<tr><th>'.$lang_array[$key].'</th>';
+ #frekvenca
+ echo '<td>'.(int)$cnt.'</td>';
+ #procenti
+ echo '<td>';
+ $percent = ($this->realUsersByStatus['3ll']['cnt'] > 0)
+ ? $cnt / $this->realUsersByStatus['3ll']['cnt'] * 100
+ : 0;
+ echo $this->formatNumber((int)$percent,NUM_DIGIT_PERCENT,'%');
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '<tr class="anl_dash_bt "><th><strong>'.$lang['srv_statistic_sum'].'</strong></th>';
+ #frekvenca
+ echo '<td><strong>'.(int)$allCnt.'</strong></td>';
+ #procenti
+ echo '<td>';
+ $percent = 100;
+ echo $this->formatNumber((int)$percent,NUM_DIGIT_PERCENT,'%');
+ echo '</td>';
+ echo '</tr>';
+ echo '</table>';
+ }
+
+ echo '</div>';
+ echo '</td>';
+ echo '</tr>';
+ echo '</table>';
+
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyStatisticProfiles.php b/admin/survey/classes/class.SurveyStatisticProfiles.php
new file mode 100644
index 0000000..3f56e4f
--- /dev/null
+++ b/admin/survey/classes/class.SurveyStatisticProfiles.php
@@ -0,0 +1,455 @@
+<?php
+/**
+ * Created on 19.03.2010
+ *
+ * @author: Gorazd Veselič
+ */
+
+
+define('SS_DATE_FORMAT', 'd.m.Y'); # format v katerem operiramo v tem klasu
+define('SS_OUTPUT_DATE_FORMAT', 'Y-m-d'); # format v katerem vrne fumkcija GetStatisticDates()
+define('SS_CALENDAR_DATE_FORMAT', '%d.%m.%Y'); # format prikaza koledarja
+define('SS_DATE_FORMAT_SHORT', 'j.n.y');
+define('SS_TIME_FORMAT_SHORT', 'G:i');
+
+define('SS_INTERVAL_1_DAY', '1 day'); # previdno pri spremembi tekstov, ker gre za PHP veljavne stringe za računanje z datumi
+define('SS_INTERVAL_2_DAY', '2 day');
+define('SS_INTERVAL_5_DAY', '5 day');
+define('SS_INTERVAL_7_DAY', '7 day');
+define('SS_INTERVAL_14_DAY', '14 day');
+define('SS_INTERVAL_1_MONTH', '1 month');
+define('SS_INTERVAL_3_MONTH', '3 month');
+define('SS_INTERVAL_6_MONTH', '6 month');
+
+session_start();
+class SurveyStatisticProfiles {
+
+ static private $surveyId = null;
+ static private $uId = null;
+
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+
+ static private $SS_ARRAYS = array( SS_INTERVAL_1_DAY,
+ SS_INTERVAL_2_DAY,
+ SS_INTERVAL_5_DAY,
+ SS_INTERVAL_7_DAY,
+ SS_INTERVAL_14_DAY,
+ SS_INTERVAL_1_MONTH,
+ SS_INTERVAL_3_MONTH,
+ SS_INTERVAL_6_MONTH); // array možnih intervalov za dropdown
+
+ protected function __construct() { }
+
+ final private function __clone() {}
+
+ static function getSurveyId() { return self::$surveyId; }
+ static function getGlobalUserId() { return self::$uId; }
+ static function getCurentProfileId() { return self::$currentProfileId; }
+
+ /** Inizializacija, poišče id privzetega profila in prebere vse profiel ki jih ima uporabnik na voljo
+ *
+ * @param $_surveyId
+ */
+ static function Init($_surveyId)
+ {
+
+ global $global_user_id, $lang;
+
+ if ($_surveyId && $global_user_id)
+ {
+ self::$surveyId = $_surveyId;
+ self::$uId = $global_user_id;
+
+ # inicializiramo datoteko z nastavitvami
+ SurveyUserSetting :: getInstance()->Init(self::$surveyId, self::$uId);
+ # preverimo ali ima uporabnik nastavljen privzet profil
+ $dsp = SurveyUserSetting :: getInstance()->getSettings('default_statistic_profile');
+
+ if ( $dsp == null || $dsp == 0 ) {
+ # nastavimo privzet profil v clas
+ $dsp = 0;
+
+ }
+ #dodamo profil iz seje
+ if ( isset($_SESSION['statistic_profile'][self::$surveyId])) {
+ #dodamo profil iz seje
+ self::$profiles['-1'] = array('id'=>'-1',
+ 'name'=>$lang['srv_temp_profile'],
+ 'starts'=>$_SESSION['statistic_profile'][self::$surveyId]['starts'],
+ 'ends'=>$_SESSION['statistic_profile'][self::$surveyId]['ends'],
+ 'interval_txt'=>$_SESSION['statistic_profile'][self::$surveyId]['interval_txt']);
+ }
+ // ni v seji, nar3edimo privzeteka
+ if ($dsp == -1 && !(isset($_SESSION['statistic_profile'][self::$surveyId]))) {
+ $dsp = 0;
+ }
+
+ self::SetDefaultProfile($dsp);
+
+ #dodamo privzet profil
+ # datum od, "ce ni podan vzamemo kreacijo ankete
+ SurveyInfo :: getInstance()->SurveyInit(self::getSurveyId());
+
+ $start_date = date(SS_DATE_FORMAT, strtotime(SurveyInfo::getInstance()->getSurveyInsertDate()));
+
+ # datum do, "ce ni podan vzamemo danasnji dan
+ $end_date = date(SS_DATE_FORMAT);// ce ne,
+
+ self::$profiles['0'] = array( 'id'=>0,
+ 'name'=>$lang['srv_default_profile'],
+ 'starts'=>$start_date,
+ 'ends'=>$end_date,
+ 'interval_txt'=>'');
+
+ # poiščemo še seznam vseh ostalih profilov uporabnika
+
+ $stringSelect = "SELECT id, name, DATE_FORMAT(starts,'".SS_CALENDAR_DATE_FORMAT."') AS starts, DATE_FORMAT(ends,'".SS_CALENDAR_DATE_FORMAT."') AS ends, interval_txt FROM srv_statistic_profile WHERE uid = '".self::getGlobalUserId()."' || uid = '0' ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = array( 'id'=>$rowSelect['id'],
+ 'name'=>$rowSelect['name'],
+ 'starts'=>$rowSelect['starts'],
+ 'ends'=>$rowSelect['ends'],
+ 'interval_txt'=>$rowSelect['interval_txt']);
+ }
+ return true;
+ } else
+ return false;
+
+ }
+
+ /** Vrne podatke trenutno izbranega profofila
+ *
+ */
+ static function GetCurentProfileData() {
+ return self::$profiles[self::$currentProfileId];
+ }
+
+ /** Vrne podatke podanega profofila
+ *
+ */
+ static function GetProfileData($pid) {
+ return self::$profiles[$pid];
+ }
+
+ /** Vrne array z start date in end date
+ *
+ */
+ static function GetStatisticDates() {
+ $_profile_data = self :: GetCurentProfileData();
+
+ # ali imam o privzete datume filtra
+ $is_default_dates = (int)($_profile_data['id'] === 0);
+
+ # nastavimo start date in end date
+ if ($_profile_data['interval_txt'] != '') {
+ # ce imamo nastavljen datum preko intervala
+ $end_date = date(SS_OUTPUT_DATE_FORMAT);
+ $start_date = date(SS_OUTPUT_DATE_FORMAT,strtotime(date(SS_OUTPUT_DATE_FORMAT, strtotime($end_date)) . ' - '.$_profile_data['interval_txt']));
+
+ } else if ($_profile_data['starts'] != '' && $_profile_data['ends'] != '') {
+ # imamo podana oba datuma
+ $start_date = date(SS_OUTPUT_DATE_FORMAT,strtotime($_profile_data['starts']));
+ $end_date = date(SS_OUTPUT_DATE_FORMAT,strtotime($_profile_data['ends']));
+ } else {
+ # napaka vzamemo datum kreacije ankete in današnji datum
+ $start_date = date(SS_OUTPUT_DATE_FORMAT,strtotime(SurveyInfo::getInstance()->getSurveyInsertDate()));
+ $end_date = date(SS_OUTPUT_DATE_FORMAT);;
+
+ }
+ # končni datum po potrebi zmanjšamo na današnji datum
+ if (strtotime($end_date) > strtotime(date(SS_OUTPUT_DATE_FORMAT))) {
+ $end_date = strtotime(date(SS_OUTPUT_DATE_FORMAT));
+ }
+ return array('start_date'=>$start_date, 'end_date'=>$end_date, 'is_default_dates' => $is_default_dates);
+ }
+
+ /** Pridobimo seznam vseh list uporabnika
+ * v obliki arraya
+ */
+ static function getProfiles() {
+ return self::$profiles;
+ }
+
+ /** Ponastavi id privzetega profila
+ *
+ */
+ static function SetDefaultProfile($pid) {
+ self::$currentProfileId = $pid;
+ $saved = SurveyUserSetting :: getInstance()->saveSettings('default_statistic_profile',$pid);
+
+ }
+ /**
+ *
+ */
+ static function RunStatisticProfile($pid,$timeline,$startDate,$endDate,$stat_interval, $asSession) {
+ if ($pid == 0 && ($asSession == false || $asSession == 'false' )) {
+ # imamo privzet profil
+ self :: SetDefaultProfile(0);
+
+ } else if ($pid > 0 && ($asSession == false || $asSession == 'false' )) {
+ # shranimo v bazo
+ //sisplet_query("UPDATE srv_statistic_profile SET timeline,startDate,endDate,stat_interval WHERE id = '".$pid."'");
+ if ($timeline == 'true') {
+ # shranjujemo od - do
+ $stat_interval = '';
+ $update = "UPDATE srv_statistic_profile SET starts = '".$startDate."', ends='".$endDate."', interval_txt = '' WHERE id = '".$pid."'";
+ } else {
+ # shranjujemo interval
+ $startDate = '';
+ $endDate = '';
+ $update = "UPDATE srv_statistic_profile SET starts = '0000-00-00 00:00:00', ends='0000-00-00 00:00:00', interval_txt = '".$stat_interval."' WHERE id = '".$pid."'";
+ }
+
+ $updated = sisplet_query($update);
+ # ce je bili updejt ok posodobimo se vrednost v profilu
+ if ($updated) {
+ self::$profiles[$pid]['starts'] = $startDate;
+ self::$profiles[$pid]['ends'] = $endDate;
+ self::$profiles[$pid]['interval_txt'] = $stat_interval;
+ }
+
+ # nastavimo privzet profil na trenutnega
+ self :: SetDefaultProfile($pid);
+
+ } else {
+ # shranjujenmo v sejo
+ if ($timeline == 'true') {
+ # shranjujemo od - do
+ $stat_interval = '';
+ } else {
+ # shranjujemo interval
+ $startDate = '';
+ $endDate = '';
+ }
+
+ if ($timeline == 'true') {
+ self::$profiles[$pid]['starts'] = $startDate;
+ self::$profiles[$pid]['ends'] = $endDate;
+ } else {
+ self::$profiles[$pid]['interval_txt'] = $stat_interval;
+ }
+
+ $_SESSION['statistic_profile'][self::$surveyId] = array('id'=>'-1',
+ 'name'=>$lang['srv_temp_profile'],
+ 'starts'=>$startDate,
+ 'ends'=>$endDate,
+ 'interval_txt'=>$stat_interval);
+
+ self :: SetDefaultProfile(-1);
+
+ }
+ return $updated;
+ }
+
+ static function RenameProfile($pid, $name) {
+
+ if (isset($pid) && $pid > 0 && isset($name) && trim($name) != "") {
+ // popravimo podatek za variables
+ $stringUpdate = "UPDATE srv_statistic_profile SET name = '".$name."' WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ return $updated;
+ } else {
+ return -1;
+ }
+ }
+
+ static function DeleteProfile($pid = 0) {
+ self :: SetDefaultProfile('0');
+ if (isset($pid) && $pid == -1) {
+ unset($_SESSION['statistic_profile'][self::$surveyId] );
+ } else if (isset($pid) && $pid > 0) {
+ // Izbrišemo profil in nastavimo privzetega
+ $stringUpdate = "DELETE FROM srv_statistic_profile WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ }
+ }
+
+ /** Funkcija kreira nov profil
+ *
+ */
+ function createStatisticProfile($timeline,$startDate,$endDate,$stat_interval,$name=null) {
+ global $lang;
+ if ($name == null || trim($name) == '' ) {
+ $name = $lang['srv_new_profile'];
+ }
+
+ if ($timeline == 'true') {
+ # shranjujemo od - do
+ $startDate = date(SS_OUTPUT_DATE_FORMAT, strtotime($startDate));
+ $endDate = date(SS_OUTPUT_DATE_FORMAT, strtotime($endDate));
+ $stat_interval = '';
+ } else {
+ # shranjujemo interval
+ $startDate = '0000-00-00';
+ $endDate = '0000-00-00';
+ }
+
+ $iStr = "INSERT INTO srv_statistic_profile (id,uid,name,starts,ends,interval_txt)".
+ " VALUES (NULL, '".self::$uId."', '".$name."', '".$startDate."', '".$endDate."', '".$stat_interval."')";
+
+ $ins = sisplet_query($iStr);
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($id > 0) {
+ self :: SetDefaultProfile($id);
+ } else {
+ self :: SetDefaultProfile(0);
+ }
+
+ return;
+ }
+
+ /** Funkcija prikaze izbor datuma
+ *
+ */
+ function displayDateFilters($current_pid = null) {
+ global $lang;
+ $_all_profiles = SurveyStatisticProfiles::getProfiles();
+
+
+ if ($current_pid == null) {
+ $current_pid = SurveyStatisticProfiles::getCurentProfileId();
+ }
+ echo '<div class="statistic_profile_left_right floatLeft">'."\n";
+ echo '<div class="statistic_profile_holder">'."\n";
+ # zlistamo vse profile
+ echo '<div id="statistic_profile" class="select">'."\n";
+ if (count($_all_profiles)) {
+ foreach ($_all_profiles as $id=>$profile) {
+ echo '<div class="option' . ($current_pid == $id ? ' active' : '') . '" id="statistic_profile_' . $id . '">' . $profile['name'] .'</div>'."\n";
+ }
+ }
+ echo ' </div>'."\n"; // statistic_profile
+ echo '</div>'."\n"; //statistic_profile_holder
+ echo '<br class="clr" />';
+ # privzetega profila ne moremo ne zbrisat ne preimenovat
+ echo '<div class="statistic_profile_button_left_holder link_no_decoration">'."\n";
+ if ($current_pid > 0) {
+ echo '<a href="#" onclick="showHideRenameStatisticProfile(\'true\'); return false;">'.$lang['srv_rename_profile'].'</a><br/>'."\n";
+ }
+ if ($current_pid != 0) {
+ echo '<a href="#" onclick="showHideDeleteStatisticProfile(\'true\'); return false;">'.$lang['srv_delete_profile'].'</a>'."\n";
+ }
+ echo '</div>'."\n"; // statistic_profile_button_left_holder
+
+ echo '</div>'."\n"; //statistic_profile_left
+
+ echo '<div class="statistic_profile_left_right floatRight">'."\n";
+ echo '<div id="statistic_profile_content">';
+ self::DisplayProfileData($current_pid);
+ echo '</div>'; // statistic_profile_content
+ echo '<br class="clr" />'."\n";
+ if ($current_pid == 0) {
+ echo '<div class="statistic_profile_note">';
+ echo $lang['srv_change_default_profile'];
+ echo '</div>'; // statistic_profile_note
+ }
+ echo '<br class="clr" />';
+ echo '<div class="statistic_profile_button_right_holder floatRight">'."\n";
+ if ($current_pid == 0) {
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="run_statistic_interval_filter(\'false\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="showHideCreateStatisticProfile(\'true\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="close_statistic_interval_filter(); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ } else if ($current_pid == -1) {
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="run_statistic_interval_filter(\'true\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="showHideCreateStatisticProfile(\'true\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="close_statistic_interval_filter(); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ } else {
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="run_statistic_interval_filter(\'false\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+// echo '<span class="floatRight spaceRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="run_statistic_interval_filter(\'true\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="showHideCreateStatisticProfile(\'true\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="close_statistic_interval_filter(); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+
+ }
+ echo '</div>'."\n"; // statistic_profile_button_right_holder
+ echo '</div>'; // statistic_profile_right
+ // cover Div
+ echo '<div id="statisticProfileCoverDiv"></div>'."\n";
+
+ // div za kreacijo novega
+ echo '<div id="newProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="newProfileName" name="newProfileName" type="text" value="" size="45" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="create_new_statistic_interval_filter(); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="showHideCreateStatisticProfile(\'false\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . $currentFilterProfile['name'] . '" size="45" />'."\n";
+ echo '<input id="renameProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="renameStatisticProfile(); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="showHideRenameStatisticProfile(\'false\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . $currentFilterProfile['name'] . '</b>?'."\n";
+ echo '<input id="deleteProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="deleteStatisticProfile(); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="showHideDeleteStatisticProfile(\'false\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+
+ }
+ /** Funkcija prikaze osnovnih informacije profila
+ *
+ */
+ function DisplayProfileData($current_pid) {
+ global $lang;
+ # podatki profila
+ $p_data = SurveyStatisticProfiles::GetProfileData($current_pid);
+
+ #kateri nacin imamo ali timeline (od - do) ali inervalsko (zadnjih....)
+ # ce je podan string interval imamo intervalno
+ if ( $p_data['interval_txt'] != null || trim($p_data['interval_txt'] != '')) {
+ $timeline = false;
+ $time = $p_data['interval_txt'];
+ $p_data['starts'] = date(SS_DATE_FORMAT,strtotime(SurveyInfo::getInstance()->getSurveyInsertDate()));
+ $p_data['ends'] = date(SS_DATE_FORMAT);
+ } else {
+ $timeline = true;
+ $time = '';
+ }
+
+ echo '<input type="radio" name="timeline" id="statistic_date_timeline" value="true" '.($timeline ? ' checked="checked"' : '').($current_pid == 0 ? ' disabled="disabled"':'').' autocomplete="off"><label> ' . $lang['srv_statistic_from'] . ': </label>'."\n";
+ echo '<input id="startDate" type="text" name="startDate" value="' . $p_data['starts'] . '" onclick="changeStatisticDate();" readonly="true" '.($current_pid == 0 ? ' disabled="disabled"':'').' autocomplete="off"/>&nbsp;';
+ echo '<span class="faicon calendar_icon icon-as_link" id="starts_img"></span>' . "\n";
+ echo '<label> ' . $lang['srv_statistic_to'] . ': </label>'."\n";
+ echo '<input id="endDate" type="text" name="endDate" value="' . $p_data['ends'] . '" onclick="changeStatisticDate();" readonly="true" '.($current_pid == 0 ? ' disabled="disabled"':'').'cautocomplete="off"/>&nbsp;';
+ echo '<span class="faicon calendar_icon icon-as_link" id="expire_img"></span>' . "\n" ;
+ echo '<br />';
+ echo '<p><input type="radio" name="timeline" id="statistic_date_interval" value="false" '.($timeline ? '' : ' checked="checked"').($current_pid == 0 ? ' disabled="disabled"':'').' autocomplete="off">'.$lang['srv_statistic_period_label'].':';
+ echo '<select name="stat_interval" id="stat_interval" onclick="changeStatisticDate(\'interval\');" '.($current_pid == 0 ? ' disabled="disabled"':'').'autocomplete="off">';
+ echo '<option value="" selected="true">'.$lang['srv_statistic_choose_interval'].'</option>';
+ foreach (self::$SS_ARRAYS as $INTERVAL) {
+ echo '<option value="'.$INTERVAL.'"' . ($time == $INTERVAL ? ' selected' : '') . '>'.$lang['srv_diagnostics_'.$INTERVAL].'</option>';
+ }
+ echo '</select>' . "\n";
+ echo '</p>' . "\n";
+
+ echo '<script type="text/javascript">' . "\n";
+ # za profil id=0 (privzet profil ne pustimo spreminjat
+ if ($current_pid != 0 ) {
+ echo
+ ' Calendar.setup({' . "\n" .
+ ' inputField : "startDate",' . "\n" .
+ ' ifFormat : "'.SS_CALENDAR_DATE_FORMAT.'",' . "\n" .
+ ' button : "starts_img",' . "\n" .
+ ' singleClick : true,' . "\n" .
+ ' onUpdate : changeStatisticDate' . "\n\r" .
+ ' });' . "\n" .
+ ' Calendar.setup({' . "\n" .
+ ' inputField : "endDate",' . "\n" .
+ ' ifFormat : "'.SS_CALENDAR_DATE_FORMAT.'",' . "\n" .
+ ' button : "expire_img",' . "\n" .
+ ' singleClick : true,' . "\n" .
+ ' onUpdate : changeStatisticDate' . "\n\r" .
+ ' })' . "\n";
+ }
+ echo '</script>' . "\n";
+
+ }
+}
+?>
diff --git a/admin/survey/classes/class.SurveyStatusCasi.php b/admin/survey/classes/class.SurveyStatusCasi.php
new file mode 100644
index 0000000..27cc59b
--- /dev/null
+++ b/admin/survey/classes/class.SurveyStatusCasi.php
@@ -0,0 +1,340 @@
+<?php
+
+class SurveyStatusCasi
+{
+ static private $sid = null; # id ankete
+ static private $uid = null; # id userja
+ static private $inited = false; # ali so profili ze inicializirani
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+
+ // lurker je mal poseben, ker je neodvisen od ostalih (user je npr. 6 in lurker)
+ static private $allStatus = array('null',0,1,2,3,4,5,6,'lurker'); // Statusi anket katere štejemo kot ustrezne
+ static private $appropriateStatus = array(6,5); // Statusi anket katere štejemo kot ustrezne
+ static private $unAppropriateStatus = array(4,3,2,1,0); // Statusi anket katere štejemo kot neustrezne
+ static private $unKnownStatus = array('null'); // Statusi anket katere štejemo kot neustrezne
+
+ static function Init($sid, $uid = null) {
+ # nastavimo surveyId
+ self::setSId($sid);
+
+ # nastavimo userja
+ self::setGlobalUserId($uid);
+ SurveyUserSetting :: getInstance()->Init(self::$sid, self::getGlobalUserId());
+ if (self::$inited == false) {
+ self::$inited = self :: RefreshData();
+ }
+ }
+
+ static function RefreshData() {
+ # preberemo podatke vseh porfilov ki so na voljo in jih dodamo v array
+ $stringSelect = "SELECT * FROM srv_status_casi WHERE uid = '".self::getGlobalUserId()."' OR (uid = '0' AND `system` =1) ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ }
+ # poiscemo privzet profil
+ self::$currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_status_casi');
+ if (!self::$currentProfileId || self::$currentProfileId == 1)
+ self::$currentProfileId = 1;
+
+ # ce imamo nastavljen curent pid in profil z tem pid ne obstaja nastavomo na privzet profil
+ if (self::$currentProfileId != 1) {
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ self::$currentProfileId = 1;
+ self::setDefaultProfileId(self::$currentProfileId);
+ }
+ }
+ # ce ne obstajajo podatki za cpid damo error
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ die("Profile data is missing!");
+ return false;
+ } else {
+ return true;
+ }
+ }
+ static function DisplayProfile( $pid = null) {
+ global $lang;
+ if ($pid == null ) {
+ $pid = self::$currentProfileId;
+ }
+
+ echo '<div id="status_profile_holder">';
+ self :: DisplayProfileOptions($pid);
+ echo '</div>';
+ echo '<div id="status_profile_data_holder">';
+ echo '<div>';
+ self :: DisplayProfileData($pid);
+ echo '</div>';
+ echo '<br><div class="floatRight">';
+
+
+ # shrani - pozeni
+ $run_lbl = ( $pid == 1 ) ? $lang['srv_run_profile'] : $lang['srv_save_run_profile'];
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="statusCasiAction(\'run\'); return false;"><span>'.$run_lbl.'</span></a></span></span>';
+
+ # preklici
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="statusCasiAction(\'cancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ # shrani kot nov profil
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="statusCasiAction(\'newName\'); return false;"><span>'.$lang['srv_save_new_profile'].'</span></a></span></span>';
+ echo '</div>';
+ echo '</div>';
+
+ // cover Div
+ echo '<div id="statusProfileCoverDiv"></div>'."\n";
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfile">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="statusCasiAction(\'newSave\'); return false;"><span>'.$lang['srv_save_profile'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="showHideNewMissingProfile(\'false\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+/*
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . self::$profiles[$pid]['name'] . '" size="45" />'."\n";
+ echo '<input id="renameProfileId" type="hidden" value="' . $pid . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="(\'deleteCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="(); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+*/
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . self::$profiles[$pid]['name'] . '</b>?'."\n";
+ echo '<input id="deleteProfileId" type="hidden" value="' . $pid . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="statusCasiAction(\'deleteCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="statusCasiAction(\'deleteConfirm\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ }
+
+ static function DisplayProfileData($pid) {
+ global $lang;
+ $curentProfileData = self :: $profiles[$pid];
+// echo '<div id="status_profile_notes" >help?'.'</div>';
+ echo '<div id="statusProfileFieldsetHolder" >';
+ echo '<fieldset id="missingProfileFieldset">'."\n";
+ echo '<legend>' . $lang['srv_missing_profile_title4'] . '</legend>'."\n";
+ echo '<form name="" id="" autocomplete="off">'."\n";
+
+ $cnt = 1;
+ echo '<table><tr>';
+ // dodamo veljavne
+ foreach (self::$appropriateStatus as $index) {
+ if ($cnt&1)
+ echo '</tr><tr>';
+ echo '<td style="width:50%">'."\n";
+ echo '<label><input name="srv_userstatus[]" type="checkbox" id="' . $index . '"' .
+ ($curentProfileData['status'.$index] == 1 ? ' checked="checked"' : '') . '/>'."\n";
+ echo $lang['srv_userstatus_' . $index]. " (".$index.")";
+ echo '</label></td>'."\n";
+ $cnt++;
+ }
+ // dodamo neveljavne
+ foreach (self::$unAppropriateStatus as $index) {
+ if ($cnt&1)
+ echo '</tr><tr>';
+ echo '<td style="width:50%">'."\n";
+ echo '<label><input name="srv_userstatus[]" type="checkbox" id="' . $index . '"' .
+ ($curentProfileData['status'.$index] == 1 ? ' checked="checked"' : '') . '/>'."\n";
+ echo $lang['srv_userstatus_' . $index]. " (".$index.")";
+ echo '</label></td>'."\n";
+ $cnt++;
+ }
+ // dodamo null
+ foreach (self::$unKnownStatus as $index) {
+
+ if ($cnt&1)
+ echo '</tr><tr>';
+ echo '<td style="width:50%">'."\n";
+ echo '<label><input name="srv_userstatus[]" type="checkbox" id="' . $index . '"' .
+ ($curentProfileData['status'.$index] == 1 ? ' checked="checked"' : '') . '/>'."\n";
+ echo $lang['srv_userstatus_' . $index]. " (".$index.")";
+ echo '</label></td>'."\n";
+ $cnt++;
+ }
+
+ echo '</tr></table>';
+
+ // lurkerji
+ echo '<hr><label><input type="checkbox" name="srv_userstatus[]" id="lurker" '.($curentProfileData['statuslurker'] == 1 ? ' checked="checked"' : '') . '> '.$lang['srv_lurkers'].'</label>';
+
+ echo '<div class="clr"></div>'."\n";
+ echo '</form>'."\n";
+ echo '</fieldset>'."\n";
+ echo '</div>'."\n";
+
+ }
+
+ static function DisplayProfileOptions($pid) {
+ global $lang;
+ echo '<div id="status_casi" class="select">';
+ foreach ( self::$profiles as $key => $profile ) {
+ echo '<div id="status_profile_'.$profile['id'].'" class="option' . ($profile['id'] == $pid ? ' active' : '') . '" value="' . $profile['id'] . '">' . $profile['name'] . '</div>';
+ }
+ echo '</div>';
+ echo '<div id="status_profile_links" class="link_no_decoration">';
+ if ($pid != 1)
+ echo '<a href="#" onclick="statusCasiAction(\'deleteAsk\'); return false;">'.$lang['srv_delete_profile'].'</a><br/>'."\n";
+ echo '</div>';
+ echo '<script>';
+ echo '$(function() {';
+ echo 'scrollToProfile("#status_profile_'.$pid.'");';
+ echo '});';
+ echo '</script>';
+
+ }
+
+ /** getProfiles
+ *
+ */
+ static function getProfiles() {
+ return self::$profiles;
+ }
+
+ /** setSurveyId
+ *
+ */
+ static function setSId($surveyId) {
+ self::$sid = $surveyId;
+ }
+
+ /** setGlobalUserId
+ *
+ */
+ static function setGlobalUserId($uid = null) {
+ if ($uid == null) {
+ global $global_user_id;
+ self::$uid = $global_user_id;
+ } else {
+ self::$uid = $uid;
+ }
+ }
+
+ /** getGlobalUserId
+ *
+ */
+ static function getGlobalUserId() {
+ return self::$uid;
+ }
+ static function getCurentProfileId() {
+ return self::$currentProfileId;
+ }
+ /**
+ *
+ * @param unknown_type $pid
+ */
+ static function setCurentProfileId($pid) {
+ if ($pid < 1)
+ $pid = 1;
+ return self::$currentProfileId = $pid;
+ }
+
+ static function setDefaultProfileId($pid) {
+ if (!$pid)
+ $pid = 1;
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_status_casi', $pid);
+ self::$currentProfileId = $pid;
+ return true;
+ }
+ static function getStatusAsArrayString() {
+
+ $mpds = self::getStatusArray(self::$currentProfileId);
+
+ $result = array();
+
+ if ($mpds) {
+ foreach ( self::$appropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1)
+ $result[$index] = $index;
+ }
+ foreach ( self::$unAppropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1)
+ $result[$index] = $index;
+ }
+ foreach ( self::$unKnownStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1)
+ $result[$index] = $index;
+ }
+ if (isset($mpds['statuslurker']) && $mpds['statuslurker'] == 1)
+ $result['lurker'] = 'lurker';
+ }
+
+ return $result;
+ }
+ static function getStatusArray($pid) {
+ $mpd = self::$profiles[$pid];
+ return $mpd;
+ }
+
+ /** Shranimo v obstoječ profil
+ *
+ * @param unknown_type $pid
+ * @param unknown_type $name
+ * @param unknown_type $status
+ */
+ static function saveProfile($pid,$status) {
+ $insert_id = 0;
+ if (isset($pid) && $pid != null && isset($status) && $status != null) {
+ if ($pid == 1) { # ce mamo privzet profil ga ne shranjujemo
+ return 1;
+ }
+ # imamo podatke, updejtamo profil v bazi
+
+ $statusi = explode(',',$status);
+ if (count(self::$allStatus) > 0 ) {
+
+ $updateString = "UPDATE srv_status_casi SET ";
+ $prefix = '';
+ foreach (self::$allStatus as $_status) {
+ $updateString .= $prefix . 'status'.$_status. ' = '.(in_array((string)$_status,$statusi) ? '1' : '0');
+ $prefix =', ';
+ }
+ $updateString .= " WHERE id = '".$pid."'";
+ }
+ $queryUpdate = sisplet_query($updateString)
+ or die(mysqli_error($GLOBALS['connect_db']));
+
+ return $pid;
+ }
+
+ }
+
+ /** Shranimo kot nov profil
+ *
+ * @param unknown_type $pid
+ * @param unknown_type $name
+ * @param unknown_type $status
+ */
+ static function saveNewProfile($pid,$name,$status) {
+ $insert_id = 0;
+ if (isset($pid) && $pid != null && isset($name) && $name != null && isset($status) && $status != null) {
+ # imamo podatke, vstavimo nov profil v bazo
+ #id uid name system statusnull status0 status1 status2 status3 status4 status5 status6
+
+ $statusi = explode(',',$status);
+ $str_lbl = '';
+ $str_vle = '';
+ foreach ($statusi as $_status) {
+ $str_lbl .= ', status'.$_status;
+ $str_vle .= ', 1';
+ }
+ $insertString = "INSERT INTO srv_status_casi (uid,name,system".$str_lbl.") VALUES ('".self::getGlobalUserId()."', '".$name."', 0".$str_vle.")";
+ $queryInsert = sisplet_query($insertString)
+ or die(mysqli_error($GLOBALS['connect_db']));
+ $insert_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+ return $insert_id;
+ }
+
+ static function Delete($pid) {
+ if ($pid != 1) {
+ $sqlDelete = sisplet_query("DELETE FROM srv_status_casi WHERE id = '$pid' AND `system` != '1'");
+ print_r("DELETE FROM srv_status_casi WHERE id = '$pid' AND `system` != '1'");
+ }
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyStatusProfiles.php b/admin/survey/classes/class.SurveyStatusProfiles.php
new file mode 100644
index 0000000..11946a3
--- /dev/null
+++ b/admin/survey/classes/class.SurveyStatusProfiles.php
@@ -0,0 +1,1247 @@
+<?php
+
+/** @author: Gorazd Veselič
+ *
+ * @Desc: za upravljanje z profili statusov za podatke in izvoze
+ *
+ */
+
+session_start();
+DEFINE (STR_DLMT, "|");
+
+class SurveyStatusProfiles
+{
+ static private $sid = null; # id ankete
+ static private $uid = null; # id userja
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+
+ // lurker je mal poseben, ker je neodvisen od ostalih (user je npr. 6 in lurker)
+ # lurker = 0 - obveezno ni lurker, lurker = 1 - obvezno je lurker, lurker = 2 - je ali ni lurker
+ static private $allStatus = array('null',0,1,2,3,4,5,6,'lurker'); // Statusi anket katere štejemo kot ustrezne
+ static private $appropriateStatus = array(6,5); // Statusi anket katere štejemo kot ustrezne
+ static private $unAppropriateStatus = array(4,3,2,1,0); // Statusi anket katere štejemo kot neustrezne
+ static private $unKnownStatus = array('null'); // Statusi anket katere štejemo kot neustrezne
+ # za awk komando
+ static private $_AWK_FILTER_TEXT = array(6=>'6',5=>'5',4=>'4',3=>'3',2=>'2',1=>'^1',0=>'0','null'=>'-1'); # texti za statuse. 6=>'6',5=>'5',4=>'4',3=>'3',2=>'2',1=>'^1',0=>'0',null=>'-1' Pri 1 je ^pomemben, če ne lahko vzame tudi -1
+
+ static private $allUserCount = 0; #Koliko je vseh userjev
+ static private $allValidCount = 0; #Koliko je veljavnih userjev
+
+ static private $survayDefaultUstrezni = 2; #privzet ustrezni profil: 2-ustrezni (5,6) 3-končani(6)
+
+ static function Init($sid, $uid = null) {
+ # nastavimo surveyId
+ self::setSId($sid);
+ SurveyInfo :: getInstance()->SurveyInit(self::$sid);
+ # nastavimo userja
+ self::setGlobalUserId($uid);
+
+ if ((int)SurveyInfo :: getInstance()->getSurveyColumn('defValidProfile') == 3) {
+ self::$survayDefaultUstrezni = 3;
+ }
+
+ # preštejemo userje
+ $str_all = "SELECT count(*) FROm srv_user WHERE ank_id='".self::$sid."' AND deleted='0' AND preview = '0'";
+ if (self::$survayDefaultUstrezni == 2) {
+ $str_valid = "SELECT count(*) FROM srv_user WHERE ank_id='".self::$sid."' AND last_status IN (5,6) AND lurker = 0 AND deleted='0' AND preview = '0' AND testdata='0'";
+ } else {
+ $str_valid = "SELECT count(*) FROM srv_user WHERE ank_id='".self::$sid."' AND last_status = '6' AND lurker = 0 AND deleted='0' AND preview = '0' AND testdata='0'";
+ }
+ $query_all = sisplet_query($str_all);
+ $query_valid = sisplet_query($str_valid);
+ list($all) = mysqli_fetch_row($query_all);
+ list($valid) = mysqli_fetch_row($query_valid);
+ self::$allUserCount = $all;
+ self::$allValidCount = $valid;
+ SurveyUserSetting :: getInstance()->Init(self::$sid, self::getGlobalUserId());
+ self :: RefreshData();
+ }
+
+ static function getAllValidCount() {
+ return self::$allValidCount;
+ }
+ static function getAllUserCount() {
+ return self::$allUserCount;
+ }
+
+
+ static function RefreshData() {
+ global $lang;
+
+ $lang_admin = SurveyInfo :: getInstance()->getSurveyColumn('lang_admin');
+
+ self::$profiles = array();
+ # dodamo sejo če obstaja
+ if (isset($_SESSION['statusProfile'])) {
+ if ( $lang_admin != 1 ) {
+ $_SESSION['statusProfile']['name'] = $lang['srv_temp_profile'];
+ }
+ self::$profiles[$_SESSION['statusProfile']['id']] = $_SESSION['statusProfile'];
+ }
+ # preberemo podatke vseh porfilov ki so na voljo in jih dodamo v array
+ $stringSelect = "SELECT * FROM srv_status_profile WHERE uid='".self::getGlobalUserId()."' OR ank_id = '".self::$sid."' OR (uid = '0' AND `system`=1) ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ if ( $lang_admin != 1 && $rowSelect['system'] == 1 ) {
+ # imamo sistemski profil v tujem jeziku popravimo tekste
+ $rowSelect['name'] = $lang['srv_status_profile_system_'.$rowSelect['id']];
+ }
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ }
+
+ # ker si Vasja skoz nekaj zmišljuje glede imen sistemskih profilov (ki so zaenkrat v bazi) jih ročno prepišemo
+ # pa še jezikovno tabelo lahko uporabimo, tak da je to boljše
+ self::$profiles[1]['name'] = $lang['srv_status_profile_system_1'];
+ self::$profiles[2]['name'] = $lang['srv_status_profile_system_2'];
+ self::$profiles[3]['name'] = $lang['srv_status_profile_system_3'];
+ # vsi statusi ni pomembno ali je lurker ali ne
+ # pri ustreznih ne sme biti lurker in ne testni
+ self::$profiles[1]['statuslurker'] = 2;
+ self::$profiles[2]['statuslurker'] = 0;
+ self::$profiles[3]['statuslurker'] = 0;
+
+ self::$profiles[1]['statustestni'] = 2;
+ self::$profiles[2]['statustestni'] = 0;
+ self::$profiles[3]['statustestni'] = 0;
+
+ // Uporabnost - vedno so vsi vklopljeni po defaultu
+ self::$profiles[1]['statusnonusable'] = 1;
+ self::$profiles[2]['statuspartusable'] = 1;
+ self::$profiles[3]['statususable'] = 1;
+
+ # poiscemo privzet profil
+ #določimo podstran
+ if (isset($_POST['meta_akcija']) && $_POST['meta_akcija'] != '') {
+ $_podstran = $_POST['meta_akcija'];
+ } else if (isset($_POST['podstran']) && $_POST['podstran'] != '') {
+ $_podstran = $_POST['podstran'];
+ } else if (isset($_GET['a']) && $_GET['a'] != '') {
+ $_podstran = $_GET['a'];
+ } else {
+ $_podstran = A_COLLECT_DATA;
+ }
+
+ if ( (($_podstran !== A_COLLECT_DATA && $_podstran !== A_COLLECT_DATA_EXPORT && $_podstran !== 'para_graph') || (isset($_GET['b']) && $_GET['b'] == 'export')) && $_podstran !== 'usable_resp' && $_podstran !== 'reminder_tracking') {
+ $_podstran = A_ANALYSIS;
+ }
+
+ // Pri izvozu podatkov uporabimo isti profil kot pri ostalih podatkih
+ if ($_podstran == A_COLLECT_DATA_EXPORT) {
+ $_podstran = A_COLLECT_DATA;
+ }
+
+ # če smo v vpogledu pohandlammo posebej
+ if (($_podstran == A_COLLECT_DATA && $_GET['m'] == 'quick_edit') || $_POST['podstran'] == 'quick_edit') {
+ $_podstran = 'vpogled';
+ }
+ self::$currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_status_profile_'.$_podstran);
+
+ if (!self::$currentProfileId) {
+
+ #self::$currentProfileId = 2;
+ self::$currentProfileId = self::$survayDefaultUstrezni; # je lahko 2 ali 3
+ }
+ # ustrezni je lahko samo če so kakšni ustrezni zapisi v bazi ob pogoju da pa neustrezni obstajajao
+ if (self::$allValidCount == 0 && self::$allUserCount > 0) {
+ if (self::$currentProfileId == 2 || self::$currentProfileId == 3 ) {
+ # privzeto nastavimo na vsi
+ self::$currentProfileId = 1;
+ }
+ }
+
+ # ce imamo nastavljen curent pid in profil z tem pid ne obstaja nastavomo na privzet profil
+ if (self::$currentProfileId != 1) {
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ self::$currentProfileId = 1;
+ }
+ }
+
+ # ce ne obstajajo podatki za cpid damo error
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ die("Profile data is missing!");
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ public static function getSystemDefaultProfile() {
+ $sysDefProf = self::$survayDefaultUstrezni; # je lahko 2 ali 3
+
+ # ustrezni je lahko samo če so kakšni ustrezni zapisi v bazi ob pogoju da pa neustrezni obstajajao
+ if (self::$allValidCount == 0 && self::$allUserCount > 0) {
+ if ($sysDefProf == 2 || $sysDefProf == 3 ) {
+ # privzeto nastavimo na vsi
+ $sysDefProf = 1;
+ }
+ }
+ return (int)$sysDefProf;
+ }
+
+ public static function getDefaultProfile() {
+ return self::$currentProfileId;
+ }
+
+ static function DisplayProfile( $pid = null) {
+ global $lang;
+
+ if ($pid == null ) {
+ $pid = self::$currentProfileId;
+ }
+
+ $popUp = new PopUp();
+ $popUp->setId('divStatusProfile');
+ $popUp->setHeaderText($lang['srv_status_settings']);
+
+ #vsebino shranimo v buffer
+ ob_start();
+ if ( self::$currentProfileId != SSP_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+ echo '<div class="popup_close"><a href="#" onClick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\'); return false;">✕</a></div>';
+
+ echo ' <div id="status_profile_holder">';
+ self :: DisplayProfileOptions($pid);
+ echo ' </div>';
+
+ echo ' <div id="status_profile_data_holder">';
+ self :: DisplayProfileData($pid);
+ echo ' <br class="clr" />';
+ echo ' </div>';
+
+ // cover Div
+ echo '<div id="statusProfileCoverDiv"></div>';
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfile">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />';
+ $button = new PopUpButton($lang['srv_save_profile']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','statusProfileAction(\'newSave\'); return false;');
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','statusProfileAction(\'newCancel\'); return false;');
+ echo '</div>';
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . self::$profiles[$pid]['name'] . '" size="45" />';
+ echo '<input id="renameProfileId" type="hidden" value="' . $pid . '" />';
+ $button = new PopUpButton($lang['srv_rename_profile_yes']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','statusProfileAction(\'renameProfile\'); return false;');
+
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','statusProfileAction(\'renameCancel\'); return false;');
+ echo '</div>';
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . self::$profiles[$pid]['name'] . '</b>?';
+ echo '<input id="deleteProfileId" type="hidden" value="' . $pid . '" />';
+
+ $button = new PopUpButton($lang['srv_delete_profile_yes']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','statusProfileAction(\'deleteConfirm\'); return false;');
+
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','statusProfileAction(\'deleteCancel\'); return false;');
+
+ echo '</div>';
+
+ $content = ob_get_clean();
+
+ #dodamo vsebino
+ $popUp->setContent($content);
+
+ /*
+ if ($pid < 0) { #Imamo sejo, lahko poženemo samo kot sejo
+ $run_lbl = $lang['srv_run_as_session_profile'];
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="statusProfileAction(\'runSession\'); return false;"><span>'.$run_lbl.'</span></a></span></span>';
+ } else {
+ # shrani - pozeni
+ $run_lbl = $lang['srv_run_profile'];
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick=""><span>'.$run_lbl.'</span></a></span></span>';
+ $run_lbl = $lang['srv_run_as_session_profile'];
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="statusProfileAction(\'runSession\'); return false;"><span>'.$run_lbl.'</span></a></span></span>';
+
+ }
+ */
+ $button = new PopUpButton($lang['srv_choose_profile']);
+ $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','statusProfileAction(\'choose\'); return false;');
+ $popUp->addButton($button);
+
+ #dodamo gumb shrani
+ if (self::$profiles[$pid]['system'] != 1 && $pid != -1)
+ {
+ $button = new PopUpButton($lang['srv_save_profile']);
+ $button -> setFloat('right')
+ -> addAction('onClick','statusProfileAction(\'save\'); return false;');
+ $popUp->addButton($button);
+ }
+
+ $button = new PopUpButton($lang['srv_new_profile_name']);
+ $button -> setFloat('right')
+ -> addAction('onClick','statusProfileAction(\'newName\'); return false;');
+ $popUp->addButton($button);
+
+ # dodamo gumb Prekliči
+ $button = new PopUpCancelButton();
+ $button -> setFloat('right');
+ $popUp->addButton($button);
+
+ echo $popUp;
+ }
+
+ static function DisplayProfileData($pid) {
+ global $lang;
+ $curentProfileData = self :: $profiles[$pid];
+// echo '<div id="status_profile_notes" >help?'.'</div>';
+
+ echo '<div id="missingProfileFieldsetHolder" >';
+ echo '<form name="" id="" autocomplete="off">';
+ echo '<fieldset class="statusProfileFieldset">';
+ echo '<legend>' . $lang['srv_missing_profile_title4'] . '</legend>';
+
+ $cnt = 1;
+
+ $disabled = $curentProfileData['system'] == 1 ? true : false;
+
+ # preverimo kaere statuse disejblamo na podlagi izbire načina kreiranja datoteke (samo 5,6 / vsi satusi)
+ list($collect_all_status) = mysqli_fetch_row(sisplet_query("SELECT collect_all_status FROM srv_data_files WHERE sid = '".self::$sid."'"));
+
+ echo '<table><tr>';
+ // dodamo veljavne
+ foreach (self::$appropriateStatus as $index) {
+ if ($cnt&1) {
+ echo '</tr><tr>';
+ }
+ echo '<td style="width:50%">';
+ echo '<label><input name="srv_userstatus[]" type="checkbox" id="' . $index . '"' .
+ ($curentProfileData['status'.$index] == 1 ? ' checked="checked"' : '') .
+ ($disabled || ( (int)$collect_all_status == 0 && $index < 5 ) ? ' disabled="true"' : '' ). '/>';
+ echo '<span'.($disabled || ( (int)$collect_all_status == 0 && $index < 5 ) ? ' class="gray"' : '' ).'>'.$lang['srv_userstatus_' . $index]. ' ('.$index.')</span>';
+ echo '</label></td>';
+ $cnt++;
+ }
+ // dodamo neveljavne
+ foreach (self::$unAppropriateStatus as $index) {
+ if ($cnt&1)
+ echo '</tr><tr>';
+ echo '<td style="width:50%">';
+ echo '<label><input name="srv_userstatus[]" type="checkbox" id="' . $index . '"' .
+ ($curentProfileData['status'.$index] == 1 ? ' checked="checked"' : '') .
+ ($disabled || ( (int)$collect_all_status == 0 && $index < 5 ) ? ' disabled="true"' : '' ) . '/>';
+ //echo $lang['srv_userstatus_' . $index]. " (".$index.")";
+ echo '<span'.($disabled || ( (int)$collect_all_status == 0 && $index < 5 ) ? ' class="gray"' : '' ).'>'.$lang['srv_userstatus_' . $index]. ' ('.$index.')</span>';
+ echo '</label></td>';
+ $cnt++;
+ }
+ // dodamo null
+ foreach (self::$unKnownStatus as $index) {
+
+ if ($cnt&1)
+ echo '</tr><tr>';
+ echo '<td style="width:50%">';
+ echo '<label><input name="srv_userstatus[]" type="checkbox" id="' . $index . '"' .
+ ($curentProfileData['status'.$index] == 1 ? ' checked="checked"' : '') .
+ ($disabled || ( (int)$collect_all_status == 0 && $index < 5 ) ? ' disabled="true"' : '' ) . '/>';
+ //echo $lang['srv_userstatus_' . $index]. " (".$index.")";
+ echo '<span'.($disabled || ( (int)$collect_all_status == 0 && $index < 5 ) ? ' class="gray"' : '' ).'>'.$lang['srv_userstatus_' . $index]. ' ('.$index.')</span>';
+ echo '</label></td>';
+ $cnt++;
+ }
+
+ echo '</tr></table>';
+
+ echo '</fieldset>';
+
+
+ if ($disabled ) {
+ $html_disabled = ' disabled="true"';
+ $css_disabled = ' class="gray"';
+ }
+
+
+ echo '<fieldset class="statusProfileFieldset">';
+ echo '<legend>' . $lang['srv_invalid_units'] . '</legend>';
+
+ // lurkerji
+ # lurker = 0 - obveezno ni lurker, lurker = 1 - obvezno je lurker, lurker = 2 - je ali ni lurker
+ #echo '<hr><label><input type="checkbox" name="srv_userstatus[]" id="lurker" '.($curentProfileData['statuslurker'] == 1 ? ' checked="checked"' : '') . ($disabled ? ' disabled="true"' : '' ) . '> '.$lang['srv_lurkers'].'</label>';
+ echo '<label'.$css_disabled.'>'.$lang['srv_lurkers'].'</label>';
+ echo '<label'.$css_disabled.'><input type="radio" name="srv_us_lurker" value="0" '.((int)$curentProfileData['statuslurker'] == 0 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['no'].'</label>';
+ echo '<label'.$css_disabled.'><input type="radio" name="srv_us_lurker" value="1" '.((int)$curentProfileData['statuslurker'] == 1 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['srv_only_empty'].'</label>';
+ echo '<label'.$css_disabled.'><input type="radio" name="srv_us_lurker" value="2" '.((int)$curentProfileData['statuslurker'] == 2 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['srv_also'].'</label>';
+ echo '<br/><label class="small">'.$lang['srv_lurkers_subnote'].'</label>';
+
+ // testni vnosi
+ # testni = 0 - obveezno ni testni, testni = 1 - obvezno je tesni, testni = 2 - je ali ni testni
+ echo '<br/><br/><label'.$css_disabled.'>'.$lang['srv_testni_vnos'].'</label>';
+ echo '<label'.$css_disabled.'><input type="radio" name="srv_us_testni" value="0" '.((int)$curentProfileData['statustestni'] == 0 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['no'].'</label>';
+ echo '<label'.$css_disabled.'><input type="radio" name="srv_us_testni" value="1" '.((int)$curentProfileData['statustestni'] == 1 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['srv_only_test'].'</label>';
+ echo '<label'.$css_disabled.'><input type="radio" name="srv_us_testni" value="2" '.((int)$curentProfileData['statustestni'] == 2 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['srv_also'].'</label>';
+
+ echo '</fieldset>';
+
+
+ // Filter na uporabnost
+ echo '<fieldset class="statusProfileFieldset">';
+ echo '<legend>' . $lang['srv_usableResp_usable_unit'] . '</legend>';
+
+ // 2->uporabni, 1->delno uporabni, 0->neuporabni
+ echo '<label'.$css_disabled.'><input type="checkbox" name="srv_us_nonusable" value="1" '.((int)$curentProfileData['statusnonusable'] == 1 ? ' checked="checked"' : '') .$html_disabled. '> '.$lang['srv_usableResp_unusable'].'</label>';
+ echo '<span class="spaceLeft"></span><label'.$css_disabled.'><input type="checkbox" name="srv_us_partusable" value="1" '.((int)$curentProfileData['statuspartusable'] == 1 ? ' checked="checked"' : '') .$html_disabled. '>'.$lang['srv_usableResp_partusable'].'</label>';
+ echo '<span class="spaceLeft"></span><label'.$css_disabled.'><input type="checkbox" name="srv_us_usable" value="1" '.((int)$curentProfileData['statususable'] == 1 ? ' checked="checked"' : '') .$html_disabled. '>'.$lang['srv_usableResp_usable'].'</label>';
+
+
+ echo '</fieldset>';
+ echo '</form>';
+ echo '</div>';
+ }
+
+ static function DisplayProfileOptions($pid) {
+ global $lang;
+
+ $_sql_string = "SELECT collect_all_status FROM srv_data_files WHERE sid = '".self::$sid."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ $_sql_row = mysqli_fetch_assoc($_sql_qry);
+
+ echo '<div id="status_profile" class="select">';
+ foreach ( self::$profiles as $key => $profile ) {
+ if ($key != 1 || ($key == 1 && (int)$_sql_row['collect_all_status'] > 0 )) {
+
+ echo '<div id="status_profile_'.$profile['id'].'" class="option' . ($profile['id'] == $pid ? ' active' : '') . '" value="'.$profile['id'].'" '.($profile['id'] == $pid ? '' : ' onclick="show_status_profile_data(' . $profile['id'] . '); return false;"').'>';
+
+ echo $profile['name'];
+
+ if($profile['id'] == $pid){
+ #dodamo gumb izbriši
+ if (self::$profiles[$pid]['system'] != 1 ){
+ echo ' <a href="#" onclick="statusProfileAction(\'deleteAsk\'); return false;" value="'.$lang['srv_delete_profile'].'"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'."\n";
+ }
+ #dodamo gumb preimenuj
+ if (self::$profiles[$pid]['system'] != 1 && $pid != -1){
+ echo ' <a href="#" onclick="statusProfileAction(\'renameAsk\'); return false;" value="'.$lang['srv_rename_profile'].'"><span class="faicon edit floatRight spaceRight"></span></a>'."\n";
+ }
+ }
+
+ echo '</div>';
+ }
+ }
+ echo '</div>';
+
+ echo '<script>';
+ echo '$(function() {';
+ echo 'scrollToProfile("#status_profile_'.$pid.'");';
+ echo '});';
+ echo '</script>';
+ }
+
+ /** klici ajax funkcij
+ *
+ */
+ static function ajax() {
+ $pid = $_POST['pid'];
+ switch ($_GET['a']) {
+ case 'displayProfile' :
+ if (isset($pid) && $pid != null)
+ {
+ self :: setCurentProfileId($pid);
+ }
+ self :: DisplayProfile($pid);
+ break;
+ case 'chooseProfile' :
+ self :: setDefaultProfileId($pid);
+ break;
+ case 'saveProfile':
+ self :: saveProfile($pid);
+ break;
+ case 'run_status_profile':
+ self :: saveProfile($pid);
+ self :: setDefaultProfileId($pid);
+ break;
+ case 'save_status_profile':
+ $new_id = self :: saveNewProfile($pid);
+ self :: setDefaultProfileId($new_id);
+ echo $new_id;
+ break;
+ case 'deleteProfile':
+ self :: DeleteProfile($pid);
+ break;
+ case 'renameProfile':
+ self :: renameProfile($pid);
+
+ break;
+ case 'showColectDataSetting':
+ self :: showColectDataSetting();
+ break;
+ case 'saveCollectDataSetting':
+ self :: saveCollectDataSetting();
+ break;
+ case 'changeOnlyValidRadio':
+ self :: changeOnlyValidRadio();
+ break;
+
+ default:
+ echo 'ERROR! Missing function for action: '.$_GET['a'].'!';
+ break;
+ }
+ }
+
+ /** getProfiles
+ *
+ */
+ static function getProfiles() {
+ return self::$profiles;
+ }
+
+ /** setSurveyId
+ *
+ */
+ static function setSId($surveyId) {
+ self::$sid = $surveyId;
+ }
+
+ /** setGlobalUserId
+ *
+ */
+ static function setGlobalUserId($uid = null) {
+ if ($uid == null) {
+ global $global_user_id;
+ self::$uid = $global_user_id;
+ } else {
+ self::$uid = $uid;
+ }
+ }
+
+ /** getGlobalUserId
+ *
+ */
+ static function getGlobalUserId() {
+ return self::$uid;
+ }
+ static function getCurentProfileId() {
+ return (int)self::$currentProfileId;
+ }
+
+ public function getProfileName($pid) {
+ return self::$profiles[$pid]['name'];
+ }
+
+ /* Vrne ID in ime trenutno izbranega profila
+ *
+ */
+ function getCurentProfile() {
+ return array('id'=>self::$currentProfileId,'name'=>self::$profiles[self::$currentProfileId]['name']);
+ }
+ /**
+ *
+ * @param unknown_type $pid
+ */
+ static function setCurentProfileId($pid) {
+ # preverimo ali profil obstaja
+ if (!isset(self::$profiles[$pid]))
+ { # če ne obstaja damo privzeto ustrezne
+ $pid = 2;
+ }
+ # ce je seja, preverimo ali obstaja cene nardimo privzetega 1
+ if ($pid == -1) {
+ if (!(isset($_SESSION['statusProfile']['-1'])))
+ $pid = 1;
+ } else if (!$pid) {
+ $pid = 1;
+ }
+
+ return self::$currentProfileId = $pid;
+ }
+
+ static function setDefaultProfileId($pid=null, $podstran = null) {
+ # ce je seja, preverimo ali obstaja cene nardimo privzetega 1
+ if ($pid == -1) {
+ if (!(isset($_SESSION['statusProfile']))) {
+ $pid = null;
+ }
+ }
+ if ($podstran == null ) {
+ if ( isset($_POST['meta_akcija']) ) {
+ $_action = $_POST['meta_akcija'];
+ } else if (isset($_POST['podstran']) ) {
+ $_action = $_POST['podstran'];
+ } else if (isset($_POST['a']) ) {
+ $_action = $_POST['a'];
+ } else if (isset($_GET['a']) ) {
+ $_action = $_GET['a'];
+ } else {
+ $_action = 'data';
+ }
+ } else {
+ $_action = $podstran;
+ }
+
+ // Pri izvozu podatkov uporabimo isti profil kot pri ostalih podatkih
+ if ($_action == A_COLLECT_DATA_EXPORT) {
+ $_action = A_COLLECT_DATA;
+ }
+
+ # če smo v vpogledu pohandlammo posebej
+ if (($_action == A_COLLECT_DATA && $_GET['m'] == 'quick_edit') || $_POST['podstran'] == 'quick_edit') {
+ $_action = 'vpogled';
+ }
+
+ # če je $pid == null odvisno od akcije nastavimo privzet profil
+ # v podatkih = 1 v analizah = 2
+ if ($pid == null || (int)$pid==0) {
+ /* po novem je privzeto vedno le ustrezni statusi
+ if ($_action == 'data') {
+ $pid = 1;
+ } else {
+ $pid = 2;
+ }
+ */
+ $pid = 2;
+ }
+
+ # če lovimo samo ustrezne, potem ne morem o izbratz vsi statusi
+ $_sql_string = "SELECT collect_all_status FROM srv_data_files WHERE sid = '".self::$sid."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ list($collect_all_status) = mysqli_fetch_row($_sql_qry);
+ if ($pid == 1 && (int)$collect_all_status == 0) {
+ $pid = 2;
+ }
+
+ # ustrezni je lahko samo če so kakšni ustrezni zapisi v bazi ob pogoju da pa neustrezni obstajajao
+ if ($pid == 2 && self::$allValidCount == 0 && self::$allUserCount > 0) {
+ $pid = 1;
+ }
+
+ # če smo izbrali drug profil resetiramo še profil profilov na trenutne nastavitve
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', '0');
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_status_profile_'.$_action, $pid);
+
+
+ self::$currentProfileId = $pid;
+ return true;
+ }
+
+ static function getStatusAsArrayString() {
+
+ $mpds = self::getStatusArray(self::$currentProfileId);
+
+ $result = array();
+
+ if ($mpds) {
+ foreach ( self::$appropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1)
+ $result[$index] = $index;
+ }
+ foreach ( self::$unAppropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1)
+ $result[$index] = $index;
+ }
+ foreach ( self::$unKnownStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1)
+ $result[$index] = $index;
+ }
+ # lurker = 0 - obveezno ni lurker, lurker = 1 - obvezno je lurker, lurker = 2 - je ali ni lurker
+ if (isset($mpds['statuslurker']) && ((int)$mpds['statuslurker'] == 0 || (int)$mpds['statuslurker'] == 1)) {
+ $result['lurker'] = 'lurker';
+ }
+ # testni = 0 - obveezno ni testni, testni = 1 - obvezno je testni, testni = 2 - je ali ni testni
+ if (isset($mpds['statustestni']) && ((int)$mpds['statustestni'] == 0 || (int)$mpds['statustestni'] == 1)) {
+ $result['testni'] = 'testni';
+ }
+ # Uporabnost
+ if (isset($mpds['statusnonusable']) && $mpds['statusnonusable'] == 1) {
+ $result['nonusable'] = 1;
+ }
+ if (isset($mpds['statuspartusable']) && $mpds['statuspartusable'] == 1) {
+ $result['partusable'] = 1;
+ }
+ if (isset($mpds['statususable']) && $mpds['statususable'] == 1) {
+ $result['usable'] = 1;
+ }
+ }
+
+ return $result;
+ }
+ static public function getStatusAsQueryString($pid = null) {
+ if ($pid == null || (int)$pid <= 0 ) {
+ $mpds = self::getStatusArray(self::$currentProfileId);
+ } else {
+ $mpds = self::getStatusArray((int)$pid);
+ }
+ $result = '';
+
+ if ($mpds) {
+ $result .= ' AND last_status IN (';
+ foreach ( self::$appropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1) {
+ $result .= $prefix.$index;
+ $prefix = ', ';
+ }
+ }
+ foreach ( self::$unAppropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1) {
+ $result .= $prefix.$index;
+ $prefix = ', ';
+ }
+ }
+ foreach ( self::$unKnownStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1) {
+ $result .= $prefix.$index;
+ $prefix = ', ';
+
+ }
+ }
+ $result .= ')';
+ # lurker = 0 - obveezno ni lurker, lurker = 1 - obvezno je lurker, lurker = 2 - je ali ni lurker
+ if (isset($mpds['statuslurker']) && (int)$mpds['statuslurker'] == 1) {
+ $result .= ' AND lurker = 1';
+ } else if (isset($mpds['statuslurker']) && (int)$mpds['statuslurker'] == 0) {
+ $result .= ' AND lurker = 0';
+ } else {
+ # lurker ni pogoj
+ }
+ # testni = 0 - obveezno ni testni, testni = 1 - obvezno je testni, testni = 2 - je ali ni testni
+ if (isset($mpds['statustestni']) && (int)$mpds['statustestni'] == 1) {
+ $result .= ' AND (testdata = 1 OR testdata = 2)';
+ } else if (isset($mpds['statustestni']) && (int)$mpds['statustestni'] == 0) {
+ $result .= ' AND testdata = 0';
+ } else {
+ # testdata ni pogoj
+ }
+ }
+
+ return $result;
+ }
+ static function getStatusArray($pid=null) {
+ if ($pid == null) {
+ $pid = self::$currentProfileId;
+ }
+ $mpd = self::$profiles[$pid];
+ return $mpd;
+ }
+
+ static function getStatusAsAWKString($pid=null) {
+ if ($pid==null){
+ $pid=self::$currentProfileId;
+ }
+ $mpds = self::getStatusArray($pid);
+ $result = array();
+ if ($mpds) {
+ foreach ( self::$appropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1 ) {
+ $result[$index] = self::$_AWK_FILTER_TEXT[$index];
+ }
+ }
+ foreach ( self::$unAppropriateStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1 ) {
+ $result[$index] = self::$_AWK_FILTER_TEXT[$index];
+ }
+ }
+ foreach ( self::$unKnownStatus as $index) {
+ if (isset($mpds['status'.$index]) && $mpds['status'.$index] == 1 ) {
+ $result[$index] = self::$_AWK_FILTER_TEXT[$index];
+ }
+ }
+ }
+
+
+ if (count($result) > 0) {
+ $forReturn = STATUS_FIELD."~/".implode(STR_DLMT,$result)."/";
+ } else {
+ $forReturn = STATUS_FIELD."~/*/";
+ }
+
+ # ali dodamo tudi lurkerje
+ if (isset($mpds['statuslurker']) && (int)$mpds['statuslurker'] == 0 ) {
+ $forReturn = '('.$forReturn.')&&('.LURKER_FIELD.'==0)';
+ } else if (isset($mpds['statuslurker']) && $mpds['statuslurker'] == 1 ) {
+ $forReturn = '('.$forReturn.')&&('.LURKER_FIELD.'==1)';
+ } else {
+ $forReturn = '('.$forReturn.')';
+ }
+ return $forReturn;
+ }
+
+ static function getStatusTestAsAWKString($test_data_sequence) {
+ $forReturn = null;
+ $mpds = self::getStatusArray(self::$currentProfileId);
+ if ($mpds && (int)$test_data_sequence > 0) {
+ # ali dodamo tudi testne
+ if (isset($mpds['statustestni']) && (int)$mpds['statustestni'] == 0 ) {
+ $forReturn = '$'.$test_data_sequence.'==0';
+ } else if (isset($mpds['statustestni']) && $mpds['statustestni'] == 1 ) {
+ $forReturn = '$'.$test_data_sequence.'==1';
+ } else {
+ $forReturn = null;
+ }
+ }
+ return $forReturn;
+ }
+
+ static function getStatusUsableAsAWKString($usable_data_sequence) {
+
+ $forReturn = null;
+
+ $mpds = self::getStatusArray(self::$currentProfileId);
+ $result = array();
+ if ($mpds && (int)$usable_data_sequence > 0) {
+ if(isset($mpds['statusnonusable']) && (int)$mpds['statusnonusable'] == 1)
+ $result[] = '0';
+
+ if(isset($mpds['statuspartusable']) && $mpds['statuspartusable'] == 1)
+ $result[] = '1';
+
+ if(isset($mpds['statususable']) && $mpds['statususable'] == 1)
+ $result[] = '2';
+ }
+
+
+ if (count($result) > 0) {
+ $forReturn = '$'.$usable_data_sequence."~/".implode(STR_DLMT,$result)."/";
+ } else {
+ $forReturn = '$'.$usable_data_sequence."~/*/";
+ }
+
+
+ return $forReturn;
+ }
+
+ /** Shranimo v obstoječ profil
+ *
+ * @param unknown_type $pid
+ * @param unknown_type $name
+ * @param unknown_type $status
+ */
+ static function saveProfile($pid) {
+ global $lang;
+ $insert_id = 0;
+
+ $status = $_POST['status'];
+
+ if (isset($pid) && $pid != null && isset($status) && $status != null) {
+ if ($pid == 1) { # ce mamo privzet profil ga ne shranjujemo
+ return 1;
+ }
+ # ce imamo session pozenemo kot sejo
+ if ($pid == -1) {
+ $statusi = explode(',',$status);
+ $_SESSION['statusProfile'] = array('id'=>'-1','uid'=>0,'name'=>$lang['srv_temp_profile'],'system'=>0);
+ foreach (self::$allStatus as $_status) {
+ $_SESSION['statusProfile']['status'.$_status] = (in_array((string)$_status,$statusi) ? '1' : '0');
+ }
+ # lurker:
+ $_SESSION['statusProfile']['statuslurker'] = ''.(int)$_POST['lurker'];
+ # testni:
+ $_SESSION['statusProfile']['statustestni'] = ''.(int)$_POST['testni'];
+
+ # uporabnost:
+ $_SESSION['statusProfile']['statusnonusable'] = ''.(int)$_POST['nonusable'];
+ $_SESSION['statusProfile']['statuspartusable'] = ''.(int)$_POST['partusable'];
+ $_SESSION['statusProfile']['statususable'] = ''.(int)$_POST['usable'];
+
+ return -1;
+ }
+ # imamo podatke, updejtamo profil v bazi
+
+ $statusi = explode(',',$status);
+ if (count(self::$allStatus) > 0 ) {
+
+ $updateString = "UPDATE srv_status_profile SET ";
+ $prefix = '';
+ foreach (self::$allStatus as $_status) {
+ $updateString .= $prefix . 'status'.$_status. ' = '.(in_array((string)$_status,$statusi) ? '1' : '0');
+ $prefix =', ';
+ }
+ # lurker:
+ $updateString .= $prefix . 'statuslurker'. ' = '.''.(int)$_POST['lurker'];
+ # testni:
+ $updateString .= $prefix . 'statustestni'. ' = '.''.(int)$_POST['testni'];
+
+ # uporabnost:
+ $updateString .= $prefix . 'statusnonusable'. ' = '.''.(int)$_POST['nonusable'];
+ $updateString .= $prefix . 'statuspartusable'. ' = '.''.(int)$_POST['partusable'];
+ $updateString .= $prefix . 'statususable'. ' = '.''.(int)$_POST['usable'];
+
+ $updateString .= " WHERE id = '".$pid."'";
+
+ }
+ $queryUpdate = sisplet_query($updateString)
+ or die(mysqli_error($GLOBALS['connect_db']));
+
+ return $pid;
+ }
+
+ }
+
+ /** Shranimo kot nov profil
+ *
+ * @param unknown_type $pid
+ * @param unknown_type $name
+ * @param unknown_type $status
+ */
+ static function saveNewProfile($pid) {
+ $name = $_POST['name'];
+ $status = $_POST['status'];
+ $insert_id = 0;
+ if (isset($pid) && $pid != null && isset($name) && $name != null && isset($status) && $status != null) {
+ # imamo podatke, vstavimo nov profil v bazo
+ #id uid name system statusnull status0 status1 status2 status3 status4 status5 status6
+
+ $statusi = explode(',',$status);
+ $str_lbl = '';
+ $str_vle = '';
+ foreach ($statusi as $_status) {
+ $str_lbl .= ', status'.$_status;
+ $str_vle .= ', 1';
+ }
+ $insertString = "INSERT INTO srv_status_profile (uid,ank_id,name,system".$str_lbl.",statuslurker,statustestni,statusnonusable,statuspartusable,statususable)
+ VALUES ('".self::getGlobalUserId()."', '".self::$sid."', '".$name."', 0".$str_vle.",'".(int)$_POST['lurker']."','".(int)$_POST['testni']."','".(int)$_POST['nonusable']."','".(int)$_POST['partusable']."','".(int)$_POST['usable']."')";
+ $queryInsert = sisplet_query($insertString)
+ or die(mysqli_error($GLOBALS['connect_db']).$insertString);
+ $insert_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+ return $insert_id;
+ }
+
+ static function DeleteProfile($pid) {
+ if ($pid == -1) {
+ unset($_SESSION['statusProfile']);
+ }
+ # izbrišemo lahko samo nesistemske profile
+ if (self::$profiles[$pid]['system'] != 1) {
+ $sqlDelete = sisplet_query("DELETE FROM srv_status_profile WHERE id = '$pid' AND `system` != '1'");
+ }
+ self::setDefaultProfileId();
+
+# meta_akcija analysis
+ }
+
+ static function renameProfile($pid)
+ {
+ $name = trim($_POST['name']);
+
+ if (!empty($name))
+ {
+
+ if ($pid == -1)
+ { # preimenujemo v seji
+ $_SESSION['statusProfile']['name'] = $name;
+ }
+
+ # preimenujemo lahko samo nesistemske profile
+ if (self::$profiles[$pid]['system'] != 1)
+ {
+ $sqlRename = sisplet_query("UPDATE srv_status_profile SET name='$name' WHERE id = '$pid' AND `system` != '1'");
+ }
+ }
+ }
+
+ static function DisplayLink($hideAdvanced = true, $hideSeperator = false) {
+ global $lang;
+ // profili statusov
+ $statusProfiles = self :: getProfiles();
+ $izbranStatusProfile = self :: getCurentProfileId();
+
+ $css = ($izbranStatusProfile == SSP_DEFAULT_PROFILE ? ' gray' : '');
+ if ($hideAdvanced == false || $izbranStatusProfile != SSP_DEFAULT_PROFILE) {
+ if ($hideSeperator == false) {
+ echo '<li class="space">&nbsp;</li>';
+ }
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" onclick="show_status_profile();return false;" title="' . $lang['srv_statusi'] . '">' . $lang['srv_statusi'] . '</span>';
+ echo '</li>';
+
+ }
+ }
+
+ public static function FileGeneratingSetting($hideAdvanced = true) {
+ global $lang, $admin_type;
+
+ $_sql_string = "SELECT collect_all_status FROM srv_data_files WHERE sid = '".self::$sid."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ $_sql_row = mysqli_fetch_assoc($_sql_qry);
+
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ $css = ((int)$_sql_row['collect_all_status'] > 0 ? ' gray' : '');
+ echo '<span class="as_link'.$css.'" onclick="showColectDataSetting(); return false;" title="' . $lang['srv_collect_data_setting_note'] . '">' . $lang['srv_collect_data_setting_note'] . '</span>';
+ echo '</li>';
+
+ return;
+ }
+
+ static function showColectDataSetting() {
+ global $lang, $admin_type;
+
+ $_sql_string = "SELECT collect_all_status FROM srv_data_files WHERE sid = '".self::$sid."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ list($collect_all_status) = mysqli_fetch_row($_sql_qry);
+
+ $str_qry_cnt_user = "SELECT count(*) FROM srv_user AS u WHERE u.ank_id = '".self::$sid."'";
+ $_qry_cnt_user = sisplet_query($str_qry_cnt_user);
+ list($all_user_cnt) = mysqli_fetch_row($_qry_cnt_user);
+
+ #vsebino shranimo v buffer
+ $content = '';
+
+ # kadar imamo uporabnikov več kakor ONLY_VALID_LIMIT (5000) ne dovolimo nastaviti na vse statuse, zato dodamo obvestilo
+ # le admin lahko nastavi da generira tudi nad 5000 takrat nastavimo collect_all_status = 2
+ if ($all_user_cnt > ONLY_VALID_LIMIT && (int)$admin_type > 1)
+ {
+ $content .= '<span class="red strong">';
+ $content .= 'Anketa vsebuje več kakor '.ONLY_VALID_LIMIT.' respondentov, zato je dovoljen prikaz le ustreznih!';
+ $content .= '</span><br/><br/>';
+ $content .= '<span class="gray">'.$lang['srv_collect_data_setting_note'] . Help :: display('srv_collect_data_setting').'</span>';
+ $content .= '<label class="gray">';
+ $content .= '<input type="checkbox" id="collect_all_status" name="collect_all_status" '.((int)$collect_all_status > 0 ? '' : ' checked' ).' autocomplete="off" disabled="disabled">';
+ $content .= $lang['srv_collect_all_status_0'].'</label>';
+ }
+ else
+ {
+ $content .= '<span '.($admin_type <= 1 ? '' : ' class="gray"').'>'.$lang['srv_collect_data_setting_note'] . Help :: display('srv_collect_data_setting').'</span>';
+ $content .= '<label'.($admin_type <= 1 ? '' : ' class="gray"').'>';
+ $content .= '<input type="checkbox" id="collect_all_status" name="collect_all_status" '.((int)$collect_all_status > 0 ? '' : ' checked').' autocomplete="off"'.($admin_type <= 1 ? '' : ' disabled="disabled"').'>';
+ $content .= $lang['srv_collect_all_status_0'].'</label>';
+ }
+ $content .= '<br class="clr">';
+ $content .= '<br class="clr">';
+ $content .= '<span class="bold as_link" onclick="deleteSurveyDataFile(\''.$lang['srv_deleteSurveyDataFile_confirm'].'\');" title="'.$lang['srv_deleteSurveyDataFile_link'].'">'.$lang['srv_deleteSurveyDataFile_link'].'</span>';
+
+
+ $popUp = new PopUp();
+ $popUp->setId('div_data_file');
+ $popUp -> setHeaderText($lang['srv_file_settings']);
+
+ #dodamo vsebino
+ $popUp -> setContent($content);
+
+ #dodamo gumb izberi profil
+ $button = new PopUpButton($lang['srv_save_profile']);
+ $button -> setFloat('right')
+ -> setButtonColor('orange')
+ -> addAction('onClick','changeColectDataStatus(); return false;');
+ $popUp->addButton($button);
+
+ # dodamo gumb Prekliči
+ $button = new PopUpCancelButton();
+ $button -> setFloat('right');
+ $popUp->addButton($button);
+
+ echo $popUp;
+ }
+
+
+ static function savecollectdatasetting() {
+ global $admin_type;
+
+ // Najprej pobrišemo vse datoteke
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init(self::$sid);
+ $SDF->clearFiles();
+
+ $_collect_all_status = (isset($_POST['collect_all_status']) && (int)$_POST['collect_all_status'] == 1 ) ? '1' : '0';
+ if ($admin_type == '0' && $_collect_all_status == '1') {
+ $_collect_all_status = '2';
+ }
+
+ // Ce imamo socialna omrezja, zacasno vedno generiramo samo ustrezne
+ if(SurveyInfo::getInstance()->checkSurveyModule('social_network')){
+ $_collect_all_status = '0';
+ }
+
+ // če smo zbrali samo statuse ustrezno, popravimo profile da ni izbran profil vsi statusi
+ if ((int)$_collect_all_status == 0) {
+ // Ce smo izbrali drug profil resetiramo še profil profilov na trenutne nastavitve
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', '0');
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_status_profile_data', 2);
+ SurveyUserSetting :: getInstance()->saveSettings('default_status_profile_analysis', 2);
+ }
+ }
+
+ static function getProfilesValues()
+ {
+ $_sql_string = "SELECT collect_all_status FROM srv_data_files WHERE sid = '".self::$sid."'";
+ $_sql_qry = sisplet_query($_sql_string);
+ list($collect_all_status) = mysqli_fetch_row($_sql_qry);
+
+
+ return array('all_status'=>(int)$collect_all_status);
+ }
+
+ static function getActiveProfileUserCount()
+ {
+ $pid = self::$currentProfileId;
+ if ($pid == 1)
+ {
+ return (int)self::$allUserCount;
+ }
+ else if( $pid == 2)
+ {
+ return (int)self::$allValidCount;
+ }
+ else
+ {
+ # preštejemo userje
+ $str_all = "SELECT count(*) FROm srv_user WHERE ank_id='".self::$sid."' AND deleted='0' AND preview = '0' ".self::getStatusAsQueryString($pid);
+ $query_all = sisplet_query($str_all);
+ list($all) = mysqli_fetch_row($query_all);
+ return $all;
+ }
+ }
+
+ static function displayOnlyValidCheckbox(){
+ global $lang;
+
+ $pid = self::$currentProfileId;
+
+ $values = self::getProfilesValues();
+ $collect_all_status = $values['all_status'];
+
+ // če ni ustreznih uporabnikov je privzeto vsi
+ if (self::$allValidCount == 0) {
+
+ $pid = 1;
+ $disabledValid = ' disabled="disabled"';
+ $disabledGray = ' gray';
+ }
+ else if (self::$allValidCount > 0 && $collect_all_status == 0) {
+
+ /*if ( $pid == 1 ) {
+ #$pid = 2;
+ $pid = self::$survayDefaultUstrezni;
+ }*/
+
+ if((int)self::$allUserCount > 1000){
+ $disabledAll = ' disabled="disabled"';
+ $disabledAllGray = ' gray';
+ }
+ }
+
+ echo '<label class="middle'.$disabledAllGray.'">';
+ echo '<input type="radio" id="statusAllUnit" name="statusOnlyValid" value="1"'.($pid == 1?' checked="checked"':'').$disabledAll.' onchange="changeOnlyValidRadio();" autocomplete="off">';
+ echo $lang['srv_data_all_units'].'&nbsp;('.(int)self::$allUserCount.')';
+ echo '</label>';
+ echo '&nbsp;';
+
+ if (self::$survayDefaultUstrezni == 2) {
+ echo '<label class="middle'.$disabledGray .'">';
+ echo '<input type="radio" id="statusValidUnit" name="statusOnlyValid" value="2"'.($pid==2?' checked="checked"':'').$disabledValid.' onchange="changeOnlyValidRadio();" autocomplete="off">';
+ echo $lang['srv_data_valid_units'].'&nbsp;('.(int)self::$allValidCount.')';
+ echo '</label>';
+ }
+ else {
+ echo '<label class="middle'.$disabledGray .'">';
+ echo '<input type="radio" id="statusValidUnit" name="statusOnlyValid" value="3"'.($pid==3?' checked="checked"':'').$disabledValid.' onchange="changeOnlyValidRadio();" autocomplete="off">';
+ echo $lang['srv_data_finished_units'].'&nbsp;('.(int)self::$allValidCount.')';
+ }
+
+ echo '&nbsp;'.Help::display('srv_data_only_valid');
+ }
+
+ static function changeOnlyValidRadio() {
+ if (isset($_POST['checked']) && (int)$_POST['checked'] > 0) {
+ $dpid = (int)$_POST['checked'];
+ } else {
+ #$dpid = 2;
+ $dpid = (int)self::$survayDefaultUstrezni;
+ }
+ self::setDefaultProfileId($dpid);
+
+ }
+
+ /** preveri obstoj profila in vrne enak id če obstaja, če ne vrne id privzetega profila
+ *
+ * @param unknown_type $pid
+ * @return unknown
+ */
+ function checkProfileExist($pid)
+ {
+ if (isset(self::$profiles[$pid]))
+ {
+ return true;
+ }
+ return false;
+ }
+
+ static function getFiltersData(){
+ global $lang;
+ $pid = self::$currentProfileId;
+
+ $pid = 1;
+ $txt = $lang['srv_data_all_units'];
+ $userCount = (int)self::$allUserCount;
+
+ $pid =2;
+ $txt = $lang['srv_data_valid_units'];
+ $srv_data_status_units = (int)self::$allValidCount;
+
+ $pid = $pid;
+ $txt = $lang['srv_data_status_units'];
+
+ $str_all = "SELECT count(*) FROm srv_user WHERE ank_id='".self::$sid."' AND deleted='0' AND preview = '0' ".self::getStatusAsQueryString($pid);
+ $query_all = sisplet_query($str_all);
+ list($all) = mysqli_fetch_row($query_all);
+ $srv_data_status_units = $all;
+
+ }
+
+ public static function usabilitySettings(){
+
+ $customUsabilitySettings = false;
+
+ $mpds = self::getStatusArray(self::$currentProfileId);
+ if($mpds) {
+ if((isset($mpds['statusnonusable']) && $mpds['statusnonusable'] == 0)
+ || (isset($mpds['statuspartusable']) && $mpds['statuspartusable'] == 0)
+ || (isset($mpds['statususable']) && $mpds['statususable'] == 0)){
+
+ $customUsabilitySettings = true;
+ }
+ }
+
+ // Pogledamo ce je kjerkoli vklopljen profil z uporabnostjo (drugace pride do konflikta, ce je recimo vklopljen v analizah in izklopljen v podatkih)
+ $currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_status_profile_'.A_COLLECT_DATA);
+ if($currentProfileId != self::$currentProfileId){
+ $mpds = self::getStatusArray($currentProfileId);
+ if($mpds) {
+ if((isset($mpds['statusnonusable']) && $mpds['statusnonusable'] == 0)
+ || (isset($mpds['statuspartusable']) && $mpds['statuspartusable'] == 0)
+ || (isset($mpds['statususable']) && $mpds['statususable'] == 0)){
+
+ $customUsabilitySettings = true;
+ }
+ }
+ }
+ $currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_status_profile_'.A_ANALYSIS);
+ if($currentProfileId != self::$currentProfileId){
+ $mpds = self::getStatusArray($currentProfileId);
+ if($mpds) {
+ if((isset($mpds['statusnonusable']) && $mpds['statusnonusable'] == 0)
+ || (isset($mpds['statuspartusable']) && $mpds['statuspartusable'] == 0)
+ || (isset($mpds['statususable']) && $mpds['statususable'] == 0)){
+
+ $customUsabilitySettings = true;
+ }
+ }
+ }
+
+ return $customUsabilitySettings;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyTelephone.php b/admin/survey/classes/class.SurveyTelephone.php
new file mode 100644
index 0000000..390544e
--- /dev/null
+++ b/admin/survey/classes/class.SurveyTelephone.php
@@ -0,0 +1,3573 @@
+<?php
+/** nov Class ki skrbi za telefonsko anketo
+ * November 2012
+ *
+ *
+ * @author Gorazd_Veselic
+ */
+define('GROUP_PAGINATE', 4); # po kolko strani grupira pri paginaciji
+define('REC_ON_PAGE', 50); # kolko zapisov na stran pri urejanju respondentov
+define('REC_ON_SEND_PAGE', 20); # kolko zapisov na stran pri pošiljanju
+set_time_limit(2400); # 30 minut
+
+
+class SurveyTelephone {
+ private $sid; # id ankete
+ private $surveySettings; # zakeširamo nastavitve ankete
+
+ var $status_z = 5; // cakaj 5 minut, ce je Zaseden
+ var $status_n = 60; // cakaj 60 minut, ce Ni odgovora
+ var $status_d = 60; // cakaj 60 minut, ce se ga prelozi
+ var $max_calls = 10; // klici najvec 10-krat
+
+ var $call_order = 0; // vrstni red klicanja (0->nakljucno, 1->fiksno, 2->po abecedi padajoce, 3->po abecedi narascajoce)
+
+ var $isAnketar = false;
+ var $telephoneSprId = null;
+
+ private $inv_variables = array('email','password','ime','priimek','naziv','telefon','drugo');
+ private $inv_variables_link = array('email'=>'email','geslo'=>'password','ime'=>'firstname','priimek'=>'lastname','naziv'=>'salutation','telefon'=>'phone','drugo'=>'custom','last_status'=>'last_status','sent'=>'sent','responded'=>'responded','unsubscribed'=>'unsubscribed');
+
+
+ function __construct($sid) {
+
+ $this->sid = $sid;
+
+ SurveyInfo::SurveyInit($this->sid);
+ $this->surveySettings = SurveyInfo::getInstance()->getSurveyRow();
+ SurveyDataSettingProfiles :: Init($this->sid);
+
+ $sql = sisplet_query("SELECT * FROM srv_telephone_setting WHERE survey_id = '$this->sid'");
+ $row = mysqli_fetch_array($sql);
+ if (mysqli_num_rows($sql) > 0) {
+ $this->status_z = $row['status_z'];
+ $this->status_n = $row['status_n'];
+ $this->status_d = $row['status_d'];
+ $this->max_calls = $row['max_calls'];
+ $this->call_order = $row['call_order'];
+ }
+
+ $this->telephoneSprId = $this->get_spr_telefon_id();
+ # če spremenljivka telefon ne obstaja jo dodamo
+ if ((int)$this->telephoneSprId == 0) {
+ $sys = $this->addSystemVariables(array('inv_field_phone'));
+ $this->telephoneSprId = $sys['telefon'];
+ }
+
+ $d = new Dostop();
+ $this->isAnketar = $d->isAnketar();
+
+ # počistimo polja
+ if (isset($_POST['recipients_list']) && $_POST['recipients_list'] != null) {
+ $_POST['recipients_list'] = mysql_real_unescape_string($_POST['recipients_list']);
+ }
+ if (isset($_POST['fields']) && $_POST['fields'] != null) {
+ $_POST['fields'] = mysql_real_unescape_string($_POST['fields']);
+ }
+ }
+
+ function ajax() {
+ if (isset($_REQUEST['m']) && trim($_REQUEST['m']) != '') {
+ $this->action($_REQUEST['m']);
+ } else {
+ echo 'Ajax error!';
+ return 'Ajax error!';
+ }
+ }
+
+ function action($action) {
+
+ $NoNavi = false;
+ if (isset($_POST['noNavi']) && $_POST['noNavi'] == 'true') {
+ $NoNavi = true;
+ }
+ if ($NoNavi == false ) {
+ echo '<div id="inv_top_navi">';
+ $this->displayNavigation();
+ echo '</div>';
+ }
+
+ if ($action == 'recipients_lists') {
+ $this->recipientsLists();
+ } else if ($action == 'view_recipients') {
+ $this->viewRecipients();
+ } else if ($action == 'start_call') {
+ $this->startCall();
+ } else if ($action == 'call') {
+ $this->Call();
+ } else if ($action == 'settings') {
+ $this->settings();
+ } else if ($action == 'settings_save') {
+ $this->settingsSave();
+ $this->settings();
+ } else if ($action == 'calling_list') {
+ $this->callingList();
+ } else if ($action == 'setSortField') {
+ $this->setSortField();
+ } else if ($action == 'set_recipient_filter') {
+ $this->setRecipientFilter();
+ } else if ($action == 'addmark') {
+ $this->addMark();
+ } else if ($action == 'preveriStevilkeTimer') {
+ $this->preveriStevilkeTimer();
+ } else if ($action == 'setNextAction') {
+ $this->setNextAction();
+ } else if ($action == 'addRecipients') {
+ $result = $this->addRecipients();
+ # prikažemo napake
+ $invalid_recipiens_array = $this->displayRecipentsErrors($result);
+ $this->viewRecipients();
+ } else if ($action == 'setUserComment') {
+ $this->setUserComment();
+ } else if ($action == 'deleteProfile') {
+ $this->deleteProfile();
+ } else if ($action == 'editProfile') {
+ $this->editProfile();
+ } else if ($action == 'updateProfile') {
+ $this->updateProfile();
+ } else if ($action == 'getProfileName') {
+ $this->getProfileName();
+ } else if ($action == 'saveNewProfile') {
+ $this->saveNewProfile();
+ } else if ($action == 'saveProfile') {
+ $attributes = array();
+ if (isset($_POST['pid'])) {
+ $attributes['pid'] = $_POST['pid'];
+ }
+ if (isset($_POST['fields'])) {
+ $attributes['fields'] = str_replace('inv_field_','',implode(',',$_POST['fields']));
+ }
+ if (isset($_POST['recipients_list'])) {
+ $attributes['recipients'] = mysql_real_unescape_string($_POST['recipients_list']);
+ }
+ $this->saveProfile($attributes);
+ } else if ($action == 'goToUser') {
+ $this->goToUser();
+ } else if ($action == 'startSurvey') {
+ $this->startSurvey();
+ } else if ($action == 'showPopupAddMarker') {
+ $this->showPopupAddMarker();
+ } else if ($action == 'undoLastStatus') {
+ $this->undoLastStatus();
+ } else {
+ $this->showTelephoneStatus();
+ }
+ }
+
+ function showTelephoneStatus() {
+ global $lang, $site_url;
+
+ # polovimo statuse respondentov
+ # skreiramo query s katerim polovimo userje in pripadajoče sistemske podatke
+ $str_fields[] = " u.id AS usr_id";
+ $str_fields[] = " u.phone";
+ $str_fields[] = " u.last_status as status";
+
+ $str_joins[] = " srv_invitations_recipients as u";
+ $str_conditions[] = " u.ank_id = '$this->sid'";
+ $str_conditions[] = " u.deleted ='0'";
+ $str_conditions[] = " TRIM(u.phone) !=''";
+ # pripravimo ostale join in condtion stavke
+
+ # polovimo še iz baze klicev, vse trenutno začete klice
+ $str_fields[] = " scc.rec_id AS sccusr";
+ $str_joins[] = " LEFT OUTER JOIN (SELECT rec_id FROM srv_telephone_current) AS scc ON scc.rec_id = u.id";
+
+ # polovimo še iz baze klicev, zadnji statuse
+ $str_fields[] = " sch.status AS schstatus";
+ $str_fields[] = " sch.user_id AS user_id";
+ $str_fields[] = " sch.insert_time AS insert_time";
+ $str_joins[] = " LEFT OUTER JOIN (SELECT rsch.status, rsch.rec_id, rsch.user_id, rsch.insert_time FROM srv_telephone_history AS rsch INNER JOIN (SELECT MAX(id) as iid, rec_id FROM srv_telephone_history GROUP BY rec_id) as insch ON insch.iid = rsch.id) AS sch ON sch.rec_id = u.id";
+
+ # join za pregled po anketarjih
+ $str_fields[] = " usr.id AS usrid";
+ $str_joins[] = " LEFT OUTER JOIN (SELECT id FROM users) AS usr ON usr.id = sch.user_id";
+
+ # zložimo query
+ $str_qry_users = "SELECT ".implode(',', $str_fields)." FROM ".implode(' ',$str_joins)." WHERE ".implode(' AND',$str_conditions);
+
+ # sortiramo po statusih
+ $statusi = array();
+ $statusi_anketar = array();
+ $contacted = 0;
+
+ $qry = sisplet_query($str_qry_users);
+ if (!$qry) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($qry)) {
+
+ // Filter na datum
+ echo '<div id="phn_dashboard_date_filter">';
+
+ $date_from = '';
+ if(isset($_GET['date_from']))
+ $date_from = strtotime($_GET['date_from']);
+
+ $date_to = '';
+ if(isset($_GET['date_to']))
+ $date_to = strtotime($_GET['date_to']);
+
+ echo '<span class="spaceRight">'.$lang['s_from'].': <input type="text" name="tel_dash_dateFrom" id="tel_dash_dateFrom" value="'.($date_from == '' ? $date_from : date('d.m.Y', $date_from)).'" style="width:70px" ></span>';
+ echo '<span class="spaceLeft spaceRight">'.$lang['s_to'].': <input type="text" name="tel_dash_dateTo" id="tel_dash_dateTo" value="'.($date_to == '' ? $date_to : date('d.m.Y', $date_to)).'" style="width:70px" ></span>';
+ echo '<script type="text/javascript">';
+ echo '$(document).ready(function() {' .
+ ' $("#tel_dash_dateFrom, #tel_dash_dateTo").datepicker({
+ showOtherMonths: true,
+ selectOtherMonths: true,
+ changeMonth: true,
+ changeYear: true,
+ dateFormat: "dd.mm.yy",
+ showAnim: "slideDown",
+ showOn: "button",
+ buttonText: "",
+ onSelect: function(selected, evnt) {
+ tel_date_filter(); return false;
+ }
+ });' .
+ '});';
+ echo '</script>';
+ echo '<span class="spaceLeft"><a href="'.$site_url.'/admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_TELEPHONE.'&m=dashboard">'.$lang['srv_clear'].'</a></span>';
+
+ echo '</div>';
+
+
+ while ($row = mysqli_fetch_assoc($qry)) {
+
+ $date = strtotime($row['insert_time']);
+
+ // Filtriramo po datumu ce imamo nastavljen filter
+ if( ($date == null && $date_from == null && $date_to == null)
+ || ($date != null && ($date_from == null || $date >= $date_from) && ($date_to == null || $date <= $date_to)) ){
+
+ $statusi[$row['schstatus']] ++;
+ $statusi_anketar[$row['usrid']] ++;
+
+ if($row['schstatus'] != '')
+ $contacted++;
+ }
+
+ $statusi_all ++;
+ }
+
+ //$contacted = (int)($statusi_all - $statusi['']);
+
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_telephone_dashboard_legend'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<p>';
+ echo '<table class="inv_dashboard_table">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_telephone_dashboard_all_respondents'].'</th>';
+ echo '<th>'.(int)$statusi_all.'</th>';
+ echo '<th>-</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+ # poslano enotam
+ echo '<tr>';
+ echo '<th>'.$lang['srv_telephone_dashboard_all_contacted'].'</th>';
+ echo '<th>'.(int)$contacted .'</th>';
+ echo '<th>'.((int)$contacted > 0 ? '100%' : '0%').'</th>';
+ echo '<th>'.Common::formatNumber(( (int)$contacted > 0 ? (int)$contacted*100/(int)$statusi_all : 0),0,'','%').'</th>';
+ echo '</tr>';
+ foreach (array('R','Z','N','T','P','A','U','D') AS $st) {
+ if ((int)$statusi[$st] > 0) {
+ if ($st == 'U') {
+ $css=' class="red"';
+ } else {
+ $css='';
+ }
+ echo '<tr>';
+ echo '<td>'.$lang['srv_telephone_status_'.$st].'</td>';
+ echo '<td'.$css.'>'.(int)$statusi[$st].'</td>';
+ echo '<td'.$css.'>'.Common::formatNumber(((int)$statusi[$st] > 0 ? (int)$statusi[$st]*100/(int)$contacted : 0),0,'','%').'</td>';
+ echo '<td'.$css.'>'.Common::formatNumber(((int)$statusi[$st] > 0 ? (int)$statusi[$st]*100/(int)$statusi_all : 0),0,'','%').'</td>';
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+ echo '</p>';
+ echo '</div>';
+ echo '</fieldset>';
+
+ $recipients_by_status = array();
+ $recipients_by_status['contacted'] = $contacted;
+
+ $sql_subStr = "SELECT sir.id, sir.last_status, su.lurker, sth.insert_time FROM srv_invitations_recipients AS sir"
+ ." INNER join srv_user AS su ON sir.id = su.inv_res_id"
+ ." RIGHT JOIN srv_telephone_history as sth ON sth.rec_id = su.inv_res_id"
+ //." WHERE sth.survey_id='$this->sid' AND sth.status IN ('U','A') AND sir.ank_id='$this->sid' AND sir.deleted ='0' AND su.ank_id='$this->sid' GROUP BY sth.rec_id";
+ ." WHERE sth.survey_id='$this->sid' AND sth.status IN ('U','A') AND sth.id=(SELECT MAX(id) FROM srv_telephone_history WHERE survey_id='$this->sid' AND status IN ('U','A') AND rec_id=sth.rec_id AND rec_id=sth.rec_id) AND sir.ank_id='$this->sid' AND sir.deleted ='0' AND su.ank_id='$this->sid' GROUP BY sth.rec_id";
+ $sql_subQry = sisplet_query($sql_subStr);
+
+ if (mysqli_num_rows($sql_subQry) > 0) {
+ while (list($uid,$last_status,$lurker,$insert_time) = mysqli_fetch_row($sql_subQry)) {
+
+ $date = strtotime($insert_time);
+
+ // Filtriramo po datumu ce imamo nastavljen filter
+ if( ($date == null && $date_from == null && $date_to == null)
+ || ($date != null && ($date_from == null || $date >= $date_from) && ($date_to == null || $date <= $date_to)) ){
+
+ switch ((int)$last_status) {
+ # 2 - E-pošta - napaka
+ case -2:
+ $recipients_by_status['not_send'] ++;
+ $recipients_by_status['error'] ++;
+ break;
+ # 0 - E-pošta - ni poslana
+ case 0:
+ $recipients_by_status['not_send'] ++;
+ break;
+ # 1 - E-pošta - neodgovor
+ case 1:
+ $recipients_by_status['send'] ++;
+ break;
+
+ # 3 - klik na nagovor
+ case 3:
+ $recipients_by_status['send'] ++;
+ $recipients_by_status['clicked'] ++;
+ break;
+ # 4 - klik na anketo
+ case 4:
+ $recipients_by_status['send'] ++;
+ $recipients_by_status['clicked'] ++;
+ break;
+ # 5 - delno prazna
+ case 5:
+ $recipients_by_status['send'] ++;
+ #$recipients_by_status['clicked'] ++;
+ if ((int)$lurker == 1) {
+ # če je lurker
+ $recipients_by_status['clicked'] ++;
+ } else {
+ $recipients_by_status['finished'] ++;
+ }
+ break;
+ # 6 - končana
+ case 6:
+ $recipients_by_status['send'] ++;
+ if ((int)$lurker == 1) {
+ # če je lurker
+ $recipients_by_status['clicked'] ++;
+ } else {
+ $recipients_by_status['finished'] ++;
+ }
+ break;
+ # null - neznan
+ default:
+ $recipients_by_status['unknown'] ++;
+ break;
+ }
+ }
+ }
+ # var_dump($recipients_by_status);
+
+ echo '<br/>';
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_telephone_dashboard_legend_finished'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<table class="inv_dashboard_table">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_telephone_dashboard_all_contacted'].'</th>';
+ echo '<th>'.(int)$recipients_by_status['contacted'].'</th>';
+ echo '<th>-</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+ #popslano enotam
+ echo '<tr>';
+ echo '<th>'.$lang['srv_telephone_dashboard_all_started'].'</th>';
+ echo '<th>'.(int)$recipients_by_status['send'].'</th>';
+ echo '<th>'.((int)$recipients_by_status['send'] > 0 ? '100%' : '0%').'</th>';
+ echo '<th>'.Common::formatNumberSimple(((int)$recipients_by_status['contacted'] > 0 ? (int)$recipients_by_status['send']*100/(int)$recipients_by_status['contacted'] : 0),0,'%').'</th>';
+ echo '</tr>';
+
+ #neodgovori
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unanswered'].'</td>';
+ $unanswered = ((int)$recipients_by_status['send']-(int)$recipients_by_status['clicked']-(int)$recipients_by_status['finished']);
+ echo '<td>'.$unanswered.'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$recipients_by_status['send'] > 0 ? $unanswered*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$recipients_by_status['contacted'] > 0 ? $unanswered*100/(int)$recipients_by_status['contacted'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_clicked'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['clicked'].'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$recipients_by_status['contacted'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['contacted'] : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ #če se slučajno pojavijo kaki neznani statusi
+ if ((int)$recipients_by_status['unknown'] > 0) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unknown'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['unknown'].'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$recipients_by_status['contacted'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['contacted'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_finished'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['finished'].'</td>';
+ echo '<td class="red">'.Common::formatNumberSimple(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td class="">'.Common::formatNumberSimple(((int)$recipients_by_status['contacted'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['contacted'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '<br>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+
+
+ // Sumarni pregled po anketarjih
+ echo '<br/>';
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_telephone_dashboard_legend_anketar'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<table class="inv_dashboard_table">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_telephone_dashboard_all_contacted'].'</th>';
+ echo '<th>'.(int)$contacted .'</th>';
+ echo '<th>'.((int)$contacted > 0 ? '100%' : '0%').'</th>';
+ echo '</tr>';
+
+ # Loop cez vse anketarje
+ $d = new Dostop();
+ $all_users = $d->getUsersDostop();
+ foreach($all_users as $user){
+ echo '<tr>';
+ echo '<td>'.$user['name'].' '.$user['surname'].' <span class="gray">('.$user['email'].')</span></td>';
+ echo '<td>'.(int)$statusi_anketar[$user['id']].'</td>';
+ echo '<td>'.Common::formatNumberSimple(((int)$statusi_anketar[$user['id']] > 0 ? (int)$statusi_anketar[$user['id']]*100/(int)$recipients_by_status['contacted'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ echo '<br>';
+ echo '</div>';
+ echo '</fieldset>';
+
+ } else {
+ echo '<p>'.$lang['srv_telephone_no_respondents'].'</p>';
+ }
+ }
+
+ function recipientsLists() {
+
+ if (isset($_POST['pid'])) {
+ $pid = (int)$_POST['pid'];
+ } else {
+ $pid = -1;
+ }
+
+ list($recipients_list,$fields) = $this->getRecipientsProfile($pid);
+ $this->addRecipientsView($fields,$recipients_list);
+ }
+
+ function getRecipientsProfile($pid) {
+ global $lang, $global_user_id;
+
+ $fields = array();
+ $recipients_list=null;
+ session_start();
+ # če ne obstaja začasen seznam ga naredimo (praznega) pid=-1
+ if (!isset($_SESSION['phn_rec_profile'][$this->sid])) {
+ $_SESSION['phn_rec_profile'][$this->sid] = array(
+ 'pid'=>-1,
+ 'name'=>$lang['srv_invitation_new_templist'],
+ 'fields'=>'phone',
+ 'respondents'=>'',
+ 'comment'=>$lang['srv_invitation_new_templist']);
+ }
+
+ #polovimo emaile in poljaiz seznama
+ if ( $pid > 0) {
+ # če imamo pid in je večji kot nič polovimo podatke iz tabele
+ $sql_string = "SELECT fields,respondents FROM srv_invitations_recipients_profiles WHERE pid = '".$pid."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ if (trim($sql_row['respondents']) != '') {
+ $recipients_list = explode("\n",trim($sql_row['respondents']));
+ }
+ $_fields = explode(",",$sql_row['fields']);
+ if (count($_fields) > 0) {
+ foreach ($_fields AS $field) {
+ $fields[] = 'inv_field_'.$field;
+ }
+ }
+ } else if ($pid == -1) {
+ # začasen profil iz seje
+ $_fields = explode(",",$_SESSION['phn_rec_profile'][$this->sid]['fields']);
+ if (count($_fields) > 0) {
+ foreach ($_fields AS $field) {
+ $fields[] = 'inv_field_'.$field;
+ }
+ }
+ if (trim($_SESSION['phn_rec_profile'][$this->sid]['respondents']) != '') {
+ $recipients_list = explode("\n",trim($_SESSION['phn_rec_profile'][$this->sid]['respondents']));
+ }
+
+ } else {
+ $recipients_list[] = '';
+ $fields[]= 'inv_field_phone';
+ }
+
+ return array($recipients_list,$fields);
+
+ }
+
+ function addRecipientsView( $fields = array(), $recipients_list=null) {
+ #prikažemo vmesnik za dodajanje respondentov
+ global $lang;
+ echo '<h2>'.$lang['srv_inv_add_recipients_heading'].'</h2>';
+
+ echo '<div id="inv_import">';
+ $this->displayAddRecipientsView($fields, $recipients_list);
+ echo '</div>'; # id="inv_import"
+ }
+
+ function displayAddRecipientsView( $fields = array(), $recipients_list=null) {
+ global $lang, $site_path, $site_url;
+ $field_list = array();
+ # odvisno od tipa sporočil prikažemo različna polja
+ # Personalizirano e-poštno vabilo
+
+ $default_fields = array(
+ 'inv_field_phone' => count($fields) == 0 ? 1 : 0,
+ 'inv_field_firstname' => 0,
+ 'inv_field_lastname' => 0,
+ 'inv_field_email' => 0,
+ 'inv_field_password' => 0,
+ 'inv_field_salutation' => 0,
+ 'inv_field_custom' => 0,
+ );
+
+ # skreiramo nov vrstni red polj
+ if (count($fields) > 0) {
+ foreach ($fields as $key=>$field) {
+ $field_list[$field] = 1;
+ if (isset($default_fields[$field])) {
+ unset($default_fields[$field]);
+ }
+ }
+ }
+
+ if (count($default_fields) > 0) {
+ foreach ($default_fields as $key =>$field) {
+ $field_list[$key] = $field;
+ unset($default_fields[$key]);
+ }
+ }
+ $import_type = isset($_POST['import_type']) ? (int)$_POST['import_type'] : 2;
+ session_start();
+ # profili respondentov
+ echo '<div id="inv_recipients_profiles_holder">';
+
+ echo '<span>'.$lang['srv_inv_recipient_select_list'].'</span><br/>';
+
+ $this->listRecipientsProfiles();
+ echo '</div>'; # id=inv_recipients_profiles_holder
+
+ echo '<div id="inv_import_list_container">';
+
+ $sqlSysMapping = sisplet_query("SELECT * FROM srv_invitations_mapping WHERE sid = '$this->sid'");
+ if (mysqli_num_rows($sqlSysMapping) > 0) {
+ $sysUserToAddQuery = sisplet_query("SELECT count(*) FROM srv_user where ank_id='".$this->sid."' AND inv_res_id IS NULL AND deleted='0'");
+ list($sysUserToAdd) = mysqli_fetch_row($sysUserToAddQuery);
+ }
+
+ echo '<span><input name="inv_import_type" id="inv_import_type2" type="radio" value="2" checked="checked" autocomplete="off"><label for="inv_import_type2">'.$lang['srv_inv_recipiens_from_list'].'</label></span>';
+ /*echo '<span><input name="inv_import_type" id="inv_import_type2" type="radio" value="2" onclick="inv_change_import_type();"'.($import_type == 2 ? ' checked="checked"' : '').' autocomplete="off"><label for="inv_import_type2">'.$lang['srv_inv_recipiens_from_list'].'</label></span>';
+ echo '<span><input name="inv_import_type" id="inv_import_type1" type="radio" value="1" onclick="inv_change_import_type();"'.($import_type == 1 ? ' checked="checked"' : '').' autocomplete="off"><label for="inv_import_type1">'.$lang['srv_inv_recipiens_from_file'].'</label></span>';
+ echo '<span><input name="inv_import_type" id="inv_import_type3" type="radio" value="3" onclick="inv_change_import_type();"'.($import_type == 3 ? ' checked="checked"' : '').' autocomplete="off"><label for="inv_import_type3">'.$lang['srv_inv_recipiens_from_system']
+ .($sysUserToAdd > 0 ? ' ('.$sysUserToAdd.')' : '').'</label></span>';
+ echo Help::display('inv_recipiens_from_system');*/
+
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+ if ($import_type == 3) {
+ #$this->displayFromSystemVariables();
+ $this->createSystemVariablesMapping();
+ } else {
+
+ # sporočilo za personalizirana e-vabila in respondente iz baze
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_field_note'].'</span>';
+ echo '<br >';
+ echo '<div id="inv_field_container">';
+ echo '<ul class="connectedSortable">';
+ $field_lang = array();
+ if (count($field_list ) > 0) {
+ foreach ($field_list AS $field => $checked) {
+ # ali je polje izbrano ( če imamo personalizirano e-vabilo, moramo nujno imeti polje email
+ $is_selected = ($checked == 1 ) ? true : false;
+
+ # če je polje obkljukano
+ $css = $is_selected ? ' class="inv_field_enabled"' : '';
+ $label_for = ' for="'.$field.'_chk"';
+
+ echo '<li id="'.$field.'"'.$css.'>';
+ echo '<input id="'.$field.'_chk" type="checkbox" class="inv_checkbox' . $hidden_checkbox . '"'.($is_selected == true ? ' checked="checked"' : '').'>';
+ echo '<label'.$label_for.'>'.$lang['srv_'.$field].'</label>';
+ echo '</li>';
+ if ($is_selected == 1) {
+ $field_lang[] = $lang['srv_'.$field];
+ }
+ }
+ }
+ echo '</ul>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ echo '<script type="text/javascript">';
+ echo "$('ul.connectedSortable').sortable({update : function () { refreshFieldsList(); }, forcePlaceholderSize: 'true',tolerance: 'pointer',placeholder: 'inv_field_placeholder',});";
+ echo '</script>';
+
+ # iz seznama
+ echo '<div id="inv_import_list"'.($import_type != 1 ? '' : ' class="hidden"').'>' ;
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_email_note'];
+ echo '<br class="clr" /><span class="inv_sample" >';
+ echo $lang['srv_inv_recipiens_sample'].'&nbsp;</span><span class="inv_sample">';
+ echo $lang['srv_telephone_add_sample'];
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo '</span>';
+ echo '<br class="clr" />'.$lang['srv_inv_recipiens_fields'].' <span id="inv_field_list" class="inv_type_0">';
+ echo implode(',',$field_lang);
+ echo '</span>';
+ echo '<br class="clr" /><textarea id="inv_recipients_list" cols="50" rows="9" name="inv_recipients_list">';
+ if (is_array($recipients_list) && count($recipients_list) > 0 ) {
+ echo implode("\n",$recipients_list);
+ }
+ echo '</textarea>';
+ echo '<br class="clr"/>';
+
+ #podatki o profilu
+ echo '<br class="clr"/>';
+ $ppid = isset($_POST['pid']) ? (int)$_POST['pid'] : -1;
+
+ echo '<span class="floatLeft">';
+ if ((int)$ppid > 0) {
+ # polovimo podatke profila
+ $sql_string = "SELECT rp.*, u.name, u.surname FROM srv_invitations_recipients_profiles AS rp LEFT JOIN users AS u ON rp.uid = u.id WHERE rp.pid = '".(int)$ppid."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ $avtor = array();
+ if (trim($sql_row['name'])) {
+ $avtor[] = trim ($sql_row['name']);
+ }
+ if (trim($sql_row['surname'])) {
+ $avtor[] = trim ($sql_row['surname']);
+ }
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray">'.$lang['srv_inv_recipiens_list_created_by'].implode(' ',$avtor).'</div>';
+ }
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray" title="'.date("d.m.Y H:i:s",strtotime($sql_row['insert_time'])).'">'.$lang['srv_inv_recipiens_list_created_day'].date("d.m.Y",strtotime($sql_row['insert_time'])).'</div>';
+ }
+ echo '<div class="gray" title="'.strip_tags($sql_row['comment']).'" style="max-width:202px;">'.$lang['srv_inv_recipiens_list_comment'].trim (strip_tags($sql_row['comment'])).'</div>';
+
+ } else {
+ echo '<div class="gray">'.$lang['srv_inv_recipiens_temporary_list'].'</div>';
+ }
+ echo '</span>';
+
+ # če že imamo prejemnike v bazi ponudimo gumb naprej
+ echo '<span class="buttonwrapper floatRight spaceLeft" ><a class="ovalbutton ovalbutton_orange" href="#" onclick="phn_add_recipients(); return false;"><span>'.$lang['srv_telephone_add'].'</span></a></span>';
+ # če je začasen avtor, ne ponudimo shrani
+ if ((int)$ppid != 0) {
+ echo '<span class="buttonwrapper floatRight spaceLeft" ><a class="ovalbutton ovalbutton_gray" href="#" onclick="phnSaveProfile(); return false;"><span>'.$lang['srv_telephone_save'].'</span></a></span>';
+ }
+ echo '<span class="buttonwrapper floatRight spaceLeft" ><a class="ovalbutton ovalbutton_gray" href="#" onclick="phnGetNewProfileName(); return false;"><span>'.$lang['srv_telephone_save_new'].'</span></a></span>';
+
+ echo '</div>'; # id=inv_import_list
+
+ }
+ echo '</div>'; # id=inv_import_list_container
+
+ echo '<br class="clr"/>';
+ }
+
+ function listRecipientsProfiles() {
+ global $lang, $global_user_id;
+ $ppid = isset($_POST['pid']) ? (int)$_POST['pid'] : -1;
+ # polovimo vse profile
+ $array_profiles = array();
+ session_start();
+ # če obstaja seznam iz seje za to anketo
+ if (isset($_SESSION['phn_rec_profile'][$this->sid])) {
+ $array_profiles[-1] = array('name' => $_SESSION['phn_rec_profile'][$this->sid]['name']);
+ }
+ $array_profiles[0] = array('name' => $lang['srv_temp_profile_author']);
+ $onlyThisSurvey = (isset($_SESSION['inv_rec_only_this_survey']) && $_SESSION['inv_rec_only_this_survey'] == false) ? 0 : 1;
+ if ($onlyThisSurvey == 0) {
+ #id-ji profilov do katerih lahko dostopamo
+ $sql_string = "SELECT name, pid FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."') OR pid IN (SELECT DISTINCT pid FROM srv_invitations_recipients_profiles_access where uid = '$global_user_id')";
+ $sql_query = sisplet_query($sql_string);
+ } else {
+ # 1
+ $sql_string = "SELECT name, pid FROM srv_invitations_recipients_profiles WHERE from_survey = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+ }
+
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $array_profiles[$sql_row['pid']] = array('name' => $sql_row['name']);
+ }
+ echo '<div id="phn_import_list_profiles">';
+
+ echo '<ol>';
+ foreach ($array_profiles AS $_pid => $profile) {
+ echo '<li pid="'.$_pid.'" class="'.($ppid === $_pid ? 'active' : '').'"'
+ .' onclick="showPhnList(\''.$_pid.'\');" >';
+ echo $profile['name'];
+ echo '</li>';
+ }
+ echo '</ol>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ if ((int)$ppid > 0) {
+ # polovimo še ostale porfile
+ $sql_string = "SELECT pid FROM srv_invitations_recipients_profiles WHERE pid='".(int)$ppid."' AND from_survey ='".$this->sid."' ";
+ $sql_query = sisplet_query($sql_string);
+
+ if (mysqli_num_rows($sql_query) > 0) {
+ # če je iz iste ankete, potem lahko urejamo
+ echo '<a href="#" onclick="phnDeleteProfile();" title="'.$lang['srv_inv_recipients_delete_profile'].'">'.$lang['srv_inv_recipients_delete_profile'].'</a><br/>';
+ echo '<a href="#" onclick="phnEditProfile();" title="'.$lang['srv_inv_recipients_edit_profile'].'">'.$lang['srv_inv_recipients_edit_profile'].'</a><br/>';
+ echo '<br class="clr"/>';
+ }
+ }
+
+ echo '<br class="clr" />';
+ }
+
+ function displayNavigation() {
+ global $lang;
+
+ # če je anketar ne vidi navigacije
+ if ($this->isAnketar == true) {
+
+ }
+ else {
+
+ if (!isset($_POST['noNavi']) || (isset($_POST['noNavi']) && $_POST['noNavi'] != 'true')) {
+ $_sub_action = $_GET['m'];
+
+ $active_step[] = array(1=>'',2=>'',3=>'',4=>'',5=>'',6=>'',7=>'');
+
+ switch ($_sub_action) {
+ case 'phn_status':
+ $active_step['1'] = ' active';
+ break;
+
+ case 'recipients_lists':
+ $active_step['2'] = ' active';
+ break;
+
+ case 'view_recipients':
+ case 'addRecipients':
+ $active_step['3'] = ' active';
+ break;
+
+ case 'goToUser':
+ case 'start_call':
+ case 'call':
+ $active_step['4'] = ' active';
+ break;
+
+ case 'settings':
+ case 'settings_save':
+ $active_step['5'] = ' active';
+ break;
+
+ case 'calling_list':
+ $active_step['6'] = ' active';
+ break;
+
+ default:
+ $active_step['1'] = ' active';
+ break;
+ }
+
+ $spaceChar = '&nbsp;';
+
+ echo '<div class="phn_step_nav'.$active_step[1].'">';
+ echo '<div class="phn_step">';
+ echo '<a href="'.$this->addUrl('dashboard').'">';
+ echo '<span class="label">'.$lang['srv_telephone_navi_dashboard'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+ if ($this->telephoneSprId) {
+ #space
+ echo '<div class="phn_space">&nbsp;</div>';
+ $class_yellow = ' yellow';
+ echo '<div class="phn_step_nav yellow">';
+
+ #navigacija
+ echo '<div class="phn_step'.$class_yellow.$active_step[2].'">';
+ echo '<a href="'.$this->addUrl('recipients_lists').'">';
+ echo '<span class="circle">1</span>';
+ echo '<span class="label">'.$lang['srv_telephone_navi_add'].'</span>';
+ echo '</a>';
+ echo '</div>';
+
+ echo '<div class="phn_step_space'.$class_yellow.'">'.$spaceChar.'</div>';
+
+ echo '<div class="phn_step'.$class_yellow.$active_step[3].'">';
+ echo '<a href="'.$this->addUrl('view_recipients').'">';
+ echo '<span class="circle">2</span>';
+ echo '<span class="label">'.$lang['srv_telephone_navi_view'].'</span>';
+ if ($disabled == false) {
+ echo '</a>';
+ }
+ echo '</div>';
+
+ echo '<div class="phn_step_space'.$class_yellow.$css_disabled.'">'.$spaceChar.'</div>';
+
+ echo '<div class="phn_step'.$class_yellow.$css_disabled.$active_step[4].'">';
+ echo '<a href="'.$this->addUrl('start_call').'">';
+ echo '<span class="circle">3</span>';
+ echo '<span class="label" >'.$lang['srv_telephone_navi_start_call'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+ #space
+ echo '<div class="phn_space">&nbsp;</div>';
+
+ // Cakalni seznam
+ echo '<div class="phn_step_nav'.$active_step[6].'" style="margin-right:20px; width:90px;">';
+ echo '<div class="phn_step">';
+ echo '<a href="'.$this->addUrl('calling_list').'">';
+ echo '<span class="label">'.$lang['srv_telephone_navi_waiting_list'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+ }
+
+ // Nastavitve
+ echo '<div class="phn_step_nav'.$active_step[5].'">';
+ echo '<div class="phn_step">';
+ echo '<a href="'.$this->addUrl('settings').'">';
+ echo '<span class="label">'.$lang['srv_telephone_navi_settings'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+ echo '<br class="clr" />';
+ echo '<br class="clr" />';
+ }
+ }
+ }
+
+ // Seznam stevilk ki so v vrsti za klicanje
+ function callingList() {
+ global $lang;
+ global $site_url;
+
+ // Najprej cakalna vrsta (stevilke ki se bodo prikazale kasneje)
+ $this->waitingList();
+
+ echo '<br /><br />';
+
+ // Se vrsta stevilk ki se trenutno klicejo
+ echo '<h2>'.$lang['srv_telephone_navi_calling_list'].'</h2>';
+
+ // Dobimo seznam vseh ki se niso bili klicani
+ $toCall = $this->getAllNumbers();
+
+
+ if (count($toCall) > 0) {
+
+ # Katera polja prikazujemo v seznamu prejemnikov
+ $fields = array();
+ $default_fields = array(
+ 'phone' => 1,
+ 'email' => 0,
+ 'password' => 0,
+ 'firstname' => 0,
+ 'lastname' => 0,
+ 'salutation' => 0,
+ 'custom' => 0,
+ );
+
+ $sql_select_fields = array();
+ $fields['ps_icon'] = 1;
+ $fields['schstatus'] = 1;
+
+ $sql_select_fields[] = " i.last_status as ps_icon";
+ $sql_select_fields[] = " i.last_status as last_status";
+ $sql_select_fields[] = " scc.rec_id AS sccusr";
+ $sql_select_fields[] = " scs.call_time AS schedule_call_time";
+ # polovimo še iz baze klicev, zadnji statuse
+ $sql_select_fields[] = " sch.status AS schstatus";
+ $sql_select_fields[] = " scm.comment AS comment";
+
+ foreach($toCall as $usr_id => $phone){
+
+ #koliko zapisov bi morali prikazovati
+ $sql_query_filterd_all = sisplet_query("SELECT i.* FROM srv_invitations_recipients AS i WHERE i.ank_id='".$this->sid."' AND i.id='".$usr_id."'");
+
+ $sql_row = mysqli_fetch_assoc($sql_query_filterd_all);
+ foreach ($default_fields AS $key => $value) {
+ # če polje še ni dodano in če ni prazno, ga dodamo
+ if ($fields[$key] == 0 && isset($sql_row[$key]) && trim($sql_row[$key]) != '') {
+ $fields[$key] = 1;
+ $sql_select_fields[] = 'i.'.$key;
+ }
+ }
+ }
+
+ $fields['schedule_call_time'] = 1;
+ $fields['last_status'] = 1;
+ $fields['comment'] = 1;
+ $fields['date_inserted'] = 1;
+ $fields['usr_email'] = 1;
+ $fields['list_id'] = 1;
+
+ # dodamo še ostala polja
+ $sql_select_fields[] = 'i.last_status';
+ $sql_select_fields[] = 'i.date_inserted';
+ $sql_select_fields[] = 'i.list_id';
+ $sql_select_fields[] = 'usrs.email AS usr_email';
+
+ #dodamo paginacijo in poiščemo zapise
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $limit_start = ($page * REC_ON_PAGE) - REC_ON_PAGE;
+
+
+ # polovimo sezname
+ $lids = array();
+ $sql_string_users = "SELECT i.list_id FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND TRIM(phone) !='' GROUP BY i.list_id ORDER BY i.id LIMIT $limit_start,".REC_ON_PAGE.'';
+ $sql_query_users = sisplet_query($sql_string_users);
+ while ($row_users = mysqli_fetch_assoc($sql_query_users)) {
+ $lids[] = $row_users['list_id'];
+ }
+
+ #seznami
+ $lists = array();
+ $lists['-1'] = array('name'=>$lang['srv_invitation_new_templist']);
+ $lists['0'] = array('name'=>$lang['srv_invitation_new_templist_author']);
+ if (count($lids) > 0 ) {
+ $sql_string_lists = "SELECT name, pid from srv_invitations_recipients_profiles WHERE pid IN(".implode(',',$lids).") ";
+ $sql_query_lists = sisplet_query($sql_string_lists);
+ while ($row_lists = mysqli_fetch_assoc($sql_query_lists)) {
+ $lists[$row_lists['pid']] = array('name'=>$row_lists['name']);
+ }
+ }
+
+ // Stevilo stevilk v vrsti
+ echo '<div id="srv_invitation_note">'.$lang['srv_telephone_calling_list_count'].': '.count($toCall).'</div>';
+
+ echo '<br class="clr"/>';
+
+ // Izrisemo tabelo
+ echo '<div style="display:inline-block;">';
+ echo '<table id="tbl_recipients_list" class="phone">';
+
+ // Header tabele
+ echo '<tr>';
+ echo '<th class="tbl_icon">&nbsp;</th>';
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ if ($fkey == 'sent' || $fkey == 'responded' || $fkey == 'unsubscribed'){
+ #echo '<th class="anl_ac tbl_icon_'.$fkey.' inv_'.$fkey.'_1" title="'.$lang['srv_inv_recipients_'.$fkey].'">&nbsp;</th>';
+ echo '<th class="anl_ac tbl_icon_'.$fkey.'" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'ps_icon' ) {
+ echo '<th class="anl_ac tbl_icon" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'date_inserted' || $fkey == 'schedule_call_time' ) {
+ echo '<th class="anl_ac tbl_date" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'schstatus' ) {
+ echo '<th class="anl_ac" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'last_status' ) {
+ echo '<th class="anl_ac" title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_last_status'].'</th>';
+ } else {
+ echo '<th title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ }
+ }
+ }
+ echo '</tr>';
+
+ // Podatki tabele
+ $cnt = 1;
+ foreach($toCall as $usr_id => $phone){
+
+ $sql_query_filterd = sisplet_query("SELECT i.id, ".implode(',',$sql_select_fields)." FROM srv_invitations_recipients AS i"
+ # polovimo še iz baze klicev, vse trenutno zacete klice
+ ." LEFT OUTER JOIN (SELECT rec_id FROM srv_telephone_current) AS scc ON scc.rec_id = i.id"
+
+ # polovimo še iz baze klicev, vse trenutno zacete klice
+ ." LEFT OUTER JOIN (SELECT rec_id, call_time FROM srv_telephone_schedule) AS scs ON scs.rec_id = i.id"
+
+ # polovimo še iz baze klicev, zadnji statuse
+ ." LEFT OUTER JOIN (SELECT rsch.status, rsch.rec_id FROM srv_telephone_history AS rsch INNER JOIN (SELECT MAX(id) as iid, rec_id FROM srv_telephone_history GROUP BY rec_id) as insch ON insch.iid = rsch.id) AS sch ON sch.rec_id = i.id"
+
+ # polovimo še morebitne komentarje
+ ." LEFT OUTER JOIN (SELECT rec_id,comment FROM srv_telephone_comment) AS scm ON scm.rec_id = i.id"
+
+ # polovimo še kdo je dodal
+ ." LEFT OUTER JOIN (SELECT id, email FROM users) AS usrs ON usrs.id = i.inserted_uid"
+
+ ." WHERE i.ank_id='".$this->sid."' AND i.id='".$usr_id."'");
+ if (!$sql_query_filterd) echo mysqli_error($GLOBALS['connect_db']);
+
+ $sql_row = mysqli_fetch_assoc($sql_query_filterd);
+
+
+ $icon = ' phn_ico_status_go';
+ switch ($sql_row['schstatus']) {
+ case 'U':
+ $icon = ' phn_ico_status';
+ break;
+ case 'R':
+ $icon = ' phn_ico_status_key';
+ break;
+ case 'N': #ga ni
+ case 'Z': #zaseden
+ case 'T': #zmenjen
+ case 'D': #prelozen
+ $icon = ' phn_ico_status_error';
+ break;
+
+ default:
+ ;
+ break;
+ }
+ # če je odjavljen damo isto ikonco za zaklepanje
+ if ((int)$row_users['unsubscribed'] == 1) {
+ $icon = ' phn_ico_status_key';
+ }
+
+ echo '<tr>';
+ echo '<td>'.$cnt.'</td>';
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ switch ($fkey) {
+
+ case 'ps_icon':
+ echo '<td class="anl_ac'.$icon.'" onclick="phnGoToUser(\''.$sql_row['id'].'\')">';
+ echo '&nbsp;';
+ echo '</td>';
+ break;
+ case 'last_status':
+ echo '<td class="ovwerflowHidden" title="'.$lang['srv_userstatus_'.$sql_row[$fkey]].'">';
+ echo '('.$sql_row[$fkey].') - '.$lang['srv_userstatus_'.$sql_row[$fkey]].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$row_users[$fkey]]['email'].'</td>';
+ break;
+ case 'comment':
+ echo '<td class="tbl_inv_left ovwerflowHidden" style="max-width:100px;" title="'.str_replace("<br>","\n",strip_tags($sql_row['comment'])).'">';
+ echo substr(strip_tags($sql_row['comment']),0,50).'</td>';
+ break;
+ case 'date_inserted':
+ case 'schedule_call_time':
+ echo '<td class="tbl_inv_left ovwerflowHidden" title="'.$sql_row[$fkey].'">';
+ echo $sql_row[$fkey].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$sql_row[$fkey]]['email'].'</td>';
+ break;
+ case 'schstatus':
+ echo '<td class="tbl_inv_left ovwerflowHidden" title="'.$lang['srv_telephone_status_'.$sql_row[$fkey]].'">';
+ echo $lang['srv_telephone_status_'.$sql_row[$fkey]];
+ echo '</td>';
+ break;
+ case 'email':
+ echo '<td>';
+ echo '<span class="as_link" onclick="showRecipientTracking(\''.$sql_row['id'].'\'); return false;">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+ echo '</span>';
+ echo '</td>';
+ break;
+ case 'list_id':
+ echo '<td>';
+ if ((int)$sql_row[$fkey] > 0) {
+ if ($lists[$sql_row[$fkey]]['name'] != '') {
+ echo '<a href="#" onclick="$(\'#globalSettingsInner\').load(\'ajax.php?t=invitations&a=use_recipients_list\', {anketa:srv_meta_anketa_id, pid:'.(int)$sql_row[$fkey].' });">'.$lists[$sql_row[$fkey]]['name'].'</a>';
+ } else {
+ echo $lang['srv_inv_recipient_list_deleted'];
+ }
+ } else {
+ echo $lists[$sql_row[$fkey]]['name'];
+ }
+ echo '</td>';
+ break;
+ default:
+ echo '<td class="tbl_inv_left">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+
+ echo '</td>';
+ break;
+ }
+ }
+ }
+ echo '</tr>';
+ @ob_flush();
+
+ $cnt++;
+ }
+
+ echo '</table>';
+ echo '</div>';
+ }
+ else {
+ echo $lang['srv_telephone_calling_list_empty'].'<br class="clr">';
+ }
+
+ echo '<br /><br /><br />';
+ }
+
+ // Seznam stevilk ki so v vrsti za klicanje
+ function waitingList() {
+ global $lang;
+ global $site_url;
+
+ echo '<h2>'.$lang['srv_telephone_navi_waiting_list'].'</h2>';
+
+
+ // Dobimo seznam vseh ki so odlozeni (bodo klicani kasneje)
+ $toCall = $this->getAllNumbersWaiting();
+
+
+ if (count($toCall) > 0) {
+
+ # Katera polja prikazujemo v seznamu prejemnikov
+ $fields = array();
+ $default_fields = array(
+ 'phone' => 1,
+ 'email' => 0,
+ 'password' => 0,
+ 'firstname' => 0,
+ 'lastname' => 0,
+ 'salutation' => 0,
+ 'custom' => 0,
+ );
+
+ $sql_select_fields = array();
+ $fields['ps_icon'] = 1;
+ $fields['schstatus'] = 1;
+
+ $sql_select_fields[] = " i.last_status as ps_icon";
+ $sql_select_fields[] = " i.last_status as last_status";
+ $sql_select_fields[] = " scc.rec_id AS sccusr";
+ $sql_select_fields[] = " scs.call_time AS schedule_call_time";
+ # polovimo še iz baze klicev, zadnji statuse
+ $sql_select_fields[] = " sch.status AS schstatus";
+ $sql_select_fields[] = " scm.comment AS comment";
+
+ foreach($toCall as $usr_id => $phone){
+
+ #koliko zapisov bi morali prikazovati
+ $sql_query_filterd_all = sisplet_query("SELECT i.* FROM srv_invitations_recipients AS i WHERE i.ank_id='".$this->sid."' AND i.id='".$usr_id."'");
+
+ $sql_row = mysqli_fetch_assoc($sql_query_filterd_all);
+ foreach ($default_fields AS $key => $value) {
+ # če polje še ni dodano in če ni prazno, ga dodamo
+ if ($fields[$key] == 0 && isset($sql_row[$key]) && trim($sql_row[$key]) != '') {
+ $fields[$key] = 1;
+ $sql_select_fields[] = 'i.'.$key;
+ }
+ }
+ }
+
+ $fields['schedule_call_time'] = 1;
+ $fields['last_status'] = 1;
+ $fields['comment'] = 1;
+ $fields['date_inserted'] = 1;
+ $fields['usr_email'] = 1;
+ $fields['list_id'] = 1;
+
+ # dodamo še ostala polja
+ $sql_select_fields[] = 'i.last_status';
+ $sql_select_fields[] = 'i.date_inserted';
+ $sql_select_fields[] = 'i.list_id';
+ $sql_select_fields[] = 'usrs.email AS usr_email';
+
+ #dodamo paginacijo in poiščemo zapise
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $limit_start = ($page * REC_ON_PAGE) - REC_ON_PAGE;
+
+
+ # polovimo sezname
+ $lids = array();
+ $sql_string_users = "SELECT i.list_id FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND TRIM(phone) !='' GROUP BY i.list_id ORDER BY i.id LIMIT $limit_start,".REC_ON_PAGE.'';
+ $sql_query_users = sisplet_query($sql_string_users);
+ while ($row_users = mysqli_fetch_assoc($sql_query_users)) {
+ $lids[] = $row_users['list_id'];
+ }
+
+ #seznami
+ $lists = array();
+ $lists['-1'] = array('name'=>$lang['srv_invitation_new_templist']);
+ $lists['0'] = array('name'=>$lang['srv_invitation_new_templist_author']);
+ if (count($lids) > 0 ) {
+ $sql_string_lists = "SELECT name, pid from srv_invitations_recipients_profiles WHERE pid IN(".implode(',',$lids).") ";
+ $sql_query_lists = sisplet_query($sql_string_lists);
+ while ($row_lists = mysqli_fetch_assoc($sql_query_lists)) {
+ $lists[$row_lists['pid']] = array('name'=>$row_lists['name']);
+ }
+ }
+
+ // Stevilo stevilk v vrsti
+ echo '<div id="srv_invitation_note">'.$lang['srv_telephone_waiting_list_count'].': '.count($toCall).'</div>';
+
+ echo '<br class="clr"/>';
+
+ // Izrisemo tabelo
+ echo '<div style="display:inline-block;">';
+ echo '<table id="tbl_recipients_list" class="phone">';
+
+ // Header tabele
+ echo '<tr>';
+ echo '<th class="tbl_icon">&nbsp;</th>';
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ if ($fkey == 'sent' || $fkey == 'responded' || $fkey == 'unsubscribed'){
+ #echo '<th class="anl_ac tbl_icon_'.$fkey.' inv_'.$fkey.'_1" title="'.$lang['srv_inv_recipients_'.$fkey].'">&nbsp;</th>';
+ echo '<th class="anl_ac tbl_icon_'.$fkey.'" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'ps_icon' ) {
+ echo '<th class="anl_ac tbl_icon" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'date_inserted' || $fkey == 'schedule_call_time' ) {
+ echo '<th class="anl_ac tbl_date" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'schstatus' ) {
+ echo '<th class="anl_ac" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ } else if ($fkey == 'last_status' ) {
+ echo '<th class="anl_ac" title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_last_status'].'</th>';
+ } else {
+ echo '<th title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].'</th>';
+ }
+ }
+ }
+ echo '</tr>';
+
+ // Podatki tabele
+ $cnt = 1;
+ foreach($toCall as $usr_id => $phone){
+
+ $sql_query_filterd = sisplet_query("SELECT i.id, ".implode(',',$sql_select_fields)." FROM srv_invitations_recipients AS i"
+ # polovimo še iz baze klicev, vse trenutno zacete klice
+ ." LEFT OUTER JOIN (SELECT rec_id FROM srv_telephone_current) AS scc ON scc.rec_id = i.id"
+
+ # polovimo še iz baze klicev, vse trenutno zacete klice
+ ." LEFT OUTER JOIN (SELECT rec_id, call_time FROM srv_telephone_schedule) AS scs ON scs.rec_id = i.id"
+
+ # polovimo še iz baze klicev, zadnji statuse
+ ." LEFT OUTER JOIN (SELECT rsch.status, rsch.rec_id FROM srv_telephone_history AS rsch INNER JOIN (SELECT MAX(id) as iid, rec_id FROM srv_telephone_history GROUP BY rec_id) as insch ON insch.iid = rsch.id) AS sch ON sch.rec_id = i.id"
+
+ # polovimo še morebitne komentarje
+ ." LEFT OUTER JOIN (SELECT rec_id,comment FROM srv_telephone_comment) AS scm ON scm.rec_id = i.id"
+
+ # polovimo še kdo je dodal
+ ." LEFT OUTER JOIN (SELECT id, email FROM users) AS usrs ON usrs.id = i.inserted_uid"
+
+ ." WHERE i.ank_id='".$this->sid."' AND i.id='".$usr_id."'");
+ if (!$sql_query_filterd) echo mysqli_error($GLOBALS['connect_db']);
+
+ $sql_row = mysqli_fetch_assoc($sql_query_filterd);
+
+
+ $icon = ' phn_ico_status_go';
+ switch ($sql_row['schstatus']) {
+ case 'U':
+ $icon = ' phn_ico_status';
+ break;
+ case 'R':
+ $icon = ' phn_ico_status_key';
+ break;
+ case 'N': #ga ni
+ case 'Z': #zaseden
+ case 'T': #zmenjen
+ case 'D': #prelozen
+ $icon = ' phn_ico_status_error';
+ break;
+
+ default:
+ ;
+ break;
+ }
+ # če je odjavljen damo isto ikonco za zaklepanje
+ if ((int)$row_users['unsubscribed'] == 1) {
+ $icon = ' phn_ico_status_key';
+ }
+
+ echo '<tr>';
+ echo '<td>'.$cnt.'</td>';
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ switch ($fkey) {
+
+ case 'ps_icon':
+ echo '<td class="anl_ac'.$icon.'" onclick="phnGoToUser(\''.$sql_row['id'].'\')">';
+ echo '&nbsp;';
+ echo '</td>';
+ break;
+ case 'last_status':
+ echo '<td class="ovwerflowHidden" title="'.$lang['srv_userstatus_'.$sql_row[$fkey]].'">';
+ echo '('.$sql_row[$fkey].') - '.$lang['srv_userstatus_'.$sql_row[$fkey]].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$row_users[$fkey]]['email'].'</td>';
+ break;
+ case 'comment':
+ echo '<td class="tbl_inv_left ovwerflowHidden" style="max-width:50px;" title="'.str_replace("<br>","\n",strip_tags($sql_row['comment'])).'">';
+ echo substr(strip_tags($sql_row['comment']),0,50).'</td>';
+ break;
+ case 'date_inserted':
+ case 'schedule_call_time':
+ echo '<td class="tbl_inv_left ovwerflowHidden" title="'.$sql_row[$fkey].'">';
+ echo $sql_row[$fkey].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$sql_row[$fkey]]['email'].'</td>';
+ break;
+ case 'schstatus':
+ echo '<td class="tbl_inv_left ovwerflowHidden" title="'.$lang['srv_telephone_status_'.$sql_row[$fkey]].'">';
+ echo $lang['srv_telephone_status_'.$sql_row[$fkey]];
+ echo '</td>';
+ break;
+ case 'email':
+ echo '<td>';
+ echo '<span class="as_link" onclick="showRecipientTracking(\''.$sql_row['id'].'\'); return false;">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+ echo '</span>';
+ echo '</td>';
+ break;
+ case 'list_id':
+ echo '<td>';
+ if ((int)$sql_row[$fkey] > 0) {
+ if ($lists[$sql_row[$fkey]]['name'] != '') {
+ echo '<a href="#" onclick="$(\'#globalSettingsInner\').load(\'ajax.php?t=invitations&a=use_recipients_list\', {anketa:srv_meta_anketa_id, pid:'.(int)$sql_row[$fkey].' });">'.$lists[$sql_row[$fkey]]['name'].'</a>';
+ } else {
+ echo $lang['srv_inv_recipient_list_deleted'];
+ }
+ } else {
+ echo $lists[$sql_row[$fkey]]['name'];
+ }
+ echo '</td>';
+ break;
+ default:
+ echo '<td class="tbl_inv_left">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+
+ echo '</td>';
+ break;
+ }
+ }
+ }
+ echo '</tr>';
+ @ob_flush();
+
+ $cnt++;
+ }
+
+ echo '</table>';
+ echo '</div>';
+ }
+ else {
+ echo $lang['srv_telephone_waiting_list_empty'].'<br class="clr">';
+ }
+ }
+
+
+
+ function addUrl($what) {
+ global $site_url;
+
+ if ($what == null || trim($what) == '') {
+ $what = 'add_recipients_view';
+ }
+ if ($what == 'clear_current') {
+ $what = 'call&n=clear_current';
+ }
+ $url = $site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_TELEPHONE.'&amp;m='.$what;
+
+ return $url;
+ }
+
+ function viewRecipients() {
+ global $lang, $site_url;
+
+ #preglej prejemnike
+ #echo '<h2>'.$lang['srv_inv_heading_step2'].$lang['srv_inv_edit_recipients_heading'].'</h2>';
+ echo '<h2>'.$lang['srv_inv_edit_recipients_heading'].'</h2>';
+ #polovimo prejemnike ki ne želijo prejemati obvestil
+
+ # nastavimo filter
+ session_start();
+ $filter = $_SESSION['inv_filter']['value'];
+ if ($filter != '') {
+ $mysql_filter = " AND ("
+ . "i.email LIKE '%".$filter."%'"
+ . "OR i.firstname LIKE '%".$filter."%'"
+ . "OR i.lastname LIKE '%".$filter."%'"
+ . "OR i.password LIKE '%".$filter."%'"
+ . "OR i.salutation LIKE '%".$filter."%'"
+ . "OR i.phone LIKE '%".$filter."%'"
+ . "OR i.custom LIKE '%".$filter."%'"
+ . ")";
+
+ $mysql_filter2 = " AND ("
+ . "i.email LIKE '%".$filter."%'"
+ . "OR i.firstname LIKE '%".$filter."%'"
+ . "OR i.lastname LIKE '%".$filter."%'"
+ . "OR i.password LIKE '%".$filter."%'"
+ . "OR i.salutation LIKE '%".$filter."%'"
+ . "OR i.phone LIKE '%".$filter."%'"
+ . "OR i.custom LIKE '%".$filter."%'"
+ . "OR scm.comment LIKE '%".$filter."%'"
+ . ")";
+ }
+
+ # preštejemo koliko imamo vseh respondentov in koliko jih je brez e-maila
+ $sql_string_all = "SELECT id FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0' AND TRIM(phone) !=''";
+ $sql_query_all = sisplet_query($sql_string_all);
+ $count_all = mysqli_num_rows($sql_query_all);
+
+ $sql_string_withot_email = "SELECT count(*) FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0' AND email IS NULL AND sent='0'";
+ $sql_query_without_email = sisplet_query($sql_string_withot_email);
+ $sql_row_without_email = mysqli_fetch_row($sql_query_without_email);
+ $count_without_email = $sql_row_without_email[0];
+
+ #koliko zapisov bi morali prikazovati
+ $sql_string_filterd_all = "SELECT i.* FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND TRIM(phone) !='' ".$mysql_filter." ORDER BY i.id";
+ $sql_query_filterd_all = sisplet_query($sql_string_filterd_all);
+ $filtred_all = mysqli_num_rows($sql_query_filterd_all);
+
+ $fields = array();
+ # Katera polja prikazujemo v seznamu prejemnikov
+ $default_fields = array(
+ 'phone' => 1,
+ 'email' => 0,
+ 'password' => 0,
+ 'firstname' => 0,
+ 'lastname' => 0,
+ 'salutation' => 0,
+ 'custom' => 0,
+ );
+
+ $sql_select_fields = array();
+ $fields['ps_icon'] = 1;
+ $fields['schstatus'] = 1;
+
+ $sql_select_fields[] = " i.last_status as ps_icon";
+ $sql_select_fields[] = " i.last_status as last_status";
+ $sql_select_fields[] = " scc.rec_id AS sccusr";
+ $sql_select_fields[] = " scs.call_time AS schedule_call_time";
+ # polovimo še iz baze klicev, zadnji statuse
+ $sql_select_fields[] = " sch.status AS schstatus";
+ $sql_select_fields[] = " scm.comment AS comment";
+
+ # pogledamo katera polja dejansko prikazujemo
+
+ while ($sql_row = mysqli_fetch_assoc($sql_query_filterd_all)) {
+ foreach ($default_fields AS $key => $value) {
+ # če polje še ni dodano in če ni prazno, ga dodamo
+ if ($fields[$key] == 0 && isset($sql_row[$key]) && trim($sql_row[$key]) != '') {
+ $fields[$key] = 1;
+ $sql_select_fields[] = 'i.'.$key;
+ }
+ }
+ }
+
+ $fields['schedule_call_time'] = 1;
+ $fields['last_status'] = 1;
+ $fields['comment'] = 1;
+ $fields['date_inserted'] = 1;
+ $fields['usr_email'] = 1;
+ $fields['list_id'] = 1;
+
+ # dodamo še ostala polja
+ $sql_select_fields[] = 'i.last_status';
+ $sql_select_fields[] = 'i.date_inserted';
+ $sql_select_fields[] = 'i.list_id';
+ $sql_select_fields[] = 'usrs.email AS usr_email';
+ #štetje vabil
+ #$fields['count_inv'] = 1;
+ #$sql_select_fields[] = 'count(siar.arch_id) AS count_inv';
+
+ #dodamo paginacijo in poiščemo zapise
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $limit_start = ($page*REC_ON_PAGE)-REC_ON_PAGE;
+
+ #dodamo sortiranje
+ $sort_string = $this->getSortString();
+
+ # $sql_string_filterd = "SELECT i.id, ".implode(',',$sql_select_fields)." FROM srv_invitations_recipients AS i LEFT JOIN srv_invitations_archive_recipients AS siar ON (i.id = siar.rec_id) WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0'".$mysql_filter.' GROUP BY siar.rec_id '.$sort_string." LIMIT $limit_start,".REC_ON_PAGE;
+ $sql_string_filterd = "SELECT i.id, ".implode(',',$sql_select_fields)." FROM srv_invitations_recipients AS i"
+ # polovimo še iz baze klicev, vse trenutno zacete klice
+ ." LEFT OUTER JOIN (SELECT rec_id FROM srv_telephone_current) AS scc ON scc.rec_id = i.id"
+
+ # polovimo še iz baze klicev, vse trenutno zacete klice
+ ." LEFT OUTER JOIN (SELECT rec_id, call_time FROM srv_telephone_schedule) AS scs ON scs.rec_id = i.id"
+
+ # polovimo še iz baze klicev, zadnji statuse
+ ." LEFT OUTER JOIN (SELECT rsch.status, rsch.rec_id FROM srv_telephone_history AS rsch INNER JOIN (SELECT MAX(id) as iid, rec_id FROM srv_telephone_history GROUP BY rec_id) as insch ON insch.iid = rsch.id) AS sch ON sch.rec_id = i.id"
+
+ # polovimo še morebitne komentarje
+ ." LEFT OUTER JOIN (SELECT rec_id,comment FROM srv_telephone_comment) AS scm ON scm.rec_id = i.id"
+
+ # polovimo še kdo je dodal
+ ." LEFT OUTER JOIN (SELECT id, email FROM users) AS usrs ON usrs.id = i.inserted_uid"
+
+ ." WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND TRIM(phone) !='' ".$mysql_filter2.' '.$sort_string." LIMIT $limit_start,".REC_ON_PAGE;
+ $sql_query_filterd = sisplet_query($sql_string_filterd);
+ if (!$sql_query_filterd) echo mysqli_error($GLOBALS['connect_db']);
+
+ # polovimo sezname
+ $lids = array();
+ $sql_string_users = "SELECT i.list_id FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND TRIM(phone) !=''".$mysql_filter." GROUP BY i.list_id ORDER BY i.id LIMIT $limit_start,".REC_ON_PAGE.'';
+ $sql_query_users = sisplet_query($sql_string_users);
+ while ($row_users = mysqli_fetch_assoc($sql_query_users)) {
+ $lids[] = $row_users['list_id'];
+ }
+
+ #seznami
+ $lists = array();
+ $lists['-1'] = array('name'=>$lang['srv_invitation_new_templist']);
+ $lists['0'] = array('name'=>$lang['srv_invitation_new_templist_author']);
+ if (count($lids) > 0 ) {
+ $sql_string_lists = "SELECT name, pid from srv_invitations_recipients_profiles WHERE pid IN(".implode(',',$lids).") ";
+ $sql_query_lists = sisplet_query($sql_string_lists);
+ while ($row_lists = mysqli_fetch_assoc($sql_query_lists)) {
+ $lists[$row_lists['pid']] = array('name'=>$row_lists['name']);
+ }
+ }
+ if (count($msgs) > 0) {
+ echo '<span class="inv_msg_note">';
+ foreach($msgs as $msg) {
+ echo '* '.$msg.'<br />';
+ }
+ echo '</span>';
+ }
+ if (count($errors) > 0) {
+ echo '<span class="inv_error_note">';
+ foreach($errors as $error) {
+ echo '* '.$error.'<br />';
+ }
+ echo '</span>';
+ }
+ if ($count_all > 0 ) {
+
+ // dodamo filtriranje
+ echo '<div id="inv_rec_filter">';
+ echo '<label>'.$lang['srv_invitation_recipients_filter'].'</label> <input id="tel_rec_filter_value" type="text" onchange="tel_filter_recipients(); return false;" value="'.$_SESSION['inv_filter']['value'].'">';
+ echo '</div>';
+
+ echo '<form id="frm_inv_rec_export" name="resp_uploader" method="post" autocomplete="off">';
+ echo '<input type="hidden" name="anketa" id="anketa" value="'.$this->sid.'">';
+ echo '<input type="hidden" name="noNavi" id="noNavi" value="true">';
+
+ //echo '<br class="clr"/>';
+
+ echo '<div id="srv_invitation_note" style="padding-top:8px;">';
+ if ($filter != '') {
+ echo '<span class="red strong">';
+ printf($lang['srv_inv_list_no_recipients_filter'],$filter);
+ echo '</span>';
+ }
+ else{
+ if ($count_all > 0 && mysqli_num_rows($sql_query_filterd) != $count_all )
+ echo $lang['srv_invitation_num_respondents_filtred'].(int)mysqli_num_rows($sql_query_filterd);
+ else
+ echo $lang['srv_invitation_num_respondents'].(int)$this->count_all;
+ }
+ echo '</div>';
+
+ echo '<br class="clr"/>';
+
+ if (mysqli_num_rows($sql_query_filterd) > 0 && $count_all > 0) {
+
+ $this->displayPagination($filtred_all);
+ echo '<div style="display:inline-block;">';
+
+ echo '<table id="tbl_recipients_list" class="phone">';
+ echo '<tr>';
+ # checkbox
+ echo '<th class="tbl_icon" colspan="3" >&nbsp;</th>';
+ /*
+ * # uredi
+ echo '<th class="tbl_liks">&nbsp;</th>';
+ # izbrisi
+ echo '<th class="tbl_liks">&nbsp;</th>';
+
+ */
+
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ if ($fkey == 'sent' || $fkey == 'responded' || $fkey == 'unsubscribed'){
+ #echo '<th class="anl_ac tbl_icon_'.$fkey.' inv_'.$fkey.'_1" title="'.$lang['srv_inv_recipients_'.$fkey].'">&nbsp;</th>';
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac tbl_icon_'.$fkey.'" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ } else if ($fkey == 'ps_icon' ) {
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac tbl_icon" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ } else if ($fkey == 'date_inserted' || $fkey == 'schedule_call_time' ) {
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac tbl_date pointer" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ } else if ($fkey == 'schstatus' ) {
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac pointer" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ } else if ($fkey == 'last_status' ) {
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac pointer" title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_last_status'].$this->addSortIcon($fkey).'</th>';
+ } else {
+ echo '<th'.$this->addSortField($fkey).' class="pointer" title="'.$lang['srv_telephone_respondents_'.$fkey].'">'.$lang['srv_telephone_respondents_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ }
+ }
+ }
+ echo '</tr>';
+ while ($sql_row = mysqli_fetch_assoc($sql_query_filterd)) {
+ $icon = ' phn_ico_status_go';
+ switch ($sql_row['schstatus']) {
+ case 'U':
+ $icon = ' phn_ico_status';
+ break;
+ case 'R':
+ $icon = ' phn_ico_status_key';
+ break;
+ case 'N': #ga ni
+ case 'Z': #zaseden
+ case 'T': #zmenjen
+ case 'D': #prelozen
+ $icon = ' phn_ico_status_error';
+ break;
+
+ default:
+ ;
+ break;
+ }
+ # če je odjavljen damo isto ikonco za zaklepanje
+ if ((int)$row_users['unsubscribed'] == 1) {
+ $icon = ' phn_ico_status_key';
+ }
+
+ echo '<tr>';
+ # checkbox
+
+ echo '<td><input type="checkbox" name="inv_rids[]" value="'.$sql_row['id'].'"></td>';
+ #izbriši
+ echo '<td class="tbl_inv_left"><span class="faicon delete_circle icon-orange_link" onclick="deleteRecipient_confirm(\''.$sql_row['id'].'\'); return false;" title="'.$lang['srv_inv_list_profiles_delete'].'"></span></td>';
+ #uredi
+ echo '<td class="tbl_inv_left"><span class="faicon quick_edit edit smaller icon-as_link" onclick="editRecipient(\''.$sql_row['id'].'\'); return false;" title="'.$lang['srv_inv_list_profiles_edit'].'"></span></td>';
+
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ switch ($fkey) {
+
+ case 'ps_icon':
+ echo '<td class="anl_ac'.$icon.'" onclick="phnGoToUser(\''.$sql_row['id'].'\')">';
+ echo '&nbsp;';
+ echo '</td>';
+ break;
+ case 'last_status':
+ echo '<td title="'.$lang['srv_userstatus_'.$sql_row[$fkey]].'">';
+ echo '('.$sql_row[$fkey].') - '.$lang['srv_userstatus_'.$sql_row[$fkey]].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$row_users[$fkey]]['email'].'</td>';
+ break;
+ case 'comment':
+ echo '<td class="tbl_inv_left ovwerflowHidden" style="max-width:100px;" title="'.str_replace("<br>","\n",strip_tags($sql_row['comment'])).'">';
+ /*echo substr(strip_tags($sql_row['comment']),0,50).'</td>';*/
+ if ($filter != '') {
+ echo $this->hightlight(substr(strip_tags($sql_row['comment']),0,50),$filter);
+ } else {
+ echo substr(strip_tags($sql_row['comment']),0,50);
+ }
+ echo '</td>';
+ break;
+ case 'date_inserted':
+ case 'schedule_call_time':
+ echo '<td class="tbl_inv_left" title="'.$sql_row[$fkey].'">';
+ echo $sql_row[$fkey].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$sql_row[$fkey]]['email'].'</td>';
+ break;
+ case 'schstatus':
+ echo '<td class="tbl_inv_left" title="'.$lang['srv_telephone_status_'.$sql_row[$fkey]].'">';
+ echo $lang['srv_telephone_status_'.$sql_row[$fkey]];
+ echo '</td>';
+ break;
+ case 'email':
+ echo '<td>';
+ echo '<span class="as_link" onclick="showRecipientTracking(\''.$sql_row['id'].'\'); return false;">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+ echo '</span>';
+ echo '</td>';
+ break;
+ case 'list_id':
+ echo '<td>';
+ if ((int)$sql_row[$fkey] > 0) {
+ if ($lists[$sql_row[$fkey]]['name'] != '') {
+ echo '<a href="#" onclick="$(\'#globalSettingsInner\').load(\'ajax.php?t=invitations&a=use_recipients_list\', {anketa:srv_meta_anketa_id, pid:'.(int)$sql_row[$fkey].' });">'.$lists[$sql_row[$fkey]]['name'].'</a>';
+ } else {
+ echo $lang['srv_inv_recipient_list_deleted'];
+ }
+ } else {
+ echo $lists[$sql_row[$fkey]]['name'];
+ }
+ echo '</td>';
+ break;
+ default:
+ echo '<td class="tbl_inv_left">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+
+ echo '</td>';
+ break;
+ }
+ }
+ }
+ echo '</tr>';
+ @ob_flush();
+ }
+ echo '</table>';
+ echo '<div id="inv_bottom_edit">';
+ echo '<span class="faicon arrow_up"></span> ';
+ echo '<span id="inv_switch_on"><a href="javascript:inv_selectAll(true);">'.$lang['srv_select_all'].'</a></span>';
+ echo '<span id="inv_switch_off" style="display:none;"><a href="javascript:inv_selectAll(false);">'.$lang['srv_deselect_all'].'</a></span>';
+ echo '&nbsp;&nbsp;<a href="#" onClick="inv_recipients_form_action(\'delete\');"><span class="faicon delete_circle icon-orange" title="'.$lang['srv_invitation_recipients_delete_selected'].'"/></span>&nbsp;'.$lang['srv_invitation_recipients_delete_selected'].'</a>';
+ echo '&nbsp;&nbsp;<a href="#" onClick="inv_recipients_form_action(\'export\');"><span class="sprites xls delete" style="height:14px; width:16px;" title="'.$lang['srv_invitation_recipients_export_selected'].'"/></span>&nbsp;'.$lang['srv_invitation_recipients_export_selected'].'</a>';
+ echo '</div>';
+ echo '</div>';
+
+ } else {
+ echo $lang['srv_inv_list_no_recipients_filtred'].'<br class="clr">';
+ }
+ echo '</form>';
+ } else {
+ echo $lang['srv_inv_list_no_recipients'].'<br class="clr">';
+ }
+
+ echo '<br /><br />';
+ }
+
+
+ /**
+ * @desc prikaze prvo stran z linkom na zacni
+ */
+ function startCall() {
+ global $lang;
+
+ #preverimo koliko številk imamo na voljo
+ $numbersAvailable = $this->getAllNumbers();
+
+ # preverimo aktivnost ankete
+ if ($this->surveySettings['active'] != 1) {
+ echo $lang['srv_inv_error9'];
+ if ($this->isAnketar == true) {
+ return;
+ }
+ }
+
+ if (count($numbersAvailable) > 0 ) {
+ echo '<h2>'.$lang['srv_telephone_call_available'];
+ echo ' '.count($numbersAvailable);
+ echo '</h2>';
+ echo '<h2><a href="index.php?anketa='.$this->sid.'&a='.A_TELEPHONE.'&m=call">'.$lang['srv_call_start'].'</a></h2>';
+ } else {
+ $this->getNextTimeCall();
+ }
+ }
+
+ /**
+ * @desc zacne s klicanjem telefonskih stevilk
+ */
+ function Call() {
+ global $site_root, $global_user_id;
+
+ $schedule = false;
+
+ // stevilka je izbrana - klicana
+ if ($_GET['usr_id'] != '' && (int)$_GET['usr_id'] > 0) {
+ $usr_id = (int)$_GET['usr_id'];
+
+ // zbrisemo cookie za izpolnjevanje -- da ne dobi od prejsnjega, ce je nehu nekje vmes
+ setcookie('survey-'.$this->sid, '', time()-3600, str_replace($_SERVER['DOCUMENT_ROOT'], '', $site_root).'main/survey/');
+
+ sisplet_query("DELETE FROM srv_telephone_schedule WHERE rec_id = '$usr_id'");
+ sisplet_query("INSERT INTO srv_telephone_current (rec_id, user_id, started_time) VALUES ('$usr_id', '".$global_user_id."', NOW())");
+ }
+ else {
+ // Po novem moramo pri kliku "klici drugo" pobrisati current iz baze
+ if(isset($_GET['n']) && $_GET['n'] == 'clear_current')
+ sisplet_query("DELETE srv_telephone_current FROM srv_telephone_current, srv_invitations_recipients
+ WHERE srv_telephone_current.user_id='".$global_user_id."' AND srv_telephone_current.rec_id = srv_invitations_recipients.id AND srv_invitations_recipients.ank_id='".$this->sid."'");
+
+ #uporabnik ni izbran določimo izberemo ga naklučno oziroma če smo dogovorjeni
+ $row = $this->get_next_number();
+ $usr_id = $row['usr_id'];
+ $schedule = (int)$row['schedule'] == 1 ? true : false;
+ }
+
+ if ((int)$usr_id > 0) {
+ # preverimo ali je uporabnik že začel klicat
+ $openedSurvey = ($_GET['usr_id'] != '' && (int)$_GET['usr_id'] > 0) ? true : false;
+ $this->userCallToShow($usr_id,$openedSurvey,$schedule);
+
+ // Po novem ze ob prikazu stevilke zaklenemo respondenta (da ga ne moreta 2 anketarja hkrati poklicati preden odpreta anketo)
+ $sql = sisplet_query("SELECT * FROM srv_telephone_current WHERE rec_id='".$usr_id."' AND user_id='".$global_user_id."' AND started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)");
+ if(mysqli_num_rows($sql) == 0)
+ sisplet_query("INSERT INTO srv_telephone_current (rec_id, user_id, started_time) VALUES ('$usr_id', '".$global_user_id."', NOW())");
+ }
+ else {
+ $this->getNextTimeCall();
+ }
+ }
+
+ function settings() {
+ global $lang, $site_url;
+
+ echo '<fieldset><legend>'.$lang['settings'].'</legend>';
+
+ echo '<form id="phn_settings" method="post">';
+ echo '<p>'.$lang['srv_call_settings_z'].' <input type="text" name="status_z" value="'.$this->status_z.'" style="width:20px" /> '.$lang['srv_call_settings_min'].'</p>';
+ echo '<p>'.$lang['srv_call_settings_n'].' <input type="text" name="status_n" value="'.$this->status_n.'" style="width:20px" /> '.$lang['srv_call_settings_min'].'</p>';
+ echo '<p>'.$lang['srv_call_settings_d'].' <input type="text" name="status_d" value="'.$this->status_d.'" style="width:20px" /> '.$lang['srv_call_settings_min'].'</p>';
+ echo '<p>'.$lang['srv_call_settings_max'].' <input type="text" name="max_calls" value="'.$this->max_calls.'" style="width:20px" /> '.$lang['srv_call_settings_calls'].'</p>';
+
+ // Vrstni red klicanja
+ echo '<p>';
+ echo $lang['srv_call_settings_call_order'].': <select name="call_order">';
+ echo '<option value="0" '.($this->call_order==0 ? ' selected="selected"' : '').'>'.$lang['srv_call_settings_call_order_0'].'</option>';
+ echo '<option value="1" '.($this->call_order==1 ? ' selected="selected"' : '').'>'.$lang['srv_call_settings_call_order_1'].'</option>';
+ echo '<option value="2" '.($this->call_order==2 ? ' selected="selected"' : '').'>'.$lang['srv_call_settings_call_order_2'].'</option>';
+ echo '<option value="3" '.($this->call_order==3 ? ' selected="selected"' : '').'>'.$lang['srv_call_settings_call_order_3'].'</option>';
+ echo '</select>';
+ echo '</p>';
+
+ #$str = "SELECT sd.uid, u.name, u.surname, u.email FROM srv_dostop AS sd LEFT JOIN users AS u ON sd.uid = u.id WHERE sd.ank_id ='$this->sid' AND FIND_IN_SET('phone',sd.dostop )>0";
+ #polovimo vse userje ki imajo dostop
+ echo '<p>';
+ echo $lang['srv_telephone_settings_access_list'];
+ printf ($lang['srv_telephone_settings_access_list_link'],$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_DOSTOP);
+ echo '<table style="margin-left:20px;"><tr><th>Anketar</th><th class="anl_al">Ime, priimek, email</th></tr>';
+ $str = "SELECT sd.uid,FIND_IN_SET('phone',sd.dostop ) AS anketar, u.name, u.surname, u.email FROM srv_dostop AS sd LEFT JOIN users AS u ON sd.uid = u.id WHERE sd.ank_id ='$this->sid'";
+ $qry = sisplet_query($str);
+ while ($sql_row = mysqli_fetch_assoc($qry)) {
+ $avtor = array();
+ if (trim($sql_row['name'])) {
+ $avtor[] = trim ($sql_row['name']);
+ }
+ if (trim($sql_row['surname'])) {
+ $avtor[] = trim ($sql_row['surname']);
+ }
+ if (trim($sql_row['email'])) {
+ $avtor[] = iconv("iso-8859-2", "utf-8",'<span class="gray">('.trim ($sql_row['email']).')</span>');
+ }
+
+ echo '<tr><td>';
+ echo '<input name="dostop['.$sql_row['uid'].']" type="checkbox"'.($sql_row['anketar']>0?' checked="checked"':'').'>';
+ echo '</td><td>';
+ if ( count($avtor) > 0 ) {
+ echo implode(', ',$avtor);
+ }
+ echo '</td></tr>';
+ }
+ echo '</table>';
+ echo '</p>';
+ echo '<span class="buttonwrapper floatLeft"><a class="ovalbutton ovalbutton_orange" href="#" onclick="phn_settings_save(); return false;">'.$lang['srv_telephone_settings_save'].'</a></span>';
+ echo '</form>';
+ echo '<br /><br />';
+
+ echo '</fieldset>';
+
+ echo '<div id="success_save" style="display:none;">'.$lang['srv_success_save'].'</div>';
+ }
+
+ function settingsSave() {
+ $this->status_z = (int)$_POST[status_z];
+ $this->status_n = (int)$_POST[status_n];
+ $this->status_d = (int)$_POST[status_d];
+ $this->max_calls = (int)$_POST[max_calls];
+ $this->call_order = (int)$_POST[call_order];
+
+ sisplet_query("REPLACE srv_telephone_setting (survey_id, status_z, status_n, status_d, max_calls, call_order) VALUES ('$this->sid', '$this->status_z ', '$this->status_n', '$this->status_d', '$this->max_calls', '$this->call_order')");
+ #dodamo dostop za anketarja
+
+ if (count($_POST['dostop']) > 0) {
+ $uids = array();
+ foreach ($_POST['dostop'] AS $uid => $on) {
+ $uids[] = $uid;
+ }
+
+ #najprej odstranimo vsem kateri niso v post
+ $str_remove = "UPDATE srv_dostop SET dostop = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', dostop, ','),CONCAT(',', 'phone', ','), ','))"
+ ." WHERE ank_id='$this->sid' AND uid NOT IN(".implode(",",$uids).")";
+ $s1 = sisplet_query($str_remove);
+ if (!$s1) echo 'err_phn_dostop_001'.mysqli_error($GLOBALS['connect_db']);
+
+ #nato dodamo vsem ki so v post.
+ ;
+ $str_update = "UPDATE srv_dostop SET dostop = CONCAT(dostop, ',phone')"
+ ." WHERE ank_id='$this->sid' AND uid IN(".implode(",",$uids).")";
+ $s2 = sisplet_query($str_update);
+ if (!$s2) echo 'err_phn_dostop_002'.mysqli_error($GLOBALS['connect_db']);
+
+ }
+ }
+
+ /**
+ * @desc vrne ID spremenljivke telefon
+ */
+ function get_spr_telefon_id () {
+
+ $sql = sisplet_query("SELECT srv_spremenljivka.id
+ FROM srv_spremenljivka, srv_grupa
+ WHERE srv_spremenljivka.variable = 'telefon'
+ AND srv_spremenljivka.sistem = '1'
+ AND srv_spremenljivka.gru_id = srv_grupa.id
+ AND srv_grupa.ank_id = '$this->sid'
+ ");
+ $row = mysqli_fetch_array($sql);
+ return $row['id'];
+ }
+
+
+ function addSortField($field){
+ $type = 'ASC';
+ session_start();
+ if ($_SESSION['phn_rec_sort_field'] == $field) {
+ if ($_SESSION['phn_rec_sort_type'] == 'DESC') {
+ $type = 'ASC';
+ } else {
+ $type = 'DESC';
+ }
+ } else {
+ $type = 'ASC';
+ }
+ return ' onclick="phn_set_sort_field(\''.$field.'\',\''.$type.'\');" ';
+ }
+ function addSortIcon($field){
+ session_start();
+ if ($_SESSION['phn_rec_sort_field'] == $field) {
+ if ($_SESSION['phn_rec_sort_type'] == 'DESC') {
+ return ' <span class="faicon sort_descending icon-blue"></span>';
+
+ } else {
+ return ' <span class="faicon sort_ascending icon-blue"></span>';
+ }
+ }
+ return;
+ }
+ function setSortField() {
+ session_start();
+ if (isset($_POST['field']) && trim($_POST['field']) != '') {
+ $_SESSION['phn_rec_sort_field'] = trim($_POST['field']);
+ } else {
+ $_SESSION['phn_rec_sort_field'] = 'date_inserted';
+ }
+ if (isset($_POST['type']) && trim($_POST['type']) != '') {
+ $_SESSION['phn_rec_sort_type'] = trim($_POST['type']);
+ } else {
+ $_SESSION['phn_rec_sort_type'] = 'ASC';
+ }
+ session_commit();
+ }
+
+ function getSortString() {
+ session_start();
+ $sort_string = ' ORDER BY i.id ASC';
+ if (isset($_SESSION['phn_rec_sort_field']) && trim($_SESSION['phn_rec_sort_field']) != '') {
+ $prefix = 'i.';
+ if ($_SESSION['phn_rec_sort_field'] == 'count_inv'
+ || $_SESSION['phn_rec_sort_field'] == 'ps_icon'
+ || $_SESSION['phn_rec_sort_field'] == 'schedule_call_time'
+ || $_SESSION['phn_rec_sort_field'] == 'comment'
+ || $_SESSION['phn_rec_sort_field'] == 'usr_email'
+ || $_SESSION['phn_rec_sort_field'] == 'schstatus') {
+ $prefix = '';
+ }
+ $sort_string = ' ORDER BY '.$prefix.trim($_SESSION['phn_rec_sort_field']);
+ if ($_SESSION['phn_rec_sort_type'] == 'DESC') {
+ $sort_string .= ' DESC, i.id DESC';
+ } else {
+ $sort_string .= ' ASC, i.id ASC';
+ }
+ }
+ return $sort_string ;
+ /*
+ session_start();
+ $sort_string = ' ORDER BY u.id';
+
+ if (isset($_SESSION['phn_rec_sort_field']) && trim($_SESSION['phn_rec_sort_field']) != '') {
+ #$prefix = 'std_'.$_SESSION['phn_rec_sort_field'].'.';
+ $sort_string = ' ORDER BY '.$prefix.trim($_SESSION['phn_rec_sort_field']);
+ if ($_SESSION['phn_rec_sort_type'] == 'DESC') {
+ $sort_string .= ' DESC';
+ } else {
+ $sort_string .= ' ASC';
+ }
+ }
+ return $sort_string;
+ */
+ }
+
+ /**
+ * @desc preveri ce je kaksna nova stevilka (tudi prek ajaxa)
+ */
+ function preveri_stevilke () {
+ global $lang;
+
+ $row = $this->get_next_number();
+
+ if ($row['usr_id'] > 0) {
+ echo '<h2 style="text-align:center">'.$lang['srv_call_next'].':</h2><br />';
+ echo '<h2 style="text-align:center">'.$row['phone'].' - ';
+ echo '<a href="index.php?anketa='.$this->sid.'&a='.A_TELEPHONE.'&m=call&usr_id='.$row['usr_id'].'">'.$lang['srv_call_call'].'</a>';
+ echo '</h2>';
+ } else {
+ echo '<h2 style="text-align:center">'.$lang['srv_call_nonumber'].'</h2><br />';
+
+ $sql1 = sisplet_query("SELECT srv_telephone_schedule.*
+ FROM srv_telephone_schedule, srv_invitations_recipients
+ WHERE
+ srv_invitations_recipients.deleted ='0' AND
+ srv_telephone_schedule.rec_id = srv_invitations_recipients.id AND
+ srv_invitations_recipients.ank_id = '$this->sid' AND
+ srv_telephone_schedule.call_time > NOW() AND
+ srv_telephone_schedule.rec_id NOT IN (
+ SELECT srv_telephone_current.rec_id
+ FROM srv_telephone_current
+ WHERE srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)
+ ) AND
+ srv_telephone_schedule.rec_id NOT IN (
+ SELECT srv_telephone_history.rec_id
+ FROM srv_telephone_history
+ GROUP BY srv_telephone_history.rec_id
+ HAVING COUNT(srv_telephone_history.id) >= '$this->max_calls'
+ )
+ ORDER BY srv_telephone_schedule.call_time ASC LIMIT 1
+ ");
+ $row1 = mysqli_fetch_array($sql1);
+ if (mysqli_num_rows($sql1) > 0)
+ echo '<p style="text-align:center">'.$lang['srv_call_nextcall'].': <b>'.datetime($row1['call_time']).'</b></p>';
+ else
+ echo '<p style="text-align:center">'.$lang['srv_call_nonumbers'].'</p>';
+
+ echo '<script>preveriStevilkeTimer();</script>';
+ }
+ }
+
+ /**
+ * @desc vrne naslednji row s stevilko za klic
+ */
+ function get_next_number () {
+ global $global_user_id;
+
+ # najprej pogledamo ce je kaksen v srv_telephone_current - mor ga obvezno razresiti ker je zaklenjen
+ $sel = "SELECT srv_invitations_recipients.id AS usr_id, TRIM(srv_invitations_recipients.phone) AS text"
+ ." FROM srv_telephone_current LEFT JOIN srv_invitations_recipients ON srv_telephone_current.rec_id = srv_invitations_recipients.id "
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND srv_telephone_current.user_id = $global_user_id"
+ ." AND srv_telephone_current.rec_id = srv_invitations_recipients.id"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ORDER BY srv_invitations_recipients.id ASC"
+ ." LIMIT 1";
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) {
+ return mysqli_fetch_array($sql);
+ }
+
+ // najprej selectamo, tiste ki so zmenjeni po urniku
+ $sel = "SELECT srv_invitations_recipients.id AS usr_id, TRIM(srv_invitations_recipients.phone) AS text, '1' AS schedule"
+ ." FROM srv_telephone_schedule LEFT JOIN srv_invitations_recipients ON srv_telephone_schedule.rec_id = srv_invitations_recipients.id "
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND srv_telephone_schedule.rec_id = srv_invitations_recipients.id"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_telephone_schedule.call_time <= NOW()"
+ ." AND srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_current.rec_id"
+ ." FROM srv_telephone_current"
+ ." WHERE srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT DISTINCT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." WHERE srv_telephone_history.status = 'R' OR srv_telephone_history.status = 'U'"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." GROUP BY srv_telephone_history.rec_id"
+ ." HAVING COUNT(srv_telephone_history.id) >= '$this->max_calls'"
+ ." )"
+ ." ORDER BY srv_telephone_schedule.call_time ASC"
+ ." LIMIT 1";
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) {
+ return mysqli_fetch_array($sql);
+ }
+
+ // ce ni nobenega na urniku pa nadaljujemo z random izbiro ostalih stevilk
+
+ /* fetch random from available
+ * exclude from fetch:
+ * - all phones which are currently active
+ * - all phones which are on the schedule for the future
+ * - all phones which have "R" or "U" status
+ * - all phones which are called more that "max_calls" setting
+ */
+
+ // Sortiranje
+ if($this->call_order == 1)
+ $order_by = ' srv_invitations_recipients.id ASC';
+ elseif($this->call_order == 2)
+ $order_by = ' srv_invitations_recipients.firstname ASC, srv_invitations_recipients.lastname ASC, srv_invitations_recipients.email ASC, srv_invitations_recipients.id ASC';
+ elseif($this->call_order == 3)
+ $order_by = ' srv_invitations_recipients.firstname DESC, srv_invitations_recipients.lastname DESC, srv_invitations_recipients.email DESC, srv_invitations_recipients.id DESC';
+ else
+ $order_by = ' RAND()';
+
+ $sel = "SELECT srv_invitations_recipients.id AS usr_id, TRIM(srv_invitations_recipients.phone) AS text, '0' AS schedule"
+ ." FROM srv_invitations_recipients"
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_current.rec_id"
+ ." FROM srv_telephone_current"
+ ." WHERE srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_schedule.rec_id"
+ ." FROM srv_telephone_schedule"
+ ." WHERE srv_telephone_schedule.call_time > NOW()"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." WHERE srv_telephone_history.status = 'R' OR srv_telephone_history.status = 'U'"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." GROUP BY srv_telephone_history.rec_id"
+ ." HAVING COUNT(srv_telephone_history.id) >= '$this->max_calls'"
+ ." )"
+ ." ORDER BY ".$order_by.""
+ ." LIMIT 1";
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ return mysqli_fetch_array($sql);
+ }
+
+ /**
+ * @desc vrne vse stevilke ki se trenutno klicejo (s pravim vrstnim redom)
+ */
+ function getAllNumbers () {
+ global $global_user_id;
+
+ $result = array();
+
+ # najprej pogledamo ce je kaksen v srv_telephone_current - mor ga obvezno razresiti ker je zaklenjen
+ $sel = "SELECT srv_invitations_recipients.id, TRIM(srv_invitations_recipients.phone) AS phone"
+ ." FROM srv_telephone_current LEFT JOIN srv_invitations_recipients ON srv_telephone_current.rec_id = srv_invitations_recipients.id "
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND srv_telephone_current.user_id = $global_user_id"
+ ." AND srv_telephone_current.rec_id = srv_invitations_recipients.id"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ORDER BY srv_invitations_recipients.id ASC";
+
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) {
+ while ( list($id,$phone) = mysqli_fetch_row($sql)) {
+ $result[$id] = $phone;
+ }
+ }
+
+ # najprej selectamo, tiste ki so zmenjeni po urniku
+ $sel = "SELECT srv_invitations_recipients.id, TRIM(srv_invitations_recipients.phone) AS phone"
+ ." FROM srv_telephone_schedule LEFT JOIN srv_invitations_recipients ON srv_telephone_schedule.rec_id = srv_invitations_recipients.id "
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND srv_telephone_schedule.rec_id = srv_invitations_recipients.id"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_telephone_schedule.call_time <= NOW()"
+ ." AND srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_current.rec_id"
+ ." FROM srv_telephone_current"
+ ." WHERE srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT DISTINCT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." WHERE srv_telephone_history.status = 'R' OR srv_telephone_history.status = 'U'"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." GROUP BY srv_telephone_history.rec_id"
+ ." HAVING COUNT(srv_telephone_history.id) >= '$this->max_calls'"
+ .")"
+ ." ORDER BY srv_invitations_recipients.id ASC";
+
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) {
+ while ( list($id,$phone) = mysqli_fetch_row($sql)) {
+ $result[$id] = $phone;
+ }
+ }
+ # ce ni nobenega na urniku pa nadaljujemo z random izbiro ostalih stevilk
+
+ /* fetch random from available
+ * exclude from fetch:
+ * - all phones which are currently active
+ * - all phones which are on the schedule for the future
+ * - all phones which have "R" or "U" status
+ * - all phones which are called more that "max_calls" setting
+ */
+
+ // Sortiranje
+ if($this->call_order == 1)
+ $order_by = ' srv_invitations_recipients.id ASC';
+ elseif($this->call_order == 2)
+ $order_by = ' srv_invitations_recipients.firstname ASC, srv_invitations_recipients.lastname ASC, srv_invitations_recipients.email ASC, srv_invitations_recipients.id ASC';
+ elseif($this->call_order == 3)
+ $order_by = ' srv_invitations_recipients.firstname DESC, srv_invitations_recipients.lastname DESC, srv_invitations_recipients.email DESC, srv_invitations_recipients.id DESC';
+ else
+ $order_by = ' RAND()';
+
+ $sel = "SELECT srv_invitations_recipients.id, TRIM(srv_invitations_recipients.phone) AS phone"
+ ." FROM srv_invitations_recipients "
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_current.rec_id"
+ ." FROM srv_telephone_current"
+ ." WHERE srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_schedule.rec_id"
+ ." FROM srv_telephone_schedule"
+ ." WHERE srv_telephone_schedule.call_time > NOW()"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." WHERE srv_telephone_history.status = 'R' OR srv_telephone_history.status = 'U'"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." GROUP BY srv_telephone_history.rec_id"
+ ." HAVING COUNT(srv_telephone_history.id) >= '$this->max_calls'"
+ ." )"
+ ."ORDER BY ".$order_by."";
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) {
+ while ( list($id,$phone) = mysqli_fetch_row($sql)) {
+ $result[$id] = $phone;
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * @desc vrne vse stevilke ki so na cakanju in bodo kasneje poklicane
+ */
+ function getAllNumbersWaiting () {
+ $result = array();
+
+ # selectamo, tiste ki so zmenjeni po urniku kasneje
+ $sel = "SELECT srv_invitations_recipients.id, TRIM(srv_invitations_recipients.phone) AS phone"
+ ." FROM srv_telephone_schedule LEFT JOIN srv_invitations_recipients ON srv_telephone_schedule.rec_id = srv_invitations_recipients.id "
+ ." WHERE srv_invitations_recipients.ank_id ='$this->sid'"
+ ." AND srv_invitations_recipients.deleted ='0'"
+ ." AND srv_telephone_schedule.rec_id = srv_invitations_recipients.id"
+ ." AND TRIM(srv_invitations_recipients.phone) != ''"
+ ." AND srv_telephone_schedule.call_time > NOW()"
+ ." AND srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_current.rec_id"
+ ." FROM srv_telephone_current"
+ ." WHERE srv_telephone_current.started_time >= DATE_SUB(NOW(), INTERVAL 2 HOUR)"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT DISTINCT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." WHERE srv_telephone_history.status = 'R' OR srv_telephone_history.status = 'U'"
+ ." ) AND"
+ ." srv_invitations_recipients.id NOT IN ("
+ ." SELECT srv_telephone_history.rec_id"
+ ." FROM srv_telephone_history"
+ ." GROUP BY srv_telephone_history.rec_id"
+ ." HAVING COUNT(srv_telephone_history.id) >= '$this->max_calls'"
+ .")"
+ ." ORDER BY srv_telephone_schedule.call_time ASC";
+
+ $sql = sisplet_query($sel);
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ if (mysqli_num_rows($sql) > 0) {
+ while ( list($id,$phone) = mysqli_fetch_row($sql)) {
+ $result[$id] = $phone;
+ }
+ }
+
+ return $result;
+ }
+
+ function addMark($options = array()) {
+ global $site_url,$global_user_id;
+
+ if (is_array($options) && isset($options['usr_id']) && (int)$options['usr_id'] > 0) {
+ $usr_id = $options['usr_id'];
+ } else {
+ $usr_id = $_GET['usr_id'];
+ }
+ if (is_array($options) && isset($options['status']) && (int)$options['status'] > 0) {
+ $status = $options['status'];
+ } else {
+ $status = $_GET['status'];
+ }
+ if (is_array($options) && isset($options['datetime']) && (int)$options['datetime'] > 0) {
+ $datetime = $options['status'];
+ } else {
+ $datetime = $_GET['datetime'];
+ }
+ if ($status != '') {
+ sisplet_query("INSERT INTO srv_telephone_history (survey_id, user_id, rec_id, insert_time, status) VALUES ('$this->sid', '".$global_user_id."', '$usr_id', NOW(), '$status')");
+ }
+
+ if ($status != 'A') {
+ sisplet_query("DELETE FROM srv_telephone_current WHERE rec_id='$usr_id'");
+ } else {
+ $s = sisplet_query("INSERT INTO srv_telephone_current (rec_id, user_id, started_time) VALUES ('$usr_id', '".$global_user_id."', NOW())");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ if ($status == 'Z') {
+ $s = sisplet_query("INSERT INTO srv_telephone_schedule (rec_id, call_time) VALUES ('$usr_id', NOW() + INTERVAL $this->status_z MINUTE) ON DUPLICATE KEY UPDATE call_time = VALUES(call_time)");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ if ($status == 'N') {
+ $s = sisplet_query("INSERT INTO srv_telephone_schedule (rec_id, call_time) VALUES ('$usr_id', NOW() + INTERVAL $this->status_n MINUTE) ON DUPLICATE KEY UPDATE call_time = VALUES(call_time)");
+ }
+ if ($status == 'D') {
+ $s = sisplet_query("INSERT INTO srv_telephone_schedule (rec_id, call_time) VALUES ('$usr_id', NOW() + INTERVAL $this->status_d MINUTE) ON DUPLICATE KEY UPDATE call_time = VALUES(call_time)");
+ }
+ if ($status == 'T' || $status == 'P') {
+ $datetime = substr($datetime,6,4).'-'.substr($datetime,3,2).'-'.substr($datetime,0,2).' '.substr($datetime,11,5).':00';
+ $s = sisplet_query("INSERT INTO srv_telephone_schedule (rec_id, call_time) VALUES ('$usr_id', '$datetime') ON DUPLICATE KEY UPDATE call_time = VALUES(call_time)");
+ }
+
+ # če je zavrnil (R) potem izbrišemo morebitne zmenke
+ if ($status == 'R' ) {
+ sisplet_query("DELETE FROM srv_telephone_schedule WHERE rec_id='$usr_id'");
+ }
+
+ #nardimo pravilne redirekte
+
+ # ker imamo spodaj exit de ne izvede klasičen komit
+ sisplet_query('COMMIT');
+
+ if ($status == 'A') {
+ header("Location: index.php?anketa=$this->sid&a=".A_TELEPHONE."&m=call&usr_id=".$usr_id.'&status='.$status);
+ exit();
+
+ } else {
+ session_start();
+ if (isset($_SESSION['phnNextAction'][$this->sid]) && (int)$_SESSION['phnNextAction'][$this->sid] == '0') {
+ # če je anketar je lako samo na klicanu
+ if ($this->isAnketar) {
+ header("Location: index.php?anketa=$this->sid&a=".A_TELEPHONE."&m=call"); #'&status='.$status
+ exit();
+ }
+ header("Location: index.php?anketa=$this->sid&a=".A_TELEPHONE."&m=view_recipients");
+ exit();
+ } else {
+ header("Location: index.php?anketa=$this->sid&a=".A_TELEPHONE."&m=call"); #.'&status='.$status
+ exit();
+ }
+ }
+ }
+
+ function preveriStevilkeTimer () {
+ $this->preveri_stevilke();
+ }
+
+ function addRecipients() {
+ global $global_user_id;
+
+ $fields = $_POST['fields'];
+ $_recipients = $_POST['recipients_list'];
+ $recipients_list = str_replace("\n\r", "\n", $recipients_list);
+
+ # povezava imena polji iz forem, z imeni polji v bazi
+ $db_vs_form_array = array(
+ 'inv_field_email' => 'email',
+ 'inv_field_firstname' => 'firstname',
+ 'inv_field_lastname' => 'lastname',
+ 'inv_field_password' => 'password',
+ 'inv_field_cookie' => 'cookie',
+ 'inv_field_salutation' => 'salutation',
+ 'inv_field_phone' => 'phone',
+ 'inv_field_custom' => 'custom',
+ );
+
+ $fields = $_POST['fields'];
+ if (!is_array($fields)) {
+ $fields = array();
+ }
+
+ # katero polje je za password
+ if (in_array('inv_field_password',$fields)) {
+ $user_password = true;
+ } else {
+ $user_password = false;
+ }
+
+ #dodamo potrebna sistemska polja
+ $this->addSystemVariables($fields);
+
+ # dodamo ustrezne uporabnike, neustrezne izpišemo še enkrat da se lahko popravijo
+ $_recipients = str_replace("\n\r", "\n", $_recipients);
+ $recipients_list = explode("\n",$_recipients);
+ $num_recipients_list = count($recipients_list);
+
+ # katero polje je za e-mail
+ if (in_array('inv_field_email',$fields)) {
+ $user_email = true;
+ } else {
+ }
+
+ # polje cookie mora bit zraven
+ if (!in_array('inv_field_cookie',$fields)) {
+ $fields[] = 'inv_field_cookie';
+ }
+
+ # polovimo že dodane prejemnike iz baze
+ $user_in_db = array();
+ $sql_string = "SELECT firstname,lastname,salutation,phone,custom FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0'";
+ $sql_query = sisplet_query($sql_string);
+
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $user_in_db[] = $sql_row['firstname'].$sql_row['lastname'].$sql_row['salutation'].$sql_row['phone'].$sql_row['custom'];
+ }
+ }
+ # katero polje je za password
+ if (in_array('inv_field_password',$fields)) {
+ $user_password = true;
+ } else {
+ $user_password = false;
+ # dodamo polje password
+ $fields[] = 'inv_field_password';
+ }
+
+ # polja za bazo
+ $db_fields = '';
+ foreach ($fields as $field) {
+ $db_fields .= ', '.$db_vs_form_array[$field];
+ }
+
+ # katera gesla (code) že imamo v bazi za to anketo
+ $password_in_db = array();
+ $sql_string = "SELECT password FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0'";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $password_in_db[$sql_row['password']] = $sql_row['password'];
+ }
+
+ $unsubscribed = array();
+ /*polovimo prejemnike ki ne želijo prejemati obvestil
+
+ $sql_string = "SELECT email FROM srv_invitations_recipients WHERE unsubscribed = '1'";
+ $sql_query = sisplet_query($sql_string);
+ $unsubscribed = array();
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $unsubscribed[] = $sql_row['email'];
+ }
+ }*/
+
+ #array z veljavnimi zapisi
+ $valid_recipiens_array = array();
+ # array z zapisi kjer so napake v geslih
+ $invalid_password_array = array();
+ #array z zapisi kjer so neveljavna gesla
+ $invalid_email_array = array();
+ #array z podvojenimi zapisi
+ $duplicate_email_array = array();
+ #aray z zapisi kjer so uporabniki izbrali da ne želijo prejemat e-mailov
+ $unsubscribed_recipiens_array = array();
+
+ if ( $num_recipients_list > 0 ) {
+ foreach ($recipients_list AS $recipient_line) {
+ $recipient_line = trim($recipient_line);
+ if ($recipient_line != null && $recipient_line != '') {
+ $line_array = explode(',',$recipient_line);
+ # predpostavljamo da je vrstica vredu
+ $invalid_line = false;
+
+ #prilagodimo izbrana polja
+ $recipent_array = array();
+ $i = 0;
+ foreach ($fields AS $field) {
+ $recipent_array[$field] = $line_array[$i];
+ $i++;
+ }
+
+ # izvedemo validacijo posameznih polij
+
+ # najprej preverimo gesla, če niso uporabniško določena, jih dodelimo sami
+ if ( $invalid_line == false ) {
+ # če še ni bilo napake ( da ne podvajamo zapisov pri katerih je več napak)
+ if ($user_password == false) {
+ # gesla določamo avtomatsko, (ne bo problemov :] )
+
+ # Izberemo random hash, ki se ni v bazi
+ do {
+ list($code,$cookie) = $this->generateCode();
+ } while (in_array($code,$password_in_db));
+ # polje za geslo je na zadnjem mestu (smo ga dodali zgoraj)
+ $recipent_array['inv_field_password'] = $code;
+ $recipent_array['inv_field_cookie'] = $cookie;
+
+ # če je vse ok, geslo dodamo v seznam že uporabljenih
+ $password_in_db[$code] = $code;
+
+ } else {
+ # gesla je določil uporabnik, (dajmo ga malo preverit)
+ $user_password = trim($recipent_array['inv_field_password']);
+
+ # preverimo ali je geslo že v bazi
+ if ($user_password == null || $user_password == '' || in_array($user_password,$password_in_db)) {
+ $invalid_password_array[] = $recipient_line;
+ $invalid_line = true;
+ }
+
+ # če je vse ok, geslo dodamo v seznam že uporabljenih
+ if ($invalid_line == false) {
+ $password_in_db[$user_password] = $user_password;
+ #dodamo še piškotek
+ list($code,$cookie) = $this->generateCode();
+ $recipent_array['inv_field_cookie'] = $cookie;
+ }
+ }
+ }
+ # če imamo emaile naredimo validacijo, preverimo zavrnitve.. itd
+ // if ($user_email == true && $invalid_line == false) {
+ if ($invalid_line == false) {
+ # # preberemo uporabniški email
+ $email_field = trim($recipent_array['inv_field_firstname'])
+ . trim($recipent_array['inv_field_lastname'])
+ . trim($recipent_array['inv_field_salutation'])
+ . trim($recipent_array['inv_field_phone'])
+ . trim($recipent_array['inv_field_custom']);
+
+
+ /* #ali je email veljaven
+ if (!$this->validEmail($email_field) && $invalid_line == false) {
+ $invalid_email_array[] = $recipient_line;
+ $invalid_line = true;
+ }*/
+
+ # ali je email podvojen
+ if (in_array(strtolower($email_field),$user_in_db) && $invalid_line == false) {
+ $duplicate_email_array[] = strtolower($recipient_line);
+ $invalid_line = true;
+ }
+
+ /* ali uporabnik ne želi prejemati sporočil (opted out)
+ if (in_array($email_field,$unsubscribed) && $invalid_line == false) {
+ $unsubscribed_recipiens_array[] = $recipient_line;
+ $invalid_line = true;
+ }*/
+
+ # če je vse ok, email dodamo v seznam že uporabljenih
+ if ( $invalid_line == false) {
+ $user_in_db[] = $email_field;
+ }
+ }
+ # če je vse ok dodamo userja k veljavnim
+ if ( $invalid_line == false) {
+ $valid_recipiens_array[] = $recipent_array;
+ }
+
+ }
+ }
+ }
+
+ $list_id = (int)$_POST['pid'];
+
+ # pripravimo sql stavek za vstavljanje
+ if (count($valid_recipiens_array ) > 0) {
+ $sql_insert_start = "INSERT INTO srv_invitations_recipients (ank_id".$db_fields.",sent,responded,unsubscribed,deleted,date_inserted,inserted_uid,list_id) VALUES ";
+ $count = 0;
+
+ $sql_insert_array = array();
+ $cnt = 0;
+ $max_in_array = 1000; # po koliko respondentov dodajamo naenkeat
+ $array_loop = 0;
+ foreach ( $valid_recipiens_array AS $recipent_fields) {
+ $cnt++;
+ $sql_insert = "('".$this->sid."'";
+ foreach ($recipent_fields as $field) {
+ $sql_insert .= ", '$field'";
+ }
+ $sql_insert .= ",'0','0','0','0',NOW(),'".$global_user_id."','".$list_id."')";
+ $sql_insert_array[$array_loop][] = $sql_insert;
+ if ($cnt >= $max_in_array) {
+ $array_loop++;
+ $cnt = 0;
+ }
+ }
+ $sql_insert_end = " ON DUPLICATE KEY UPDATE firstname=VALUES(firstname), lastname=VALUES(lastname), salutation=VALUES(salutation), phone=VALUES(phone), custom=VALUES(custom), deleted='0', date_inserted=NOW()";
+
+ # v loopu dodamo posamezne respondente po skupinah (ker kadar je respondentov veliko mysql crkne)
+ if (count($sql_insert_array) > 0) {
+ foreach ($sql_insert_array AS $sub_insert_array) {
+ $query_insert = $sql_insert_start. implode(',',$sub_insert_array) .$sql_insert_end;
+ $sqlQuery = sisplet_query($query_insert);
+ $rows = mysqli_affected_rows($GLOBALS['connect_db']);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ sisplet_query("COMMIT");
+
+ }
+ }
+
+ return array( 'valid_recipiens' => $valid_recipiens_array,
+ 'invalid_password' => $invalid_password_array,
+ 'invalid_email' => $invalid_email_array,
+ 'duplicate_email' => $duplicate_email_array,
+ 'unsubscribed' => $unsubscribed_recipiens_array);
+ }
+
+
+ function addSystemVariables($variables) {
+ $user_base = 0;
+ global $site_path;
+ $system_fields = array(
+ 'inv_field_email' => 'email',
+ 'inv_field_firstname' => 'ime',
+ 'inv_field_lastname' => 'priimek',
+ # 'inv_field_password' => 'geslo', # gesla ne dodajamo kot sistemsko spremenljivko
+ 'inv_field_salutation' => 'naziv',
+ 'inv_field_phone' => 'telefon',
+ 'inv_field_custom' => 'drugo',
+ );
+ $variablesResult=array();
+ $sqlb = sisplet_query("SELECT branching, user_base FROM srv_anketa WHERE id = '".$this->sid."'");
+ $rowb = mysqli_fetch_array($sqlb);
+
+ $ba = new BranchingAjax($this->sid);
+ if (count($variables) > 0) {
+
+ // zakaj je bi ta reverse???
+ //$variables = array_reverse($variables,true);
+ foreach ($variables as $var) {
+ if (isset($system_fields[$var])) {
+ $spr_id = null;
+
+ if (isset($system_fields[$var])) {
+ $variable = $system_fields[$var];
+ } else {
+ $variable = str_replace('inv_field_', '', $var);
+ }
+
+ $sqlVariable = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.variable='".$variable."' AND s.gru_id=g.id AND g.ank_id='".$this->sid."'");
+ if (mysqli_num_rows($sqlVariable) == 0 && $variable!='pass') { // če varabla še ne obstaja jo kreiramo
+ // za polje pass - Geslo ne kreiramo sistemske variable
+
+ if ($variable != 'language') {
+ $user_base = 1;
+ }
+
+ // dodamo novo spremenljivko na konec, tip je 21
+ ob_start();
+ $ba->ajax_spremenljivka_new(0, 0, 1, 0, 21);
+ $spr_id = $ba->spremenljivka;
+ ob_clean();
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET variable='".$variable."', variable_custom='1', naslov='".$variable."', sistem='1', visible='0' WHERE id='$spr_id'");
+ if (!$s) echo 'err435'.mysqli_error($GLOBALS['connect_db']);
+
+ } else {
+ list($spr_id) = mysqli_fetch_row($sqlVariable);
+ }
+ $variablesResult[$variable] = (int)$spr_id;
+
+ }
+ }
+ }
+ // če je potreben updejt (ampak najbrž je itak na 1 zaradi e-mail)
+ if ($user_base > 0 && $user_base != $rowb['user_base']) {
+ $sql = sisplet_query("UPDATE srv_anketa SET user_base='$user_base' WHERE id='" . $this->sid . "'");
+ SurveyInfo :: getInstance()->resetSurveyData();
+ }
+
+ return $variablesResult;
+ }
+
+ function generateCode() {
+ $cookie = md5(mt_rand(1, mt_getrandmax()) . '@' . $_SERVER['REMOTE_ADDR']);
+
+ return array(substr($cookie,0,6), $cookie);
+ }
+
+ function displayRecipentsErrors($result) {
+ global $lang;
+ $valid_recipiens = is_array($result['valid_recipiens']) ? $result['valid_recipiens'] : array();
+ $invalid_password = is_array($result['invalid_password']) ? $result['invalid_password'] : array();
+ $insert_errors = is_array($result['insert_errors']) ? $result['insert_errors'] : array();
+
+ # dodani so bili nekateri uporabniki
+ if (count($valid_recipiens) > 0) {
+ echo '<div id="inv_recipiens_added">';
+ echo $lang['srv_inv_recipiens_add_success_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList1\').toggle();">'. count($valid_recipiens).'</span></span><br>';
+ echo '<div id="invRecipiensList1" class="displayNone"><br/>';
+ foreach ($valid_recipiens AS $fields) {
+ if (is_array($fields)) {
+ echo strtolower($fields['telefon']);
+ if (trim($fields['ime']) != '') {
+ echo ', '.$fields['ime'];
+ }
+ if (trim($fields['priimek']) != '') {
+ echo ', '.$fields['priimek'];
+ }
+ } else {
+ echo strtolower($fields);
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+ echo '</div>';
+ }
+
+ if ( (count($invalid_password) + count($insert_errors) ) > 0 ) {
+ echo '<div id="inv_recipiens_rejected">';
+
+ # ni veljavnih uporabnikov
+ if (count($valid_recipiens) == 0 ) {
+ echo $lang['srv_inv_recipiens_add_error'].'<br/>';
+ }
+
+
+ # neveljavena gesla
+ if (count($invalid_password) > 0) {
+ echo $lang['srv_inv_recipiens_add_invalid_password_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList5\').toggle();">'.count($invalid_password).'!</span></span><br />';
+ echo '<div id="invRecipiensList5" class="displayNone"><br/>';
+ foreach ($invalid_password AS $fields) {
+ if (is_array($fields)) {
+ echo strtolower($fields['telefon']);
+ if (trim($fields['ime']) != '') {
+ echo ', '.$fields['ime'];
+ }
+ if (trim($fields['priimek']) != '') {
+ echo ', '.$fields['priimek'];
+ }
+ } else {
+ echo strtolower($fields);
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+ }
+
+ # napake pri insertiranju
+ if (count($insert_errors) > 0) {
+ echo $lang['srv_inv_recipiens_add_invalid_password_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList5\').toggle();">'.count($invalid_password).'!</span></span><br />';
+ echo '<div id="invRecipiensList5" class="displayNone"><br/>';
+ foreach ($insert_errors AS $fields) {
+ if (is_array($fields)) {
+ echo strtolower($fields['telefon']);
+ if (trim($fields['ime']) != '') {
+ echo ', '.$fields['ime'];
+ }
+ if (trim($fields['priimek']) != '') {
+ echo ', '.$fields['priimek'];
+ }
+ } else {
+ echo strtolower($fields);
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+ }
+
+ echo '</div>';
+
+ return array_merge($invalid_password, $insert_errors) ;
+ }
+ return array();
+ }
+
+ function setNextAction() {
+ $phnNextAction = (int)$_REQUEST['phnNextAction'];
+ session_start();
+ $_SESSION['phnNextAction'][$this->sid] =$phnNextAction;
+ session_commit();
+ }
+
+ function getNextTimeCall() {
+ global $lang;
+ echo '<h2>'.$lang['srv_call_nonumber'].'</h2>';
+
+ # preverimo ali imamo kaj na shedučling
+ $str = "SELECT DATE_FORMAT(MIN(scs.call_time), '%d.%m.%Y %H:%i:%s') AS minTime"
+ ." FROM srv_telephone_schedule AS scs LEFT JOIN srv_invitations_recipients AS sir ON scs.rec_id = sir.id WHERE sir.ank_id='$this->sid' AND sir.deleted='0'";
+ $qry = sisplet_query($str);
+ if (mysqli_num_rows($qry) > 0) {
+ list($nextTime) = mysqli_fetch_row($qry);
+
+ echo $lang['srv_call_nonumbers_time'];
+ echo ' <span class="strong">'.$nextTime.'</span>';
+ }
+ }
+
+ function setUserComment() {
+
+ $usr_id = (int)$_POST['usr_id'];
+ $comment = $_POST['comment'];
+
+ $comment = trim(strip_tags($comment));
+
+ $strInsert = "INSERT INTO srv_telephone_comment (rec_id, comment_time, comment) VALUES ('$usr_id', NOW(), '$comment') ON DUPLICATE KEY UPDATE comment_time = VALUES(comment_time), comment = VALUES(comment)";
+ $qryInsert = sisplet_query($strInsert);
+ }
+
+ function getProfileName(){
+ global $lang,$site_url, $global_user_id;
+
+ $array_profiles = array();
+
+ # polovimo še ostale porfile
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."') AND from_survey = '".$this->sid. "'";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $array_profiles[$sql_row['pid']] = array('name' => $sql_row['name'], 'comment'=>$sql_row['comment']);
+ }
+
+
+ echo '<div id="inv_recipients_profile_name">';
+ echo '<span class="inv_new_list_note">';
+ echo $lang[''].'Izberite seznam kamor želite dodati prejemnike. Izbirate lahko med:<br/><ul><li>\'Nov seznam\' - prejemniki se dodajo v nov seznam, kateremu določite ime</li><li>\'Začasen seznam\' - seznam obstaja samo v času seje brskalnika</li><li>ali izberete obstoječ seznam, h kateremu se bodo dodali prejemniki</li></ul><br/>';
+ echo '</span>';
+ echo $lang['srv_invitation_recipients_list_add'].':&nbsp;';
+ echo '<select id="profile_id" onchange="inv_new_recipients_list_change(this);" autofocus="autofocus" tabindex="2">';
+ echo '<option value="0" class="gray bold"'.((int)$_POST['pid'] > 0 ? '' : ' selected="selected"' ).'>'.$lang['srv_invitation_new_list'].'</option>';
+ echo '<option value="-1" class="gray bold">'.$lang['srv_invitation_new_templist'].'</option>';
+ if (count($array_profiles) > 0){
+ foreach($array_profiles AS $key => $profile) {
+ echo '<option value="'.$key.'" comment="'.$profile['comment'].'"'.($_POST['pid'] == $key ? ' selected="selected"' : '').'>'.$profile['name'].'</option>';
+ }
+ }
+ echo '</select>';
+ echo '<span id="new_recipients_list_span" '.((int)$_POST['pid'] > 0 ? ' class="displayNone"' : '' ).'>';
+ echo '<br><br/>';
+ echo '<label>'.$lang['srv_inv_recipient_list_name'];
+ # zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ $new_name = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id' AND from_survey='$this->sid'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q)) {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+
+ echo '<input type="text" id="rec_profile_name" value="'.$new_name.'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+ echo '<br/><br/>';
+ echo $lang['srv_inv_recipient_list_comment'];
+ echo '<textarea id="rec_profile_comment" tabindex="3" rows="2" ></textarea>';
+ echo '<br class="clr" /><br class="clr" />';
+ echo '<span class="buttonwrapper floatLeft spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="phnSaveNewProfile(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</div>'; # id="inv_view_arch_recipients"
+ echo '<script type="text/javascript">';
+ echo "$('#rec_profile_name').focus();";
+ echo '</script>';
+ }
+
+ function saveNewProfile() {
+ global $lang, $global_user_id;
+
+ $profile_id = (int)$_POST['profile_id'];
+ $profile_name = $_POST['profile_name'];
+ $profile_comment = $_POST['profile_comment'];
+ $recipients_list = $_POST['recipients_list'];
+ $fields = str_replace('inv_field_','',implode(',',$_POST['fields']));
+
+ if (trim($fields) != '' && trim($recipients_list) != '') {
+ if ($profile_id < 0) {
+ # shranimo v začasen profil
+ session_start();
+ $_SESSION['phn_rec_profile'][$this->sid] = array(
+ 'pid'=>-1,
+ 'name'=>$lang['srv_invitation_new_templist'],
+ 'fields'=>$fields,
+ 'respondents'=>$recipients_list,
+ 'comment'=>$profile_comment
+ );
+ } else if ($profile_id == 0) {
+ #shranjujemo v nov profil
+
+ # dodelimo ime
+ #zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ if($profile_name == ''){
+ $new_name = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id' AND from_survey='$this->sid'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q)) {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+ }
+ else{
+ $new_name = $profile_name;
+ }
+
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles".
+ " (name,uid,fields,respondents,insert_time,comment, from_survey) ".
+ " VALUES ('$new_name', '$global_user_id', '$fields', '$recipients_list', NOW(), '$profile_comment', '$this->sid' )";
+ $sqlQuery = sisplet_query($sql_insert);
+ if (!$sqlQuery) {
+ $return['success'] = '0';
+ $return['msg'] = mysqli_error($GLOBALS['connect_db']);
+ } else {
+ $return['success'] = '1';
+ $return['pid'] = mysqli_insert_id($GLOBALS['connect_db']);
+
+ }
+ } else {
+ $this->saveProfile(array('pid'=>$profile_id,'fields'=>$fields,'recipients'=>$recipients_list));
+ }
+ }
+ list($recipients_list,$fields) = $this->getRecipientsProfile($profile_id);
+ $_POST['pid'] = $profile_id;
+ $this->addRecipientsView($fields,$recipients_list);
+ }
+
+ function saveProfile($atributes) {
+ $pid = (int)$atributes['pid'];
+ $fields = $atributes['fields'];
+ $recipients = $atributes['recipients'];
+ $comment = $atributes['comment'] !== null ? ", comment='".$atributes['comment']."' " : '';
+ if (trim($fields) != '' && trim($recipients) != '' && $pid > 0) {
+ # updejtamo obstoječ profil
+ $sql_update = " UPDATE srv_invitations_recipients_profiles".
+ " SET fields = '$fields', respondents ='$recipients', insert_time=NOW() $comment WHERE pid = '$pid'";
+ $sqlQuery = sisplet_query($sql_update);
+ }
+
+ if (!$sqlQuery) {
+ $return['success'] = '0';
+ $return['msg'] = mysqli_error($GLOBALS['connect_db']);
+ } else {
+ $return['success'] = '1';
+ $return['pid'] = $pid;
+ }
+ list($recipients_list,$fields) = $this->getRecipientsProfile($pid);
+ $_POST['pid'] = $pid;
+ $this->addRecipientsView($fields,$recipients_list);
+ }
+
+ function deleteProfile() {
+ global $global_user_id;
+ $id = (int)$_POST['pid'];
+ if ((int)$id > 0) {
+
+ $sql_string = "DELETE FROM srv_invitations_recipients_profiles WHERE pid='".$id."' ";
+ $sqlQuery = sisplet_query($sql_string);
+ sisplet_query("COMMIT");
+ }
+ }
+
+ function editProfile() {
+ global $lang, $site_url, $global_user_id;
+ $return = array('error'=>'0');
+ $pid = (int)$_POST['pid'];
+ if ($pid > 0) {
+ $sql_string = "SELECT name, comment, respondents FROM srv_invitations_recipients_profiles WHERE pid='".$pid."'";
+ $sqlQuery = sisplet_query($sql_string);
+ $sqlRow = mysqli_fetch_assoc($sqlQuery);
+
+ echo '<div id="inv_recipients_profile_name">';
+ echo '<div id="inv_error_note" class="hidden"></div>';
+ echo '<table>';
+ echo '<tr><td>'.$lang['srv_inv_recipient_list_name'].'</td>';
+ echo '<td>';
+ echo '<input type="text" id="rec_profile_name" value="'.$sqlRow['name'].'" autofocus="autofocus">';
+ echo '</td></tr>';
+ echo '<tr><td>'.$lang['srv_inv_recipient_list_comment'].'</td>';
+ echo '<td>';
+ echo '<input type="text" id="rec_profile_comment" value="'.$sqlRow['comment'].'" >';
+ echo '</td></tr>';
+ echo '<tr><td>'.$lang['srv_inv_recipient_list_recipients'].'</td>';
+ echo '<td>';
+ echo '<textarea id="rec_profile_respondents" style="width:250px; height:150px;">'.$sqlRow['respondents'].'</textarea>';
+ echo '</td></tr>';
+ echo '</table>';
+
+ echo '<input type="hidden" id="rec_profile_pid" value="'.$pid.'" >';
+
+ echo '<br class="clr" /><br class="clr" />';
+ echo '<span class="buttonwrapper floatLeft spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="phnUpdateProfile(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</div>'; # id="inv_view_arch_recipients"
+
+ }
+ }
+
+ function updateProfile() {
+ global $lang,$site_url, $global_user_id;
+ $return = array('error'=>'0', 'msg'=>'');
+ $pid = (int)(int)$_POST['pid'];
+
+ $profile_name = (isset($_POST['profile_name']) && trim($_POST['profile_name']) != '') ? trim($_POST['profile_name']) : '';
+ $profile_comment = (isset($_POST['profile_comment']) && trim($_POST['profile_comment']) != '') ? trim($_POST['profile_comment']) : '';
+ $profile_respondents = (isset($_POST['profile_respondents']) && trim($_POST['profile_respondents']) != '') ? trim($_POST['profile_respondents']) : '';
+ if ($pid > 0) {
+
+ if ($profile_name != '') {
+ $sql_update = "UPDATE srv_invitations_recipients_profiles SET name = '$profile_name', comment = '$profile_comment', respondents = '$profile_respondents' WHERE pid = '$pid'";
+ $sqlQuery = sisplet_query($sql_update);
+ sisplet_query("COMMIT");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error);
+ } else {
+ $return = array('error'=>'0', 'msg'=>$sql_update);
+
+ }
+ sisplet_query("COMMIT");
+ } else {
+ $return = array('error'=>'1', 'msg'=>$lang['srv_inv_msg_1']);
+ }
+
+ } else {
+ $return = array('error'=>'1', 'msg'=>$lang['srv_inv_msg_2']);
+ }
+
+ echo json_encode($return);
+ return json_encode($return);
+ }
+
+ function goToUser() {
+ $usr_id = (int)$_POST['showUser'];
+ $this->userCallToShow($usr_id,false,false);
+ }
+
+
+ function userCallToShow($usr_id,$openedSurvey,$schedule) {
+ global $lang;
+ global $site_url;
+ global $site_root;
+
+ $sql1 = sisplet_query("SELECT * FROM srv_invitations_recipients WHERE id = '$usr_id' AND deleted='0'");
+ $row1 = mysqli_fetch_array($sql1);
+
+ echo '<table id="phn_call_table">';
+ # echo '<table style="width:100%" border="1">';
+ echo '<tr>
+ <th style="width:33%">'.$lang['srv_telephone_table_history'].'</th>
+ <th style="width:33%">'.$lang['srv_telephone_table_calling'].'</th>
+ <th style="width:34%">'.$lang['srv_telephone_table_comments'].'</th>
+ </tr>';
+
+ echo '<tr><td valign="top">';
+ $canCall = true;
+ $userStatus = array();
+ $last_status = '';
+ $sql2 = sisplet_query("SELECT DATE_FORMAT(insert_time, '%d.%m.%Y %H:%i:%s'), status FROM srv_telephone_history WHERE rec_id='$usr_id' ORDER BY insert_time ASC");
+ if (mysqli_num_rows($sql2) > 0 ) {
+ while (list($insert_time, $status) = mysqli_fetch_array($sql2)) {
+ echo '<p>'.$insert_time.' - <strong>'.$lang['srv_telephone_status_'.$status].'</strong></p>';
+ if ($status == 'U' || $status == 'R') {
+ # preverimo ali lahko uporabnika še kontaktiramo
+ $canCall = false;
+ }
+ $userStatus[$status] = true;
+ $last_status = $status;
+ }
+ } else {
+ echo $lang['srv_telephone_status_'];
+ }
+ echo '</td>';
+
+ echo '<td valign="top">';
+ if ($canCall == true) {
+ if ($openedSurvey) {
+ # zaprli smo aktivno anketo, prikažemo naslednji korak oz. izbiro zaključne akcije
+ echo '<h2 class="red">'.$lang['srv_telephone_calling_number_end'].'</h2>';
+ echo '<h2 class="red">'.$row1['phone'].'</h2>';
+
+ } else {
+ echo '<h2 class="red">'.$lang['srv_telephone_calling_number'].($schedule == true ? $lang['srv_telephone_call_was_schedule']:'').'</h2>';
+ echo '<h2 class="red">'.$row1['phone'].'</h2>';
+ }
+
+ if($row1['firstname'] != '')
+ echo '<h2>'.$lang['name'].': '.$row1['firstname'].'</h2>';
+ if($row1['lastname'] != '')
+ echo '<h2>'.$lang['surname'].': '.$row1['lastname'].'</h2>';
+ if($row1['email'] != '')
+ echo '<h2>'.$lang['email'].': '.$row1['email'].'</h2>';
+ if($row1['custom'] != '')
+ echo '<h2>Custom: '.$row1['custom'].'</h2>';
+ }
+ else {
+ # onemogočimo ponovno klicanje uporabnika ker je zaključena ali je zavrnil
+ echo'<h2 class="red">';
+ if (isset($userStatus['U'])) {
+ echo $lang['srv_telephone_call_action_cant_edit_U'];
+ } elseif (isset($userStatus['R'])) {
+ echo $lang['srv_telephone_call_action_cant_edit_R'];
+ }
+ echo'</h2>';
+ echo '<h2 class="red">'.$row1['phone'].'</h2>';
+
+ if($row1['firstname'] != '')
+ echo '<h2>'.$lang['name'].': '.$row1['firstname'].'</h2>';
+ if($row1['lastname'] != '')
+ echo '<h2>'.$lang['surname'].': '.$row1['lastname'].'</h2>';
+ if($row1['email'] != '')
+ echo '<h2>'.$lang['email'].': '.$row1['email'].'</h2>';
+ if($row1['custom'] != '')
+ echo '<h2>Custom: '.$row1['custom'].'</h2>';
+
+ echo $lang['srv_telephone_calling_next_step'];
+ echo '<div style="padding-left: 20px;">';
+ echo '<p class="bold"><a href="'.$this->addUrl('view_recipients').'">'.$lang['srv_telephone_call_action_view_recipients'].'</a></p>';
+ echo '</div>';
+ }
+
+
+ #Uvod
+ $intro = $this->surveySettings['introduction'];
+ if (trim($intro) == '') {
+ $intro = $lang['srv_intro'];
+ }
+
+ echo '<p>'.$lang['srv_telephone_call_introduction'];
+ echo '<div class="phn_user_intro">';
+ echo $intro;
+ echo '</div>';
+ echo '</p>';
+ echo '<br/>';
+
+ echo '</td>';
+
+ echo '<td valign="top">';
+
+
+ if ($canCall == true) {
+ if ($openedSurvey) {
+ # zaprli smo aktivno anketo, prikažemo naslednji korak oz. izbiro zaključne akcije
+ echo '<p class="red strong">'.$lang['srv_telephone_calling_step_action'].'</p>';
+ } else {
+ echo '<p class="red strong">'.$lang['srv_telephone_calling_next_step'].'</p>';
+ }
+
+ echo '<div style="padding-left: 20px;">';
+ if ($openedSurvey) {
+ # uporqabnik je odprl anketo
+ echo '<p><a href="ajax.php?anketa='.$this->sid.'&t='.A_TELEPHONE.'&m=addmark&usr_id='.$usr_id.'&status=U">'.$lang['srv_call_successful2'].'</a></p>';
+ } else {
+ # uporabnik še ni odprl ankete
+ echo '<p><span class="as_link" onclick="phnStartSurvey(\''.$usr_id.'\');">'.$lang['srv_call_open_startCall'].$lang['srv_call_open'].'</span></p>';
+ }
+ if ($openedSurvey) {
+ } else {
+ # če smo na userju, potem smo ga dobili, zato ne more bit nedosegljiv ali zaseden
+ echo '<p><a href="ajax.php?anketa='.$this->sid.'&t='.A_TELEPHONE.'&m=addmark&usr_id='.$usr_id.'&status=Z">'.$lang['srv_call_zaseden'].'</a></p>';
+ echo '<p><a href="ajax.php?anketa='.$this->sid.'&t='.A_TELEPHONE.'&m=addmark&usr_id='.$usr_id.'&status=N">'.$lang['srv_call_ga_ni'].'</a></p>';
+ }
+
+ echo '<p><a href="#" onclick="phnShowPopupAddMarker(\''.$usr_id.'\',\'T\'); return false;">'.$lang['srv_call_zmenjen'].'</a></p>';
+ echo '<p><a href="#" onclick="phnShowPopupAddMarker(\''.$usr_id.'\',\'P\'); return false;">'.$lang['srv_call_prekinjen'].'</a></p>';
+ echo '<p><a href="ajax.php?anketa='.$this->sid.'&t='.A_TELEPHONE.'&m=addmark&usr_id='.$usr_id.'&status=D">'.$lang['srv_call_prelozen'].'</a></p>';
+
+ # preverimo koliko številk še imamo razen trenutno izbrane
+ $toCall = $allUsers = $this->getAllNumbers();
+ unset($allUsers[$usr_id]);
+
+ # na voljo je še nekaj številk, izberemo novo
+ if ($allUsers > 0) {
+ // Dovolimo izbrati novo stevilko samo v primeru ko imamo nakljucno sortiranje
+ if($this->call_order == 0)
+ echo '<p><br /><a href="'.$this->addUrl('clear_current').'">'.$lang['srv_telephone_call_action_cancel_nextNumber'].' ('.count($toCall).')</a></p>';
+ }
+ # na voljo je samo ta številka, ne moremo ponudit druge
+ else {
+ echo '<p><br /><a href="'.$this->addUrl('start_call').'">'.$lang['srv_telephone_call_action_cancel_preview'].' ('.count($toCall).')</a></p>';
+ }
+
+ // Razveljavimo zadnji status (undo)
+ if($last_status == 'A')
+ echo '<p><a href="#" onClick="phnUndoStatus(\''.$usr_id.'\')">'.$lang['srv_telephone_call_action_undo_status'].' (»'.$last_status.'«)</a></p>';
+
+ echo '<div id="telephone_popup" />';
+ echo '</div>';
+
+ } else {
+ # onemogočimo ponovno klicanje uporabnika ker je zaključena ali je zavrnil
+ echo '<p class="red strong">'.$lang['srv_telephone_calling_next_step'].'</p>';
+ echo '<div style="padding-left: 20px;">';
+
+ // Seznam respondentov
+ echo '<p><a href="'.$this->addUrl('view_recipients').'">'.$lang['srv_telephone_call_action_view_recipients'].'</a></p>';
+
+ # preverimo koliko številk še imamo razen trenutno izbrane
+ $toCall = $allUsers = $this->getAllNumbers();
+ unset($allUsers[$usr_id]);
+
+ # na voljo je še nekaj številk, izberemo novo
+ if ($allUsers > 0) {
+ // Dovolimo izbrati novo stevilko samo v primeru ko imamo nakljucno sortiranje
+ if($this->call_order == 0)
+ echo '<p><a href="'.$this->addUrl('call').'">'.$lang['srv_telephone_call_action_cancel_nextNumber'].' ('.count($toCall).')</a></p>';
+ }
+ # na voljo je samo ta številka, ne moremo ponudit druge
+ else {
+ echo '<p><a href="'.$this->addUrl('start_call').'">'.$lang['srv_telephone_call_action_cancel_preview'].' ('.count($toCall).')</a></p>';
+ }
+
+ // Razveljavimo zadnji status (undo)
+ echo '<p><a href="#" onClick="phnUndoStatus(\''.$usr_id.'\')">'.$lang['srv_telephone_call_action_undo_status'].' (»'.$last_status.'«)</a></p>';
+ }
+ # spodnje akcije
+ # če je anketar ne prikazujemo nextAction
+ if ($this->isAnketar == false) {
+ echo '<div style="border-top:1px solid gray;">';
+ echo '<p>';
+ session_start();
+ $nextAction = 1;
+
+ if (isset($_SESSION['phnNextAction'][$this->sid]) && (int)$_SESSION['phnNextAction'][$this->sid]==0) {
+ $nextAction = 0;
+ }
+ echo '<label><input type="radio" name="phnNextAction" id="phn_exit" value="0"'.($nextAction == 0?' checked="checked"':'').' onchange="phnNextActionChange(this); return false;">';
+ echo $lang['srv_telephone_call_action_cancel'].'</label>';
+ echo '<label><input type="radio" name="phnNextAction" id="phn_next" value="1"'.($nextAction == 1?' checked="checked"':'').' onchange="phnNextActionChange(this); return false;">';
+ echo $lang['srv_telephone_call_action_nextNumber'].'</label>';
+ echo '</p>';
+ echo '</div>';
+ }
+
+ $str_comment = "SELECT comment from srv_telephone_comment WHERE rec_id = '$usr_id'";
+ $qry_comment = sisplet_query($str_comment);
+ $row_comment = mysqli_fetch_assoc($qry_comment);
+ echo '<p>';
+ echo $lang['srv_telephone_call_comment'];
+ echo '<div id="phn_user_comment" class="editable" onblur="phnSetUserComment(this,\''.$usr_id.'\');return false;" contentEditable="true">';
+ echo $row_comment['comment'];
+ echo '</div>';
+ echo '</p>';
+
+ echo '</td></tr>';
+
+ echo '</table>';
+ }
+
+
+ /* Paginacija za pregled reposndentov
+ *
+ */
+ function displayPagination($all_records) {
+ global $lang,$site_url;
+ #trenutna stran
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $current = is_numeric($_GET['page']) && (int)$_GET['page'] > 0 ? $page : '1';
+
+ $all = ceil($all_records / REC_ON_PAGE);
+
+ # current nastavimo na zadnji element
+ if ( $all > 1) {
+
+
+ echo '<div id="pagination" style="margin-bottom:10px;">';
+ $baseUrl = $site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_TELEPHONE.'&m=view_recipients&page=';
+
+ # povezava -10
+ if ($all > 10) {
+ if ($current - 10 >= 0) {
+ echo('<div><a href="'.$baseUrl.($current - 10).'">-10</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">-10</div>');
+ }
+ }
+
+ # povezava na prejšnjo stran
+ $prev_page = $current - 1 ? $current - 1 :$current;
+ if( ($current - 1) >= 1) {
+ echo('<div><a href="'.$baseUrl.$prev_page.'">'.$lang['previous_page_short'].'</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">'.$lang['previous_page_short'].'</div>');
+ }
+
+ # povezave za vmesne strani
+ $middle = $all / 2;
+ $skipped = false;
+ for($a = 1; $a <= $all; $a++) {
+ if ($all < ((GROUP_PAGINATE+1) * 2) || $a <= GROUP_PAGINATE || $a > ($all-GROUP_PAGINATE)
+
+ || ( abs($a-$current) < GROUP_PAGINATE)) {
+ if ($skipped == true) {
+ echo '<div class="spacePage">.&nbsp;.&nbsp;.</div>';
+ $skipped = false;
+ }
+ if($a == $current) {
+ # brez href povezave
+ echo('<div class="currentPage">'.($a).'</div>');
+ } else {
+ echo('<div><a href="'.$baseUrl.$a.'">'.($a).'</a></div>');
+ }
+ } else {
+ $skipped = true;
+ }
+ }
+ # povezava na naslednjo stran
+ $next_page = ($current + 1) ? ($current + 1) : $current;
+ if(($current ) < $all) {
+ echo('<div><a href="'.$baseUrl.$next_page.'">'.$lang['next_page_short'].'</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">'.$lang['next_page_short'].'</div>');
+ }
+ if ($all > 10) {
+ if ($current + 10 < $all) {
+ echo('<div><a href="'.$baseUrl.($current + 10).'">+10</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">+10</div>');
+ }
+ }
+
+ $rec_on_page = $all != $current ? REC_ON_PAGE : ( $all_records - ($all-1)*REC_ON_PAGE);
+ echo '<div class="justtext">'.$lang['srv_inv_pagination_shown'].$rec_on_page.$lang['srv_inv_pagination_shown_records'].'</div>';
+ echo '</div>';
+ }
+ else{
+ echo '<br />';
+ }
+ }
+
+ function startSurvey() {
+ # nastavimo marker na A
+ # in vrnemo dva urlja, enega za reload strani, drugega pa odpiranje ankete
+ global $lang,$site_url, $global_user_id;
+
+ $return = array('error'=>'1', 'msg'=>'Napaka','reloadUrl'=>'','surveyUrl'=>'');
+
+ if ((int)$_POST['usr_id'] > 0) {
+ $usr_id = (int)$_POST['usr_id'];
+
+ # nastavimo url za nastavitev statusa in reload strani
+ $return['reloadUrl'] = $site_url.'admin/survey/ajax.php?anketa='.$this->sid.'&t='.A_TELEPHONE.'&m=addmark&usr_id='.$usr_id.'&status=A';
+ #ajax.php?anketa='.$this->sid.'&t='.A_TELEPHONE.'&m=addmark&usr_id='.$usr_id.'&status=A
+
+ #preberemo vse podatke respondenta
+ $res_sel = "SELECT * FROM srv_invitations_recipients WHERE id ='$usr_id'";
+ $res_query = sisplet_query($res_sel);
+ $res_row = mysqli_fetch_assoc($res_query);
+
+ #preverimo ali že obstaja povezava med respondentom in userjem
+ $chk_user = "SELECT id, pass FROM srv_user WHERE inv_res_id='$usr_id' AND ank_id='".$this->sid."'";
+ $chk_query = sisplet_query($chk_user);
+ $return['msg'] = $chk_user;
+ if (mysqli_num_rows($chk_query) > 0) {
+ # user že obstaja
+ $user_data = mysqli_fetch_assoc($chk_query);
+
+ # sestavimo še url za odpiranje izpolnjevanja ankete
+ $return['surveyUrl'] = $site_url.'a/'.Common::encryptAnketaID($this->sid).'&survey-'.$this->sid.'&code='.$user_data['pass'];
+ $return['error'] = '';
+ }
+ else {
+ # user še ne obstaja vstavimo njegove podatke
+ # polovimo sistemske spremenljivke z vrednostmi
+ $strSistemske = "SELECT s.id, s.naslov, s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".$this->sid."' AND variable IN('" . implode("','",$this->inv_variables)."') ORDER BY g.vrstni_red, s.vrstni_red";
+ $qrySistemske = sisplet_query($strSistemske);
+ $sys_vars = array();
+ $sys_vars_ids = array();
+
+ while ($row = mysqli_fetch_assoc($qrySistemske)) {
+ $sys_vars[$row['id']] = array('id'=>$row['id'], 'variable'=>$row['variable'],'naslov'=>$row['naslov']);
+ $sys_vars_ids[] =$row['id'];
+ }
+
+ $sqlVrednost = sisplet_query("SELECT spr_id, id AS vre_id FROM srv_vrednost WHERE spr_id IN(".implode(',',$sys_vars_ids).") ORDER BY vrstni_red ASC ");
+ while ($row = mysqli_fetch_assoc($sqlVrednost)) {
+ if (!isset($sys_vars[$row['spr_id']]['vre_id'])) {
+ $sys_vars[$row['spr_id']]['vre_id'] = $row['vre_id'];
+ }
+ }
+
+ $strInsert = "INSERT INTO srv_user (ank_id, email, cookie, pass, last_status, time_insert, inv_res_id)"
+ ." VALUES ('$this->sid','$res_row[email]','$res_row[cookie]', '$res_row[password]', '0', NOW(), '$res_row[id]') ON DUPLICATE KEY UPDATE cookie = '$res_row[cookie]', pass='$res_row[password]'";
+ sisplet_query($strInsert);
+ $srv_usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ sisplet_query("COMMIT");
+ if ($srv_usr_id) {
+ $strInsertDataText = array();
+
+ # dodamo še podatke za posameznega userja za sistemske spremenljivke
+ foreach ($sys_vars AS $sid => $spremenljivka) {
+ $_user_variable = $this->inv_variables_link[$spremenljivka['variable']];
+ if (trim($res_row[$_user_variable]) != '' && $res_row[$_user_variable] != null) {
+ $strInsertDataText[] = "('".$sid."','".$spremenljivka['vre_id']."','".trim($res_row[$_user_variable])."','".$srv_usr_id."')";
+ }
+ }
+
+ # vstavimo v srv_userbase
+ $strInsert = "INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ('$srv_usr_id','0',NOW(),'$global_user_id')";
+ sisplet_query($strInsert);
+
+ # vstavimo v srv_userstatus
+ $strInsert = "INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ('$srv_usr_id', '0', '0', NOW())";
+ sisplet_query($strInsert);
+
+ # vstavimo v srv_data_text
+ $db_table = (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) ? '_active' : '';
+ if (count($strInsertDataText) > 0) {
+ $strInsert = "INSERT INTO srv_data_text".$db_table." (spr_id, vre_id, text, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataText);
+ sisplet_query($strInsert);
+ }
+ sisplet_query("COMMIT");
+
+ # sestavimo še url za odpiranje izpolnjevanja ankete
+ $return['surveyUrl'] = $site_url.'a/'.Common::encryptAnketaID($this->sid).'&survey-'.$this->sid.'&code='.$res_row[password];
+ $return['error'] = '';
+ }
+ }
+ }
+
+ echo json_encode($return);
+
+ exit;
+ }
+
+ function showPopupAddMarker() {
+ global $lang;
+ $newDate = date('d.m.Y H:i', time()+3600 );
+ $marker = $_POST['marker'];
+ $usr_id = (int)$_POST['usr_id'];
+
+ if ($usr_id > 0 && ($marker == 'P' || $marker == 'T')) {
+ if ($marker == 'T') {
+ # zmenjen
+ echo $lang['srv_telephone_call_mark_T_note'];
+ } else if ($marker == 'P') {
+ #prekinjen
+ echo $lang['srv_telephone_call_mark_P_note'];
+ }
+
+ echo '<p><form name="'.$marker.'">';
+ echo '<input id="'.$marker.'_datetime" type="text" name="'.$marker.'_datetime" value="'.$newDate.'" />
+ <span class="faicon calendar_icon icon-as_link" id="'.$marker.'_datetime_image"></span>
+ <script type="text/javascript">
+ Calendar.setup({
+ inputField : "'.$marker.'_datetime",
+ ifFormat : "%d.%m.%Y %H:%M",
+ button : "'.$marker.'_datetime_image",
+ singleClick : true
+ });
+ </script></form>
+ </p>';
+
+ if ($marker == 'T') {
+ echo '<span class="buttonwrapper floatRight spaceRight" ><a class="ovalbutton ovalbutton_orange" href="#" onclick="phnAddMarker(\''.$usr_id.'\',\''.$marker.'\'); return false;"><span>'.$lang['srv_call_zmenjen'].'</span></a></span>';
+ } else if ($marker == 'P') {
+ echo '<span class="buttonwrapper floatRight spaceRight" ><a class="ovalbutton ovalbutton_orange" href="#" onclick="phnAddMarker(\''.$usr_id.'\',\''.$marker.'\'); return false;"><span>'.$lang['srv_call_prekinjen'].'</span></a></span>';
+ }
+ }
+ echo '<span class="buttonwrapper floatRight spaceRight" ><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#telephone_popup\').hide(); $(\'#fade\').fadeOut(\'slow\'); "><span>'.$lang['srv_cancel'].'</span></a></span>';
+ }
+
+ // Nastavimo filter za pregled respondentov
+ function setRecipientFilter(){
+
+ session_start();
+
+ $_SESSION['inv_filter']['value'] = trim($_POST['tel_filter_value']);
+
+ session_commit();
+ }
+
+ function hightlight($str, $keywords = '') {
+ $keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
+ $style = 'inv_high';
+ $style_i = 'inv_high_i';
+ /* Apply Style */
+ $var = '';
+
+ foreach(explode(' ', $keywords) as $keyword)
+ {
+ $replacement = "<span class='".$style."'>".$keyword."</span>";
+ $var .= $replacement." ";
+ $str = str_ireplace($keyword, $replacement, $str);
+ }
+
+ /* Apply Important Style */
+
+ $str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
+
+ return $str;
+ }
+
+ // Pobrisemo zadnji status respondenta (undo)
+ private function undoLastStatus(){
+
+ if(isset($_POST['usr_id'])){
+ $usr_id = $_POST['usr_id'];
+
+ $sql = sisplet_query("DELETE FROM srv_telephone_history WHERE rec_id='".$usr_id."' AND survey_id='".$this->sid."' ORDER BY insert_time DESC LIMIT 1");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+}
diff --git a/admin/survey/classes/class.SurveyTextAnalysis.php b/admin/survey/classes/class.SurveyTextAnalysis.php
new file mode 100644
index 0000000..2f083e8
--- /dev/null
+++ b/admin/survey/classes/class.SurveyTextAnalysis.php
@@ -0,0 +1,407 @@
+<?php
+
+class SurveyTextAnalysis{
+
+ private $anketa; # id ankete
+ private $db_table; # katere tabele uporabljamo
+
+
+ function __construct($anketa){
+ global $lang;
+
+ if ((int)$anketa > 0){
+
+ $this->anketa = $anketa;
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ }
+ else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+
+ function displayTable(){
+ global $lang;
+
+ $data = $this->getData();
+
+
+ // Tabela z vsotami stevil znakov - po straneh in vprasanjih
+ echo '<h2>'.$lang['srv_text_analysis_title1'].'</h2>';
+ echo '<table class="text_analysis_table">';
+
+ // Header row
+ echo '<tr>';
+
+ echo '<th style="width:120px;">'.$lang['srv_text_analysis_page'].'</th>';
+ echo '<th style="width:120px;">'.$lang['srv_text_analysis_question'].'</th>';
+
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_charCount'].'</th>';
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_charCountBlank'].'</th>';
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_charCountHTML'].'</th>';
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_wordCount'].'</th>';
+
+ echo '</tr>';
+
+ // Loop po straneh v anketi
+ foreach($data['grupe'] as $gru_id => $grupa){
+
+ // Loop po vprasanjih na strani
+ foreach($grupa['spremenljivke'] as $spr_id => $spremenljivka){
+
+ echo '<tr>';
+
+ echo '<td>'.$grupa['naslov'].'</td>';
+ echo '<td>'.$spremenljivka['variable'].'</td>';
+
+ echo '<td>'.$spremenljivka['sum_char_count'].'</td>';
+ echo '<td>'.$spremenljivka['sum_char_count_noBlank'].'</td>';
+ echo '<td>'.$spremenljivka['sum_char_count_html'].'</td>';
+ echo '<td>'.$spremenljivka['sum_word_count'].'</td>';
+
+ echo '</tr>';
+ }
+
+ // Vsota znakov na strani
+ echo '<tr class="sum">';
+
+ echo '<td>'.$grupa['naslov'].'</td>';
+ echo '<td>'.$lang['srv_text_analysis_sum'].'</td>';
+
+ echo '<td>'.$grupa['sum_char_count'].'</td>';
+ echo '<td>'.$grupa['sum_char_count_noBlank'].'</td>';
+ echo '<td>'.$grupa['sum_char_count_html'].'</td>';
+ echo '<td>'.$grupa['sum_word_count'].'</td>';
+
+ echo '</tr>';
+ }
+
+ // Vsota znakov v anketi
+ echo '<tr class="sum">';
+
+ echo '<td></td>';
+ echo '<td>'.$lang['srv_text_analysis_sumSurvey'].'</td>';
+
+ echo '<td>'.$data['sum_char_count'].'</td>';
+ echo '<td>'.$data['sum_char_count_noBlank'].'</td>';
+ echo '<td>'.$data['sum_char_count_html'].'</td>';
+ echo '<td>'.$data['sum_word_count'].'</td>';
+
+ echo '</tr>';
+
+ echo '</table>';
+
+
+ // Tabela s podrobnostmi - stevilo znakov po posameznih vprasnajih in vrednostih
+ echo '<h2>'.$lang['srv_text_analysis_title2'].'</h2>';
+ echo '<table class="text_analysis_table">';
+
+ // Header row
+ echo '<tr>';
+
+ echo '<th style="width:120px;">'.$lang['srv_text_analysis_page'].'</th>';
+ echo '<th style="width:120px;">'.$lang['srv_text_analysis_question'].'</th>';
+ echo '<th style="width:120px;">'.$lang['srv_text_analysis_value'].'</th>';
+ echo '<th>'.$lang['srv_text_analysis_text'].'</th>';
+
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_charCount'].'</th>';
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_charCountBlank'].'</th>';
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_charCountHTML'].'</th>';
+ echo '<th style="width:130px;">'.$lang['srv_text_analysis_wordCount'].'</th>';
+
+ echo '</tr>';
+
+ // Loop po straneh v anketi
+ foreach($data['grupe'] as $gru_id => $grupa){
+
+ // Loop po vprasanjih na strani
+ foreach($grupa['spremenljivke'] as $spr_id => $spremenljivka){
+
+ echo '<tr class="colored">';
+
+ echo '<td>'.$grupa['naslov'].'</td>';
+ echo '<td>'.$spremenljivka['variable'].'</td>';
+ echo '<td></td>';
+
+ $naslov = strip_tags($spremenljivka['naslov']);
+ $naslov = ($spremenljivka['char_count'] > 50) ? substr($naslov, 0, 47).'...' : $naslov;
+ echo '<td>'.$naslov.'</td>';
+
+ echo '<td>'.$spremenljivka['char_count'].'</td>';
+ echo '<td>'.$spremenljivka['char_count_noBlank'].'</td>';
+ echo '<td>'.$spremenljivka['char_count_html'].'</td>';
+ echo '<td>'.$spremenljivka['word_count'].'</td>';
+
+ echo '</tr>';
+
+ // Loop po vrednostih v vprasanju
+ foreach($spremenljivka['vrednosti'] as $vre_id => $vrednost){
+
+ echo '<tr>';
+
+ echo '<td>'.$grupa['naslov'].'</td>';
+ echo '<td>'.$spremenljivka['variable'].'</td>';
+ echo '<td>'.$vrednost['variable'].'</td>';
+
+ $naslov = strip_tags($vrednost['naslov']);
+ $naslov = ($vrednost['char_count'] > 50) ? substr($naslov, 0, 47).'...' : $naslov;
+ echo '<td>'.$naslov.'</td>';
+
+ echo '<td>'.$vrednost['char_count'].'</td>';
+ echo '<td>'.$vrednost['char_count_noBlank'].'</td>';
+ echo '<td>'.$vrednost['char_count_html'].'</td>';
+ echo '<td>'.$vrednost['word_count'].'</td>';
+
+ echo '</tr>';
+ }
+ }
+ }
+
+ echo '</table>';
+ }
+
+ // Preracunamo vse potrebne podatke
+ function getData(){
+
+ $data = array();
+
+ $data['sum_char_count'] = 0;
+ $data['sum_char_count_noBlank'] = 0;
+ $data['sum_char_count_html'] = 0;
+ $data['sum_word_count'] = 0;
+
+ // Loop cez vse vrednosti v vprasanjih na straneh v anketi
+ $sqlGrupa = sisplet_query("SELECT id, ank_id, naslov, vrstni_red FROM srv_grupa WHERE ank_id='$this->anketa' ORDER BY vrstni_red ASC");
+ while($rowGrupa = mysqli_fetch_array($sqlGrupa)){
+
+ $data['grupe'][$rowGrupa['id']]['naslov'] = $rowGrupa['naslov'];
+
+ $data['grupe'][$rowGrupa['id']]['sum_char_count'] = 0;
+ $data['grupe'][$rowGrupa['id']]['sum_char_count_noBlank'] = 0;
+ $data['grupe'][$rowGrupa['id']]['sum_char_count_html'] = 0;
+ $data['grupe'][$rowGrupa['id']]['sum_word_count'] = 0;
+
+ $sqlSpr = sisplet_query("SELECT id, naslov, variable, vrstni_red FROM srv_spremenljivka WHERE gru_id='".$rowGrupa['id']."' ORDER BY vrstni_red ASC");
+ while($rowSpr = mysqli_fetch_array($sqlSpr)){
+
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['variable'] = $rowSpr['variable'];
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['naslov'] = $rowSpr['naslov'];
+
+ $naslov = utf8_decode(html_entity_decode($rowSpr['naslov'], ENT_COMPAT, 'utf-8'));
+
+ // Stevilo znakov za naslov vprasanja
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['char_count'] = strlen(strip_tags($naslov));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['char_count_noBlank'] = strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['char_count_html'] = strlen($naslov);
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['word_count'] = count(explode(" ", strip_tags($naslov)));
+
+ // Stevilo vseh znakov v vprasanju (se sesteva z znaki v vrednostih)
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_char_count'] = strlen(strip_tags($naslov));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_char_count_noBlank'] = strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_char_count_html'] = strlen($naslov);
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_word_count'] = count(explode(" ", strip_tags($naslov)));
+
+ // Stevilo vseh znakov na strani (se sesteva z znaki v vrednostih)
+ $data['grupe'][$rowGrupa['id']]['sum_char_count'] += strlen(strip_tags($naslov));
+ $data['grupe'][$rowGrupa['id']]['sum_char_count_noBlank'] += strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['grupe'][$rowGrupa['id']]['sum_char_count_html'] += strlen($naslov);
+ $data['grupe'][$rowGrupa['id']]['sum_word_count'] += count(explode(" ", strip_tags($naslov)));
+
+ // Stevilo vseh znakov v anketi (se sesteva z znaki v vrednostih)
+ $data['sum_char_count'] += strlen(strip_tags($naslov));
+ $data['sum_char_count_noBlank'] += strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['sum_char_count_html'] += strlen($naslov);
+ $data['sum_word_count'] += count(explode(" ", strip_tags($naslov)));
+
+ $sqlVre = sisplet_query("SELECT id, naslov, variable, vrstni_red FROM srv_vrednost WHERE spr_id='".$rowSpr['id']."' ORDER BY vrstni_red ASC");
+ while($rowVre = mysqli_fetch_array($sqlVre)){
+
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['vrednosti'][$rowVre['id']]['variable'] = $rowVre['variable'];
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['vrednosti'][$rowVre['id']]['naslov'] = $rowVre['naslov'];
+
+ $naslov = utf8_decode(html_entity_decode($rowVre['naslov'], ENT_COMPAT, 'utf-8'));
+
+ // Stevilo znakov za vrednost
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['vrednosti'][$rowVre['id']]['char_count'] = strlen(strip_tags($naslov));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['vrednosti'][$rowVre['id']]['char_count_noBlank'] = strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['vrednosti'][$rowVre['id']]['char_count_html'] = strlen($naslov);
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['vrednosti'][$rowVre['id']]['word_count'] = count(explode(" ", strip_tags($naslov)));
+
+ // Stevilo vseh znakov v vprasanju (se sesteva z znaki v vrednostih)
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_char_count'] += strlen(strip_tags($naslov));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_char_count_noBlank'] += strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_char_count_html'] += strlen($naslov);
+ $data['grupe'][$rowGrupa['id']]['spremenljivke'][$rowSpr['id']]['sum_word_count'] += count(explode(" ", strip_tags($naslov)));
+
+ // Stevilo vseh znakov na strani (se sesteva z znaki v vrednostih)
+ $data['grupe'][$rowGrupa['id']]['sum_char_count'] += strlen(strip_tags($naslov));
+ $data['grupe'][$rowGrupa['id']]['sum_char_count_noBlank'] += strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['grupe'][$rowGrupa['id']]['sum_char_count_html'] += strlen($naslov);
+ $data['grupe'][$rowGrupa['id']]['sum_word_count'] += count(explode(" ", strip_tags($naslov)));
+
+ // Stevilo vseh znakov v anketi (se sesteva z znaki v vrednostih)
+ $data['sum_char_count'] += strlen(strip_tags($naslov));
+ $data['sum_char_count_noBlank'] += strlen(strip_tags(str_replace(" ","",$naslov)));
+ $data['sum_char_count_html'] += strlen($naslov);
+ $data['sum_word_count'] += count(explode(" ", strip_tags($naslov)));
+ }
+ }
+ }
+
+ return $data;
+ }
+
+
+ function exportCSVTable($table=1){
+ global $lang;
+
+ $data = $this->getData();
+
+ $csvArray = array();
+
+ // Izpisemo prvo tabelo (z vsotami po vprasanjih in straneh)
+ if($table == 1){
+
+ // Header row
+ $csvRow = array();
+
+ $csvRow[] = $lang['srv_text_analysis_page'];
+ $csvRow[] = $lang['srv_text_analysis_question'];
+
+ $csvRow[] = $lang['srv_text_analysis_charCount'];
+ $csvRow[] = strip_tags($lang['srv_text_analysis_charCountBlank']);
+ $csvRow[] = strip_tags($lang['srv_text_analysis_charCountHTML']);
+ $csvRow[] = $lang['srv_text_analysis_wordCount'];
+
+ $csvArray[] = $csvRow;
+
+ // Loop po straneh v anketi
+ foreach($data['grupe'] as $gru_id => $grupa){
+
+ // Loop po vprasanjih na strani
+ foreach($grupa['spremenljivke'] as $spr_id => $spremenljivka){
+
+ $csvRow = array();
+
+ $csvRow[] = $grupa['naslov'];
+ $csvRow[] = $spremenljivka['variable'];
+
+ $csvRow[] = $spremenljivka['sum_char_count'];
+ $csvRow[] = $spremenljivka['sum_char_count_noBlank'];
+ $csvRow[] = $spremenljivka['sum_char_count_html'];
+ $csvRow[] = $spremenljivka['sum_word_count'];
+
+ $csvArray[] = $csvRow;
+ }
+
+ // Vsota znakov na strani
+ $csvRow = array();
+
+ $csvRow[] = $grupa['naslov'];
+ $csvRow[] = $lang['srv_text_analysis_sum'];
+
+ $csvRow[] = $grupa['sum_char_count'];
+ $csvRow[] = $grupa['sum_char_count_noBlank'];
+ $csvRow[] = $grupa['sum_char_count_html'];
+ $csvRow[] = $grupa['sum_word_count'];
+
+ $csvArray[] = $csvRow;
+ }
+
+ // Vsota znakov v anketi
+ $csvRow = array();
+
+ $csvRow[] = ' ';
+ $csvRow[] = $lang['srv_text_analysis_sumSurvey'];
+
+ $csvRow[] = $data['sum_char_count'];
+ $csvRow[] = $data['sum_char_count_noBlank'];
+ $csvRow[] = $data['sum_char_count_html'];
+ $csvRow[] = $data['sum_word_count'];
+
+ $csvArray[] = $csvRow;
+ }
+ // Izpisemo drugo tabelo (posamezno stevilo znakov po vprasanju in variabli)
+ else{
+
+ // Header row
+ $csvRow = array();
+
+ $csvRow[] = $lang['srv_text_analysis_page'];
+ $csvRow[] = $lang['srv_text_analysis_question'];
+ $csvRow[] = $lang['srv_text_analysis_value'];
+ $csvRow[] = $lang['srv_text_analysis_text'];
+
+ $csvRow[] = $lang['srv_text_analysis_charCount'];
+ $csvRow[] = strip_tags($lang['srv_text_analysis_charCountBlank']);
+ $csvRow[] = strip_tags($lang['srv_text_analysis_charCountHTML']);
+ $csvRow[] = $lang['srv_text_analysis_wordCount'];
+
+ $csvArray[] = $csvRow;
+
+ // Loop po straneh v anketi
+ foreach($data['grupe'] as $gru_id => $grupa){
+
+ // Loop po vprasanjih na strani
+ foreach($grupa['spremenljivke'] as $spr_id => $spremenljivka){
+
+ $csvRow = array();
+
+ $csvRow[] = $grupa['naslov'];
+ $csvRow[] = $spremenljivka['variable'];
+ $csvRow[] = ' ';
+
+ $naslov = strip_tags($spremenljivka['naslov']);
+ $naslov = ($spremenljivka['char_count'] > 50) ? substr($naslov, 0, 47).'...' : $naslov;
+ $csvRow[] = $naslov;
+
+ $csvRow[] = $spremenljivka['char_count'];
+ $csvRow[] = $spremenljivka['char_count_noBlank'];
+ $csvRow[] = $spremenljivka['char_count_html'];
+ $csvRow[] = $spremenljivka['word_count'];
+
+ $csvArray[] = $csvRow;
+
+ // Loop po vrednostih v vprasanju
+ foreach($spremenljivka['vrednosti'] as $vre_id => $vrednost){
+
+ $csvRow = array();
+
+ $csvRow[] = $grupa['naslov'];
+ $csvRow[] = $spremenljivka['variable'];
+ $csvRow[] = $vrednost['variable'];
+
+ $naslov = strip_tags($vrednost['naslov']);
+ $naslov = ($vrednost['char_count'] > 50) ? substr($naslov, 0, 47).'...' : $naslov;
+ $csvRow[] = $naslov;
+
+ $csvRow[] = $vrednost['char_count'];
+ $csvRow[] = $vrednost['char_count_noBlank'];
+ $csvRow[] = $vrednost['char_count_html'];
+ $csvRow[] = $vrednost['word_count'];
+
+ $csvArray[] = $csvRow;
+ }
+ }
+ }
+ }
+
+ // Izvozimo CSV
+ $fp = fopen('php://output', 'w');
+
+ header('Content-Type: application/csv charset=windows-1250');
+ header('Content-Disposition: attachement; filename="textAnalysis_'.$this->anketa.'.csv";');
+
+ foreach ($csvArray as $row) {
+ fputcsv($fp, $row, ';', ' ');
+ }
+
+ fclose($fp);
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyTheme.php b/admin/survey/classes/class.SurveyTheme.php
new file mode 100644
index 0000000..9793b76
--- /dev/null
+++ b/admin/survey/classes/class.SurveyTheme.php
@@ -0,0 +1,997 @@
+<?php
+
+class SurveyTheme {
+
+ private $sid = null; # id ankete
+ private $surveyInfo = null; # podatki ankete
+
+ public $current_skin = null; # trenutni skin
+ public $current_mobile_skin = null; # trenutni mobilni skin
+ private $current_group = null; # grupa trenutnega skina
+ private $groups = array(); # grupe z skini
+
+ function __construct($sid=0, $themePreview = false) {
+ global $site_path;
+ global $site_domain;
+ global $global_user_id;
+ global $admin_type;
+ global $debug;
+
+ $this->sid = $sid;
+
+ SurveyInfo::getInstance()->SurveyInit($sid);
+ $this->surveyInfo = SurveyInfo::getInstance()->getSurveyRow();
+ $this->current_skin = $this->surveyInfo['skin'];
+ $this->current_mobile_skin = $this->surveyInfo['mobile_skin'];
+
+ # polovimo grupe skinov
+ # dodamo sistemsko
+ $this->groups['0'] = array('name'=>'Sistemske teme');
+ $this->groups['-1'] = array('name'=>'Lastne teme');
+ $this->groups['-2'] = array('name'=>'Safe teme');
+ $this->groups['-3'] = array('name'=>'Mobilne teme');
+
+ $skinsArray = array();
+ $skinsArrayPersonal = array();
+
+ # polovimo vse skine v direktoriju
+ $dir = opendir($site_path . 'main/survey/skins/');
+ while ($file = readdir($dir)) {
+
+ $ext = pathinfo($file, PATHINFO_EXTENSION);
+ if ($ext == 'css' && $file[0] != '_' && $file[0] != '.') {
+
+ // Lastne teme
+ if (strpos($file, $global_user_id.'_') === true) {
+ $this->groups[-1]['skins'][] = $file;
+
+ if ($file == $this->current_skin.'.css')
+ $this->current_group = -1;
+ }
+ // Ni uporabniska tema
+ else {
+
+ // Standardni skini
+ $standard_skins = array(
+ 1 => '1kaBlue.css',
+ 2 => '1kaRed.css',
+ 3 => '1kaOrange.css',
+ 4 => '1kaGreen.css',
+ 5 => '1kaPurple.css',
+ 6 => '1kaBlack.css',
+ 7 => '1kaOffice.css',
+ 8 => '1kaNature.css',
+ 9 => 'Otroci3.css',
+ 10 => 'Otroci4.css',
+ 11 => 'Embed.css',
+ 12 => 'Embed2.css',
+ 13 => 'Slideshow.css'
+ );
+ //if((($admin_type == '0' || $admin_type == '1') && (strpos($site_url, 'www.1ka.si') || strpos($site_url, 'test.1ka.si'))) || $debug == '1'){
+ $standard_skins[14] = 'Uni.css';
+ $standard_skins[15] = 'Fdv.css';
+ $standard_skins[16] = 'Cdi.css';
+ $standard_skins[17] = 'WebSM.css';
+ //}
+
+ // Novi safe skini so v loceni skupini
+ $safe_skins = array(
+ 'Center.css',
+ 'Center2.css',
+ 'Oko.css',
+ 'Oko2.css',
+ 'Otroci.css',
+ 'Otroci2.css',
+ 'Safe.css',
+ 'Safe2.css',
+ 'Safe3.css'
+ );
+
+ // Mobile skini
+ $mobile_skins = array(
+ 1 => 'MobileBlue.css',
+ 2 => 'MobileRed.css',
+ 3 => 'MobileOrange.css',
+ 4 => 'MobileGreen.css',
+ 5 => 'MobilePurple.css',
+ 6 => 'MobileBlack.css'
+ );
+ //if((($admin_type == '0' || $admin_type == '1') && (strpos($site_url, 'www.1ka.si') || strpos($site_url, 'test.1ka.si'))) || $debug == '1'){
+ $mobile_skins[7] = 'MobileUni.css';
+ $mobile_skins[8] = 'MobileFdv.css';
+ $mobile_skins[9] = 'MobileCdi.css';
+ //}
+
+ // Safe skini
+ if(in_array($file, $safe_skins)){
+ $this->groups[-2]['skins'][] = $file;
+
+ if ($file == $this->current_skin.'.css')
+ $this->current_group = -2;
+ }
+ // Mobile skini
+ elseif($key = array_search($file, $mobile_skins)){
+ $this->groups[-3]['skins'][$key] = $file;
+ }
+ // Navadni skini
+ elseif($key = array_search($file, $standard_skins)){
+ $this->groups[0]['skins'][$key] = $file;
+
+ if ($file == $this->current_skin.'.css')
+ $this->current_group = 0;
+ }
+ }
+ }
+ }
+
+ // Sortiramo skine
+ ksort($this->groups[0]['skins']);
+
+ // Sortiramo safe skine - po abecedi
+ sort($this->groups[-2]['skins']);
+
+ // Sortiramo mobilne skine
+ ksort($this->groups[-3]['skins']);
+ }
+
+ function getGroups () {
+
+ return $this->groups;
+ }
+
+ function Ajax() {
+ switch ($_GET['a']) {
+ case 'changeGroup':
+ $this->displayGroupThemes($_POST['gid']);
+ break;
+ case 'changeTheme':
+ $this->changeTheme($_POST['css'],$_POST['gid']);
+ break;
+ case 'changeProgressbar':
+ $this->changeProgressbar();
+ break;
+ case 'theme_rename':
+ $this->themeRename($_POST['msg']);
+ break;
+ case 'theme_rename_confirm':
+ $this->themeRenameConfirm();
+ break;
+ case 'theme_delete':
+ $this->themeDelete();
+ break;
+ case 'add_theme':
+ $this->ajax_add_theme();
+ break;
+ case 'checboxThemeSave':
+ $this->ajaxSaveChecboxTheme($_POST['anketa'],$_POST['checkbox']);
+ breake;
+
+ default:
+ print_r("<pre>");
+ print_r($_POST);
+ print_r($_GET);
+ break;
+ }
+ }
+
+
+ function displayGroup($groupId = null) {
+ global $lang;
+
+ if ($groupId == null)
+ $groupId = 0;
+
+ echo '<div class="themes-content">';
+
+ echo '<div id="div_theme_groups">';
+ $this->displayGroupSelector($groupId);
+ echo '</div>';
+
+ echo '<div id="div_theme_group_holder">';
+ $this->displayGroupThemes($groupId);
+ echo '</div>';
+
+ // tole sem premaknil izven onload.js da se ne klice vedno po nepotrebnem
+ ?><script> themes_init(); </script><?
+
+ echo '</div>';
+ }
+
+ function handleEditing() {
+ global $lang;
+ global $global_user_id;
+
+ // preusmeritev, ko kliknemo na prilagodi pri sistemski temi in naredimo nov profil
+ if ( isset($_GET['profile_new']) ) {
+
+ if ($_GET['name'] != '')
+ $name = $_GET['name'];
+ else
+ $name = $_GET['profile_new'].'';
+
+ $sql = sisplet_query("INSERT INTO srv_theme_profiles (id, usr_id, skin, name) VALUES ('', '$global_user_id', '".$_GET['profile_new']."', '".$name."')");
+ $profile = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $s = sisplet_query("UPDATE srv_anketa SET skin='".$_GET['profile_new']."', skin_profile='".$profile."' WHERE id = '".$this->sid."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ header("Location: index.php?anketa=".$this->sid."&a=theme-editor&profile=".$profile.'&newalert=1');
+ die();
+ }
+
+ // preusmeritev, ko kliknemo na prilagodi pri sistemski MOBILNI temi in naredimo nov profil
+ if ( isset($_GET['profile_new_mobile']) ) {
+
+ if ($_GET['name'] != '')
+ $name = $_GET['name'];
+ else
+ $name = $_GET['profile_new_mobile'].'';
+
+ $sql = sisplet_query("INSERT INTO srv_theme_profiles_mobile (id, usr_id, skin, name) VALUES ('', '$global_user_id', '".$_GET['profile_new_mobile']."', '".$name."')");
+ $profile = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $s = sisplet_query("UPDATE srv_anketa SET mobile_skin='".$_GET['profile_new_mobile']."', skin_profile_mobile='".$profile."' WHERE id = '".$this->sid."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ header("Location: index.php?anketa=".$this->sid."&a=theme-editor&profile=".$profile.'&newalert=1&mobile=1');
+ die();
+ }
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ // urejanje CSSa
+ if ( $_GET['t'] == 'css' ) {
+
+ // CSS za mobilen skin
+ if($_GET['mobile'] == '1'){
+ $sqlp = sisplet_query("SELECT usr_id, skin FROM srv_theme_profiles_mobile WHERE id = '".$_GET['profile']."'");
+ $rowp = mysqli_fetch_array($sqlp);
+
+ $skin = $rowp['skin'];
+
+ // nastavljena je sistemska tema, moramo jo spremeniti v lastno
+ if (strpos($skin, $rowp['usr_id'].'_') === false) {
+
+ $skin_name = $rowp['usr_id'].'_'.$skin;
+ $css_content = file_get_contents('../../main/survey/skins/'.$skin.'.css');
+
+ $name = $rowp['usr_id'].'_'.$skin;
+
+ while ( file_exists('../../main/survey/skins/'.$name.'.css') ) {
+ $name = $name.'1';
+ }
+
+ $f = fopen('../../main/survey/skins/'.$name.'.css', 'w');
+ fwrite($f, $css_content);
+ fclose($f);
+
+ $skin = $name;
+
+ sisplet_query("UPDATE srv_theme_profiles_mobile SET skin = '$skin' WHERE id = '".$_GET['profile']."'");
+ }
+ }
+ else{
+ $sqlp = sisplet_query("SELECT usr_id, skin FROM srv_theme_profiles WHERE id = '".$_GET['profile']."'");
+ $rowp = mysqli_fetch_array($sqlp);
+
+ $skin = $rowp['skin'];
+
+ // nastavljena je sistemska tema, moramo jo spremeniti v lastno
+ if (strpos($skin, $rowp['usr_id'].'_') === false) {
+
+ $skin_name = $rowp['usr_id'].'_'.$skin;
+ $css_content = file_get_contents('../../main/survey/skins/'.$skin.'.css');
+
+ $name = $rowp['usr_id'].'_'.$skin;
+
+ while ( file_exists('../../main/survey/skins/'.$name.'.css') ) {
+ $name = $name.'1';
+ }
+
+ $f = fopen('../../main/survey/skins/'.$name.'.css', 'w');
+ fwrite($f, $css_content);
+ fclose($f);
+ //header("Location: index.php?anketa=".$this->sid."&a=edit_css&skin=".$name."&newalert=1");
+ //die();
+
+ $skin = $name;
+
+ sisplet_query("UPDATE srv_theme_profiles SET skin = '$skin' WHERE id = '".$_GET['profile']."'");
+ }
+ }
+
+ $_GET['skin'] = $skin;
+ }
+ }
+
+ // urejanje teme
+ function displayEditing () {
+ global $lang;
+ global $global_user_id;
+
+ $mobile = (isset($_GET['mobile']) && $_GET['mobile'] == '1') ? '_mobile' : '';
+
+ // najprej se pohendla ce gre za nove profile itd...
+ $this->handleEditing();
+
+ echo '<div class="themes-content">';
+
+ $sql = sisplet_query("SELECT name FROM srv_theme_profiles".$mobile." WHERE id = '".$_GET['profile']."'");
+ $row = mysqli_fetch_array($sql);
+
+ echo '<h2>'.$lang['srv_themes_mod'].': <span class="red">'.$row['name'].'</span></h2>';
+ //self::displayTabs();
+
+ if ( !isset($_GET['t']) ) {
+
+ $ste = new SurveyThemeEditor($this->sid);
+ $ste->display();
+
+ } elseif ( $_GET['t'] == 'css' ) {
+
+ $this->edit_css();
+
+ } elseif ( $_GET['t'] == 'upload' ) {
+
+ $this->upload_css();
+
+ }
+
+ echo '</div>';
+ }
+
+
+ function displayGroupSelector ($groupId = null) {
+ global $lang,$site_url;
+ global $global_user_id;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $simple_name = $this->current_skin;
+
+ if ($row['skin_profile'] == 0) {
+ $skin_name = $this->strip_name($simple_name);
+ } else {
+ $sqla = sisplet_query("SELECT name FROM srv_theme_profiles WHERE id = '".$row['skin_profile']."'");
+ $rowa = mysqli_fetch_array($sqla);
+ $skin_name = $rowa['name'];
+ }
+
+
+ echo '<span class="theme_header">'.$lang['srv_current_theme'].': ';
+ if($row['skin_profile'] == 0){
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=theme-editor&profile_new=' . $simple_name . '"><span class="bold" style="font-size:16px;">' . $skin_name . '</span>' . '</a>';
+ }else {
+ echo '<a href="index.php?anketa=' . $this->sid . '&a=theme-editor&profile=' . $row['skin_profile'] . '"><span class="bold" style="font-size:16px;">' . $skin_name . '</span>' . '</a>';
+ }
+
+ echo '</span><br /><br />';
+ }
+
+ function displayAdvancedSettings ($groupId) {
+ global $lang,$site_url;
+ global $site_path, $global_user_id;
+ global $admin_type;
+
+ $row = $this->surveyInfo;
+
+ $simple_name = $this->current_skin;
+
+ echo '<h2><a href="#" onclick="javascript:$(\'#show_more\').slideToggle(); return false;">'.$lang['srv_show_all_settings'].'</a></h2>';
+
+ echo '<fieldset id="show_more" style="display:none; margin-bottom:40px">';
+
+ echo '<br /><span class="bold">'.$lang['srv_offline_edit'].':</span>';
+ echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->sid . '" method="post" />';
+ echo '<p><label for="skin">' . $lang['srv_uploadtheme'] . ':</label> ';
+ echo '<input type="file" name="fajl" onchange="submit();" onmouseout="survey_upload();" />';
+ echo ' (' . $lang['srv_skintmpl1'] . ' <a href="' . $site_url . 'main/survey/skins/'.$row['skin'].'.css" target="_blank">' . $lang['srv_skintmpl'] . '</a>)';
+ echo '</p></form>';
+ echo '<p style="font-size:90%; color: gray">'.$lang['srv_skin_disclamer'].'</p>';
+
+ echo '<br /><span class="bold">'.$lang['srv_upload_pic'].':</span>';
+
+ echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->sid . '" method="post" />';
+ echo '<p><label for="skin">' . $lang['srv_upload_pic2'] . ':</label> ';
+ echo '<input type="file" name="fajl" onchange="submit();" onmouseout="survey_upload();" />';
+ echo '</p></form>';
+ echo '<p style="font-size:90%; color: gray">'.$lang['srv_upload_pic_disclaimer'].'</p><br />';
+
+ // prikazemo uploadane slike
+ $dir = opendir($site_path . 'main/survey/uploads/');
+ $skinsArray = array();
+ $skinsArrayPersonal = array();
+ while ($file = readdir($dir)) {
+
+ if ( $file!='.' && $file!='..') {
+ $allowed = false;
+
+ if (is_numeric( substr($file, 0, strpos($file, '_')) )) {
+ $owner = (int)substr($file, 0, strpos($file, '_'));
+ if ($owner == $global_user_id)
+ $allowed = true;
+ }
+
+ if ($allowed) {
+ echo '<a href="'.$site_url.'main/survey/uploads/'.$file.'" target="_blank"><img src="'.$site_url.'main/survey/uploads/'.$file.'" alt="" style="max-width:200px; max-height:200px"></a> ';
+ }
+ }
+ }
+ echo '</fieldset>';
+ }
+
+ function ajaxSaveChecboxTheme($idAnkete, $value){
+ sisplet_query("UPDATE srv_anketa SET skin_checkbox='$value' WHERE id='$idAnkete'");
+ }
+
+
+ function displayGroupThemes ($groupId) {
+ global $lang;
+ global $site_domain;
+
+ // Custom skini
+ $this->displayThemes(-1);
+
+ // Ostali default skini
+ $this->displayThemes($groupId);
+
+ // Mobilni skini
+ $this->displayThemes(-3);
+
+ // Safe skini - samo na domeni safe.si in test.1ka.si (za testiranje)
+ if(strpos($site_domain, "safe.si") || $site_domain == "test.1ka.si"){
+ $this->displayThemes(-2);
+ }
+ }
+
+ function displayThemes ($groupId) {
+ global $lang, $site_url;
+ global $global_user_id;
+
+ //if (count($this->groups[$groupId]['skins'])>0 || $groupId == -1) {
+
+ $rowa = SurveyInfo::getSurveyRow();
+
+ if($groupId == -2)
+ echo '<h2>'.$lang['srv_safe_themes'].'</h2>';
+ elseif ($groupId == -3)
+ echo '<h2>'.$lang['srv_mobile_themes'].'</h2>';
+ elseif ($groupId != -1)
+ echo '<h2>'.$lang['srv_system_themes'].'</h2>';
+ else{
+ echo '<h2>'.$lang['srv_user_themes'].' ';
+ echo '<span class="user_themes_button faicon plus icon-blue pointer" style="margin-bottom:6px;" onClick="toggle_custom_themes(); return false;"> </span>';
+ echo '</h2>';
+ }
+
+ echo '<div id="div_theme_group" '.($groupId==-1 ? ' class="custom" style="display:none;"' : '').'>';
+
+ $sqlg = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='$this->sid' ORDER BY vrstni_red ASC LIMIT 1");
+ $rowg = mysqli_fetch_array($sqlg);
+ $grupa = $rowg['id'];
+
+ $profiles = 0;
+
+
+ // Profili lastnih tem
+ if ($groupId == -1) {
+
+ // preverimo se, ce trenutno izbran skin pripada drugemu userju (v tem primeru ga vseeno prikazemo)
+ $is_current = false;
+ if ( isset($this->groups[$groupId]['skins']) && count($this->groups[$groupId]['skins']) > 0 ) {
+ foreach ($this->groups[$groupId]['skins'] AS $skinid => $skin) {
+ $simple_name = preg_replace("/\.css$/", '', $skin);
+ $is_current = ($this->current_skin == $simple_name && $rowa['skin_profile'] == 0) ? true : false;
+ }
+ }
+ $sql = sisplet_query("SELECT id FROM srv_theme_profiles WHERE usr_id = '$global_user_id' ORDER BY name ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+ $is_current = ($rowa['skin_profile'] == $row['id']) ? true : false;
+ }
+ if (!$is_current) {
+ $append_skin = " OR id = '".$rowa['skin_profile']."' ";
+ } else {
+ $append_skin = "";
+ }
+
+ // Custom navadni skini
+ $sql = sisplet_query("SELECT id, name, skin FROM srv_theme_profiles WHERE usr_id = '$global_user_id' $append_skin ORDER BY name ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $skin = $row['skin'];
+ $src = ''.SurveyInfo::getSurveyLink().'&grupa='.$grupa.'&no_preview=1&preview=on&theme_profile='.$row['id'].'';
+ $is_current_skin = ($rowa['skin_profile'] == $row['id']) ? true : false;
+
+ echo '<div class="custom_theme_holder '.($is_current_skin ? ' active' : '').'">';
+
+ // Title
+ echo '<span class="custom_theme_title" gid="'.$groupId.'" css="'.urlencode($skin).'" alt="'.$row['name'].'" title="'.$lang['srv_changetheme'].'" onclick="te_change_profile(\''.$row['id'].'\', true); return false;" alt="'.$row['name'].'">'.substr($row['name'], 0, 30).(strlen($row['name']) > 30 ? '...' : '').'</span>';
+
+ // Preview theme
+ echo ' <a href="#" class="theme_links_preview" src="'.$src.'"><span class="custom_theme_preview"><span class="faicon preview"></span>'.$lang['srv_poglejanketo2'].'</span></a>';
+
+ // Delete theme
+ if ($groupId == -1)
+ echo ' <a href="#" onclick="if (confirm(\''.$lang['srv_ask_delete'].'\')) te_delete_profile(\''.$row['id'].'\', false); return false;" class="theme_delete" css="'.urlencode($skin).'"><span class="custom_theme_delete"><span class="faicon delete_circle icon-orange"></span> '.$lang['srv_anketadelete_txt'].'</span></a>';
+
+ // Edit theme
+ echo ' <a href="index.php?anketa='.$this->sid.'&a=theme-editor&profile='.$row['id'].'"><span class="custom_theme_edit"><span class="faicon palette"></span> '.$lang['edit3'].'</span></a>';
+
+ echo '</div>';
+
+ $profiles++;
+ }
+
+ // Custom mobile skini
+ $sql = sisplet_query("SELECT id, name, skin FROM srv_theme_profiles_mobile WHERE usr_id = '$global_user_id' ORDER BY name ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $skin = $row['skin'];
+ $src = ''.SurveyInfo::getSurveyLink().'&grupa='.$grupa.'&no_preview=1&preview=on&theme_profile='.$row['id'].'&mobile=1';
+ $is_current_skin = ($rowa['skin_profile_mobile'] == $row['id']) ? true : false;
+
+ echo '<div class="custom_theme_holder '.($is_current_skin ? ' active' : '').'">';
+
+ // Title
+ echo '<span class="custom_theme_title" gid="'.$groupId.'" css="'.urlencode($skin).'" alt="'.$row['name'].'" title="'.$lang['srv_changetheme'].'" onclick="te_change_profile(\''.$row['id'].'\', true, true); return false;" alt="'.$row['name'].'">'.substr($row['name'], 0, 30).(strlen($row['name']) > 30 ? '...' : '').' <span class="italic">('.$lang['srv_mobile_theme'].')</span></span>';
+
+ // Preview theme
+ echo ' <a href="#" class="theme_links_preview" src="'.$src.'"><span class="custom_theme_preview"><span class="faicon preview"></span>'.$lang['srv_poglejanketo2'].'</span></a>';
+
+ // Delete theme
+ if ($groupId == -1)
+ echo ' <a href="#" onclick="if (confirm(\''.$lang['srv_ask_delete'].'\')) te_delete_profile(\''.$row['id'].'\', true); return false;" class="theme_delete" css="'.urlencode($skin).'"><span class="custom_theme_delete"><span class="faicon delete_circle icon-orange"></span> '.$lang['srv_anketadelete_txt'].'</span></a>';
+
+ // Edit theme
+ echo ' <a href="index.php?anketa='.$this->sid.'&a=theme-editor&profile='.$row['id'].'&mobile=1"><span class="custom_theme_edit"><span class="faicon palette"></span> '.$lang['edit3'].'</span></a>';
+
+ echo '</div>';
+
+ $profiles++;
+ }
+
+ if(mysqli_num_rows($sql) > 0)
+ echo '<br />';
+ }
+
+ if ( isset($this->groups[$groupId]['skins']) && count($this->groups[$groupId]['skins']) > 0 ) {
+
+ foreach ($this->groups[$groupId]['skins'] AS $skinid => $skin) {
+ $simple_name = preg_replace("/\.css$/", '', $skin);
+ $is_current_skin = ($this->current_skin == $simple_name && $rowa['skin_profile'] == 0) ? true : false;
+ $is_current_mobile_skin = ($this->current_mobile_skin == $simple_name && $rowa['skin_profile_mobile'] == 0) ? true : false;
+
+ $src = ''.SurveyInfo::getSurveyLink().'&grupa='.$grupa.'&no_preview=1&preview=on&theme='.$skin.'';
+ if(substr($skin, 0, 6) == 'Mobile')
+ $src .= '&mobile=1';
+
+ echo '<div class="theme_label '.($is_current_skin || $is_current_mobile_skin ? 'span_theme_current' : '').'">';
+
+ echo '<div class="theme_label_content">';
+
+ // Preview slika
+ if ($groupId == -1) echo '<a href="#" class="theme_delete theme" gid="'.$groupId.'" css="'.urlencode($skin).'">'.$lang['srv_anketadelete_txt'].'</a>';
+ //echo '<span class="theme_links_rename as_link" theme="'.urlencode($skin).'">Preimenuj</span>';
+ if ($groupId == -1)
+ echo '<img src="'.$site_url.'public/img/skins_previews/'.($groupId==-1?'usertheme':urlencode($simple_name)).'.png" onclick="te_change_profile_oldskin(\''.$simple_name.'\', true); return false;" gid="'.$groupId.'" css="'.urlencode($skin).'" alt="'.$simple_name.'" title="'.$lang['srv_changetheme'].'">';
+ else
+ echo '<img src="'.$site_url.'public/img/skins_previews/'.urlencode($simple_name).'.png" class="theme" gid="'.$groupId.'" css="'.urlencode($skin).'" alt="'.$simple_name.'" title="'.$lang['srv_changetheme'].'">';
+
+ // Ime teme
+ echo '<span class="theme_name">';
+ echo $this->strip_name($simple_name.($simple_name=='1kaBlue' || $simple_name=='MobileBlue' ? ' ('.$lang['default'].')' : ''));
+ // Vprasajcki
+ if($simple_name == 'Embed' || $simple_name == 'Embed2' || $simple_name == 'Fdv' || $simple_name == 'Uni' || $simple_name == 'Slideshow')
+ echo ' '.Help :: display('srv_skins_'.$simple_name);
+ if($groupId == -1)
+ echo ' (CSS)';
+ echo '</span>';
+
+ echo '</div>';
+
+ if($is_current_skin)
+ echo ' <a href="index.php?anketa='.$this->sid.'&a=theme-editor&profile_new='.$rowa['skin'].'"><span class="faicon palette"></span> '.$lang['srv_te_theme_edit'].'</a>';
+
+ if($is_current_mobile_skin)
+ echo ' <a href="index.php?anketa='.$this->sid.'&a=theme-editor&profile_new_mobile='.$rowa['mobile_skin'].'"><span class="faicon palette"></span> '.$lang['srv_te_theme_edit'].'</a>';
+
+ echo '<a href="#" class="theme_links_preview" src="'.$src.'"><span class="faicon preview"></span> '.$lang['srv_poglejanketo2'].'</a>';
+
+ echo '</div>';
+ }
+ }
+ elseif ($profiles == 0) {
+ echo '<p>'.$lang['srv_te_no_profiles'].'</p>';
+ echo '<br />';
+ }
+
+ echo '</div>';
+ }
+
+ function changeTheme($css, $gid) {
+ global $site_path;
+
+ $_theme = urldecode($_POST['css']);
+
+ $dir = $site_path . 'main/survey/skins/';
+
+ if (file_exists($dir.$_theme)) {
+ $_theme = preg_replace("/\.css$/", '', $_theme);
+
+ // Mobilna anketa
+ if($gid == -3){
+ $strUpdate = "UPDATE srv_anketa SET mobile_skin = '$_theme', skin_profile_mobile='0' WHERE id=".$this->sid;
+ $updated = sisplet_query($strUpdate);
+ sisplet_query("COMMIT");
+
+ SurveyInfo::getInstance()->resetSurveyData();
+
+ $this->current_mobile_skin = $_theme;
+ }
+ else{
+ // Nastavimo se mobilni skin glede na osnovnega
+ $mobile_skin_update = '';
+ if(in_array($_theme, array('1kaBlue', '1kaRed', '1kaOrange', '1kaGreen', '1kaPurple', '1kaBlack'))){
+ $mobile_skin = str_replace('1ka', 'Mobile', $_theme);
+ $mobile_skin_update = ", mobile_skin='".$mobile_skin."', skin_profile_mobile='0'";
+ }
+ elseif(in_array($_theme, array('Uni', 'Fdv', 'Cdi'))){
+ $mobile_skin = 'Mobile'.$_theme;
+ $mobile_skin_update = ", mobile_skin='".$mobile_skin."', skin_profile_mobile='0'";
+ }
+
+ $strUpdate = "UPDATE srv_anketa SET skin = '$_theme', skin_profile='0' ".$mobile_skin_update." WHERE id=".$this->sid;
+ $updated = sisplet_query($strUpdate);
+ sisplet_query("COMMIT");
+
+ SurveyInfo::getInstance()->resetSurveyData();
+
+ $this->current_skin = $_theme;
+
+ // Popravimo se mobile skin ce smo ga slucajno preklopili
+ if($mobile_skin_update != '')
+ $this->current_mobile_skin = $mobile_skin;
+ }
+ }
+
+ ob_start();
+ $this->displayGroupThemes(0);
+ $data['group_themes'] = ob_get_clean();
+ ob_start();
+ $this->displayGroupSelector();
+ $data['theme_name'] = ob_get_clean();
+
+ echo json_encode($data);
+ }
+
+ function changeProgressbar() {
+ $progressbar = $_POST['progressbar'];
+ $strUpdate = "UPDATE srv_anketa SET progressbar = '$progressbar' WHERE id=".$this->sid;
+ $updated = sisplet_query($strUpdate);
+ sisplet_query("COMMIT");
+ SurveyInfo :: getInstance()->resetSurveyData();
+ }
+
+ function themeRename($msg = array()) {
+ global $lang, $global_user_id;
+ echo '<div id="div_theme_fullscreen">';
+ echo '<div class="div_theme_fullscreen_content">';
+ print_r("<PRE>");
+ print_r($msg);
+ print_r($_POST);
+ print_r("</PRE>");
+ $_theme_new = (isset($_POST['theme_new_name']) ? $_POST['theme_new_name'] : $_POST['theme']);
+ $_theme_new = urldecode(preg_replace("/\.css$/", '', $_theme_new));
+ # Če gre za lastno temo odstranimo $global_user_id+_
+ if (is_numeric( substr($_theme_new, 0, strpos($_theme_new, '_')) )) {
+ $owner = (int)substr($_theme_new, 0, strpos($_theme_new, '_'));
+ if ($owner == $global_user_id) {
+ # odstranimo $global_user_id_
+ $_theme_new = preg_replace("/^".$global_user_id."_/", '', $_theme_new);
+ }
+ }
+
+ echo '<input id="theme" name="theme" type="hidden" value="'.$_POST['theme'].'">';
+ echo '<label>Novo ime:</label><input id="theme_new_name" name="theme_new_name" type="text" value="'.$_theme_new.'">';
+ echo '</div>'; #inv_FS_content
+ echo '<div class="div_theme_fullscreen_btm">';
+ echo '<span id="theme_rename_confirm" class="floatRight spaceRight buttonwrapper" ><a class="ovalbutton ovalbutton_orange" href="#" ><span>'.$lang['srv_rename_profile_yes'].'</span></a></span>';
+ echo '<span id="theme_rename_cancle" class="floatRight spaceRight buttonwrapper" ><a class="ovalbutton ovalbutton_silver" href="#" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function themeRenameConfirm() {
+ global $lang, $global_user_id, $site_path;
+ $dir = $site_path . 'main/survey/skins/';
+ $return = array('msg'=>'', 'error'=>'1', 'theme'=>$_POST['theme'], 'theme_new_name'=>$_POST['theme_new_name']);
+ $_theme_old = urldecode($_POST['theme']);
+
+ $_theme_new = preg_replace("/\.css$/", '', urldecode($_POST['theme_new_name']));
+
+ # preverimo ali gre za lastno temo, na začetku dodamo $global_user_id+_
+ if (is_numeric( substr($_theme_old, 0, strpos($_theme_old, '_')) )) {
+ $owner = (int)substr($_theme_old, 0, strpos($_theme_old, '_'));
+ if ($owner == $global_user_id) {
+ # gre za lastno temo, na začetku preventivno odstranimo $global_user_id_ in ga nato dodamo
+ $_theme_new = $global_user_id.'_'.preg_replace("/^".$global_user_id."_/", '', $_theme_new);
+ }
+ }
+
+ # novo ime ne sme biti prazno
+ if (trim($_theme_new) == '' || $_theme_new == null) {
+ $return['error'] = 1;
+ $return['msg'] = 'Ime teme ne sme biti prazno!';
+ echo json_encode($return);
+ exit;
+ }
+ $_theme_new = $_theme_new.'.css';
+ # preverimo obstoj stare datoteke
+ if (!file_exists($dir.$_theme_old)) {
+ $return['error'] = 2;
+ $return['msg'] = 'Izvorna datoteka ne obstaja!';
+ echo json_encode($return);
+ exit;
+ }
+
+ #preverimo ali je novo ime enako staremu
+ if ($_theme_old == $_theme_new) {
+ $return['error'] = 3;
+ $return['msg'] = 'Novo ime je enako staremu!';
+ echo json_encode($return);
+ exit;
+ }
+
+ # preverimo in preprečimo obstoj datoteke z novim imenom
+ if (file_exists($dir.$_theme_new)) {
+ $return['error'] = 4;
+ $return['msg'] = 'Datoteka s tem imenom že obstaja!';
+ echo json_encode($return);
+ exit;
+ }
+
+ #preimenujemo datoteko
+ if ((int)rename($dir.$_theme_old,$dir.$_theme_new) == true) {
+ #datoteka je bila uspešno preimenovana, popravimo še v bazi, če je potrebno
+ $simple_name = preg_replace("/\.css$/", '', $_theme_new);
+ $strUpdate = "UPDATE srv_anketa SET skin = '".$simple_name."' WHERE id=".$this->sid;
+ $updated = sisplet_query($strUpdate);
+ sisplet_query("COMMIT");
+ $return = array('msg'=>(int)$updated, 'error'=>'0', 'theme'=>urlencode($_theme_new), 'theme_new_name'=>$_theme_new);
+ echo json_encode($return);
+ exit;
+ } else {
+ $return['error'] = 5;
+ $return['msg'] = 'Pri preimenovanju je prišlo do napake!';
+ echo json_encode($return);
+ exit;
+ }
+
+ # vse je ok!
+ echo json_encode($return);
+ exit;
+
+ }
+
+ // izbrise temo
+ function themeDelete() {
+ global $site_path;
+ global $global_user_id;
+
+ $dir = $site_path . 'main/survey/skins/';
+ $skin = urldecode( $_POST['css'] );
+
+ // preverimo, da ima na zacetku user ID, da ne bo brisal kar vsega po vrsti XX_ ter .css na koncu
+ if ( substr($skin, 0, strpos($skin, '_')+1 ) == $global_user_id.'_' && substr($skin, -4) == '.css' ) {
+
+ unlink($dir.$skin);
+
+ }
+
+ $sql = sisplet_query("SELECT skin FROM srv_anketa WHERE id = '{$_POST['anketa']}'");
+ $row = mysqli_fetch_array($sql);
+
+ if ($row['skin'] == substr($skin, 0, -4)) {
+ sisplet_query("UPDATE srv_anketa SET skin='Default' WHERE id = '{$_POST['anketa']}'");
+ }
+ }
+
+ // iz imena skina odstrani uid stevilko userja in _
+ function strip_name ($simple_name) {
+
+ // Popravimo se default skine - vstavimo presledek da lepse izgleda
+ $skins = array(
+ '1kaBlue (Privzeto)', '1kaRed', '1kaOrange', '1kaGreen', '1kaPurple', '1kaBlack', '1kaOffice', '1kaNature',
+ 'MobileBlue (Privzeto)', 'MobileRed', 'MobileOrange', 'MobileGreen', 'MobilePurple', 'MobileBlack',
+ 'MobileUni', 'MobileFdv', 'MobileCdi'
+ );
+ if(in_array($simple_name, $skins)){
+ $simple_name = preg_replace('/(?<!\ )[A-Z]/', ' $0', $simple_name);
+ }
+
+ if ( is_numeric( substr($simple_name, 0, strpos($simple_name, '_')) ) )
+ $simple_name = substr($simple_name, strpos($simple_name, '_')+1);
+
+ return $simple_name;
+ }
+
+ function upload_css() {
+ global $lang;
+ global $site_url;
+
+ $row = SurveyInfo::getSurveyRow();
+
+ $default = 'Default';
+ $skin = ($row['skin'] == '') ? $default : $row['skin'];
+
+ echo '<br /><span class="bold">'.$lang['srv_add_theme_upload'].'</span>';
+ echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->sid . '&profile='.$_GET['profile'].'" method="post">';
+ echo '<p><label for="skin">' . $lang['srv_uploadtheme'] . ':</label> ';
+ echo '<input type="file" name="fajl" onchange="submit();">';
+ echo ' (' . $lang['srv_skintmpl1'] . ' <a href="' . $site_url . 'main/survey/skins/'.$skin.'.css" target="_blank">' . $lang['srv_skintmpl'] . '</a>)';
+ echo '</p></form>';
+
+
+ echo '<p style="font-size:90%; color: gray">'.$lang['srv_skin_disclamer'].'</p>';
+
+ echo '<a href="#" onclick="$(\'#vrednost_edit\').hide().html(\'\'); return false;" style="position:absolute; right:10px; bottom:10px">'.$lang['srv_zapri'].'</a>';
+
+ }
+
+ function edit_css () {
+ global $lang;
+ global $site_url;
+ global $site_path;
+ global $admin_type;
+ global $global_user_id;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $skin = $_GET['skin'];
+
+ echo '<div id="theme-editor">';
+
+ echo '<div id="theme-editor-warning">'.$lang['srv_themes_edit_warning'].'</div>';
+
+ echo '<form name="editcss" action="ajax.php?anketa='.$this->sid.'&a=save_editcss" method="post" onsubmit="return false;">';
+
+ $profile = $_GET['profile'];
+ $mobile = (isset($_GET['mobile']) && $_GET['mobile'] == '1') ? true : false;
+
+ $sqlp = sisplet_query("SELECT usr_id FROM srv_theme_profiles".($mobile ? '_mobile' : '')." WHERE id = '$profile'");
+ $rowp = mysqli_fetch_array($sqlp);
+
+ $skin_name = str_replace($rowp['usr_id'].'_', '', $skin);
+
+ //echo '<p>'.$lang['srv_skinname'].': <input type="text" name="skin_name" value="'.$skin_name.'" /></p>';
+ echo '<input type="hidden" name="skin_name" value="'.$skin_name.'">';
+ echo '<input type="hidden" name="profile" value="'.$_GET['profile'].'">';
+ echo '<input type="hidden" name="mobile" value="'.($mobile ? '1' : '0').'">';
+
+ echo '<br />';
+
+ echo '<span class="bold">'.$lang['srv_themes_edit'].'</span>';
+ echo '<p><textarea name="css_content" style="width:100%; height: 400px">';
+
+ readfile('../../main/survey/skins/'.$skin.'.css');
+
+ echo '</textarea></p>';
+
+ echo '<p>';
+
+ echo '<p><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange btn_savesettings floatLeft spaceRight" href="#" onclick="';
+ ?>$.post('ajax.php?anketa=<?=$this->sid?>&a=save_editcss', $('form[name=editcss]').serialize(), function (data) {
+ //if ( $('input[name=skin_name]').val() != $('input[name=old_name]').val() ) {
+ // window.location.href = 'index.php?anketa=<?=$this->sid?>&a=edit_css&skin='+data;
+ //} else {
+ var iframe = document.getElementById('theme-preview-iframe');
+ iframe.src = iframe.src;
+ if ( $('input[name=current_skin]').is(':checked') ) $('input[name=current_skin]').attr('disabled', true);
+ //}
+ }); return false;<?php
+ echo '"><span>'. $lang['edit1337'] . '</span></a>';
+
+ //echo '<a class="ovalbutton ovalbutton_gray spaceRight floatLeft" href="index.php?anketa='.$this->sid.'&a=tema"><span>'.$lang['srv_theme_save_as_new'].'</span></a>';
+
+ echo '<a class="ovalbutton ovalbutton_gray floatLeft" href="index.php?anketa='.$this->sid.'&a=tema"><span>'.$lang['back'].'</span></a></p>';
+ echo '<div class="clr"></div>';
+ echo '</div></p>';
+ echo '</form>';
+
+ echo '<br /><p><a href="#" onclick="javascript:$(\'#show_more\').slideToggle(); return false;">'.$lang['srv_upload_pic'].'</a></p>';
+
+ echo '<fieldset id="show_more" style="'.($_GET['pic']=='open'?'':'display:none;').' margin-bottom:40px">';
+
+
+ echo '<br /><span class="bold">'.$lang['srv_upload_pic'].':</span>';
+ /*echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->sid . '&logo=1" method="post" />';
+ echo '<p><label for="skin">' . $lang['srv_upload_logo'] . ':</label> ';
+ echo '<input type="file" name="fajl" onchange="submit();" onmouseout="survey_upload();" />';
+ echo '</p></form>'; */
+
+ echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->sid . '&skin='.$skin.'&profile='.$_GET['profile'].'" method="post" />';
+ echo '<p><label for="skin">' . $lang['srv_upload_pic2'] . ':</label> ';
+ echo '<input type="file" name="fajl" onchange="submit();" onmouseout="survey_upload();" />';
+ echo '</p></form>';
+ echo '<p style="font-size:90%; color: gray">'.$lang['srv_upload_pic_disclaimer'].'</p><br />';
+
+ // prikazemo uploadane slike
+ $dir = opendir($site_path . 'main/survey/uploads/');
+ $skinsArray = array();
+ $skinsArrayPersonal = array();
+ while ($file = readdir($dir)) {
+
+ if ( $file!='.' && $file!='..') {
+ $allowed = false;
+
+ if (is_numeric( substr($file, 0, strpos($file, '_')) )) {
+ $owner = (int)substr($file, 0, strpos($file, '_'));
+ if ($owner == $global_user_id)
+ $allowed = true;
+ }
+
+ if ($allowed) {
+ echo '<a href="'.$site_url.'main/survey/uploads/'.$file.'" target="_blank"><img src="'.$site_url.'main/survey/uploads/'.$file.'" alt="" style="max-width:200px; max-height:200px"></a> ';
+ }
+ }
+ }
+ echo '</fieldset>';
+
+ echo '<div id="success_save"></div>';
+
+ echo '</div>';
+
+ $sql = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='$this->sid' ORDER BY vrstni_red ASC LIMIT 1");
+ $row = mysqli_fetch_array($sql);
+ $grupa = $row['id'];
+
+ //echo '<div id="theme-preview"><iframe id="theme-preview-iframe" src="'.SurveyInfo::getSurveyLink().'&grupa='.$grupa.'&no_preview=1&preview=on&theme='.$skin.'"></iframe></div>';
+ echo '<div id="theme-preview"><iframe id="theme-preview-iframe" src="'.SurveyInfo::getSurveyLink().'&grupa='.$grupa.'&no_preview=1&preview=on&theme_profile='.$_GET['profile'].'&theme-preview=1'.($mobile ? '&mobile=1' : '').'"></iframe><div class="theme-overflow"></div></div>';
+
+ //echo '</div>';
+
+ //echo '<div class="clr"></div>';
+
+ //echo '</div>';
+
+ SurveyThemeEditor::new_theme_alert($skin_name, true);
+ }
+
+ function ajax_add_theme () {
+ global $lang;
+ global $site_url;
+
+ $row = SurveyInfo::getSurveyRow();
+
+ $default = 'Default';
+
+ echo '<h3 style="color:#900">'.$lang['srv_add_theme_css'].'</h3>';
+
+ echo '<p>'.$lang['srv_select_base_theme'].': <select name="new_theme" id="new_theme" onchange="$(\'input[name=name]\').val( $(this).val() );">';
+ foreach ($this->groups[0]['skins'] AS $key => $val) {
+ $skin = str_replace('.css', '', $val);
+ echo '<option value="'.$skin.'" '.($skin==$default?'selected':'').'>'.$skin.'</option>';
+ }
+ echo '</select> <span style="font-size:90%; color: gray">'.$lang['srv_select_base_theme_2'].'</span></p>';
+ echo '<p>'.$lang['srv_skinname'].': <input type="text" name="name" value="'.$default.'"></p>';
+
+ echo '<p><input type="submit" value="'.$lang['add'].'" onclick="window.location.href=\'index.php?anketa='.$this->sid.'&a=edit_css&new=1&skin=\'+$(\'#new_theme\').val()+\'&name=\'+$(\'input[name=name]\').val(); return false;"></p>';
+
+ echo '<br /><h3 style="color:#900">'.$lang['srv_add_theme_upload'].'</h3>';
+ echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->sid . '" method="post">';
+ echo '<p><label for="skin">' . $lang['srv_uploadtheme'] . ':</label> ';
+ echo '<input type="file" name="fajl" onchange="submit();">';
+ echo ' (' . $lang['srv_skintmpl1'] . ' <a href="' . $site_url . 'main/survey/skins/'.$row['skin'].'.css" target="_blank">' . $lang['srv_skintmpl'] . '</a>)';
+ echo '</p></form>';
+
+
+ echo '<p style="font-size:90%; color: gray">'.$lang['srv_skin_disclamer'].'</p>';
+
+ echo '<a href="#" onclick="$(\'#vrednost_edit\').hide().html(\'\'); return false;" style="position:absolute; right:10px; bottom:10px">'.$lang['srv_zapri'].'</a>';
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyThemeEditor.php b/admin/survey/classes/class.SurveyThemeEditor.php
new file mode 100644
index 0000000..ef85967
--- /dev/null
+++ b/admin/survey/classes/class.SurveyThemeEditor.php
@@ -0,0 +1,533 @@
+<?php
+
+class SurveyThemeEditor {
+
+ private $anketa = null;
+ private $profile = null;
+
+ private $mobile = '';
+
+ static $fonts = array(
+ 1 => 'Palatino Linotype, Book Antiqua, Palatino, serif',
+ 2 => 'Times New Roman, Times, serif',
+ 3 => 'Arial, Helvetica, sans-serif',
+ 4 => 'Arial Black, Gadget, sans-serif',
+ 5 => 'Comic Sans MS, cursive, sans-serif',
+ 6 => 'Impact, Charcoal, sans-serif',
+ 7 => 'Lucida Sans Unicode, Lucida Grande, sans-serif',
+ 8 => 'Tahoma, Geneva, sans-serif',
+ 9 => 'Trebuchet MS, Helvetica, sans-serif',
+ 10 => 'Verdana, Geneva, sans-serif',
+ 11 => 'Courier New, Courier, monospace',
+ 12 => 'Lucida Console, Monaco, monospace',
+ 13 => 'Georgia, serif',
+
+ );
+
+ function __construct ($anketa, $ajax=false) {
+ global $site_path, $global_user_id;
+
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+ $row = SurveyInfo::getSurveyRow();
+
+ $this->profile = (int)$_GET['profile'];
+
+ $this->mobile = (isset($_GET['mobile']) && $_GET['mobile'] == '1') ? '_mobile' : '';
+
+ if ($ajax) return;
+
+ if ( ! $this->profile > 0 ) die();
+ }
+
+ function display () {
+ global $lang;
+ global $global_user_id;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ $sqla = sisplet_query("SELECT id, name, logo FROM srv_theme_profiles".$this->mobile." WHERE id = '$this->profile'");
+ $rowa = mysqli_fetch_array($sqla);
+
+ self::new_theme_alert($rowa['name']);
+
+ echo '<div id="theme-editor">';
+ echo '<input type="hidden" name="profile" id="profile" value="'.$this->profile.'">';
+
+ $mobile = (isset($_GET['mobile']) && $_GET['mobile'] == '1') ? 1 : 0;
+ echo '<input type="hidden" name="mobile" id="mobile" value="'.$mobile.'">';
+
+ echo '<div id="picker"></div>';
+
+ echo '<fieldset><legend>'.$lang['srv_skinname'].'</legend>';
+ echo '<p>'.$lang['srv_skinname'].': <input type="text" name="skin-name" value="'.$rowa['name'].'" onblur="te_change_name(this);"></p>';
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ // Mobilni skin nima logotipa
+ if($mobile != 1){
+ echo '<fieldset><legend>'.$lang['srv_upload_logo'].'</legend>';
+ echo '<form name="upload" enctype="multipart/form-data" action="upload.php?anketa=' . $this->anketa . '&logo=1&te=1&profile='.$this->profile.'" method="post" />';
+ echo '<p>' . $lang['srv_upload_logo'] . ': ';
+ echo '<input type="file" name="fajl" onchange="submit();" onmouseout="survey_upload();" />';
+ if ($rowa['logo'] != '') {
+ echo '<p>'.$rowa['logo'];
+ echo ' <a href="#" onclick="survey_remove_logo(\''.$this->profile.'\'); return false" title="'.$lang['srv_te_remove_setting'].'"><span class="faicon delete_circle icon-orange_link"></span></a>';
+ echo '</p>';
+ }
+ echo '</p></form>';
+ echo '</fieldset>';
+
+ echo '<br />';
+ }
+
+ // Mobilni skin nima progressbara
+ if($mobile != 1){
+ $sqlg = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id = '$this->anketa'");
+ if (mysqli_num_rows($sqlg) > 1) {
+ echo '<fieldset><legend>'.$lang['srv_te_progressbar'].'</legend>';
+ echo '<div id="theme_progressbar">';
+ echo '<p><label>' . $lang['srv_te_progressbar_show'] . ':</label> ';
+ echo '<label for="theme_progressbar_1"><input type="radio" id="theme_progressbar_1" name="progressbar" value="1"' . ($row['progressbar'] == 1 ? ' checked="checked"' : '') . ' autocomplete="off"/>' . $lang['yes'] . '</label> ';
+ echo '<label for="theme_progressbar_0"><input type="radio" id="theme_progressbar_0" name="progressbar" value="0"' . ($row['progressbar'] == 0 ? ' checked="checked"' : '') . ' autocomplete="off"/>' . $lang['no1'] . '</label> ';
+ echo '</p></div>'; # id="theme_progressbar"
+ echo '</fieldset>';
+
+ echo '<br />';
+ }
+ }
+
+ echo '<fieldset><legend>'.$lang['srv_te_survey_h_text'].'</legend>';
+ $this->displayOption(1, 1);
+ $this->displayOption(1, 4);
+ $this->displayOption(1, 2);
+ $this->displayOption(1, 3);
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ echo '<fieldset><legend>'.$lang['srv_te_outer_frame'].'</legend>';
+ $this->displayOption(6, 3);
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ echo '<fieldset><legend>'.$lang['srv_te_question_border'].'</legend>';
+ $this->displayOption(5, 5);
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ echo '<fieldset><legend>'.$lang['srv_te_question_text'].'</legend>';
+ $this->displayOption(2, 1);
+ $this->displayOption(2, 4);
+ $this->displayOption(2, 2);
+ $this->displayOption(5, 3);
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ echo '<fieldset><legend>'.$lang['srv_te_answers_text'].'</legend>';
+ $this->displayOption(3, 1);
+ $this->displayOption(3, 4);
+ $this->displayOption(3, 2);
+ $this->displayOption(4, 3);
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ // Custom checkbox/radio (stars, smilies, thumbs)
+ echo '<fieldset>';
+ // Radio/checkboxi za pc
+ if($mobile != 1){
+ echo '<legend>'.$lang['srv_te_custom_checkbox_radio'].'</legend>';
+ $this->displayOption(7, 7);
+ $this->displayOption(7, 15);
+ //$this->displayOption(10, 17);
+ }
+ // Radio/checkboxi za mobitel
+ else{
+ echo '<legend>'.$lang['srv_te_custom_mobile_checkbox_radio'].'</legend>';
+ $this->displayOption(7, 8);
+ $this->displayOption(7, 16);
+ // Za mobitel ne rabimo accessibility ikon
+ //$this->displayOption(10, 17);
+ }
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ // Tooltipster/slovar/glossary
+ echo '<fieldset><legend>'.$lang['srv_te_custom_glossary_popup'].'</legend>';
+ $this->displayOption(8, 9);
+ $this->displayOption(8, 11);
+ $this->displayOption(8, 10);
+ $this->displayOption(8, 12);
+ echo '</fieldset>';
+
+ echo '<br />';
+
+ echo '<fieldset><legend>'.$lang['srv_te_custom_glossary_keywords'].'</legend>';
+ $this->displayOption(9, 9);
+ $this->displayOption(9, 13);
+ $this->displayOption(9, 14);
+ echo '</fieldset>';
+
+
+ echo '<p><label><input type="checkbox" name="current_skin" value="1" '.($row['skin_profile'] == $rowa['id']?'checked disabled':'').' onchange="$(this).attr(\'disabled\', true); te_change_profile(\''.$this->profile.'\'); return false;"> '.$lang['srv_save_set_theme'].'</label></p>';
+
+ echo '<p>';
+ echo '<div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange floatLeft" href="index.php?anketa='.$this->anketa.'&a=tema"><span>'.$lang['edit1337'].'</span></a></div>';
+ echo '</p>';
+
+ echo '</div>';
+
+ $this->preview();
+
+ ?>
+ <script>
+ $(document).ready(function() {
+ init_themeEditor();
+ });
+ </script>
+ <?
+
+ //echo '</div>';
+
+ }
+
+ static function new_theme_alert ($name, $css=false) {
+ global $lang;
+
+ return;
+ if ($_GET['newalert'] != '1') return;
+
+ echo '<div id="new_theme_alert">';
+ echo '<p>';
+ printf($lang['srv_new_theme_alert'.($css?'_css':'')], $name);
+ echo '</p>';
+ echo '</div>';
+
+ ?>
+ <script>
+ $('#new_theme_alert').delay(5000).slideUp();
+ </script>
+ <?
+
+ }
+
+ /**
+ * poskrbi za razlicne opcije nastavitev teme
+ *
+ * za prikaz v anketi skrbi funkcija themeEditor(); v main/Survey.php
+ *
+ * @param mixed $id
+ * @param mixed $type
+ */
+ function displayOption ($id, $type) {
+ global $lang;
+
+ $sql = sisplet_query("SELECT value FROM srv_theme_editor".$this->mobile." WHERE profile_id='$this->profile' AND id='$id' AND type='$type'");
+ $row = mysqli_fetch_array($sql);
+
+ echo '<p>';
+
+ // pisava
+ if ($type == 1) {
+
+ echo ''.$lang['srv_te_font_family'].': <select name="font'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">';
+ echo '<option value=""'.(''==$row['value']?' selected':'').' style="font-size:13px">'.$lang['srv_te_default'].'</option>';
+ foreach (self::$fonts AS $key => $val) {
+ echo '<option value="'.$key.'"'.($key==$row['value']?' selected':'').' style="font-family: '.$val.'; font-size:13px">'.substr($val, 0, strpos($val, ',')).'</option>';
+ }
+ echo '</select> ';
+
+ if ($row['value'] != '')
+ echo '<a href="#" onclick="te_remove_setting(\''.$id.'\', \''.$type.'\'); return false;" title="'.$lang['srv_te_remove_setting'].'"><span class="sprites arrow_undo"></span></a>';
+
+ // barva pisave, barva ozadja
+ } elseif (($type == 3 && $id != 1) || in_array($type, [2, 9, 10, 13, 15, 16])) {
+
+ if ($row['value'] == '') $value = '#000000'; else $value = $row['value'];
+
+ if ($type == 2 || $type == 9)
+ echo ''.$lang['srv_te_font_color'].': ';
+ elseif ($type == 3)
+ echo ''.$lang['srv_te_background_color'].': ';
+ elseif($type == 10)
+ echo ''.$lang['srv_te_custom_border_color'].': ';
+ elseif($type == 13)
+ echo ''.$lang['srv_te_custom_background_keywords'].': ';
+ elseif($type == 15)
+ echo ''.$lang['srv_te_custom_icon_pc_color'].': ';
+ elseif($type == 16)
+ echo ''.$lang['srv_te_custom_icon_mobile_color'].': ';
+
+ if ($row['value'] == '') echo '<span><a href="#" onclick="$(\'#color-'.$id.'-'.$type.'\').show(); $(this).parent().hide(); return false;" title="'.$lang['edit4'].'">'.$lang['srv_te_default'].' <span class="faicon edit"></span></a></span>';
+
+ echo '<span id="color-'.$id.'-'.$type.'" '.($row['value']==''?'style="display:none;"':'').'>';
+ echo '<input type="text" id="color'.$id.'-'.$type.'" class="colorwell auto-save" name="color'.$id.'-'.$type.'" value="'.$value.'" data-id="'.$id.'" data-type="'.$type.'"> ';
+ echo '<a href="#" onclick="te_remove_setting(\''.$id.'\', \''.$type.'\'); return false;" title="'.$lang['srv_te_remove_setting'].'"><span class="sprites arrow_undo"></span></a>';
+ echo '</span>';
+
+ // velikost pisave
+ } elseif ($type == 4) {
+
+ echo ''.$lang['srv_te_font_size'].': <select name="fontsize'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">';
+ echo '<option value=""'.(''==$row['value']?' selected':'').'>'.$lang['srv_te_default'].'</option>';
+ for ($i=50; $i<=200; $i+=10) {
+ echo '<option value="'.$i.'"'.($i==$row['value']?' selected':'').' style="font-size: '.$i.'%;">'.$i.'%</option>';
+ }
+ echo '</select> ';
+
+ if ($row['value'] != '')
+ echo '<a href="#" onclick="te_remove_setting(\''.$id.'\', \''.$type.'\'); return false;" title="'.$lang['srv_te_remove_setting'].'"><span class="sprites arrow_undo"></span></a>';
+
+ // border vprasanja
+ } elseif ($type == 5) {
+
+ if ($row['value'] == '') $value = '1'; else $value = $row['value'];
+
+ echo $lang['srv_te_question_border'].': <select name="question_border'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">';
+ echo '<option value="" '.(''==$row['value']?' selected':'').'>'.$lang['default'].'</option>';
+ echo '<option value="0" '.($row['value']=='0'?' selected':'').'>'.$lang['srv_te_question_border_0'].'</option>';
+ echo '<option value="1" '.($row['value']=='1'?' selected':'').'>'.$lang['srv_te_question_border_1'].'</option>';
+ echo '<option value="2" '.($row['value']=='2'?' selected':'').'>'.$lang['srv_te_question_border_2'].'</option>';
+ echo '</select> ';
+
+ // izbira custom checkbox/radio gumbov
+ } elseif($type == 7 ) {
+ echo $lang['srv_te_custom_icon_pc'] . ': ';
+ echo '<select id="izbira-checkbox-gumbov" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">
+ <option value="0" '.(($row['value'] == 0 || is_null($row['value'])) ? " selected":"").'>'.$lang['default'].'</option>
+ <option value="18" '.($row['value'] == 18 ? " selected":"").'>18 px</option>
+ <option value="21" '.($row['value'] == 21 ? " selected":"").'>21 px</option>
+ <option value="25" '.($row['value'] == 25 ? " selected":"").'>25 px</option>
+ <option value="30" '.($row['value'] == 30 ? " selected":"").'>30 px</option>
+ <option value="35" '.($row['value'] == 35 ? " selected":"").'>35 px</option>
+ <option value="40" '.($row['value'] == 40 ? " selected":"").'>40 px</option>
+ <option value="45" '.($row['value'] == 45 ? " selected":"").'>45 px</option>
+ <option value="50" '.($row['value'] == 50 ? " selected":"").'>50 px</option>
+ <option value="55" '.($row['value'] == 55 ? " selected":"").'>55 px</option>
+ </select>';
+
+
+ } elseif($type == 8) {
+ echo $lang['srv_te_custom_icon_mobile'] . ': ';
+ echo '<select id="izbira-checkbox-gumbov" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">
+ <option value="0" '.(($row['value'] == 0 || is_null($row['value'])) ? " selected":"").'>'.$lang['default'].'</option>
+ <option value="21" '.($row['value'] == 20 ? " selected":"").'>20 px</option>
+ <option value="25" '.($row['value'] == 25 ? " selected":"").'>25 px</option>
+ <option value="30" '.($row['value'] == 30 ? " selected":"").'>30 px</option>
+ <option value="35" '.($row['value'] == 35 ? " selected":"").'>35 px</option>
+ <option value="40" '.($row['value'] == 40 ? " selected":"").'>40 px</option>
+ <option value="45" '.($row['value'] == 45 ? " selected":"").'>45 px</option>
+ <option value="50" '.($row['value'] == 50 ? " selected":"").'>50 px</option>
+ <option value="55" '.($row['value'] == 55 ? " selected":"").'>55 px</option>
+ </select>';
+
+ // Izpišemo border opcije
+ } elseif($type == 11) {
+ echo $lang['srv_te_custom_border_size'].': ';
+ echo '<select name="bordersize'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">';
+ echo '<option value=""'.(''==$row['value']?' selected':'').'>'.$lang['srv_te_default'].'</option>';
+ for ($i=1; $i<=6; $i++) {
+ echo '<option value="'.$i.'"'.($i==$row['value']?' selected':'').'>'.$i.'px</option>';
+ }
+ echo '</select> ';
+
+ } elseif($type == 12) {
+ echo $lang['srv_te_custom_border_radius'].': ';
+ echo '<select name="borderradius'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">';
+ echo '<option value=""'.(''==$row['value']?' selected':'').'>'.$lang['srv_te_default'].'</option>';
+ for ($i=5; $i<=30; $i+=5) {
+ echo '<option value="'.$i.'"'.($i==$row['value']?' selected':'').'>'.$i.'px</option>';
+ }
+ echo '</select> ';
+
+ // Stil pisave bold, italic, underline
+ } elseif($type == 14) {
+ echo $lang['srv_te_custom_font_style_keywords'].': ';
+ echo '<select name=""keyword_style'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save">';
+ echo '<option value=""'.(''==$row['value']?' selected':'').'>'.$lang['srv_te_default'].'</option>';
+ echo '<option value="bold" '.('bold'==$row['value']?' selected':'').'>'.$lang['srv_te_custom_font_style_keywords_bold'].'</option>';
+ echo '<option value="italic" '.('italic'==$row['value']?' selected':'').'>'.$lang['srv_te_custom_font_style_keywords_italic'].'</option>';
+ echo '<option value="underline" '.('underline'==$row['value']?' selected':'').'>'.$lang['srv_te_custom_font_style_keywords_underline'].'</option>';
+ echo '</select> ';
+
+ // Accessibility checkbox (radio/checkboxi niso obarvani)
+ } elseif($type == 17) {
+ echo '<label for="accessibility'.$id.'">'.$lang['srv_te_custom_icon_accessibility'].': ';
+ echo '<input type="checkbox" value="1" name="accessibility'.$id.'" id="accessibility'.$id.'" data-id="'.$id.'" data-type="'.$type.'" class="auto-save" '.($row['value'] == '1' ? ' checked="checked"' : '').'></label>';
+ }
+
+ echo '</p>';
+ }
+
+ function preview () {
+
+ $sql = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='$this->anketa' ORDER BY vrstni_red ASC LIMIT 1");
+ $row = mysqli_fetch_array($sql);
+ $grupa = $row['id'];
+
+ $mobile = (isset($_GET['mobile']) && $_GET['mobile'] == '1') ? '&mobile=1' : '';
+
+ echo '<div id="theme-preview"><iframe id="theme-preview-iframe" src="'.SurveyInfo::getSurveyLink().'&grupa='.$grupa.'&no_preview=1&preview=on&theme_profile='.$this->profile.'&theme-preview=1'.$mobile.'"></iframe><div class="theme-overflow"></div></div>';
+ }
+
+ static function getFont ($font) {
+ return self::$fonts[$font];
+ }
+
+ function ajax() {
+
+ if ($_GET['a'] == 'auto_save') {
+ $this->ajax_auto_save();
+
+ } elseif ($_GET['a'] == 'change_profile') {
+ $this->ajax_change_profile();
+
+ } elseif ($_GET['a'] == 'change_profile_oldskin') {
+ $this->ajax_change_profile_oldskin();
+
+ } elseif ($_GET['a'] == 'delete_profile') {
+ $this->ajax_delete_profile();
+
+ } elseif ($_GET['a'] == 'add_theme') {
+ $this->ajax_add_theme();
+
+ } elseif ($_GET['a'] == 'change_name') {
+ $this->ajax_change_name();
+
+ }
+
+ }
+
+ function ajax_auto_save() {
+
+ $id = $_POST['id'];
+ $type = $_POST['type'];
+ $value = $_POST['value'];
+
+ if ($value == '') {
+ $s = sisplet_query("DELETE FROM srv_theme_editor".$this->mobile." WHERE profile_id='$this->profile' AND id='$id' AND type='$type'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ } else {
+ $s = sisplet_query("REPLACE INTO srv_theme_editor".$this->mobile." (profile_id, id, type, value) VALUES ('$this->profile', '$id', '$type', '$value')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ function ajax_change_profile () {
+
+ $sql = sisplet_query("SELECT skin FROM srv_theme_profiles".$this->mobile." WHERE id = '$this->profile'");
+ $row = mysqli_fetch_array($sql);
+
+ if($this->mobile == '_mobile')
+ $s = sisplet_query("UPDATE srv_anketa SET mobile_skin='".$row['skin']."', skin_profile_mobile='".$this->profile."' WHERE id = '".$this->anketa."'");
+ else
+ $s = sisplet_query("UPDATE srv_anketa SET skin='".$row['skin']."', skin_profile='".$this->profile."' WHERE id = '".$this->anketa."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ }
+
+ function ajax_change_profile_oldskin () {
+ global $global_user_id;
+
+ $skin = $_POST['skin'].'';
+ $name = str_replace($global_user_id.'_', '', $skin);
+
+ $sql = sisplet_query("INSERT INTO srv_theme_profiles".$this->mobile." (id, usr_id, skin, name) VALUES ('', '$global_user_id', '$skin', '$name')");
+ $profile = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $s = sisplet_query("UPDATE srv_anketa SET skin='".$skin."', skin_profile='".$profile."' WHERE id = '".$this->anketa."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo 'index.php?anketa='.$this->anketa.'&a=theme-editor&profile='.$profile.'&newalert=1';
+
+ }
+
+ function ajax_delete_profile () {
+ global $site_path;
+ global $global_user_id;
+
+ $row = SurveyInfo::getSurveyRow();
+
+ if($this->mobile == '_mobile'){
+ if ($row['skin_profile_mobile'] == $this->profile) {
+ $s = sisplet_query("UPDATE srv_anketa SET skin_profile_mobile='0', mobile_skin='MobileBlue' WHERE id = '".$this->anketa."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ $sql = sisplet_query("SELECT skin FROM srv_theme_profiles_mobile WHERE id = '$this->profile'");
+ $row = mysqli_fetch_array($sql);
+
+ // ce ima svojo temo, jo zbrisemo
+ if ( strpos($row['skin'], $global_user_id.'_') !== false ) {
+ $dir = $site_path . 'main/survey/skins/';
+ unlink($dir.$row['skin'].'.css');
+ }
+
+ $s = sisplet_query("DELETE FROM srv_theme_profiles_mobile WHERE id = '$this->profile'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ else{
+ if ($row['skin_profile'] == $this->profile) {
+ $s = sisplet_query("UPDATE srv_anketa SET skin_profile='0', skin='1kaBlue' WHERE id = '".$this->anketa."'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ $sql = sisplet_query("SELECT skin FROM srv_theme_profiles WHERE id = '$this->profile'");
+ $row = mysqli_fetch_array($sql);
+
+ // ce ima svojo temo, jo zbrisemo
+ if ( strpos($row['skin'], $global_user_id.'_') !== false ) {
+ $dir = $site_path . 'main/survey/skins/';
+ unlink($dir.$row['skin'].'.css');
+ }
+
+ $s = sisplet_query("DELETE FROM srv_theme_profiles WHERE id = '$this->profile'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ function ajax_add_theme() {
+ global $lang;
+ global $site_url;
+
+ ob_clean();
+
+ $row = SurveyInfo::getSurveyRow();
+
+ $st = new SurveyTheme($this->anketa, true);
+ $groups = $st->getGroups();
+
+ $default = 'Default';
+
+ echo '<h3 style="color:#900">'.$lang['srv_add_theme'].'</h3>';
+
+ echo '<p>'.$lang['srv_select_base_theme'].': <select name="new_theme" id="new_theme" onchange="$(\'input[name=name]\').val( $(this).val() + \'\' );">';
+ foreach ($groups[0]['skins'] AS $key => $val) {
+ $skin = str_replace('.css', '', $val);
+ echo '<option value="'.$skin.'" '.($skin==$default?'selected':'').'>'.$skin.'</option>';
+ }
+ echo '</select> <span style="font-size:90%; color: gray">'.$lang['srv_select_base_theme_2'].'</span></p>';
+
+ echo '<p>'.$lang['srv_skinname'].': <input type="text" name="name" value="'.$default.'"></p>';
+
+ echo '<p><input type="submit" value="'.$lang['add'].'" onclick="window.location.href=\'index.php?anketa='.$this->anketa.'&a=theme-editor&profile_new=\'+$(\'#new_theme\').val()+\'&name=\'+$(\'input[name=name]\').val(); return false;"></p>';
+
+ echo '<a href="#" onclick="$(\'#vrednost_edit\').hide().html(\'\'); return false;" style="position:absolute; right:10px; bottom:10px">'.$lang['srv_zapri'].'</a>';
+ }
+
+ function ajax_change_name() {
+
+ $s = sisplet_query("UPDATE srv_theme_profiles".$this->mobile." SET name='".$_POST['name']."' WHERE id = '".$_GET['profile']."'");
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyTimeProfiles.php b/admin/survey/classes/class.SurveyTimeProfiles.php
new file mode 100644
index 0000000..0c88b11
--- /dev/null
+++ b/admin/survey/classes/class.SurveyTimeProfiles.php
@@ -0,0 +1,707 @@
+<?php
+/**
+ * Created on 13.01.2011
+ *
+ * @author: Gorazd Veselič
+ */
+
+
+
+define('STP_INTERVAL_1_DAY', '1 day'); # previdno pri spremembi tekstov, ker gre za PHP veljavne stringe za računanje z datumi
+define('STP_INTERVAL_2_DAY', '2 day');
+define('STP_INTERVAL_5_DAY', '5 day');
+define('STP_INTERVAL_7_DAY', '7 day');
+define('STP_INTERVAL_14_DAY', '14 day');
+define('STP_INTERVAL_1_MONTH', '1 month');
+define('STP_INTERVAL_3_MONTH', '3 month');
+define('STP_INTERVAL_6_MONTH', '6 month');
+
+
+define('STP_DEFAULT_PROFILE', 0);
+
+class SurveyTimeProfiles {
+
+ static private $surveyId = null;
+ static private $uId = null;
+
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+
+ static private $start_date = null; # začetek ankete
+ static private $end_date = null; # konec ankete
+
+ static private $STP_ARRAYS = array( STP_INTERVAL_1_DAY,
+ STP_INTERVAL_2_DAY,
+ STP_INTERVAL_5_DAY,
+ STP_INTERVAL_7_DAY,
+ STP_INTERVAL_14_DAY,
+ STP_INTERVAL_1_MONTH,
+ STP_INTERVAL_3_MONTH,
+ STP_INTERVAL_6_MONTH); // array možnih intervalov za dropdown
+
+ static function getSurveyId() { return self::$surveyId; }
+ static function getGlobalUserId() { return self::$uId; }
+ static function getCurentProfileId() { return (int)self::$currentProfileId; }
+
+ /** Inizializacija, poišče id privzetega profila in prebere vse profiel ki jih ima uporabnik na voljo
+ *
+ * @param $_surveyId
+ */
+ static function Init($_surveyId)
+ {
+
+ global $global_user_id, $lang;
+
+ if ($_surveyId && $global_user_id)
+ {
+ self::$surveyId = $_surveyId;
+ self::$uId = $global_user_id;
+
+ # inicializiramo datoteko z nastavitvami
+ SurveyUserSetting :: getInstance()->Init(self::$surveyId, self::$uId);
+ # preverimo ali ima uporabnik nastavljen privzet profil
+ $dsp = SurveyUserSetting :: getInstance()->getSettings('default_time_profile');
+
+ if ( $dsp == null ) {
+ # nastavimo privzet profil v clas
+ $dsp = 0;
+ }
+
+ #dodamo profil iz seje
+ if ( (int)$dsp == -1 ) {
+ if ( isset($_SESSION['time_profile'][self::$surveyId])) {
+ #dodamo profil iz seje
+ self::$profiles['-1'] = array('id'=>'-1',
+ 'name'=>$lang['srv_temp_profile'],
+ 'type'=>$_SESSION['time_profile'][self::$surveyId]['type'],
+ 'starts'=>$_SESSION['time_profile'][self::$surveyId]['starts'],
+ 'ends'=>$_SESSION['time_profile'][self::$surveyId]['ends'],
+ 'interval_txt'=>$_SESSION['time_profile'][self::$surveyId]['interval_txt']);
+ $dsp = -1;
+
+ } else {
+ // ni v seji, naredimo privzetega
+ $dsp = 0;
+ }
+ }
+
+ # če mamo spremembo shranimo
+ self::SetDefaultProfileId((int)$dsp);
+
+ #dodamo privzet profil
+ # datum od, "ce ni podan vzamemo kreacijo ankete
+ SurveyInfo :: getInstance()->SurveyInit(self::getSurveyId());
+
+ self::$start_date = date(STP_DATE_FORMAT, strtotime(SurveyInfo::getInstance()->getSurveyInsertDate()));
+
+ # datum do, "ce ni podan vzamemo danasnji dan
+ self::$end_date = date(STP_DATE_FORMAT);// ce ne,
+
+ # dodamo sistemski profil
+ self::$profiles['0'] = array( 'id'=>0,
+ 'type'=>0,
+ 'name'=>$lang['srv_default_profile'],
+ 'starts'=>self::$start_date,
+ 'ends'=>self::$end_date,
+ 'interval_txt'=>'');
+
+ # poiščemo še seznam vseh ostalih profilov uporabnika
+ $stringSelect = "SELECT id, name, type, DATE_FORMAT(starts,'".STP_CALENDAR_DATE_FORMAT."') AS starts, DATE_FORMAT(ends,'".STP_CALENDAR_DATE_FORMAT."') AS ends, interval_txt FROM srv_time_profile WHERE uid = '".self::getGlobalUserId()."' || uid = '0' ORDER BY id";
+ $querySelect = sisplet_query($stringSelect);
+
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = array( 'id'=>$rowSelect['id'],
+ 'name'=>$rowSelect['name'],
+ 'type'=>$rowSelect['type'],
+ 'starts'=>$rowSelect['starts'],
+ 'ends'=>$rowSelect['ends'],
+ 'interval_txt'=>$rowSelect['interval_txt']);
+ }
+
+ # nastavimo id profil klassa na izbran
+ self::$currentProfileId = (int)$dsp;
+
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ static function getSystemDefaultProfile() {
+ return (int)STP_DEFAULT_PROFILE;
+ }
+
+ /** Vrne podatke trenutno izbranega profofila
+ *
+ */
+ static function GetCurentProfileData() {
+ return self::$profiles[self::$currentProfileId];
+ }
+
+ /** Vrne podatke podanega profofila
+ *
+ */
+ static function GetProfileData($pid) {
+ return self::$profiles[$pid];
+ }
+
+ public function getProfileName($pid) {
+ return self::$profiles[$pid]['name'];
+ }
+
+ /** Vrne array z start date in end date
+ *
+ */
+ static function GetDates($forceDefaultFilter = false) {
+ if ($forceDefaultFilter == false) {
+ $_profile_data = self :: GetCurentProfileData();
+ # ali imam o privzete datume filtra
+ $is_default_dates = ((int)$_profile_data['id'] == 0 ? true : false);
+ } else {
+ # zaradi možnosti masovnega zbiranja vsilimo privzet datum
+ $_profile_data = self::$profiles[0];
+ # ali imam o privzete datume filtra
+ $is_default_dates = true;
+ }
+
+ # nastavimo start date in end date
+ if ($_profile_data['interval_txt'] != '') {
+ # ce imamo nastavljen datum preko intervala
+ $end_date = date(STP_OUTPUT_DATE_FORMAT);
+ $start_date = date(STP_OUTPUT_DATE_FORMAT,strtotime(date(STP_OUTPUT_DATE_FORMAT, strtotime($end_date)) . ' - '.$_profile_data['interval_txt']));
+
+ } else if ($_profile_data['starts'] != '' && $_profile_data['ends'] != '') {
+ # imamo podana oba datuma
+ $start_date = date(STP_OUTPUT_DATE_FORMAT,strtotime($_profile_data['starts']));
+ $end_date = date(STP_OUTPUT_DATE_FORMAT,strtotime($_profile_data['ends']));
+ } else {
+ # napaka vzamemo datum kreacije ankete in današnji datum
+ $start_date = date(STP_OUTPUT_DATE_FORMAT,strtotime(SurveyInfo::getInstance()->getSurveyInsertDate()));
+ $end_date = date(STP_OUTPUT_DATE_FORMAT);;
+
+ }
+ # končni datum po potrebi zmanjšamo na današnji datum
+ if (strtotime($end_date) > strtotime(date(STP_OUTPUT_DATE_FORMAT))) {
+ $end_date = date(STP_OUTPUT_DATE_FORMAT);
+ }
+ return array('start_date'=>$start_date, 'end_date'=>$end_date, 'is_default_dates' => $is_default_dates);
+ }
+
+ /** Pridobimo seznam vseh list uporabnika
+ * v obliki arraya
+ */
+ static function getProfiles() {
+ return self::$profiles;
+ }
+
+ /* Vrne ID in ime trenutno izbranega profila
+ *
+ */
+ function getCurentProfile() {
+ return array('id'=>self::$currentProfileId,'name'=>self::$profiles[self::$currentProfileId]['name']);
+ }
+
+ /** Ponastavi id privzetega profila
+ *
+ */
+ static function SetDefaultProfile($pid) {
+ self::SetDefaultProfileId($pid);
+ }
+
+ static function SetDefaultProfileId($pid) {
+
+ self::$currentProfileId = (int)$pid;
+
+ $saved = SurveyUserSetting :: getInstance()->saveSettings('default_time_profile',(int)$pid);
+ }
+
+ static function ChooseProfile($pid) {
+ # če smo izbrali drug profil resetiramo še profil profilov na trenutne nastavitve
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', '0');
+
+ self::SetDefaultProfileId((int)$pid);
+ self::$currentProfileId = (int)$pid;
+
+ }
+
+ /**
+ *
+ */
+ static function SaveProfile($pid,$type,$startDate,$endDate,$stat_interval) {
+ global $lang;
+ if ((int)$pid == 0 ) {
+ # imamo privzet profil
+ self :: ChooseProfile((int)$pid);
+ $updated = true;
+ } else if ((int)$pid > 0) {
+ # shranimo v bazo
+ if ((int)$type == 0) { # $type = '0';
+ # shranjujemo od - do
+ $stat_interval = '';
+ $_startDate = date(STP_OUTPUT_DATE_FORMAT, strtotime($startDate));
+ $_endDate = date(STP_OUTPUT_DATE_FORMAT, strtotime($endDate));
+
+ $update = "UPDATE srv_time_profile SET starts = '".$_startDate."', ends='".$_endDate."', type='".$type."', interval_txt = '' WHERE id = '".$pid."'";
+ } else { # $type = '1';
+ # shranjujemo interval
+ $startDate = '';
+ $endDate = '';
+ $type = '1';
+ $update = "UPDATE srv_time_profile SET starts = '0000-00-00 00:00:00', ends='0000-00-00 00:00:00', type='".$type."', interval_txt = '".$stat_interval."' WHERE id = '".$pid."'";
+ }
+
+ $updated = sisplet_query($update);
+ # ce je bili updejt ok posodobimo se vrednost v profilu
+ if ($updated) {
+ self::$profiles[$pid]['type'] = $type;
+ self::$profiles[$pid]['starts'] = $startDate;
+ self::$profiles[$pid]['ends'] = $endDate;
+ self::$profiles[$pid]['interval_txt'] = $stat_interval;
+ }
+
+ # nastavimo privzet profil na trenutnega
+ self :: ChooseProfile((int)$pid);
+
+ } else {
+ # shranjujenmo v sejo
+ $_SESSION['time_profile'][self::$surveyId] = array('id'=>'-1',
+ 'name'=>$lang['srv_temp_profile']);
+
+ if ((int)$type == 0) { # $type = '0';
+ # shranjujemo od - do
+ $_SESSION['time_profile'][self::$surveyId]['type'] = '0';
+ $_SESSION['time_profile'][self::$surveyId]['starts'] = date(STP_OUTPUT_DATE_FORMAT, strtotime($startDate));
+ $_SESSION['time_profile'][self::$surveyId]['ends'] = date(STP_OUTPUT_DATE_FORMAT, strtotime($endDate));
+ unset($_SESSION['time_profile'][self::$surveyId]['interval_txt']);
+ } else {
+ $_SESSION['time_profile'][self::$surveyId]['type'] = '1';
+ $_SESSION['time_profile'][self::$surveyId]['interval_txt'] = $stat_interval;
+ unset($_SESSION['time_profile'][self::$surveyId]['starts']);
+ unset($_SESSION['time_profile'][self::$surveyId]['ends']);
+ }
+ self::$profiles[$pid] = $_SESSION['time_profile'][self::$surveyId];
+
+ $updated = true;
+ self :: ChooseProfile((int)$pid);
+
+ }
+ return $updated;
+ }
+
+ static function RenameProfile($pid, $name) {
+
+ if (isset($pid) && $pid > 0 && isset($name) && trim($name) != "") {
+ // popravimo podatek za variables
+ $stringUpdate = "UPDATE srv_time_profile SET name = '".$name."' WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ return $updated;
+ } else {
+ return -1;
+ }
+ }
+
+ static function DeleteProfile($pid = 0) {
+
+ if (isset($pid) && $pid == -1) {
+ unset($_SESSION['time_profile'][self::$surveyId] );
+ } else if (isset($pid) && $pid > 0) {
+ // Izbrišemo profil in nastavimo privzetega
+ $stringUpdate = "DELETE FROM srv_time_profile WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ }
+ # nastavimo privzet profil
+ self::ChooseProfile('0');
+ }
+
+ /** Funkcija kreira nov profil
+ *
+ */
+ function createProfile($type,$startDate,$endDate,$stat_interval,$name=null) {
+ global $lang;
+ if ($name == null || trim($name) == '' ) {
+ $name = $lang['srv_new_profile'];
+ }
+
+ if ($type == '0') {
+ # shranjujemo od - do
+ $startDate = date(STP_OUTPUT_DATE_FORMAT, strtotime($startDate));
+ $endDate = date(STP_OUTPUT_DATE_FORMAT, strtotime($endDate));
+ $stat_interval = '';
+ } else {
+ # shranjujemo interval
+ $startDate = '0000-00-00';
+ $endDate = '0000-00-00';
+ $type = '1';
+ }
+
+ $iStr = "INSERT INTO srv_time_profile (id,uid,name,type,starts,ends,interval_txt)".
+ " VALUES (NULL, '".self::$uId."', '".$name."', '".$type."', '".$startDate."', '".$endDate."', '".$stat_interval."')";
+
+ $ins = sisplet_query($iStr);
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($id > 0) {
+ self :: ChooseProfile($id);
+ } else {
+ self :: ChooseProfile(0);
+ }
+
+ return;
+ }
+
+ /** prikažemo dropdown z izbranim profilom in link do nastavitev profila
+ *
+ *
+ */
+ static function DisplayLink($hideAdvanced = true, $showseperator = true) {
+ global $lang;
+
+ $profiles = self :: getProfiles();
+ $izbranProfil = self :: getCurentProfileId();
+
+ $css = ($izbranProfil == STP_DEFAULT_PROFILE ? ' gray' : '');
+ if ($hideAdvanced == false || $izbranProfil != STP_DEFAULT_PROFILE) {
+ if ($showseperator == true) {
+ echo '<li class="space">&nbsp;</li>';
+ }
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="link_time_profile" title="' . $lang['srv_time_profile_link_title'] . '" onClick="timeProfileAction(\'showProfiles\');">' . $lang['srv_time_profile_link'] . '</span>';
+ echo '</li>';
+
+ }
+ }
+
+
+ /** Funkcija prikaze izbor datuma
+ *
+ */
+ static function displayProfiles($current_pid = null) {
+ global $lang;
+ $_all_profiles = self::getProfiles();
+
+ // Naslov
+ echo '<h2>'.$lang['srv_obdobje_settings'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="timeProfileAction(\'cancel\'); return false;">✕</a></div>';
+
+ if ($current_pid == null) {
+ $current_pid = self::getCurentProfileId();
+ }
+ $currentFilterProfile = $_all_profiles[$current_pid];
+
+ if ( $current_pid != STP_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+ echo '<div class="time_profile_left_right floatLeft">';
+ echo '<div class="time_profile_holder">';
+ # zlistamo vse profile
+
+ echo '<div id="time_profile" class="select">';
+
+ if (count($_all_profiles)) {
+ foreach ($_all_profiles as $id=>$profile) {
+
+ echo '<div class="option' . ($current_pid == $id ? ' active' : '') . '" id="time_profile_' . $id . '" value="'.$id.'">';
+
+ echo $profile['name'];
+
+ if($current_pid == $id){
+ # privzetega profila ne moremo ne zbrisat ne preimenovat
+ if ($current_pid != 0) {
+ echo '<a href="#" title="'.$lang['srv_delete_profile'].'" onclick="timeProfileAction(\'show_delete\'); return false;"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>';
+ }
+ if ($current_pid > 0) {
+ echo '<a href="#" title="'.$lang['srv_rename_profile'].'" onclick="timeProfileAction(\'show_rename\'); return false;"><span class="faicon edit floatRight spaceRight"></span></a>';
+ }
+ }
+
+ echo '</div>';
+ }
+ }
+ echo ' </div>'; // time_profile
+ echo '</div>'; //time_profile_holder
+
+ echo '</div>'; //time_profile_left
+
+
+ echo '<div class="time_profile_left_right floatRight">';
+ echo '<div id="time_profile_content">';
+ self::DisplayProfileData($current_pid);
+ echo '</div>'; // time_profile_content
+ echo '</div>'; // time_profile_right
+
+
+ echo '<div class="time_profile_button_right_holder floatRight">';
+ if ($current_pid == 0) {
+ echo '<span class="floatRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="timeProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+# echo '<span class="floatRight spaceRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'run_profile\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'show_create\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ } else if ($current_pid == -1) {
+ echo '<span class="floatRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="timeProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'show_create\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ } else {
+ echo '<span class="floatRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="timeProfileAction(\'run_profile\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'show_create\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+
+ }
+ echo '</div>'; // time_profile_button_right_holder
+
+
+ // cover Div
+ echo '<div id="timeProfileCoverDiv"></div>';
+
+ // div za kreacijo novega
+ echo '<div id="newProfileDiv">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="newProfileName" name="newProfileName" type="text" value="" size="50" />';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="timeProfileAction(\'do_create\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'cancel_create\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '</div>';
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . $currentFilterProfile['name'] . '" size="50" />';
+ echo '<input id="renameProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="timeProfileAction(\'do_rename\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'cancel_rename\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '</div>';
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . $currentFilterProfile['name'] . '</b>?';
+ echo '<input id="deleteProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="timeProfileAction(\'do_delete\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="timeProfileAction(\'cancel_delete\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>';
+ echo '</div>';
+ }
+
+ /** Funkcija prikaze osnovnih informacije profila
+ *
+ */
+ static function DisplayProfileData($current_pid) {
+ global $lang;
+ # podatki profila
+ $p_data = self::GetProfileData($current_pid);
+
+ #kateri nacin imamo ali type (od - do) ali inervalsko (zadnjih....)
+ # ce je podan string interval imamo intervalno
+ $type = $p_data['type'];
+ if ( $type == '0') {
+ $time = '';
+ } else {
+ $p_data['starts'] = date(STP_DATE_FORMAT,strtotime(SurveyInfo::getInstance()->getSurveyInsertDate()));
+ $p_data['ends'] = date(STP_DATE_FORMAT);
+ $time = $p_data['interval_txt'];
+ }
+
+ echo '<input type="radio" name="type" id="time_date_type" value="0" '.($type == '0' ? ' checked="checked"' : '').' autocomplete="off"><label> ' . $lang['srv_time_profile_from'] . ': </label>';
+ echo '<input id="startDate" type="text" name="startDate" value="' . $p_data['starts'] . '" onclick="changeTimeProfileType();" readonly="true" '.' autocomplete="off"/>&nbsp;';
+ echo '<span class="faicon calendar_icon icon-as_link" id="starts_img"></span>';
+ echo '<label> ' . $lang['srv_time_profile_to'] . ': </label>';
+ echo '<input id="endDate" type="text" name="endDate" value="' . $p_data['ends'] . '" onclick="changeTimeProfileType();" readonly="true" '.'cautocomplete="off"/>&nbsp;';
+ echo '<span class="faicon calendar_icon icon-as_link" id="expire_img"></span>' . "\n" ;
+ echo '<br />';
+ echo '<p><input type="radio" name="type" id="time_date_interval" value="1" '.($type == '0' ? '' : ' checked="checked"').' autocomplete="off">'.$lang['srv_statistic_period_label'].':';
+ echo '<select name="stat_interval" id="stat_interval" onclick="changeTimeProfileType(\'interval\');" '.'autocomplete="off">';
+ echo '<option value="" selected="true">'.$lang['srv_time_profile_choose_interval'].'</option>';
+ foreach (self::$STP_ARRAYS as $INTERVAL) {
+ echo '<option value="'.$INTERVAL.'"' . ($time == $INTERVAL ? ' selected' : '') . '>'.$lang['srv_diagnostics_'.$INTERVAL].'</option>';
+ }
+ echo '</select>';
+ echo '</p>';
+
+ echo '<script type="text/javascript">';
+ # za profil id=0 (privzet profil ne pustimo spreminjat
+ echo
+ ' Calendar.setup({' . "\n" .
+ ' inputField : "startDate",' . "\n" .
+ ' ifFormat : "'.STP_CALENDAR_DATE_FORMAT.'",' . "\n" .
+ ' button : "starts_img",' . "\n" .
+ ' singleClick : true,' . "\n" .
+ ' onUpdate : changeTimeProfileType' . "\n" .
+ ' });' . "\n" .
+ ' Calendar.setup({' . "\n" .
+ ' inputField : "endDate",' . "\n" .
+ ' ifFormat : "'.STP_CALENDAR_DATE_FORMAT.'",' . "\n" .
+ ' button : "expire_img",' . "\n" .
+ ' singleClick : true,' . "\n" .
+ ' onUpdate : changeTimeProfileType' . "\n" .
+ ' })';
+
+ echo '</script>';
+
+ }
+
+ public static function ajax() {
+ switch ($_GET['a']) {
+ case 'showProfile':
+ self::displayProfiles($_POST['pid']);
+ break;
+ case 'createProfile':
+ self::createNewProfile();
+ break;
+ case 'changeProfile':
+ self::ChooseProfile($_POST['pid']);
+ break;
+ case 'renameProfile':
+ self::RenameProfile($_POST['pid'], $_POST['name']);
+ break;
+ case 'deleteProfile':
+ self::DeleteProfile($_POST['pid']);
+ break;
+ case 'saveProfile':
+ self::SaveProfile($_POST['pid'],$_POST['type'],$_POST['startDate'],$_POST['endDate'],$_POST['stat_interval']);
+ break;
+ default:
+ print_r("<pre>");
+ print_r($_POST);
+ print_r($_GET);
+ break;
+ }
+ }
+
+ /** Kreira nov profil z datumom od začetka ankete do danes
+ *
+ */
+ public static function createNewProfile() {
+ global $lang;
+
+ if ($_POST['profileName'] == null || trim($_POST['profileName']) == '' ) {
+ $_POST['profileName'] = $lang['srv_new_profile'];
+ }
+
+ $type = '0';;
+ $stat_interval = '';
+
+ $startdate = date(STP_OUTPUT_DATE_FORMAT, strtotime(self::$start_date));
+ $enddate = date(STP_OUTPUT_DATE_FORMAT, strtotime(self::$end_date));
+
+ $iStr = "INSERT INTO srv_time_profile (id,uid,name,type,starts,ends,interval_txt)".
+ " VALUES (NULL, '".self::getGlobalUserId()."', '".$_POST['profileName']."', '".$type."', '".$startdate."', '".$enddate."', '".$stat_interval."')";
+
+ $ins = sisplet_query($iStr);
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($id > 0) {
+ self::ChooseProfile($id);
+ } else {
+ $id = 0;
+ self::ChooseProfile($id);
+ }
+
+ return $id;
+ }
+
+ /** Vrne filter v obliki stringa primernega za uporabo filtriranja z AWK
+ *
+ */
+ public static function getFilterForAWK ($sequenca = null) {
+ # če manjka sekvenca mamo napako in ne delamo filtra
+ if ($sequenca == null || $sequenca == '') {
+ return '';
+ }
+
+ $_profile = self::GetCurentProfileData();
+ #za privzet porfil id = 0 ne delamo časovnih omejitev
+ if ($_profile['id'] == '0') {
+ return '';
+ } else {
+ # odvisno od tipa profila pripravimo omejitve datuma
+ $set=false;
+
+ if ($_profile['type'] == '0') {
+ $result = '(';
+ $prefix = '';
+ # imamo range od - do
+ # spremenimo oba datuma v unixtime
+
+ $startUnixDate = date("U", strtotime($_profile['starts']));
+ $endUnixDate = date("U", strtotime($_profile['ends']));
+
+ if ((int)$startUnixDate > 0 ) {
+ $result .= '$'.$sequenca. ' > ' . $startUnixDate;
+ $prefix = ' && ';
+ $set=true;
+ }
+ if ((int)$endUnixDate > 0 ) {
+ # + 86 400 seconds = one day
+ $result .= $prefix. '$'.$sequenca. ' < ' . ($endUnixDate+ 86400) ;
+ $set=true;
+ }
+ $result .= ')';
+
+ } else {
+ #imamo interval zadnjih XXX dni
+
+ $date = date("Y-m-d");// current date
+ $unix_date = strtotime(date("Y-m-d", strtotime($date)) . " -".$_profile['interval_txt']);
+
+ if ((int)$unix_date > 0 && $_profile['interval_txt'] != null && $_profile['interval_txt'] =! '') {
+ $result = '($'.$sequenca. ' > ' . $unix_date.')';
+ $set=true;
+ }
+ }
+ if ($set == true) {
+ return $result;
+ }
+ }
+
+
+ }
+
+ /** Izpišemo opozorilo če ni privzet profil
+ *
+ */
+ static function printIsDefaultProfile() {
+ global $lang;
+ if (self::$currentProfileId != 0) {
+ $cp_data = self::GetCurentProfileData();
+ echo '<div id="timeProfileDafaultNote">';
+
+ # odvisno od tipa profila izpišemo ali obdobje ali interval
+ if ($cp_data['type'] == 0) {
+ # obdobje: od - do
+ echo $lang['srv_time_profile_filter_dates'];
+ echo date(STP_DATE_FORMAT, strtotime($cp_data['starts']));
+ echo $lang['srv_time_profile_filter_dates_2'];
+ echo date(STP_DATE_FORMAT, strtotime($cp_data['ends']));
+ } else {
+ # interval: zadnjih x dni
+ echo $lang['srv_time_profile_filter_period'];
+ echo ($lang['srv_diagnostics_'.$cp_data['interval_txt']]);
+ }
+
+ echo '&nbsp;&nbsp;&nbsp;';
+ echo '<span class="as_link" id="link_time_profile_edit">'.$lang['srv_profile_edit'].'</span>';
+ echo '&nbsp;&nbsp;';
+ echo '<span class="as_link" id="link_time_profile_remove">'.$lang['srv_profile_remove'].'</span>';
+ echo '</div>';
+ echo '<br class="clr"/>';
+
+ return true;
+
+ } else {
+ return false;
+ }
+ }
+
+ /** preveri obstoj profila in vrne enak id če obstaja, če ne vrne id privzetega profila
+ *
+ * @param unknown_type $pid
+ * @return unknown
+ */
+ function checkProfileExist($pid)
+ {
+ if (isset(self::$profiles[$pid]))
+ {
+ return true;
+ }
+ return false;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyUrlLinks.php b/admin/survey/classes/class.SurveyUrlLinks.php
new file mode 100644
index 0000000..0fa3856
--- /dev/null
+++ b/admin/survey/classes/class.SurveyUrlLinks.php
@@ -0,0 +1,278 @@
+<?php
+
+class SurveyUrlLinks
+{
+
+ private $_anketa;
+
+ public function __construct($anketa = null)
+ {
+ try {
+ if (!empty($anketa) && (int)$anketa > 0)
+ {
+ $this->_anketa = $anketa;
+ }
+ else
+ {
+ throw new Exception('Error: survey ID is missing. (HashUrl)');
+ }
+ } catch (Exception $e) {
+ die( $e->getMessage().' Exiting script!');
+ }
+
+ return $this;
+ }
+
+ public function ajax()
+ {
+ $action = $_GET['a'];
+ switch ($action)
+ {
+ case 'showLinks' :
+ self :: showUrlLinks();
+ break;
+ case 'addLink' :
+ self :: addLink();
+ break;
+ case 'saveComment' :
+ self :: saveComment();
+ case 'saveRefresh' :
+ self :: saveRefresh();
+ case 'saveAccessPassword' :
+ self :: saveAccessPassword();
+ break;
+ case 'deleteLink' :
+ self :: deleteLink();
+ break;
+ default:
+ $this->showUrlLinks();
+ break;
+ }
+
+ }
+
+ function showUrlLinks($msg=null){
+ global $lang, $site_url;
+
+ $podstran = $_REQUEST['podstran'];
+ $m = $_REQUEST['m'];
+
+ $popUp = new PopUp();
+ $popUp->setId('div_survey_links');
+ $popUp->setHeaderText($lang['srv_public_link_title'].':');
+
+ #vsebino shranimo v buffer
+ ob_start();
+
+ echo '<div class="popup_close"><a href="#" onClick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\'); return false;">✕</a></div>';
+
+ if ($msg != null){
+ echo ($msg);
+ echo '<br />';
+ }
+ $hashUrl = new HashUrl($this->_anketa);
+ $links = $hashUrl->getSurveyHashes();
+ if (count($links) == 0){
+ echo $lang['srv_public_link_noLink'].'<br />';
+ }
+ echo '<p><a href="#" onclick="addSurveyUrlLink(\''.$podstran.'\',\''.$m.'\');">'.$lang['srv_public_link_addLink'].'</a></p>';
+ if (count($links) > 0){
+
+ echo '<caption>'.$lang['srv_public_link_existing'].'</caption>';
+ echo '<table class="tbl_survey_links">';
+
+ echo '<tr>';
+ echo '<th>&nbsp;</th>';
+ echo '<th></th>';
+ echo '<th>'.$lang['srv_inv_archive_comment'].'</th>';
+ echo '<th>'.$lang['url'].'</th>';
+ echo '<th>'.$lang['srv_analiza_archive_access_password_label'].'</th>';
+ echo '<th>'.$lang['srv_public_link_refresh'].'</th>';
+ echo '<th>'.$lang['srv_public_link_linkTo'].'</th>';
+ echo '<th>'.$lang['srv_public_link_creationDate'].'</th>';
+ echo '<th>'.$lang['srv_public_link_created'].'</th>';
+ echo '</tr>';
+ foreach ($links as $key => $link){
+ echo '<tr>';
+ echo '<td>';
+ echo '<a href="#" onclick="deleteSurveyUrlLinks(\''.$this->_anketa.'\',\''.$link['hash'].'\',\''.$podstran.'\',\''.$m.'\');" title="'.$lang['srv_public_link_deleteLink'].'"><span class="sprites dataLinkDelete"></span></a>';
+ echo '</td>';
+ echo '<td>';
+ echo $lang['srv_hash_url_'.$link['properties']['a']];
+ echo '</td>';
+
+ echo '<td>';
+ echo '<span class="editable hash_comment" name="hash_comment" id="hash_comment_'.$this->_anketa.'_'.$link['hash'].'" data-hash="'.$link['hash'].'" data-anketa="'.$this->_anketa.'" contenteditable="true" style="display: block;width:100%" onblur="hash_comment_change(this);">';
+ print_r($link['comment']);
+ echo '</span></td>';
+
+ echo '<td>';
+ //if this link is edited, inform editor of mobile App or API users
+ echo '<a href="'.$site_url.'podatki/'.$this->_anketa.'/'.$link['hash'].'/" target="_blank">';
+ echo $site_url.'podatki/'.$this->_anketa.'/'.$link['hash'].'/</a>';
+ echo '</td>';
+
+ echo '<td>';
+ echo '<span class="editable hash_comment" name="access_password" id="access_password_'.$this->_anketa.'_'.$link['hash'].'" contenteditable="true" data-hash="'.$link['hash'].'" data-anketa="'.$this->_anketa.'" onblur="hash_access_password_change(this);" onpaste="return false;" onkeypress="return (this.innerText.length < 25);" style="min-width: 100px;max-width: 100px;">';
+ print_r($link['access_password']);
+ echo '</span></td>';
+
+ echo '<td style="text-align: center;">';
+ echo '<input type="checkbox" name="hash_link_refresh" id="hash_link_refresh_'.$this->_anketa.'_'.$link['hash'].'" data-hash="'.$link['hash'].'" data-anketa="'.$this->_anketa.'" onchange="hash_refresh_change(this);"'. (($link['refresh'] == '1') ? ' checked' : '') .'>';
+ echo '</td>';
+
+ echo '<td>';
+ if ($link['page'] == $hashUrl::PAGE_DATA){
+ $page = $lang['srv_public_link_data'];
+ }
+ if ($link['page'] == $hashUrl::PAGE_ANALYSIS){
+ $page = $lang['srv_public_link_analyse'];
+ }
+ echo $page;
+ if ($link['properties']['a'] == A_ANALYSIS && isset($link['properties']['m'])) {
+ if ($link['properties']['m'] == M_ANALYSIS_DESCRIPTOR
+ || $link['properties']['m'] == M_ANALYSIS_FREQUENCY
+ || $link['properties']['m'] == M_ANALYSIS_SUMMARY
+ || $link['properties']['m'] == M_ANALYSIS_SUMMARY_NEW
+ || $link['properties']['m'] == M_ANALYSIS_CREPORT
+ || $link['properties']['m'] == M_ANALYSIS_CHARTS) {
+ echo ' (' . $lang['srv_'.$link['properties']['m']].')';
+ }
+ }
+ echo '</td>';
+
+ echo '<td title="'.$link['add_date'].', '.$link['add_time'].'">';
+ echo $link['add_date'];
+
+ echo '</td>';
+
+ echo '<td>';
+ echo $link['email'];
+ echo '</td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+
+ #dodamo vsebino
+ $content = ob_get_clean();
+ $popUp->setContent($content);
+
+ # dodamo gumb Preklici
+ $buttonClose = new PopUpCancelButton();
+ $buttonClose->setCaption($lang['srv_zapri'])->setTitle($lang['srv_zapri']);
+ $buttonClose->setFloat('right');
+ $popUp->addButton($buttonClose);
+
+ echo $popUp;
+
+ }
+
+ function addLink(){
+ global $lang;
+ global $global_user_id;
+
+ #zaenkrat samo za podatke in par analiz
+ $podstran = (isset($_REQUEST['podstran']) && ($_REQUEST['podstran'] == A_COLLECT_DATA || $_REQUEST['podstran'] == A_ANALYSIS ))
+ ? $_REQUEST['podstran']
+ : 'data';
+ $m = (isset($_REQUEST['m']))
+ ? $_REQUEST['m']
+ : '';
+
+ # polovimo trenutno nastavljene profile
+ SurveyUserSetting::getInstance()->Init($this->_anketa, $global_user_id);
+
+ $this->addLinkAPI($global_user_id, $podstran, $m);
+
+ $this->showUrlLinks($lang['srv_public_link_linkAdded']);
+ }
+
+ //da se lahko kreira linke tudi prek API
+ function addLinkAPI ($user_id, $podstran, $m){
+ SurveyStatusProfiles :: Init($this->_anketa, $user_id);
+ $_PROFILE_ID_STATUS = SurveyStatusProfiles :: getCurentProfileId();
+
+ SurveyVariablesProfiles::Init($this->_anketa);
+ $_PROFILE_ID_VARIABLE = SurveyVariablesProfiles::getCurentProfileId();
+
+ SurveyConditionProfiles::Init($this->_anketa, $user_id);
+ $_PROFILE_ID_CONDITION = SurveyConditionProfiles::getCurentProfileId();
+
+ $hashUrl = new HashUrl($this->_anketa);
+ $newHash = $hashUrl->getNewHash();
+ $hashUrl->setPage($podstran);
+
+ $properties = array(
+ 'anketa'=>$this->_anketa,
+ 'a'=>$podstran,
+ 'm'=>$m,
+ 'profile_id_status'=>$_PROFILE_ID_STATUS,
+ 'profile_id_variable'=>$_PROFILE_ID_VARIABLE,
+ 'profile_id_condition'=>$_PROFILE_ID_CONDITION
+ );
+
+ // Ce gre za porocilo po meri dodamo se id porocila in id avtorja
+ if($m == M_ANALYSIS_CREPORT){
+ $creportProfile = SurveyUserSetting :: getInstance()->getSettings('default_creport_profile');
+ $creportProfile = isset($creportProfile) && $creportProfile != '' ? $creportProfile : 0;
+ $creportAuthor = SurveyUserSetting :: getInstance()->getSettings('default_creport_author');
+ $creportAuthor = isset($creportAuthor) && $creportAuthor != '' ? $creportAuthor : $user_id;
+
+ $properties['creportProfile'] = $creportProfile;
+ $properties['creportAuthor'] = $creportAuthor;
+ }
+
+ $hashUrl->saveProperty($newHash, $properties);
+ }
+
+ function saveComment() {
+
+ $hashUrl = new HashUrl($this->_anketa);
+ $hash = $_REQUEST['hash'];
+ $comment = $_REQUEST['comment'];
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($comment, -4) == '<br>') {
+ $comment = substr($comment, 0, -4);
+ }
+
+ $hashUrl->updateComment($hash,$comment);
+ }
+
+ function saveRefresh() {
+
+ $hashUrl = new HashUrl($this->_anketa);
+ $hash = $_REQUEST['hash'];
+ $refresh = $_REQUEST['refresh'];
+
+ $hashUrl->updateRefresh($hash,$refresh);
+ }
+
+ function saveAccessPassword() {
+
+ $hashUrl = new HashUrl($this->_anketa);
+ $hash = $_REQUEST['hash'];
+ $pass = $_REQUEST['access_password'];
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($comment, -4) == '<br>') {
+ $comment = substr($comment, 0, -4);
+ }
+
+ $hashUrl->updateAccessPassword($hash,$pass);
+ }
+
+ function deleteLink() {
+ global $lang;
+
+ $hashUrl = new HashUrl($this->_anketa);
+ $hash = $_REQUEST['hash'];
+
+ $hashUrl->deleteLink($hash);
+
+ $this->showUrlLinks($lang['srv_public_link_linkDeleted']);
+ }
+
+}
diff --git a/admin/survey/classes/class.SurveyUsableResp.php b/admin/survey/classes/class.SurveyUsableResp.php
new file mode 100644
index 0000000..48e5cea
--- /dev/null
+++ b/admin/survey/classes/class.SurveyUsableResp.php
@@ -0,0 +1,783 @@
+<?php
+
+class SurveyUsableResp{
+
+ private $anketa; # id ankete
+ private $db_table; # katere tabele uporabljamo
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo (zakeširamo)
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ public $_PROFILE_ID_VARIABLE = ''; # filter po statusih, privzeto izvažamo 6 in 5
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ private $_missings = array();
+ private $_unsets = array();
+
+ private $displayEditIconsSettings = false; # ali prikazujemo okno s checkboxi za nastavitve tabele s podatki
+
+ private $cols_with_value = array(); # kateri stolpci imajo vrednosti
+ private $show_with_zero = false; # Ali prikazujemo stolpce z vrednostmi 0
+ private $show_details = false; # Ali prikazujemo stolpce s podrobnimi vrednostmi (-1, -2...)
+ private $show_calculations = false; # Ali prikazujemo stolpce s podrobnimi izracuni (UML, UNL...)
+ private $show_with_other = true; # Ali prikazujemo vrstice "Drugo"
+ private $show_with_text = true; # Ali prikazujemo vrstice tipa "besedilo"
+
+ public $bottom_usable_limit = 50; # Spodnja meja za usable respondente (def. 50%)
+ public $top_usable_limit = 80; # Zgornja meja za usable respondente (def. 80%) - unusable (50-), partially usable (50-80), usable(80+)
+
+ private $sortField = 'recnum'; # Polje po katerem sortiramo tabelo
+ private $sortType = 0; # Nacin sortiranja (narascajoce/padajoce)
+
+
+ function __construct($anketa, $generateDataFile=true){
+ global $lang;
+ global $global_user_id;
+
+ if ((int)$anketa > 0){
+
+ $this->anketa = $anketa;
+
+ SurveyAnalysisHelper::getInstance()->Init($this->anketa);
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ Common::deletePreviewData($this->anketa);
+
+
+ // Poskrbimo za datoteko s podatki
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->anketa);
+
+ if($generateDataFile)
+ $SDF->prepareFiles();
+
+ $this->headFileName = $SDF->getHeaderFileName();
+ $this->dataFileName = $SDF->getDataFileName();
+ $this->dataFileStatus = $SDF->getStatus();
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_SRV_DELETED) {
+ Common::noDataAlert();
+ exit();
+ }
+
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->anketa);
+ SurveyUserSetting::getInstance()->Init($this->anketa, $global_user_id);
+ SurveyConditionProfiles :: Init($this->anketa, $global_user_id);
+ SurveyTimeProfiles :: Init($this->anketa, $global_user_id);
+ SurveyVariablesProfiles :: Init($this->anketa, $global_user_id);
+ SurveyDataSettingProfiles :: Init($this->anketa);
+
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->anketa);
+ $this->sessionData = SurveyUserSession::getData();
+
+ if(isset($_SESSION['sid_'.$this->anketa]['usabilityIcons_settings']))
+ $this->displayEditIconsSettings = ($_SESSION['sid_'.$this->anketa]['usabilityIcons_settings']);
+
+ if (file_exists($this->headFileName) && $this->headFileName !== null && $this->headFileName != ''){
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ # nastavimo filtre uporabnika
+ $this->setUserFilters();
+
+ # nastavimo sortiranje
+ if(isset($_GET['sortField']))
+ $this->sortField = $_GET['sortField'];
+ if(isset($_GET['sortType']))
+ $this->sortType = $_GET['sortType'];
+ }
+ else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+ public function getMissings(){
+ return $this->_missings;
+ }
+
+ public function getUnsets(){
+ return $this->_unsets;
+ }
+
+ public function getColsWithValue(){
+ return $this->cols_with_value;
+ }
+
+ public function showCalculations(){
+ return $this->show_calculations;
+ }
+
+ public function showDetails(){
+ return $this->show_details;
+ }
+
+ public function showWithZero(){
+ return $this->show_with_zero;
+ }
+
+
+
+ function displayUsableRespTable(){
+ global $lang;
+
+ // Prikaz nastavitev
+ $this->displayUsableSettings();
+
+ # ali imamo testne podatke
+ if ($this->_HAS_TEST_DATA){
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml($this->anketa);
+ $SSH -> displayTestDataBar(true);
+ }
+
+ // Izracunamo vse podatke
+ $usability = $this->calculateData();
+ $userData = $usability['data'];
+
+ // Sortiramo podatke
+ foreach ($userData as $key => $row) {
+ $mid[$key] = $row[$this->sortField];
+ }
+ if($this->sortType == 0)
+ array_multisort($mid, SORT_ASC, $userData);
+ else
+ array_multisort($mid, SORT_DESC, $userData);
+
+
+ # ali odstranimo stolpce kateri imajo same 0
+ if ($this->show_with_zero == false) {
+ # odstranimo missinge brez vrednosti
+ foreach ($this->_missings AS $_key => $_missing) {
+ if (!isset($this->cols_with_value[$_key]) || $this->cols_with_value[$_key] == false) {
+ unset($this->_missings[$_key]);
+ }
+ }
+ # odstranimo neveljavne brez vrednosti
+ foreach ($this->_unsets AS $_key => $_unset) {
+ if (!isset($this->cols_with_value[$_key]) || $this->cols_with_value[$_key] == false) {
+ unset($this->_unsets[$_key]);
+ }
+ }
+ }
+
+
+ echo '<div id="usable_table"><table id="tbl_usable_respondents" '.($this->show_details==true && $this->show_calculations==true ? '' : ' style="width:100%"').'>';
+
+ // Header row
+ echo '<tr>';
+
+ if($this->sortType == 1){
+ $sortType = 0;
+ $arrow = ' <span class="faicon sort_ascending"></span>';
+ }
+ else{
+ $sortType = 1;
+ $arrow = ' <span class="faicon sort_descending"></span>';
+ }
+
+ echo '<th class="recnum" rowspan="2" style="width:60px;"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=recnum&sortType='.$sortType.'">Recnum'./*$lang['recnum'].*/($this->sortField=='recnum' ? $arrow : '').'</a></th>';
+ echo '<th class="all" rowspan="2">'.$lang['srv_usableResp_qcount'].'</th>';
+
+ echo '<th class="data" colspan=4>'.$lang['srv_usableResp_exposed'].'</th>';
+
+ echo '<th class="data" rowspan="2"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=breakoff&sortType='.$sortType.'">'.$lang['srv_usableResp_breakoff'].($this->sortField=='breakoff' ? $arrow : '').'</th>';
+
+ echo '<th class="usable" colspan="2">'.$lang['srv_usableResp_usability'].'</th>';
+
+ // ali odstranimo vse stolpce s podrobnimi vrednostmi (-1, -2...)
+ if ($this->show_details == true) {
+ foreach ($this->_missings AS $value => $text){
+ $cnt_miss++;
+ echo "<th rowspan=\"2\" class=\"unusable\" title=\"".$lang['srv_usableResp_'.$text]."\" >{$value}<br/>(".$lang['srv_usableResp_'.$text].")</th>";
+ }
+ foreach ($this->_unsets AS $value => $text){
+ $cnt_undefined++;
+ echo "<th rowspan=\"2\" class=\"unusable\" title=\"".$lang['srv_usableResp_'.$text]."\">{$value}<br/>(".$lang['srv_usableResp_'.$text].")</th>";
+ }
+ }
+
+ // ali prikazemo podrobne izracune
+ if ($this->show_calculations == true) {
+ echo '<th class="calculation" rowspan="2">UNL</th>';
+ echo '<th class="calculation" rowspan="2">UML</th>';
+ echo '<th class="calculation" rowspan="2">UCL</th>';
+ echo '<th class="calculation" rowspan="2">UIL</th>';
+ echo '<th class="calculation" rowspan="2">UAQ</th>';
+ }
+
+ echo '</tr>';
+
+ echo '<tr>';
+ echo '<th class="data"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=valid&sortType='.$sortType.'">'.$lang['srv_anl_valid'].($this->sortField=='valid' ? $arrow : '').'</th>';
+ echo '<th class="data"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=nonsubstantive&sortType='.$sortType.'">'.$lang['srv_usableResp_nonsubstantive'].($this->sortField=='nonsubstantive' ? $arrow : '').'</th>';
+ echo '<th class="data"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=nonresponse&sortType='.$sortType.'">'.$lang['srv_usableResp_nonresponse'].($this->sortField=='nonresponse' ? $arrow : '').'</th>';
+ echo '<th class="data"><span class="bold">'.$lang['srv_anl_suma1'].'</span></th>';
+
+ echo '<th class="usable"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=usable&sortType='.$sortType.'">%'.($this->sortField=='usable' ? $arrow : '').'</a></th>';
+ echo '<th class="usable status"><a href="index.php?anketa='.$this->anketa.'&a=usable_resp&sortField=status&sortType='.$sortType.'">Status'.($this->sortField=='status' ? $arrow : '').'</a></th>';
+ echo '</tr>';
+
+
+ // Izpis podatkov vsakega respondenta
+ foreach($userData as $key => $user){
+
+ // Obarvamo vrstico glede na status (belo, rumeno, rdece)
+ if($user['status'] == 0)
+ $css_usable = 'unusable';
+ elseif($user['status'] == 1)
+ $css_usable = 'partusable';
+ else
+ $css_usable = 'usable';
+
+
+ // Prva vrstica z vrednostmi
+ echo '<tr class="'.$data['css'].' '.$css_usable.'">';
+
+ echo '<td rowspan="2" class="recnum"><a href="index.php?anketa='.$this->anketa.'&a=data&m=quick_edit&usr_id='.$user['usr_id'].'&quick_view=1">'.$user['recnum'].'</a></td>';
+
+ // Vsi
+ echo '<td rowspan="2" class="all">'.$user['all'].'</td>';
+
+ // Ustrezni
+ echo '<td class="data">'.$user['valid'].'</td>';
+
+ // Non-substantive
+ echo '<td class="data">'.$user['nonsubstantive'].'</td>';
+
+ // Non-response
+ echo '<td class="data">'.$user['nonresponse'].'</td>';
+
+ // Skupaj
+ echo '<td class="data sum bold">'.($user['valid']+$user['nonsubstantive']+$user['nonresponse']+$user['breakoff']).'</td>';
+
+ // Breakoffs
+ echo '<td class="data breakoff">'.$user['breakoff'].'</td>';
+
+ // Uporabni
+ echo '<td class="usable">'.$user['usable'].'</td>';
+ echo '<td class="usable status" rowspan="2">'.$user['status'].'</td>';
+
+ // ali odstranimo vse stolpce s podrobnimi vrednostmi (-1, -2...)
+ if ($this->show_details == true) {
+ foreach ($this->_missings AS $value => $text){
+ echo '<td class="unusable">'.$user[$value].'</td>';
+ }
+ foreach ($this->_unsets AS $value => $text){
+ echo '<td class="unusable">'.$user[$value].'</td>';
+ }
+ }
+
+ // ali prikazemo podrobne izracune
+ if ($this->show_calculations == true) {
+ echo '<td class="calculation" rowspan="2">'.common::formatNumber($user['UNL']*100, 0, null, '%').'</td>';
+ echo '<td class="calculation" rowspan="2">'.common::formatNumber($user['UML']*100, 0, null, '%').'</td>';
+ echo '<td class="calculation" rowspan="2">'.common::formatNumber($user['UCL']*100, 0, null, '%').'</td>';
+ echo '<td class="calculation" rowspan="2">'.common::formatNumber($user['UIL']*100, 0, null, '%').'</td>';
+ echo '<td class="calculation" rowspan="2">'.common::formatNumber($user['UAQ']*100, 0, null, '%').'</td>';
+ }
+
+ echo '</tr>';
+
+
+ // Druga vrstica s procenti
+ echo '<tr class="multiVariablesHeader '.$user['css'].' '.$css_usable.'">';
+
+ // Ustrezni
+ echo '<td class="data">'.common::formatNumber($user['validPercent'], 0, null, '%').'</td>';
+
+ // Non-substantive
+ echo '<td class="data">'.common::formatNumber($user['nonsubstantivePercent'], 0, null, '%').'</td>';
+
+ // Non-response
+ echo '<td class="data">'.common::formatNumber($user['nonresponsePercent'], 0, null, '%').'</td>';
+
+ // Skupaj
+ //echo '<td class="data bold">'.common::formatNumber(($user['validPercent']+$user['nonsubstantivePercent']+$user['nonresponsePercent']+$user['breakoffPercent']), 0, null, '%').'</td>';
+ echo '<td class="data sum bold">'.common::formatNumber(100, 0, null, '%').'</td>';
+
+ // Breakoffs
+ echo '<td class="data breakoff">'.common::formatNumber($user['breakoffPercent'], 0, null, '%').'</td>';
+
+ // Uporabni
+ echo '<td class="usable">'.common::formatNumber($user['usablePercent'], 0, null, '%').'</td>';
+
+ // ali odstranimo vse stolpce s podrobnimi vrednostmi (-1, -2...)
+ if ($this->show_details == true) {
+ foreach ($this->_missings AS $value => $text){
+ $val = $user[$value];
+ $val = ($all > 0) ? ($val / $all * 100) : 0;
+ echo '<td class="unusable">'.common::formatNumber($val, 0, null, '%').'</td>';
+ }
+ foreach ($this->_unsets AS $value => $text){
+ $val = $user[$value];
+ $val = ($all > 0) ? ($val / $all * 100) : 0;
+ echo '<td class="unusable">'.common::formatNumber($val, 0, null, '%').'</td>';
+ }
+ }
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+
+ /*echo '<div class="usable_sum">';
+ echo '<div class="usable_legend" style="background-color:#ffffff;"></div> '.$lang['srv_usableResp_usable'].': <span class="bold">'.$usability['usable'].'</span>';
+ echo '<div class="usable_legend" style="background-color:#ffffe3;"></div> '.$lang['srv_usableResp_partusable'].': <span class="bold">'.$usability['partusable'].'</span> ';
+ echo '<div class="usable_legend" style="background-color:#ffe8e8;"></div> '.$lang['srv_usableResp_unusable'].': <span class="bold">'.$usability['unusable'].'</span>';
+ echo '</div>';*/
+ echo '<div class="usable_sum">';
+ //echo '<span class="bold">'.$lang['srv_usableResp_usability'].': </span>';
+ if($usability['all'] > 0){
+ echo '<span class="usable_legend spaceLeft spaceRight" style="background-color:#ffffff;">'.$lang['srv_usableResp_usable_unit'].' - Status 2 ('.$this->top_usable_limit.'%-100%): <span class="bold">'.$usability['usable'].' ('.common::formatNumber($usability['usable']/$usability['all']*100, 0, null, '%').')</span></span>';
+ echo '<span class="usable_legend spaceLeft spaceRight" style="background-color:#ffffe3;">'.$lang['srv_usableResp_partusable_unit'].' - Status 1 ('.$this->bottom_usable_limit.'%-'.$this->top_usable_limit.'%): <span class="bold">'.$usability['partusable'].' ('.common::formatNumber($usability['partusable']/$usability['all']*100, 0, null, '%').')</span></span>';
+ echo '<span class="usable_legend spaceLeft" style="background-color:#ffe8e8;">'.$lang['srv_usableResp_unusable_unit'].' - Status 0 (0%-'.$this->bottom_usable_limit.'%): <span class="bold">'.$usability['unusable'].' ('.common::formatNumber($usability['unusable']/$usability['all']*100, 0, null, '%').')</span></span>';
+ }
+ else{
+ echo '<span class="usable_legend spaceLeft spaceRight" style="background-color:#ffffff;">'.$lang['srv_usableResp_usable_unit'].' - Status 2 ('.$this->top_usable_limit.'%-100%): <span class="bold">'.$usability['usable'].' ('.common::formatNumber(0, 0, null, '%').')</span></span>';
+ echo '<span class="usable_legend spaceLeft spaceRight" style="background-color:#ffffe3;">'.$lang['srv_usableResp_partusable_unit'].' - Status 1 ('.$this->bottom_usable_limit.'%-'.$this->top_usable_limit.'%): <span class="bold">'.$usability['partusable'].' ('.common::formatNumber(0, 0, null, '%').')</span></span>';
+ echo '<span class="usable_legend spaceLeft" style="background-color:#ffe8e8;">'.$lang['srv_usableResp_unusable_unit'].' - Status 0 (0%-'.$this->bottom_usable_limit.'%): <span class="bold">'.$usability['unusable'].' ('.common::formatNumber(0, 0, null, '%').')</span></span>';
+ }
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function displayUsableSettings(){
+ global $lang;
+
+ // Div z nastavitvami ki se razpre
+ echo '<div id="dataSettingsCheckboxes" '.($this->displayEditIconsSettings ? '' : ' style="display:none;"').'>';
+ echo '<div id="toggleDataCheckboxes2" onClick="toggleDataCheckboxes(\'usability\');"><span class="faicon close icon-orange" style="padding-bottom:2px;"></span> '.$lang['srv_data_settings_checkboxes2'].'</div>';
+
+
+ echo '<div id="usable_respondents_settings">';
+
+ echo $lang['srv_usableResp_limit'].': ';
+
+ echo '<span class="spaceLeft spaceRight">'.$lang['srv_usableResp_bottom_limit'].': <input type="text" id="bottom_usable_limit" size="2" onblur="changeUsableRespSetting(this);" value="'.$this->bottom_usable_limit.'" />%</span>';
+ echo '<span class="spaceLeft spaceRight">'.$lang['srv_usableResp_top_limit'].': <input type="text" id="top_usable_limit" size="2" onblur="changeUsableRespSetting(this);" value="'.$this->top_usable_limit.'" />%</span>';
+
+ echo '<br />';
+
+ echo '<div style="margin-top:10px;">';
+ echo $lang['srv_usableResp_show'].': ';
+
+ // Prikaz neničelnih stolpcev
+ echo '<label class="spaceLeft spaceRight">';
+ echo '<input type="checkbox" id="show_with_zero" onclick="changeUsableRespSetting(this);" '.($this->show_with_zero == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_usableResp_showZero'];
+ echo '</label>';
+
+ // Prikaz podrobnosti
+ echo '<label class="spaceLeft spaceRight">';
+ echo '<input type="checkbox" id="show_details" onclick="changeUsableRespSetting(this);" '.($this->show_details == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_usableResp_showDetails'];
+ echo '</label>';
+
+ // Prikaz podrobnih izracunov
+ echo '<label class="spaceLeft">';
+ echo '<input type="checkbox" id="show_calculations" onclick="changeUsableRespSetting(this);" '.($this->show_calculations == true ? ' checked="checked"' : '').' autocomplete="off">';
+ echo $lang['srv_usableResp_showCalc'];
+ echo '</label>';
+ echo '</div>';
+
+ echo '</div>';
+
+
+ echo '</div>';
+ }
+
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter(){
+ /*if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED)
+ {
+ return false;
+ }*/
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ || ($_time_profile_awk != "" && $_time_profile_awk != null))
+ {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null)
+ {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD)
+ {
+ if (isset($this->_HEADERS['testdata']))
+ {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+
+ $smv = new SurveyMissingValues($this->anketa);
+ $smv -> Init();
+
+ $smv_array = $smv->GetSurveyMissingValues($this->anketa);
+ if (!empty($smv_array[1])){
+ foreach ($smv_array[1] AS $_survey_missings)
+ {
+ $this->_missings[$_survey_missings['value']] = $_survey_missings['text'];
+
+ }
+ }
+ if (!empty($smv_array[2])){
+ foreach ($smv_array[2] AS $_survey_unsets)
+ {
+ $this->_unsets[$_survey_unsets['value']] = $_survey_unsets['text'];
+ }
+ }
+ }
+
+ private function setUserFilters(){
+ # Nastavimo filtre variabel
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+ if ($dvp != $_currentVariableProfile) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', $_currentVariableProfile);
+ }
+ $this->_PROFILE_ID_VARIABLE = $_currentVariableProfile;
+
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['usable_resp']['show_with_zero'])) {
+ $this->show_with_zero = $this->sessionData['usable_resp']['show_with_zero'];
+ }
+
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['usable_resp']['show_details'])) {
+ $this->show_details = $this->sessionData['usable_resp']['show_details'];
+ }
+
+ # ali prikazujemo tudi stolpce z izracuni
+ if (isset($this->sessionData['usable_resp']['show_calculations'])) {
+ $this->show_calculations = $this->sessionData['usable_resp']['show_calculations'];
+ }
+
+ # ali prikazujemo vrstice "Drugo"
+ $this->show_with_other = true;
+ if (isset($this->sessionData['usable_resp']['show_with_other'])) {
+ $this->show_with_other = $this->sessionData['usable_resp']['show_with_other'];
+ }
+
+ # ali prikazujemo vrstice tipa "besedilo"
+ $this->show_with_text = true;
+ if (isset($this->sessionData['usable_resp']['show_with_text'])) {
+ $this->show_with_text = $this->sessionData['usable_resp']['show_with_text'];
+ }
+
+ # Spodnja in zgornja meja za usable
+ if (isset($this->sessionData['usable_resp']['bottom_usable_limit'])) {
+ $this->bottom_usable_limit = $this->sessionData['usable_resp']['bottom_usable_limit'];
+ }
+ # ali prikazujemo tudi stolpce z 0 vrednostmi
+ if (isset($this->sessionData['usable_resp']['top_usable_limit'])) {
+ $this->top_usable_limit = $this->sessionData['usable_resp']['top_usable_limit'];
+ }
+ }
+
+
+ // Zgeneriramo datoteko in izracunamo frekvence (stevilo 1, -1, -2...) za vsako enoto
+ private function collectData(){
+ global $site_path;
+
+ # polovimo frekvence statusov odgovorov za posameznega respondenta (stevilo -1, -2...)
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ #array za imeni tmp fajlov, ki jih nato izbrišemo
+ $tmp_file = $folder.'tmp_export_'.$this->anketa.'_usable_resp.php';
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ # s katero sekvenco se začnejo podatki, da ne delamo po nepotrebnem za ostala polja
+ $start_sequence = $this->_HEADERS['_settings']['dataSequence'];
+ # s katero sekvenco se končajo podatki da ne delamo po nepotrebnem za ostala polja
+ $end_sequence = $this->_HEADERS['_settings']['metaSequence']-1;
+ # sekvenca recnuma
+ $recnum_sequence = $this->_HEADERS['recnum']['sequences'];
+
+ # naredimo datoteko z frekvencami
+ # za windows sisteme in za linux sisteme
+ if (IS_WINDOWS ) {
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" "{{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} {{for (n in arr) {delete arr[n]}}} {delete arr} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[$i]++}} '.$status_filter.' {{for (n in arr) { print NR,$'.$recnum_sequence.',$1,n,arr[n]}}}" '.$this->dataFileName;
+ $command .= ' | sed "s*\x27*`*g" ';
+ $command .= ' | awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} { print \"$frequency[\",$1,\"]\",\"[\x27\",$4,\"\x27]\",\"=\",$5,\";\"} { print \"$frequency[\",$1,\"]\",\"[\"usr_id\"]\",\"=\",$3,\";\"} { print \"$frequency[\",$1,\"]\",\"[\"recnum\"]\",\"=\",$2,\";\"}" >> '.$tmp_file;
+ }
+ else {
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" \' {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} {{for (n in arr) {delete arr[n]}}} {delete arr} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[$i]++}} '.$status_filter.' {{for (n in arr) { print NR,$'.$recnum_sequence.',$1,n,arr[n]}}}\' '.$this->dataFileName;
+ $command .= ' | sed \'s*\x27*`*g\' ';
+ $command .= ' | awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} { print "$frequency[",$1,"]","[\x27",$4,"\x27]","=\x27",$5,"\x27;"} { print "$frequency[",$1,"]","[\"usr_id\"]","=\x27",$3,"\x27;"} { print "$frequency[",$1,"]","[\"recnum\"]","=\x27",$2,"\x27;"}\' >> '.$tmp_file;
+ }
+
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+
+ $out = shell_exec($command);
+
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ // Loop cez podatke da vidimo kateri stolpci so prazni
+ foreach ($frequency AS $seq => $freqData) {
+
+ if (empty($freqData)) {
+ continue;
+ }
+
+ foreach ($freqData AS $key => $cnt){
+ if (is_numeric($key) && (isset($this->_missings[(int)$key]) || isset($this->_unsets[(int)$key])))
+ $this->cols_with_value[(int)$key] += $cnt;
+ elseif($key != 'recnum')
+ $this->cols_with_value['valid'] += $cnt;
+ }
+ }
+
+ return $frequency;
+ }
+
+ // Gremo cez enote in izracunamo uporabne vrednosti (uporabnost, breakoff...)
+ public function calculateData(){
+
+ // Preko datoteke preberemo frekvence za posamezne userje (1, -1, -2...)
+ $data = $this->collectData();
+
+ $css = '';
+ $usability = array();
+
+ // Loop cez vse responente
+ $counter = 1;
+ foreach($data as $key1 => $frequencies){
+
+ // Prestejemo vse in veljavne
+ $all = 0;
+ $valid = 0;
+ $usable = 0; // valid + nonsubstantive
+ $nonsubstantive = 0; // -97,-98...
+ $nonresponse = 0; // -1
+ $preskok = 0; // -2
+ $breakoff = 0; // -3
+ $naknadno = 0; // -4
+ $status = 0; // 0->unusable, 1->part. usable, 2->usable
+ foreach($frequencies as $key => $cnt){
+
+ if(!array_key_exists($key, $this->_missings) && !array_key_exists($key, $this->_unsets) && $key!==''){
+ $valid += $cnt;
+ $usable += $cnt;
+ }
+
+ if(array_key_exists($key, $this->_unsets)){
+ $nonsubstantive += $cnt;
+ $usable += $cnt;
+ }
+
+ if($key == -1)
+ $nonresponse += $cnt;
+
+ if($key == -3)
+ $breakoff+= $cnt;
+
+ if($key == -2)
+ $preskok+= $cnt;
+
+ if($key == -4)
+ $naknadno+= $cnt;
+
+ $all += $cnt;
+ }
+
+ // odstejemo polje recnum
+ $all -= $frequencies['recnum'];
+ $valid -= $frequencies['recnum'];
+ $usable -= $frequencies['recnum'];
+
+ // odstejemo polje usr_id
+ $all -= $frequencies['usr_id'];
+ $valid -= $frequencies['usr_id'];
+ $usable -= $frequencies['usr_id'];
+
+ //$validPercent = ($all > 0) ? ($valid / $all * 100) : 0;
+ //$nonsubstantivePercent = ($valid + $nonsubstantive > 0) ? ($nonsubstantive / ($valid + $nonsubstantive) * 100) : 0;
+ //$nonresponsePercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($nonresponse / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+ $validPercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($valid / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+ $nonsubstantivePercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($nonsubstantive / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+ $nonresponsePercent = ($valid + $nonsubstantive + $nonresponse > 0) ? ($nonresponse / ($valid + $nonsubstantive + $nonresponse) * 100) : 0;
+
+ //$breakoffPercent = ($valid + $nonsubstantive + $nonresponse + $breakoff > 0) ? ($breakoff / ($valid + $nonsubstantive + $nonresponse + $breakoff) * 100) : 0;
+ $breakoffPercent = $breakoff / $all * 100;
+
+ //$usablePercent = ($valid + $nonsubstantive + $nonresponse + $breakoff > 0) ? ($usable / ($valid + $nonsubstantive + $nonresponse + $breakoff) * 100) : 0;
+
+ // Posebni izracuni
+ $UNL = (($valid + $nonsubstantive + $nonresponse) > 0) ? $nonresponse / ($valid + $nonsubstantive + $nonresponse) : 0; // Delez neodgovorov
+ $UBL = ($all > 0) ? $breakoff / $all : 0; // Delez prekinitev
+ $UML = $UBL + (1 - $UBL) * $UNL;
+ $UCL = 1 - $UML; // Uporabnost
+ $UIL = (($valid + $nonsubstantive + $nonresponse + $preskok) > 0) ? $preskok /($valid + $nonsubstantive + $nonresponse + $preskok) : 0; // Delez preskokov
+ $UAQ = ($all > 0) ? $naknadno / $all : 0; // Delez naknadnih
+
+ // Ce nimamo veljavnih in nevsebinskih je UCL vedno 0
+ $UCL = ($valid + $nonsubstantive == 0) ? 0 : $UCL;
+
+ $usablePercent = $UCL * 100;
+
+ if($usablePercent < (int)$this->bottom_usable_limit){
+ $css_usable = 'unusable';
+ $status = 0;
+ $usability['unusable']++;
+ }
+ elseif($usablePercent >= (int)$this->bottom_usable_limit && $usablePercent < (int)$this->top_usable_limit){
+ $css_usable = 'partusable';
+ $status = 1;
+ $usability['partusable']++;
+ }
+ else{
+ $css_usable = 'usable';
+ $status = 2;
+ $usability['usable']++;
+ }
+ $usability['all']++;
+
+ // Nastavimo izracunane podatke za respondenta
+ $usability['data'][$counter]['recnum'] = $frequencies['recnum'];
+ $usability['data'][$counter]['usr_id'] = $frequencies['usr_id'];
+ $usability['data'][$counter]['css'] = $css;
+ $usability['data'][$counter]['status'] = $status;
+ $usability['data'][$counter]['all'] = $all;
+ $usability['data'][$counter]['valid'] = $valid;
+ $usability['data'][$counter]['nonsubstantive'] = $nonsubstantive;
+ $usability['data'][$counter]['nonresponse'] = $nonresponse;
+ $usability['data'][$counter]['breakoff'] = $breakoff;
+ $usability['data'][$counter]['usable'] = $usable;
+ $usability['data'][$counter]['validPercent'] = $validPercent;
+ $usability['data'][$counter]['usablePercent'] = $usablePercent;
+ $usability['data'][$counter]['nonsubstantivePercent'] = $nonsubstantivePercent;
+ $usability['data'][$counter]['nonresponsePercent'] = $nonresponsePercent;
+ $usability['data'][$counter]['breakoffPercent'] = $breakoffPercent;
+ $usability['data'][$counter]['UNL'] = $UNL;
+ $usability['data'][$counter]['UML'] = $UML;
+ $usability['data'][$counter]['UCL'] = $UCL;
+ $usability['data'][$counter]['UIL'] = $UIL;
+ $usability['data'][$counter]['UAQ'] = $UAQ;
+
+ // ali odstranimo vse stolpce s podrobnimi vrednostmi (-1, -2...)
+ foreach ($this->_missings AS $value => $text){
+ $usability['data'][$counter][$value] = (isset($frequencies[$value]) ? $frequencies[$value] : '0');
+ }
+ foreach ($this->_unsets AS $value => $text){
+ $usability['data'][$counter][$value] = (isset($frequencies[$value]) ? $frequencies[$value] : '0');
+ }
+
+
+ $css = ($css == 'colored') ? '' : 'colored';
+ $counter++;
+ }
+
+ return $usability;
+ }
+
+ // Ali imamo zgenerirano datoteko ali ne
+ public function hasDataFile(){
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED)
+ return false;
+ else
+ return true;
+ }
+
+ public function setStatusFilter($status=''){
+
+ $this->_CURRENT_STATUS_FILTER = $status;
+ }
+
+ function ajax(){
+
+ $action = $_GET['a'];
+
+ switch ($action){
+ case 'changeSetting' :
+ $this->ajax_change_settings();
+ break;
+ }
+ }
+ private function ajax_change_settings(){
+
+ $value = $_POST['value'];
+ $what = $_POST['what'];
+
+ if($value == 'true')
+ $value = true;
+ elseif($value == 'false')
+ $value = false;
+
+ $this->sessionData['usable_resp'][$what] = $value;
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyUserSession.php b/admin/survey/classes/class.SurveyUserSession.php
new file mode 100644
index 0000000..a839878
--- /dev/null
+++ b/admin/survey/classes/class.SurveyUserSession.php
@@ -0,0 +1,149 @@
+<?php
+
+/** Class ki je nadomestil session pri nastavitvah userja
+ * Januar 2013
+ *
+ *
+ *
+ * @author Peter Hrvatin
+ *
+ */
+class SurveyUserSessionDestructor
+{
+ /** pokli�emo destruktor funkcijo
+ *
+ */
+ public function __destruct()
+ {
+ SurveyUserSession::destruct();
+ }
+}
+
+class SurveyUserSession
+{
+
+ private static $destructorInstance;
+ private static $ank_id = null; // ID ankete
+ private static $dataArray = array();
+
+
+ static function Init($anketa = null)
+ {
+ global $global_user_id;
+
+ if (null === self::$destructorInstance)
+ self::$destructorInstance = new SurveyUserSessionDestructor();
+
+ if ($anketa == null || (int)$anketa == 0 || !is_numeric($anketa)) {
+ throw new Exception('Survey ID is mandatory for SurveyUserSession!');
+ }
+ self::$ank_id = $anketa;
+
+ # preberemo vse nastavitve za to anketo - ce jih se nimamo
+ if (!is_countable(self::$dataArray) || count(self::$dataArray) == 0) {
+ $sql = sisplet_query("SELECT data FROM srv_user_session WHERE ank_id='" . self::$ank_id . "' AND usr_id='$global_user_id'");
+ $row = mysqli_fetch_array($sql);
+
+ self::$dataArray = unserialize($row['data']);
+ }
+ }
+
+ static function getData($what = null)
+ {
+
+ if (self::$ank_id == null) {
+ throw new Exception('Survey ID is mandatory for SurveyUserSession!');
+ return null;
+ }
+
+ if ($what == null) {
+ return self::$dataArray;
+ } else if (isset(self::$dataArray[$what])) {
+ return self::$dataArray[$what];
+ }
+
+ return null;
+ }
+
+ public static function saveData($value, $what = null)
+ {
+ global $global_user_id;
+
+ if (self::$ank_id == null) {
+ throw new Exception('Survey ID is mandatory for SurveyUserSession!');
+ return null;
+ }
+
+
+ // Ce smo uporabili vse podatke
+ if ($what == null) {
+ self::$dataArray = $value;
+
+ // Brez tega break nekje ne dela - TODO
+ $dataString = mysqli_real_escape_string($GLOBALS['connect_db'], serialize(self::$dataArray));
+ $sql = sisplet_query("INSERT INTO srv_user_session (ank_id, usr_id, data) VALUES ('" . self::$ank_id . "', '$global_user_id', '$dataString') ON DUPLICATE KEY UPDATE data='$dataString'");
+
+ return true;
+ } // Ce smo uporabljali podatke samo za posamezno podstran
+ else {
+ if (!is_string($what)) {
+ throw new Exception('Variable \'what\' must be string!');
+ return null;
+ } else {
+ self::$dataArray[$what] = $value;
+ return true;
+ }
+ }
+ }
+
+ /**
+ * Izbriši seje za dotičnega uporabnika
+ */
+ public static function delete()
+ {
+ global $global_user_id;
+
+ if (self::$ank_id == null) {
+ throw new Exception('Survey ID is mandatory for SurveyUserSession!');
+ return null;
+ }
+
+ sisplet_query("DELETE FROM srv_user_session WHERE ank_id = '" . self::$ank_id . "' AND usr_id='" . $global_user_id . "'");
+ }
+
+ /** ob ukinitvi klassa shranimo vse vrednosti
+ *
+ */
+ static public function destruct()
+ {
+ global $global_user_id;
+ global $connect_db;
+
+ if (self::$ank_id == null) {
+ throw new Exception('Survey ID is mandatory for SurveyUserSession!');
+ return null;
+ }
+
+ // v destructu več nimamo connect_db resoursa
+ if ($connect_db == null) {
+ // poizkusimo še 1x
+ global $mysql_server, $mysql_username, $mysql_password, $mysql_database_name;
+ if (!$connect_db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database_name)) {
+ die ('Please try again later [ERR: DB])');
+ }
+ }
+
+ # pripravimo string za shranjevanje
+ if (is_countable(self::$dataArray) && count(self::$dataArray) > 0) {
+ $dataString = mysqli_real_escape_string($GLOBALS['connect_db'], serialize(self::$dataArray));
+
+ $sql = sisplet_query("INSERT INTO srv_user_session (ank_id, usr_id, data) VALUES ('" . self::$ank_id . "', '$global_user_id', '$dataString') ON DUPLICATE KEY UPDATE data='$dataString'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ // Dodano ker drugace ne zapise v bazo (zaradi ExclusiveLock classa)
+ sisplet_query("COMMIT");
+ }
+ }
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyUserSetting.php b/admin/survey/classes/class.SurveyUserSetting.php
new file mode 100644
index 0000000..0627f2a
--- /dev/null
+++ b/admin/survey/classes/class.SurveyUserSetting.php
@@ -0,0 +1,118 @@
+<?php
+/**
+ * Created on 4.5.2009
+ *
+ * @author: GOrazd Vesleič
+ *
+ * @desc: za nastavitve uporabnikov, za vsako anketo posebej
+ */
+
+ class SurveyUserSetting
+{
+ static private $instance;
+
+ static private $surveyId = null;
+ static private $userId = null;
+ static private $inited = false;
+ static private $rowUserInit = null;
+
+ protected function __construct() {}
+
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveyUserSetting();
+ }
+ return self::$instance;
+ }
+
+ /** napolnimo podatke
+ *
+ */
+ static function Init($_surveyId, $_userId)
+ {
+ if ($_surveyId && $_userId)
+ {
+ self::$surveyId = $_surveyId;
+ self::$userId = $_userId;
+
+ self::$inited=true;
+ return true;
+ }
+ else
+ return false;
+ }
+
+ static function getSurveyId() { return self::$surveyId; }
+ static function getUserId() { return self::$userId; }
+
+ static function useIfinReport() { // stara funkcija
+ $use_if_in_report = self::getSettings('use_if_in_report');
+ if ($use_if_in_report == null)
+ $use_if_in_report = 1;
+ return $use_if_in_report; }
+
+ static function setShowPdfIf($set) { // stara funkcija
+ $value = $set?1:0;
+ self::saveSettings('use_if_in_report', $value);
+ }
+
+
+ static function getSettings($what) {
+ $selectSql = "SELECT value FROM srv_user_setting_for_survey WHERE sid = '".self::$surveyId."' AND uid = '".self::$userId."' AND what = '".$what."'";
+ $sqlUserSetting = sisplet_query($selectSql);
+ $rowUserSetting = mysqli_fetch_assoc($sqlUserSetting);
+ return $rowUserSetting['value'];
+ }
+
+ static function getAll() {
+ $result = array();
+ $selectSql = "SELECT what, value FROM srv_user_setting_for_survey WHERE sid = '".self::$surveyId."' AND uid = '".self::$userId."'";
+ $sqlUserSetting = sisplet_query($selectSql);
+ while (list($what,$value) =mysqli_fetch_row($sqlUserSetting))
+ {
+ $result[] = array('what'=>$what,'value'=>$value);
+ }
+ return $result;
+ }
+
+ static function saveSettings($what, $value) {
+
+ if ($what != null) {
+ $insertString = "INSERT INTO srv_user_setting_for_survey (sid, uid, what, value) VALUES " .
+ "('".self::$surveyId."', '".self::$userId."', '".$what."', '".$value."') " .
+ "ON DUPLICATE KEY UPDATE value='".$value."'";
+ $insert = sisplet_query($insertString);
+ sisplet_query('COMMIT');
+ }
+
+ return $insert;
+ }
+ static function removeSettings($what) {
+ if ($what != null) {
+ $deleteString = "DELETE FROM srv_user_setting_for_survey WHERE sid = '".self::$surveyId."' AND uid = '".self::$userId."' AND what = '".$what."'";
+ $delete = sisplet_query($deleteString);
+ }
+
+ return $insert;
+ }
+
+ static function getUserRow () {
+ global $global_user_id;
+
+ if (!self::$rowUserInit) {
+ $queryUserInit = sisplet_query("SELECT * FROM users WHERE id = '".$global_user_id."'");
+ self::$rowUserInit = mysqli_fetch_assoc($queryUserInit);
+ }
+
+ return self::$rowUserInit;
+ }
+
+}
+?>
diff --git a/admin/survey/classes/class.SurveyVariableView.php b/admin/survey/classes/class.SurveyVariableView.php
new file mode 100644
index 0000000..4dc1557
--- /dev/null
+++ b/admin/survey/classes/class.SurveyVariableView.php
@@ -0,0 +1,85 @@
+<?php
+
+class VariableView {
+
+ static private $_instance; # Singleton static instance
+ static private $_sid; # id ankete
+
+ static private $SDF = null; # class za inkrementalno dodajanje fajlov
+ static private $headFileName = null; # pot do header fajla
+ static private $dataFileName = null; # pot do data fajla
+ static private $dataFileStatus = null; # status data datoteke
+ static private $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ /**
+ * Get the singleton instance of this class and enable writing at shutdown.
+ *
+ * $VariableView = VariableView::instance();
+ *
+ * @return VariableView
+ */
+ public static function instance() {
+ if (self::$_instance === NULL) {
+ // Create a new instance
+ self::$_instance = new self;
+ }
+ return self::$_instance;
+ }
+
+ public static function init($sid) {
+ self::$_sid = $sid;
+
+ # polovimo variable ankete
+ #inicializiramo class za datoteke
+ self::$SDF = SurveyDataFile::get_instance();
+ self::$SDF->init($sid);
+
+ self::$headFileName = self::$SDF->getHeaderFileName();
+ self::$dataFileName = self::$SDF->getDataFileName();
+ self::$dataFileStatus = self::$SDF->getStatus();
+ self::$_HEADERS = self::$SDF->getHeader();
+
+ }
+
+ public static function displayVariables() {
+ global $lang;
+
+ echo '<table class="variableView">';
+
+ echo '<thead><tr>';
+ echo '<th>'.$lang['srv_variableView_h_'].'</th>';
+ echo '<th>'.$lang['srv_variableView_h_type'].'</th>';
+ echo '<th>'.$lang['srv_variableView_h_width'].'</th>';
+ echo '<th>'.$lang['srv_variableView_h_decimals'].'</th>';
+ echo '<th>'.$lang['srv_variableView_h_label'].'</th>';
+ echo '<th>'.$lang['srv_variableView_h_measure'].'</th>';
+ echo '</tr></thead>';
+
+ echo '<tbody>';
+
+ foreach (self::$_HEADERS AS $skey => $spremenljivka) {
+
+ if (is_numeric($spremenljivka['tip']) && $spremenljivka['tip'] != '' && $spremenljivka['tip'] != 'm' && $spremenljivka['tip'] != 'sm') {
+
+ $spss = $spremenljivka['grids'][0]['variables'][0]['spss'];
+ $spss_type = substr($spss,0,1);
+ $spss_length = explode('.',substr($spss,1));
+ $spr_id = explode('_',$skey);
+ $spr_id = $spr_id[0];
+ $legenda = Cache::spremenljivkaLegenda($spr_id);
+
+ echo '<tr>';
+ echo '<td>'.$spremenljivka['variable'].'</td>';
+ echo '<td>'.$legenda['izrazanje'].'</td>';
+ echo '<td>'.(int)$spss_length['0'].'</td>';
+ echo '<td>'.(int)$spss_length['1'].'</td>';
+ echo '<td>'.$spremenljivka['naslov'].'</td>';
+ echo '<td>'.$legenda['skala'].'</td>';
+ echo '</tr>';
+ }
+ }
+
+ echo '</tbody>';
+ echo '</table>';
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyVariablesProfiles.php b/admin/survey/classes/class.SurveyVariablesProfiles.php
new file mode 100644
index 0000000..110f767
--- /dev/null
+++ b/admin/survey/classes/class.SurveyVariablesProfiles.php
@@ -0,0 +1,649 @@
+<?php
+/**
+ * Created on 10.04.2013
+ *
+ * @author: Gorazd Veselič
+ *
+ * @desc: za shranjevanje in nalaganje profilov variabel za posamezno anketo
+ *
+ * Profil -1 je rezerviran za sejo
+ * Profil 0 je rezerviran za privzet profil - Vse vrednosti
+ *
+ */
+DEFINE ('SVP_DEFAULT_PROFILE', 0);
+DEFINE (NEW_LINE, "\n");
+
+class SurveyVariablesProfiles
+{
+ static private $sid = null; # id ankete
+ static private $availableProfiles = array(); # array kamor shranimo vse doseglijive profile
+ static private $profiles = array(); # array kamor shranimo podatke o trenutnem profilu
+ static private $currentId = SVP_DEFAULT_PROFILE; # trenutno izbran profil
+ static private $SDF = null; # trenutno izbran profil
+
+
+ /** Inicializacija
+ * $uid=null še je posledica starega classa Je potrebno povsod zamenjat Init funkcijo
+ */
+ static function Init($sid) {
+ global $global_user_id;
+
+ self::$sid = $sid;
+
+ #inicializiramo class za datoteke
+ self::$SDF = SurveyDataFile::get_instance();
+ self::$SDF->init($sid);
+
+ #polovimo vse profile
+ self::getProfiles();
+
+ #inicaliziramo nastavitve uporabnika
+ SurveyUserSetting :: getInstance()->Init($sid, $global_user_id);
+ self::$currentId = self:: getCurentProfileId();
+ }
+
+ static function setCurrentProfileId($pid)
+ {
+ if (isset(self::$profiles[$pid])){
+ self::$currentId = $pid;
+ }
+ else{
+ self::$currentId = SVP_DEFAULT_PROFILE;
+ }
+ }
+
+ static function getProfiles() {
+ global $lang;
+
+ # če imamo sejo preberemo iz seje
+ if ( isset($_SESSION['variables_profile'][self::$sid]))
+ {
+ self::$profiles[-1] = $_SESSION['variables_profile'][self::$sid];
+ }
+ #dodamo profil vse variable
+ $svp_av = self::$SDF->getSurveyVariables();
+ $all_variables = array();
+ if (count($svp_av) > 0)
+ {
+ foreach($svp_av AS $v_id => $seq)
+ {
+ $all_variables[] = $v_id;
+ }
+ }
+ $variables = serialize($all_variables);
+ self::$profiles[SVP_DEFAULT_PROFILE] = array('id'=>SVP_DEFAULT_PROFILE, 'name'=>$lang['srv_all_vars'].' *', 'variables'=>$variables);
+
+ # preberemo še profile iz baze
+ $stringSelect = "SELECT id, name, variables FROM srv_variable_profiles WHERE sid = '".self::$sid."'";
+ $sqlQuery = sisplet_query($stringSelect);
+ while (list($id,$name,$variables) = mysqli_fetch_row($sqlQuery))
+ {
+ self::$profiles[$id] = array('id'=>$id,
+ 'name'=>$name,
+ 'variables'=>$variables);
+ }
+ }
+
+ /** Trenutno izbran profil
+ *
+ */
+ static function getCurentProfileId() {
+
+ # poiscemo privzet profil
+ $_dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ self::$currentId = $_dvp;
+
+ if ($_dvp == null || !isset(self::$profiles[self::$currentId])) {
+ $_dvp = SVP_DEFAULT_PROFILE;
+ self::$currentId = $_dvp;
+ self::setDefaultProfile(self::$currentId);
+ }
+
+ return (int)self::$currentId;
+ }
+
+ static function getSystemDefaultProfile() {
+ return (int)SVP_DEFAULT_PROFILE;
+ }
+
+ static function checkDefaultProfile($dvp=0) {
+ // preverimo ali izbran privzet profil obstaja
+ if ($dvp == -1) { //preverimo sejo
+ if ( isset($_SESSION['variables_profile'][self::$sid]) ) {
+ return $_SESSION['variables_profile'][self::$sid]['id'];
+ } else { // morali bi imeti sejo pa je ni, zato nastavimo na privzetega (1)
+ $dvp = SVP_DEFAULT_PROFILE;
+ }
+ }
+
+ if ($dvp > 0 ) {
+ $stringSelect = "SELECT id FROM srv_variable_profiles WHERE id = '".$dvp."'";
+ $sqlSelect = sisplet_query($stringSelect);
+
+ if (mysqli_num_rows($sqlSelect) > 0) {// profil obstaja
+ $rowSelect = mysqli_fetch_assoc($sqlSelect);
+ return $rowSelect['id'];
+ }
+ }
+
+ # ce ne izberemo osnovni profil
+ return SVP_DEFAULT_PROFILE;
+ }
+
+ /**
+ *
+ * Enter description here ...
+ * @param $pid - profil ID
+ * @param $ignoreInspect - ce je profil inspect, in ga moramo ignorirat potem vrnemo prazn array
+ */
+ static function getProfileVariables($pid = null, $ignoreInspect=false)
+ {
+ if ($pid === null)
+ {
+ $pid = self::getCurentProfileId();
+ }
+
+ if ($ignoreInspect == true)
+ {
+ return array();
+ }
+
+ # ce profil ni inspect ali ce ga ne ignoriramone vrnemo variable
+ $variables = unserialize(self::$profiles[$pid]['variables']);
+ if (is_array($variables))
+ {
+ $result=array();
+ if (count($variables) > 0)
+ {
+ foreach ($variables AS $key => $variable)
+ {
+ $result[$variable] = $variable;
+ }
+ }
+ return $result;
+ }
+ else
+ {
+ return array();
+ }
+ return array();
+ }
+
+
+ public function getProfileName($pid) {
+ return self::$profiles[$pid]['name'];
+ }
+
+ /**
+ *
+ * @param $ignoreInspect - ce je profil inspect, in ga moramo ignorirat
+ */
+ static function DisplayLink($ignoreInspect=false,$hideAdvanced = true) {
+ global $lang;
+ $izbranProfil = self::checkDefaultProfile(self::$currentId);
+
+ $css = ($izbranProfil == SVP_DEFAULT_PROFILE ? ' gray' : '');
+
+ if ($hideAdvanced == false || $css != ' gray') {
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" onclick="displayVariableProfile();" title="'.$lang['srv_filtri'].'">'.$lang['srv_filtri'].'</span>';
+ echo '</li>';
+
+ }
+ }
+
+ /**
+ * @param $ignoreInspect - ce je profil inspect, in ga moramo ignorirat potem vrnemo prazn array
+ */
+ static function getProfileString($ignoreInspect = false) {
+ global $lang;
+
+ $pid = self::checkDefaultProfile(self::$currentId);
+ if ($ignoreInspect == true) {
+ return;
+ }
+
+ $svp_pv = self::getProfileVariables($pid);
+ $svp_av = self::$SDF->getSurveyVariables();
+
+ if (count($svp_pv) > 0 && count($svp_pv) != count($svp_av)) {
+ $vars = array();
+ foreach ($svp_pv AS $vkey => $variable) {
+ $variable_data = self::$SDF->getHeaderVariable($variable);
+ $vars[] = $variable_data['variable'];
+ }
+
+ $variable_label = implode(', ',$vars);
+ echo '<div id="variableProfileNote">';
+ echo '<span class="floatLeft">'.$lang['srv_profile_variables_is_filtred'].'</span>';
+ echo '<span class="floatLeft">'.$variable_label.'</span>';
+
+ echo '<span class="as_link spaceLeft" onclick="displayVariableProfile();">'.$lang['srv_profile_edit'].'</span>';
+ echo '<span class="as_link spaceLeft" onclick="removeVariableProfile();">'.$lang['srv_profile_remove'].'</span>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ return true;
+ }
+ return false;
+ }
+
+ static function chooseProfile($pid){
+
+ # če smo izbrali drug profil resetiramo še profil profilov na trenutne nastavitve
+ SurveyUserSetting :: getInstance()->saveSettings('default_profileManager_pid', '0');
+
+ if(isset(self::$profiles[$pid]))
+ {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', $pid);
+ }
+ else
+ {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', SVP_DEFAULT_PROFILE);
+ }
+ }
+
+ static function ajax() {
+
+ $pid = $_POST['pid'];
+
+ if ($_POST['podstran'] == 'monitoring') {
+ self::$monitoring = true; self::refreshAvailableProfiles();
+ };
+
+ switch ($_GET['a']) {
+ case 'displayProfile':
+ self::displayProfiles($_POST['pid']);
+
+ break;
+ case 'changeProfile':
+ self::displayProfiles($_POST['pid']);
+ break;
+ case 'chooseProfile':
+ self::chooseProfile($_POST['pid']);
+ break;
+ case 'saveProfile':
+ self::saveProfile();
+ break;
+ case 'saveNewProfile':
+ $new_id = self :: newProfileVariables();
+ break;
+ case 'renameProfile':
+ $updated = self::renameVariableProfile($_POST['pid'],$_POST['name']);
+ break;
+ case 'deleteProfile':
+ self::deleteVariableProfile($_POST['pid']);
+ break;
+ }
+ }
+
+
+ static function displayProfiles ($cvp = null) {
+ global $lang;
+
+ $popUp = new PopUp();
+ $popUp->setId('div_variable_profiles');
+ $popUp->setHeaderText($lang['srv_spremenljivke_settings']);
+
+ #vsebino shranimo v buffer
+ ob_start();
+
+ echo '<div class="popup_close"><a href="#" onClick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\'); return false;">✕</a></div>';
+
+ if ($cvp == null)
+ $cvp = self::$currentId;
+ $svp_ap = self::$profiles;
+ $svp_pv = self :: getProfileVariables($cvp);
+ $svp_av = self::$SDF->getSurveyVariables();
+
+ if ( self::$currentId != SVP_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div>';
+ echo '<br class="clr" />';
+ }
+
+ echo '<div class="variable_profile_holder">';
+ echo ' <div id="variable_profile" class="select">';
+ foreach ($svp_ap as $key => $value) {
+
+ echo '<div class="option'.($cvp==$value['id']?' active':'').'" value="'.$value['id'].'" '.($cvp==$value['id'] ? '' : ' onclick="changeVariableProfile(\''.$value['id'].'\');"').'>';
+
+ echo $value['name'];
+
+ if($cvp == $value['id']){
+ // izbriši
+ if ((int)$cvp != 0){
+ echo ' <a href="#" onclick="variableProfileAction(\'deleteAsk\'); return false;" value="'.$lang['srv_delete_profile'].'"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'."\n";
+ }
+ // preimenuj
+ if ((int)$cvp != 0){
+ echo ' <a href="#" onclick="variableProfileAction(\'renameAsk\'); return false;" value="'.$lang['srv_rename_profile'].'"><span class="faicon edit icon-as_link floatRight spaceRight"></span></a>'."\n";
+ }
+ }
+
+ echo '</div>';
+ }
+ echo ' </div>';
+
+ // izberi / odznaci vse
+ echo '<div style="position:absolute; bottom:20px; left:20px;">';
+ echo '<a href="#" onClick="variableProfileSelectAll(1); return false;">'.$lang['srv_select_all'].'</a>';
+ echo ' / <a href="#" onClick="variableProfileSelectAll(0); return false;">'.$lang['srv_deselect_all'].'</a>';
+ echo '</div>';
+
+ echo '</div>';
+
+
+ echo '<div id="vp_list">';
+
+ $empty = count($svp_pv) == 0;
+ echo '<ul id="vp_list_ul" class="left">';
+ if (count($svp_av) > 0)
+ {
+ foreach($svp_av as $key => $variabla)
+ {
+ $_name = self::$SDF->getVariableName($key);
+ $checked = ($empty || in_array($key, $svp_pv));
+ echo '<li'.($checked?' class="selected"':'').'>';
+ echo '<label>';
+ echo '<input type="checkbox" '.($checked?' checked="checekd"':'').' name="vp_list_li" value="'.$key.'" id="variable_'.$key.'" onchange="variableProfileCheckboxChange(this);">'.limitString($_name);
+ echo '</label></li>';
+ }
+ }
+ echo '</ul>';
+
+ echo '</div>';
+ // cover Div
+ echo '<div id="variableProfileCoverDiv"></div>';
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfile">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />';
+ $button = new PopUpButton($lang['srv_save_profile']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','variableProfileAction(\'newSave\'); return false;');
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','variableProfileAction(\'newCancel\'); return false;');
+ echo '</div>';
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': ';
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="'.$svp_ap[$cvp]['name'].'" size="45" />';
+ echo '<input id="renameProfileId" type="hidden" value="'.$pid.'" />';
+ $button = new PopUpButton($lang['srv_rename_profile_yes']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','variableProfileAction(\'renameProfile\'); return false;');
+
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','variableProfileAction(\'renameCancel\'); return false;');
+ echo '</div>';
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>'.$svp_ap[$cvp]['name'].'</b>?';
+ echo '<input id="deleteProfileId" type="hidden" value="'.$pid.'" />';
+
+ $button = new PopUpButton($lang['srv_delete_profile_yes']);
+ echo $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','variableProfileAction(\'deleteConfirm\'); return false;');
+
+ $button = new PopUpButton($lang['srv_cancel']);
+ echo $button -> setFloat('right')
+ -> addAction('onClick','variableProfileAction(\'deleteCancel\'); return false;');
+ echo '</div>';
+
+ $content = ob_get_clean();
+ #dodamo vsebino
+ $popUp->setContent($content);
+
+ # gumb izberi
+ $button = new PopUpButton($lang['srv_choose_profile']);
+ $button -> setFloat('right')
+ ->setButtonColor('orange')
+ -> addAction('onClick','variableProfileAction(\'choose\'); return false;');
+ $popUp->addButton($button);
+
+ # gumb shrani
+ if ((int)$cvp != 0)
+ {
+ $button = new PopUpButton($lang['srv_save_profile']);
+ $button -> setFloat('right')
+ ->setButtonColor('gray')
+ -> addAction('onClick','variableProfileAction(\'save\'); return false;');
+ $popUp->addButton($button);
+ }
+
+ # gumb shrani kot now
+ $button = new PopUpButton($lang['srv_new_profile_name']);
+ $button -> setFloat('right')
+ -> addAction('onClick','variableProfileAction(\'newName\'); return false;');
+ $popUp->addButton($button);
+
+ # dodamo gumb Preklici
+ $button = new PopUpCancelButton();
+ $button -> setFloat('right');
+ $popUp->addButton($button);
+
+
+ echo $popUp;
+ }
+
+
+ static function setProfileVariables($pid, $variables)
+ {
+ global $lang;
+ # če je pid < 1 ga shranimo v sejo
+ if ($pid < 1)
+ {
+ $pid = -1;
+ session_start();
+
+ # nastavimo kot sejo
+ $_SESSION['variables_profile'][self::$sid] = array(
+ 'id' => "$pid",
+ 'name' => $lang['srv_missing_profile_temp'],
+ 'variables' => $variables);
+
+ self::$profiles[$pid] = $_SESSION['variables_profile'][self::$sid];
+ session_commit();
+
+ }
+ else
+ {
+ $updateString = "UPDATE srv_variable_profiles SET variables = '".$variables."' WHERE id='".$pid."' AND sid = '". self::$sid."'";
+ $sqlupdate = sisplet_query($updateString) or die(mysqli_error($GLOBALS['connect_db']));
+ self::$profiles[$pid]['variables'] = $variables;
+ }
+
+ //echo $pid;
+ return $pid;
+ }
+
+ function saveProfile()
+ {
+ global $lang;
+
+ $pid = $_POST['pid'];
+ $strArray = explode("&",$_POST['vp_list_li']);
+
+ $variables = array();
+ foreach ($strArray as $item)
+ {
+ $array = explode("=", $item);
+ $variables[] = $array[1];
+ }
+ $variables = serialize($variables);
+
+ return self::setProfileVariables($pid, $variables);
+ }
+
+
+ static function newProfileVariables() {
+ global $lang;
+
+ $profileId = -1;
+ $numrows = -1;
+
+ $profileName = $_POST['name'];
+ if (empty($profileName))
+ {
+ $profileName = $lang['srv_new_profile_name'];
+ }
+
+ # ime profila preverima ali obstaja
+ do
+ { # preverimo ali ime že obstaja
+ $selectSqlProfile = "SELECT id FROM srv_variable_profiles WHERE name = '".$profileName."' AND sid = '".self::$sid."'";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+ $numrows = mysqli_num_rows($sqlProfileSetting);
+ if ($numrows != 0)
+ { # ime že obstaja zgeneriramo novo
+ srand(time());
+ $profileName .= rand(0, 9);
+ }
+ }
+ while ($numrows != 0);
+
+ $strArray = explode("&",$_POST['vp_list_li']);
+ $variables = array();
+ foreach ($strArray as $item) {
+ $array = explode("=", $item);
+ $variables[] = $array[1];
+ }
+ $variables = serialize($variables);
+
+ $stringInsert = "INSERT INTO srv_variable_profiles (sid,name,variables) " .
+ "VALUES ('".self::$sid."','".$profileName."','".$variables."')";
+ sisplet_query($stringInsert);
+ $insertId = mysqli_insert_id($GLOBALS['connect_db']);
+
+ # osvežimo profile
+ self::getProfiles();
+
+ #nastavimo privzetega
+ self::chooseProfile($insertId);
+
+ echo $insertId;
+
+ return $insertId;
+
+ }
+
+ function deleteVariableProfile($pid) {
+ if ($pid < 0 )
+ { // seja -
+ session_start();
+ unset($_SESSION['variables_profile'][self::$sid]);
+ unset(self::$profiles[$pid]);
+ session_commit();
+ }
+ else if( $pid > 0)
+ {
+ $deleteString = "DELETE FROM srv_variable_profiles WHERE id='".$pid."' AND sid = '". self::$sid."'";
+ $sqlDelete = sisplet_query($deleteString);
+ unset(self::$profiles[$pid]);
+ }
+ $pid = SVP_DEFAULT_PROFILE;
+
+ return self::chooseProfile($pid);
+ }
+
+
+ function renameVariableProfile($profileId, $newProfileName) {
+ global $lang;
+
+ $sqlInsert = -1;
+ if ( !empty($profileId) && (int)$profileId > 0)
+ {
+ if ( $newProfileName == null || $newProfileName == "" )
+ {
+ $newProfileName = $lang['srv_new_profile_name'];
+ }
+
+ $numrows = -1;
+ do { // preverimo ali ime že obstaja
+ $selectSqlProfile = "SELECT id FROM srv_variable_profiles WHERE name = '".$newProfileName."' AND sid = '".self::$sid."'";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+
+ $numrows = mysqli_num_rows($sqlProfileSetting);
+ if ($numrows != 0) { // ime že obstaja zgeneriramo novo
+ srand(time());
+ $newProfileName .= rand(0, 9);
+ }
+ } while ($numrows != 0);
+
+ $updateString = "UPDATE srv_variable_profiles SET name = '".$newProfileName."' WHERE id = '".$profileId."' AND sid = '".self::$sid."'";
+ $sqlInsert = sisplet_query($updateString);
+ }
+
+ return $sqlInsert;
+ }
+
+ /** Nastavimo profil kot zacasen inspect
+ *
+ * Enter description here ...
+ * @param $variables
+ */
+ function setProfileInspect($variables) {
+ global $lang;
+
+ # nastavimo kot sejo
+ $pid = -1;
+
+ if (is_array($variables))
+ {
+ $variables = serialize($variables);
+ }
+
+ self::$profiles[$pid] = array('id'=>$pid, 'name'=>$lang['srv_inspect_temp_profile'], 'variables'=>$variables);
+ session_start();
+ $_SESSION['variables_profile'][self::$sid] = self::$profiles[$pid];
+ session_commit();
+ # dodoamo še v class
+ self::setDefaultProfile($pid);
+ }
+
+ /** old class compatibility **/
+ static function setDefaultProfile($pid) {
+ self::chooseProfile($pid);
+ }
+ /** old class compatibility **/
+ static function setDefaultProfileId($pid) {
+ self::chooseProfile($pid);
+ }
+
+ /** preveri obstoj profila in vrne enak id če obstaja, če ne vrne id privzetega profila
+ *
+ * @param unknown_type $pid
+ * @return unknown
+ */
+ function checkProfileExist($pid)
+ {
+ if (isset(self::$profiles[$pid]))
+ {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+function limitString($input, $limit = 100) {
+
+ // Return early if the string is already shorter than the limit
+ if(strlen($input) < $limit) {
+ return $input;
+ }
+
+ $regex = "/(.{1,$limit})\b/";
+ preg_match($regex, $input, $matches);
+
+ return $matches[1].'...';
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyZankaProfiles.php b/admin/survey/classes/class.SurveyZankaProfiles.php
new file mode 100644
index 0000000..7b341a6
--- /dev/null
+++ b/admin/survey/classes/class.SurveyZankaProfiles.php
@@ -0,0 +1,546 @@
+<?php
+/**
+ * Created on 8.1.2010
+ *
+ * @author: Mitja Kuščer
+ *
+ * Revriten on 9.11.2010
+ * @author: Gorazd Veselič
+ *
+ * @desc: za shranjevanje in nalaganje profilov zank za posamezno anketo
+ *
+ * Profil 0 je rezerviran za sejo
+ * Profil 1 je rezerviran za privzet profil - Vse vrednosti
+ *
+ * funkcije:
+ *
+ * Init - inicializira profil in naloži trenutne vrednosti iz baze ali seje za določenega userja
+ *
+ */
+session_start();
+
+define('SZP_DEFAULT_PROFILE', 0);
+
+class SurveyZankaProfiles {
+
+ static private $sid = null; # id ankete
+ static private $uid = null; # id userja
+
+ static private $currentProfileId = null; # trenutno profil
+ static private $profiles = array(); # seznam vseh profilov od uporabnika
+ static private $inited = false; # ali so profili ze inicializirani
+ static private $clearZankaProfile = false; #
+
+ static function Init($sid, $uid = null) {
+ # nastavimo sid
+ self::$sid = $sid;
+
+ if (isset($uid) && $uid > 0) {
+ self :: $uid = $uid ;
+ } else {
+ global $global_user_id;
+ self :: $uid = $global_user_id;
+ }
+
+ SurveyUserSetting :: getInstance()->Init(self::$sid, self::$uid);
+ if (self::$inited == false) {
+ self::$inited = self :: RefreshData();
+ }
+ }
+
+
+ static function RefreshData() {
+
+ self::$profiles = array();
+
+ # dodamo sistemske profile, skreiramo jih "on the fly"
+ self :: addSystemProfiles();
+
+ # preberemo podatke vseh porfilov ki so na voljo in jih dodamo v array
+ $stringSelect = "SELECT * FROM srv_zanka_profiles WHERE sid='" . self::$sid . "' AND uid='" . self::$uid . "' ";
+ $querySelect = sisplet_query($stringSelect);
+
+ if (mysqli_num_rows($querySelect)) {
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ }
+ }
+ # poiscemo privzet profil
+ self::$currentProfileId = SurveyUserSetting :: getInstance()->getSettings('default_zanka_profile');
+
+ if (self::$currentProfileId === null) {
+ self::$currentProfileId = 0;
+ }
+
+ # ce imamo nastavljen curent pid in profil z tem pid ne obstaja nastavomo na privzet profil
+ if (self::$currentProfileId > 0) {
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ self::$currentProfileId = 0;
+ self::setDefaultProfileId(self::$currentProfileId);
+ }
+ }
+
+ # ce ne obstajajo podatki za cpid damo error
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ self::$currentProfileId = 0;
+
+ if (!isset(self::$profiles[self::$currentProfileId])) {
+ echo ("Profile data is missing! (class.SurveyZankaProfile");
+ return false;
+ } else {
+ self::setDefaultProfileId(self::$currentProfileId);
+ return true;
+ }
+ } else {
+ return true;
+ }
+
+ }
+
+ static function setDefaultProfileId($pid = null) {
+ if ($pid === null) {
+ $pid = 0;
+ }
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_zanka_profile', $pid);
+ self::$currentProfileId = $pid;
+ return true;
+ }
+
+ static function addSystemProfiles() {
+ global $lang;
+
+ # dodamo iz seje
+ session_start();
+ if ( isset($_SESSION['zanka_profile']) ) {
+ self::$profiles['-1'] = array( 'id' => $_SESSION['zanka_profile'][self::$sid]['id'],
+ 'name' => $_SESSION['zanka_profile'][self::$sid]['name'],
+ 'system'=> $_SESSION['zanka_profile'][self::$sid]['system'],
+ 'variables'=> $_SESSION['zanka_profile'][self::$sid]['variables'],
+ 'mnozenje' => $_SESSION['zanka_profile'][self::$sid]['mnozenje']);
+ }
+ # skreiramo sistemske profile za vse spremenljivke
+ self::$profiles['0'] = array('id'=>'0','uid'=>self::$uid,'name'=>$lang['srv_zanka_profile_all'],'system'=>1);
+
+ }
+
+ static function DisplayLink($hideAdvanced = true) {
+ global $lang;
+ // profili statusov
+ $allProfiles = self :: $profiles;
+ $css = (self::$currentProfileId == SZP_DEFAULT_PROFILE ? ' gray' : '');
+ if ($hideAdvanced == false || self::$currentProfileId != SZP_DEFAULT_PROFILE) {
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="link_zanka_profile" title="' . $lang['srv_zanke'] . '" onClick="zankaProfileAction(\'showProfiles\');">' . $lang['srv_zanke'] . '</span>'."\n";
+ echo '</li>';
+
+ }
+ }
+
+ static function getProfileData($pid) {
+ // preverimo ali smo v razredu že lovili podatke za ta profil, potem jih preberemo čene jih osvežimo
+ if ( isset( self::$profiles[$pid] ) ) {
+ return self::$profiles[$pid];
+ } else {
+ self::$inited = self :: RefreshData();
+ return self::$profiles[$pid];
+ }
+ }
+
+ static function ajax() {
+ $pid = $_POST['pid'];
+ switch ($_GET['a']) {
+ case 'show_profile' :
+ self :: showProfiles($pid);
+ break;
+ case 'change_profile' :
+ self :: setDefaultProfileId($pid);
+ break;
+ case 'createProfile' :
+ self :: createProfile();
+ break;
+ case 'delete_profile' :
+ self :: deleteProfile();
+ break;
+ case 'rename_profile' :
+ self :: renameProfile();
+ break;
+ case 'run' :
+ self :: runProfile();
+ break;
+ default:
+ echo 'ERROR! Missing function for action: '.$_GET['a'].'! (SurveyZankaProfile)';
+ break;
+ }
+ }
+ static function showProfiles ($pid = null) {
+ global $lang;
+
+ echo '<div class="popup_close"><a href="#" onClick="zankaProfileAction(\'cancle\'); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_zanka_settings'].'</h2>';
+
+ if ($pid === null) {
+ # poiščmo uporabniški privzeti profil
+ $pid = self::$currentProfileId;
+ }
+
+ # variable profila
+ $szp_pv = explode(',',self::$profiles[$pid]['variables']);
+
+ # ali imamo množenje
+ $mnozenje = self::$profiles[$pid]['mnozenje'];
+
+ #vse možne variable
+ $sdf = SurveyDataFile::get_instance();
+ $sdf->init(self::$sid);
+ $szp_av =$sdf->getSurveyVariables(array(1,2,3));
+ // variable razdelimo na dve grupi, na vse možne in posebej izbrane
+ $selected_variables = array();
+ if (self::$clearZankaProfile == false) {
+ foreach ($szp_pv as $key => $variabla) {
+ if (isset($szp_av[$variabla])) {
+ $selected_variables[$variabla] = $variabla;
+ unset($szp_av[$variabla]);
+ }
+ }
+ }
+ #echo '<div id="currentZankaProfile">'.$lang['srv_analiza_selected_profile'].': <b>' . self::$profiles[$pid]['name'] . '</b></div >'.NEW_LINE;
+
+ if ( self::$currentProfileId != SZP_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+
+ echo '<div class="zanka_profile_holder">'.NEW_LINE;
+ echo ' <div id="zanka_profile" class="select">'.NEW_LINE;
+ if (count(self::$profiles) > 0 ){
+ foreach (self::$profiles as $key => $value) {
+
+ if ($value['id'] != null) {
+
+ echo '<div class="option' . ($pid == $value['id'] ? ' active' : '') . '" id="zanka_profile_' . $value['id'] . '" value="'.$value['id'].'">';
+
+ echo $value['name'];
+
+ if($value['id'] == $pid){
+ if ( $pid != 0) {
+ # sistemskega ne pustimo izbrisat
+ echo ' <a href="#" title="'.$lang['srv_delete_profile'].'" onclick="zankaProfileAction(\'deleteAsk\'); return false;"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'.NEW_LINE;
+ }
+ if ( $pid > 0) {
+ # seje in sistemskega ne pustimo preimenovat
+ echo ' <a href="#" title="'.$lang['srv_rename_profile'].'" onclick="zankaProfileAction(\'renameAsk\'); return false;"><span class="faicon edit icon-as_link floatRight spaceRight"></span></a>'.NEW_LINE;
+ }
+ }
+
+ echo '</div>'.NEW_LINE;
+ }
+ }
+ }
+ echo ' </div>'.NEW_LINE;
+
+ echo '<div class="clr"></div>'.NEW_LINE;
+
+ echo '</div>'.NEW_LINE;
+
+ // izrišemo dva stolpca z možnostjo premikanja enih in drugih variabelS
+ echo '<div id="fs_list">'.NEW_LINE;
+ echo '<div class="left link_no_decoration">'.NEW_LINE;
+ echo $lang['srv_select'].NEW_LINE;
+ echo '<a href="#" onclick="return $.dds.selectAll(\'fs_list_3\');">'.$lang['srv_all'].'</a>'.NEW_LINE;
+ echo '<a href="#" onclick="return $.dds.selectNone(\'fs_list_3\');">'.$lang['srv_none'].'</a> '.NEW_LINE;
+ echo '<a href="#" onclick="return $.dds.selectInvert(\'fs_list_3\');">'.$lang['srv_invert'].'</a>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ echo '<div class="left link_no_decoration" style="width:200px; text-align:center">'.NEW_LINE;
+ echo '<a href="#" onclick="zankaProfileAction(\'clearDdsZanka\'); return false;">'.$lang['srv_clear'].'</a>'.NEW_LINE;
+ echo '<input type="checkbox" name="mnozenje" id="mnozenje" value="1"'.($mnozenje==1?' checked="checked"':'').' autocomplete="off"/><label for="mnozenje">'.$lang['srv_analiza_krat'].'</label>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+
+ echo '<div class="right link_no_decoration">'.NEW_LINE;
+ echo $lang['srv_select'].NEW_LINE;
+ echo '<a href="#" onclick="return $.dds.selectAll(\'fs_list_4\');">'.$lang['srv_all'].'</a>'.NEW_LINE;
+ echo '<a href="#" onclick="return $.dds.selectNone(\'fs_list_4\');">'.$lang['srv_none'].'</a> '.NEW_LINE;
+ echo '<a href="#" onclick="return $.dds.selectInvert(\'fs_list_4\');">'.$lang['srv_invert'].'</a>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ echo '<br class="clr" />'.NEW_LINE;
+ echo '<br />'.NEW_LINE;
+ echo '<div class="left fs_container">'.NEW_LINE;
+ echo '<ul id="fs_list_3" class="left">'.NEW_LINE;
+ $sdf = SurveyDataFile::get_instance();
+ $sdf->init($sid);
+ if (count($szp_av) > 0) {
+ foreach($szp_av as $key => $variabla) {
+ $_name = $sdf->getVariableName($key);
+ echo '<li id="variabla_'.$key.'">'.self::limitString($_name).'</li>'.NEW_LINE;
+ }
+ }
+ echo '</ul>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ echo '<div class="right fs_container">'.NEW_LINE;
+ echo '<ul id="fs_list_4" class="left">'.NEW_LINE;
+ if (count($selected_variables) > 0 ) {
+ foreach($selected_variables as $key => $variabla) {
+ $_name = $sdf->getVariableName($key);
+ echo '<li id="variabla_'.$key.'">'.self::limitString($_name).'</li>'.NEW_LINE;
+ }
+ }
+ echo '</ul>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ echo '<script type="text/javascript">'.NEW_LINE;
+ echo '$(document).ready(function() {';
+ echo '$(function(){'.NEW_LINE;
+ echo ' mychange = function ( $list ){'.NEW_LINE;
+ echo ' $("#"+$list.attr("id")+"_serialised").html( $.dds.serialize( $list.attr("id")) );'.NEW_LINE;
+ echo '}'.NEW_LINE;
+ echo '$(".fs_container ul").drag_drop_selectable({'.NEW_LINE;
+ echo 'onListChange:mychange'.NEW_LINE;
+ echo '});'.NEW_LINE;
+ echo '});'.NEW_LINE;
+ echo '});'.NEW_LINE;
+ echo '</script>'.NEW_LINE;
+
+ echo '<br class="clr" />'.NEW_LINE;
+
+ echo '</div>'.NEW_LINE;
+
+ echo '<div id="missingProfilebuttons">'.NEW_LINE;
+ if ((int)$pid < 0 ) {// pri seji in sistemskem ne pustimo shranjevanja
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zankaProfileAction(\'runSession\'); return false;"><span>'.$lang['srv_run_as_session_profile'].'</span></a></span></span>'.NEW_LINE;
+ } else {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zankaProfileAction(\'run\'); return false;"><span>'.$lang['srv_save_and_run_profile'].'</span></a></span></span>'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zankaProfileAction(\'runSession\'); return false;"><span>'.$lang['srv_run_as_session_profile'].'</span></a></span></span>'.NEW_LINE;
+ }
+
+ echo '<span class="floatRight spaceLeft"><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zankaProfileAction(\'newName\'); return false;"><span>'.$lang['srv_save_new_profile'].'</span></a></span></span>'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft"><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zankaProfileAction(\'cancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'.NEW_LINE;
+
+ echo '</div>'.NEW_LINE;
+ echo '<div id="zankaProfileCoverDiv"></div>'.NEW_LINE;
+
+ // div za shranjevanje novega profila
+ echo '<div id="newProfileDiv">'.$lang['srv_missing_profile_name'].': '.NEW_LINE;
+ echo '<input id="newProfileName" name="newProfileName" type="text" size="45" />'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zankaProfileAction(\'newCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zankaProfileAction(\'newCreate\'); return false;"><span>'.$lang['srv_save_profile'].'</span></a></span></span>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': '.NEW_LINE;
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . self::$profiles[$pid]['name'] . '" size="45" />'.NEW_LINE;
+ echo '<input id="renameProfileId" type="hidden" value="' . $czp . '" />'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zankaProfileAction(\'renameConfirm\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zankaProfileAction(\'renameCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'.NEW_LINE;
+
+ echo '</div>'.NEW_LINE;
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . self::$profiles[$pid]['name'] . '</b>?'.NEW_LINE;
+ echo '<input id="deleteProfileId" type="hidden" value="' . $czp . '" />'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zankaProfileAction(\'deleteConfirm\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'.NEW_LINE;
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zankaProfileAction(\'deleteCancle\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'.NEW_LINE;
+ echo '</div>'.NEW_LINE;
+ }
+
+
+ static function createProfile() {
+ global $lang;
+ $profileId = -1;
+ $numrows = -1;
+ $profileName = $_POST['profileName'];
+
+ // počistimo podatke
+ $data = str_replace(array('variabla_', ' '), array('',''), $_POST['data']);
+ $mnozenje = $_POST['mnozenje'];
+
+ // ime profila preverima ali obstaja
+ if (!$profileName || $profileName == null || $profileName == "")
+ $profileName = $lang['srv_new_profile_ime'];
+
+ do { // preverimo ali ime že obstaja
+ $selectSqlProfile = "SELECT * FROM srv_zanka_profiles WHERE name = '" . $profileName . "' AND sid = '" . self::$sid . "' AND uid = '" . self::$uid . "'";
+ $sqlProfileSetting = sisplet_query($selectSqlProfile);
+ $numrows = mysqli_num_rows($sqlProfileSetting);
+ if ($numrows != 0) { // ime že obstaja zgeneriramo novo
+ srand(time());
+ $profileName .= rand(0, 9);
+ }
+ } while ($numrows != 0);
+
+ // poiščemo zadnji id
+ $selectProfileId = "SELECT max(id) as last_id FROM srv_zanka_profiles WHERE sid = '" . self::$sid . "' AND uid = '" . self::$uid . "'";
+ $sqlProfileId = sisplet_query($selectProfileId);
+ $rowProfileId = mysqli_fetch_assoc($sqlProfileId);
+ $profileId = $rowProfileId['last_id']+1;
+
+ $stringInsert = "INSERT INTO srv_zanka_profiles (id, sid, uid, name, system, variables, mnozenje) " .
+ "VALUES ('".$profileId."', '" . self::$sid . "', '" . self::$uid . "', '" . $profileName . "', '0', '".$data."', '".$mnozenje."')";
+
+ sisplet_query($stringInsert);
+ $insertId = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($insertId > 0) {
+ $profileId = $insertId;
+ }
+ self::setDefaultProfileId($profileId);
+ return $profileId;
+ }
+
+ static function deleteProfile() {
+ $pid = $_POST['pid'];
+ if ($pid > 0 ) {
+ $deleteString = "DELETE FROM srv_zanka_profiles WHERE id = '" . $pid . "' ";
+ $sqlDelete = sisplet_query($deleteString);
+ if (!$sqlDelete) echo mysqli_error($GLOBALS['connect_db']);
+ } else if ($pid == '-1') {
+ # zbrišemo sejo
+ unset($_SESSION['zanka_profile'][self::$sid]);
+ }
+
+ $pid = 0;
+ SurveyUserSetting :: getInstance()->saveSettings('default_zanka_profile', $pid);
+ self::$currentProfileId = $pid;
+ self::RefreshData();
+ }
+
+ static function renameProfile() {
+ global $lang;
+ $sqlInsert = -1;
+ $name = $_POST['name'];
+ $pid = $_POST['pid'];
+
+ if ( $pid != null && $pid != "" && $pid > 0) {
+ if ( $name == null || $name == "" ) {
+ $name = $lang['srv_new_profile_ime'];
+ }
+
+ $updateString = "UPDATE srv_zanka_profiles SET name = '" . $name . "' WHERE id = '" . $pid . "'";
+ $sqlInsert = sisplet_query($updateString);
+ }
+ return $sqlInsert;
+ }
+
+ static function runProfile() {
+ global $lang;
+
+ $data = str_replace(array('variabla_', ' '), array('',''), $_POST['data']);
+ $mnozenje = isset($_POST['mnozenje']) && $_POST['mnozenje'] == '1' ? '1' : '0';
+ $pid = $_POST['pid'];
+ if ($_POST['run'] != 'runSession') {
+ # shranimo podatke v normalni profil in ga zaženemo
+
+ if ($pid > 0) {
+
+ $updateString = "UPDATE srv_zanka_profiles SET variables = '" . $data . "', mnozenje='$mnozenje' WHERE id = '" . $pid . "' AND sid = '". self::$sid."' AND uid='". self::$uid."'";
+
+ $sqlupdate = sisplet_query($updateString) or die(mysqli_error($GLOBALS['connect_db']));
+ SurveyUserSetting :: getInstance()->saveSettings('default_zanka_profile', $pid);
+ } else if ($pid == 0) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_zanka_profile', $pid);
+ }
+ } else {
+ # shranimo podatke v sejo
+ $_SESSION['zanka_profile'][self::$sid] = array('id' => '-1',
+ 'name' => $lang['srv_zanka_profile_session'],
+ 'system'=> '1',
+ 'variables'=> $data,
+ 'mnozenje' => $mnozenje
+ );
+ SurveyUserSetting :: getInstance()->saveSettings('default_zanka_profile', '-1');
+ }
+
+ self::RefreshData();
+
+ }
+
+ /** Vrne array z awk stringi filtrov za posamezno variablo v zanki
+ *
+ */
+ static function getFiltersForLoops() {
+ $result = array();
+ $_spr_for_loops = explode(',',self::$profiles[self::$currentProfileId]['variables']);
+
+ $i = 0;
+ if (count($_spr_for_loops) > 0) {
+ foreach ($_spr_for_loops AS $_spr) {
+ $sdf = SurveyDataFile::get_instance();
+ $sdf->init(self::$sid);
+ $_spr_data = $sdf->getHeaderVariable($_spr);
+ if ($_spr_data['tip'] == 1 || $_spr_data['tip'] == 3) {
+ # radio oz, dropdown
+
+ # zloopamo skozi opcije
+ if (count($_spr_data['options']) > 0 ) {
+ foreach ($_spr_data['options'] AS $o_key => $option) {
+ $_results[$i][] = array('filter' => '$'.$_spr_data['grids']['0']['variables']['0']['sequence'].' == '.$o_key,
+ 'text' => '('.$_spr_data['grids']['0']['variables']['0']['variable'].') ' .$_spr_data['grids']['0']['variables']['0']['naslov'] . ' = '.$option);
+ }
+ }
+
+ } else if ($_spr_data['tip'] === '2') {
+ # checkbox
+ #zloopamo po vrednostih in dodamo filtre za 1-checked 2-not checked
+ foreach ($_spr_data['grids'] as $g_key => $grid) {
+ foreach ($grid['variables'] as $v_key_group => $variable) {
+ $_results[$i][] = array('filter' => '$'.$variable['sequence'].' == 0',
+ 'text' => '('.$variable['variable'].') ' .$variable['naslov'] . ' = 0');
+ $_results[$i][] = array('filter' => '$'.$variable['sequence'].' == 1',
+ 'text' => '('.$variable['variable'].') ' .$variable['naslov'] . ' = 1');
+ }
+ }
+ }
+ $i++;
+
+ }
+
+ }
+
+ # če mamo množenje, lahko izvedemo samo nad dvema spremenljivkama
+ if (self::$profiles[self::$currentProfileId]['mnozenje'] == 1) {
+ if (count($_results[0]) > 0) {
+ foreach ($_results[0] AS $_result0) {
+ if (count($_results[1]) > 0) {
+ foreach ($_results[1] AS $_result1) {
+ $result[] = array('filter' => $_result0['filter'].' && '.$_result1['filter'],
+ 'text' => $_result0['text'].' && '.$_result1['text']
+ );
+
+ }
+ } else {
+ # imamo samo 1 spremenljivko
+ $result[] = array('filter' => $_result0['filter'],
+ 'text' => $_result0['text']
+ );
+ }
+ }
+ }
+ } else {
+
+ $result = $_results[0];
+ }
+ return $result;
+ }
+
+ /** če v krostabih izberemo tretjo variablo (ctrl+click)
+ * povozimo obstoječe zanke, in tretjo variablo dodamo v loop kot začasen profil
+ * Enter description here ...
+ * @param $variable
+ */
+
+ function setLoopsForCrostabs($variable) {
+ # poiščemo spremenljivko
+ print_r("v:".$variable);
+ }
+ static function limitString($input, $limit = 100) {
+ // Return early if the string is already shorter than the limit
+ if(strlen($input) < $limit) {return $input;}
+
+ $regex = "/(.{1,$limit})\b/";
+ preg_match($regex, $input, $matches);
+ return $matches[1].'...';
+ }
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.SurveyZoom.php b/admin/survey/classes/class.SurveyZoom.php
new file mode 100644
index 0000000..593a1ee
--- /dev/null
+++ b/admin/survey/classes/class.SurveyZoom.php
@@ -0,0 +1,915 @@
+<?php
+define('ZOOM_DEFAULT_PROFILE', 0);
+class SurveyZoom
+{
+ static private $sid; # id ankete
+ static private $uid = null; # id userja
+ static private $db_table; # katere tabele uporabljamo
+ static private $enabled = false; # ali imamo vklopljen zoom
+ static private $profiles = array(); # profili zooma
+ static private $currentProfileId = 0; # trenutno profil
+ static private $extended = true; # ali imamo razširjen prikaz (privzeto)
+ static private $showVariables = true; # ali prikazujemo okno z variablami
+
+ function __construct($sid) {
+ global $global_user_id;
+
+ self::$sid = $sid;
+ self::$uid = $global_user_id;
+
+ session_start();
+ if (isset($_SESSION['surveyZoom'][self::$sid])) {
+ if (isset($_SESSION['surveyZoom'][self::$sid]['extended'])
+ && $_SESSION['surveyZoom'][self::$sid]['extended'] == false) {
+ self::$extended = false;
+ } else {
+ self::$extended = true;
+ }
+
+ if (isset($_SESSION['surveyZoom'][self::$sid]['showVariables'])
+ && $_SESSION['surveyZoom'][self::$sid]['showVariables'] == false) {
+ self::$showVariables = false;
+ } else {
+ self::$showVariables = true;
+ }
+ } else {
+ self::$extended = true;
+ self::$showVariables = true;
+ }
+
+ self::getProfiles();
+ }
+
+ function getProfiles() {
+ global $lang;
+
+ # inicializiramo datoteko z nastavitvami
+ SurveyUserSetting :: getInstance()->Init(self::$sid, self::$uid);
+
+ # polovimo profile iz baze
+ $stringSelect = "SELECT * FROM srv_zoom_profiles WHERE sid='" . self::$sid . "' AND uid='" . self::$uid . "'";
+ $querySelect = sisplet_query($stringSelect);
+
+ #prvi profil je privezti - brez zooma
+ self::$profiles[0] = array('id'=>0, 'name'=>$lang['srv_default_without']);
+
+ # če obstajajo profili iz baze jih dodamo
+ if (mysqli_num_rows($querySelect)) {
+ #najprej dodamo sejo če obstaja
+ session_start();
+ if (isset($_SESSION['surveyZoom'][self::$sid])) {
+ self::$profiles[-1] = $_SESSION['surveyZoom'][self::$sid];
+ }
+
+ while ( $rowSelect = mysqli_fetch_assoc($querySelect) ) {
+ self::$profiles[$rowSelect['id']] = $rowSelect;
+ self::$profiles[$rowSelect['id']]['vars'] = unserialize($rowSelect['vars']);
+ self::$profiles[$rowSelect['id']]['conditions'] = unserialize($rowSelect['conditions']);
+ }
+ } else {
+ # v bazi ni profilov
+
+ #nato dodamo sejo če obstaja
+ session_start();
+ if (isset($_SESSION['surveyZoom'][self::$sid])) {
+ self::$profiles[-1] = $_SESSION['surveyZoom'][self::$sid];
+ }
+
+ }
+
+
+ # preverimo ali ima uporabnik nastavljen privzet profil
+ $dzp = SurveyUserSetting :: getInstance()->getSettings('default_zoom_profile');
+ if ($dzp == -1 || $dzp > 0 ) {
+ self::$currentProfileId = $dzp;
+ } else {
+ self::$currentProfileId = 0;
+ self::SetDefaultProfile(0);
+ }
+
+
+
+ # če uporabnik nima profilov, in obstajajo demografske spremenljivke naredimo nov DM profil
+ if (count(self::$profiles) == 1 ) { # 1profil je vedno (privzeti)
+ $all_spr = Cache::cache_all_srv_spremenljivka(self::$sid);
+ $variables_to_add = array();
+ if (is_countable($all_spr) && count($all_spr) > 0) {
+ foreach ($all_spr AS $id => $spr) {
+ if (in_array($spr['variable'], array('XSPOL','XIZOBRAZBA','XSTAROST','DMspol','DMizobrazba','DMstarost'))
+ || Demografija::getInstance()->isDemografija($spr['variable'])) {
+ $variables_to_add[] = $id;
+ }
+ }
+ }
+
+ if (count ($variables_to_add) > 0 ) {
+ # dodamo profil in ga izberemo za privzetega
+
+ $_SESSION['surveyZoom'][self::$sid] = array('id'=>-1, 'name'=>$lang['srv_zoom_profile_demografija'],'vars'=>$variables_to_add, 'conditions'=> '', 'if_id'=>0);
+ self::$profiles[-1] = array('id'=>$pid, 'sid'=>self::$sid, 'uid'=>self::$uid, 'name'=>$lang['srv_zoom_profile_demografija'], 'vars'=>$variables_to_add,'conditions'=>'');
+ if (!isset($_POST['pid']) && !((int)$_POST['pid'] > 0)) {
+ #self::SetDefaultProfile(-1);
+ #self::$currentProfileId = -1;
+ }
+ }
+ }
+
+ }
+
+ static function DisplayLink($hideAdvanced = true) {
+ global $lang;
+
+ $css = (self::$currentProfileId == 0 ? ' gray' : '');
+
+ if ($hideAdvanced == false || self::$currentProfileId != 0) {
+ echo '<li class="space">&nbsp;</li>';
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" id="link_zoom" title="'.$lang['srv_zoom_setting'].'" onclick="showZoomSettings();">'.$lang['srv_zoom_setting'].'</span>';
+ echo '</li>';
+
+ }
+ }
+
+ function ajax() {
+ switch ($_GET['a']) {
+ case 'showProfile':
+ self::showProfile();
+ break;
+ case 'changeProfile':
+ self::changeProfile($_POST['pid']);
+ break;
+ case 'saveProfile':
+ self::saveProfile();
+ break;
+ case 'deleteProfile':
+ self::deleteProfile($_POST['pid']);
+ break;
+ case 'renameProfile':
+ self::renameProfile();
+ break;
+ case 'changeZoomCheckbox':
+ self::changeZoomCheckbox();
+ break;
+ case 'removeZoomCheckbox':
+ self::removeZoomCheckbox();
+ break;
+ case 'createNewProfile':
+ self::createNewProfile();
+ break;
+ case 'togleExtended':
+ self::togleExtended();
+ break;
+ case 'toggleShowZoomVariables':
+ self::toggleShowZoomVariables();
+ break;
+
+ case 'doZoomFromInspect':
+ self::doZoomFromInspect();
+ break;
+
+ default:
+ print_r("<pre>");
+ print_r($_GET);
+ print_r($_POST);
+ print_r("</pre>");
+ break;
+ }
+ }
+
+ static function getCurentProfileId() { return self::$currentProfileId; }
+ /** Ponastavi id privzetega profila
+ *
+ */
+ static function SetDefaultProfile($pid) {
+ self::$currentProfileId = $pid;
+ $saved = SurveyUserSetting :: getInstance()->saveSettings('default_zoom_profile',$pid);
+ }
+
+ function changeProfile($pid) {
+ $tmp_profiles = self::$profiles;
+ # če profil z pid ne obstaja nastavimo prvega iz baze (ki pa ni demografija)
+ if (!isset($tmp_profiles[$pid]) && count($tmp_profiles) > 0) {
+ if (isset($tmp_profiles[-1]) && (int)$pid != -1) {
+ unset($tmp_profiles[-1]);
+ }
+ if (count($tmp_profiles) > 0){
+ $pid = key(self::$profiles);
+ } else {
+ $pid = 0;
+ }
+
+ }
+ self::SetDefaultProfile($pid);
+ }
+
+ function showProfile() {
+ global $lang;
+
+ echo '<div class="popup_close"><a href="#" onClick="zoomProfileAction(\'cancel\'); return false;">✕</a></div>';
+
+ // Naslov
+ echo '<h2>'.$lang['srv_zoom_setting'].'</h2>';
+
+ if ($current_pid == null) {
+ $current_pid = self::getCurentProfileId();
+ }
+
+ $currentFilterProfile = self::$profiles[$current_pid];
+ if ( self::$currentProfileId != ZOOM_DEFAULT_PROFILE ) {
+ echo '<div id="not_default_setting">';
+ echo $lang['srv_not_default_setting'];
+ echo '</div><br class="clr displayNone">';
+ }
+
+ echo '<div id="zoom_profiles_left">';
+ echo '<span id="zoom_profiles_holder">';
+ # zlistamo vse profile
+ echo '<span id="zoom_profiles" class="select">';
+ if (count(self::$profiles)) {
+ foreach (self::$profiles as $id => $profile) {
+
+ echo '<div class="option' . ($current_pid == $id ? ' active' : '') . '" id="zoom_profile_' . $id . '" value="'.$id.'" '.($current_pid == $id ? '' : ' onclick="zoomChangeProfile(\''.$id.'\')"').'>';
+
+ echo $profile['name'];
+
+ if($current_pid == $id){
+ # sistemskega ne moremo izbrisati
+ if ($current_pid != 0) {
+ echo '<a href="#" title="'.$lang['srv_delete_profile'].'" onclick="zoomProfileAction(\'showDelete\'); return false;"><span class="faicon delete_circle icon-orange_link floatRight" style="margin-top:1px;"></span></a>'."\n";
+ }
+
+ # sistemskega in seje ne moremo preimenovati
+ if ($current_pid > 0) {
+ echo '<a href="#" title="'.$lang['srv_rename_profile'].'" onclick="zoomProfileAction(\'showRename\'); return false;"><span class="faicon edit icon-as_link floatRight spaceRight"></span></a>'."\n";
+ }
+ }
+
+ echo '</div>';
+ }
+ }
+ echo '</span>'; # zoom_profilea
+ echo '</span>'; # zoom_profiles_holder
+
+ echo '</div>'; # zoom_profiles_left
+
+
+ echo '<div id="zoom_profiles_right">'."\n";
+ if ($current_pid == 0) {
+ echo '<div id="zoom_note">';
+ echo $lang['srv_change_default_profile'];
+ echo '</div>'; // zoom_profile_note
+ echo '<br class="clr" />'."\n";
+ }
+
+ echo '<div id="zoom_content">';
+ self::DisplayProfileData($current_pid);
+ echo '</div>'; // zoom_profile_content
+
+ echo '</div>'; // zoom_profile_right
+
+
+ echo '<div id="zoom_button_holder">'."\n";
+ if ((int)$current_pid <= 0 ) {
+ echo '<span class="floatRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zoomProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'newName\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+ } else {
+ echo '<span class="floatRight" title="'.$lang['srv_save_run_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zoomProfileAction(\'runProfile\'); return false;"><span>'.$lang['srv_run_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_run_as_session_profile'] . '"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'run_session_profile\'); return false;"><span>'.$lang['srv_run_as_session_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_create_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'newName\'); return false;"><span>'.$lang['srv_create_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_close_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'cancel\'); return false;"><span>'.$lang['srv_close_profile'] . '</span></a></div></span>';
+
+ }
+ echo '</div>'."\n"; // zoom_button_holder
+
+
+ // cover Div
+ //echo '<div id="zoom_cover_div"></div>'."\n";
+
+ // div za kreacijo novega
+ echo '<div id="newProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="newProfileName" name="newProfileName" type="text" value="" size="45" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zoomProfileAction(\'newCreate\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'newCancel\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameProfileDiv">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="renameProfileName" name="renameProfileName" type="text" value="' . $currentFilterProfile['name'] . '" size="45" />'."\n";
+ echo '<input id="renameProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zoomProfileAction(\'doRename\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'cancelRename\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteProfileDiv">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . $currentFilterProfile['name'] . '</b>?'."\n";
+ echo '<input id="deleteProfileId" type="hidden" value="' . $currentFilterProfile['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="zoomProfileAction(\'doDelete\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="zoomProfileAction(\'cancelDelete\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+ }
+
+ /** Funkcija prikaze osnovnih informacije profila
+ *
+ */
+ function DisplayProfileData($current_pid=null) {
+ global $lang;
+ if (isset($_POST['error'])) {
+ echo '<span class="red">* '.$lang[$_POST['error']].'</span><br/>';
+ }
+ # podatki profila
+ if ($current_pid == null) {
+ $current_pid = self::$currentProfileId;
+ }
+ $cp = self::$profiles[$current_pid];
+ $vars = $cp['vars'];
+
+ $all_spr = Cache::cache_all_srv_spremenljivka(self::$sid,true);
+
+ echo '<span>'.$lang['srv_zoom_choose'].'</span>';
+
+ if (count($all_spr) > 0)
+ foreach ($all_spr AS $id => $spremenljivka) {
+ if ( in_array($spremenljivka['tip'], array(1,2,3) ) ) {
+ echo '<div class="zoom_var">';
+
+ echo '<label>';
+ echo '<input name="zoom_vars" id="zoom_var_'.$spremenljivka['id'].'" value="'.$spremenljivka['id'].'" type="checkbox"'
+ .(is_array($vars) && in_array($spremenljivka['id'],$vars) ? ' checked' : '').'>';
+ echo strip_tags($spremenljivka['variable']).' - '.strip_tags($spremenljivka['naslov']).'</label>';
+
+ echo '</div>';
+ } else if ( in_array($spremenljivka['tip'], array(6,16,17))) {
+ echo '<div class="zoom_var">';
+
+ # izpišemo glavno spremenljivko
+ echo '<label style="margin-left:20px;">';
+ echo strip_tags($spremenljivka['variable']).' - '.strip_tags($spremenljivka['naslov']).'</label>';
+
+ # izpišemo gride (zamaknjeno)
+ $sql = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$id' AND other = 0 ORDER BY vrstni_red");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ echo '<label style="margin-left:25px; margin-top:5px;">';
+ echo '<input name="zoom_vars" id="zoom_var_'.$spremenljivka['id'].'_'.$row['id'].'" value="'.$spremenljivka['id'].'_'.$row['id'].'" type="checkbox"'
+ .(is_array($vars) && in_array($spremenljivka['id'].'_'.$row['id'],$vars) ? ' checked' : '').'>';
+ echo strip_tags($row['variable']).' - '.strip_tags($row['naslov']).'</label>';
+ }
+ echo '</div>';
+ }
+ }
+
+ echo '<br class="clr"/>';
+ }
+
+ /* Shranimo izbrane variable in resetiramo if na 0, ter pobrišemo morebitni pogoj če obstaja
+ *
+ */
+ static function SaveProfile() {
+ global $lang, $global_user_id;
+ $pid = isset($_POST['pid']) && (int)$_POST['pid'] > 0
+ ? (int)$_POST['pid'] # normaln profil
+ : -1; #seja
+ $profil_data = self::$profiles[$pid];
+
+ # preverimo ali je star profil imel kak if če ja ga pobrišemo
+ if ((int)$profil_data['if_id'] > 0 ) {
+ if ((int)$if_id > 0) {
+ $delStr = "DELETE FROM srv_if WHERE id = '$if_id'";
+ sisplet_query($delStr);
+ $delStr = "DELETE FROM srv_condition WHERE if_id = '$if_id'";
+ sisplet_query($delStr);
+ sisplet_query("COMMIT");
+ }
+ }
+
+ # ali delamo preko seje ali baze
+ if ($pid > 0) {
+ # shranimo v bazo
+ $vars = serialize(isset($_POST['vars']) ? $_POST['vars'] : '');
+ $updateString = "UPDATE srv_zoom_profiles SET vars = '$vars', conditions='', if_id=0 WHERE id='$pid'";
+ $updatequery = sisplet_query($updateString);
+ sisplet_query("COMMIT");
+
+ } else {
+ session_start();
+ # shranjujenmo v sejo
+ $pid=-1;
+ #LANG
+ $_SESSION['surveyZoom'][self::$sid] = array('id'=>-1,'vars'=>$_POST['vars'], 'conditions'=> '', 'if_id'=>0);
+ if (!isset($_SESSION['surveyZoom'][self::$sid]['name']) || $_SESSION['surveyZoom'][self::$sid]['name'] == '') {
+ $_SESSION['surveyZoom'][self::$sid]['name'] = $lang['srv_zoom_profile_session'];
+ }
+
+ session_commit();
+ }
+ self::SetDefaultProfile($pid);
+ }
+
+ /** shranimo nov profil
+ *
+ * Enter description here ...
+ */
+ function createNewProfile() {
+ global $lang,$global_user_id;
+ $return = array('newId' => -1, 'error'=>'1','msg'=> 'Profila ni bilo mogoče kreirati!' );
+
+ #LANG
+ $name = isset($_POST['name']) ? $_POST['name'] : 'Nov profil';
+ $vars = serialize(isset($_POST['vars']) ? $_POST['vars'] : '');
+
+ $iStr = "INSERT INTO srv_zoom_profiles (sid, uid, name,vars,conditions) VALUES ('".self::$sid."', '".self::$uid."', '$name','$vars','')";
+ $sql = sisplet_query($iStr);
+ $return['msg'] =$iStr;
+ if (!$sql) {
+ $return['error'] = '1';
+ $return['msg'] = 'Pri kreiranju profila so bile težave!';
+ } else {
+ $pid = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+ $return['newId'] = $pid;
+ self::getProfiles();
+ self::SetDefaultProfile($pid);
+ $return['error'] = '0';
+ $return['msg'] = 'Profil je bil uspešno kreiran:'.$pid;
+ }
+ echo json_encode($return);
+ exit;
+
+ }
+
+ static function deleteProfile($pid = 0) {
+
+ #pobrišemo pogoj če obstaha
+ $if_id = self::$profiles[$pid]['if_id'];
+ if ((int)$if_id > 0) {
+ $stringUpdate = "DELETE FROM srv_if WHERE id = ".$if_id;
+ $updated = sisplet_query($stringUpdate);
+ sisplet_query("COMMIT");
+ }
+
+ if (isset($pid) && $pid == -1) {
+ session_start();
+ unset($_SESSION['surveyZoom'][self::$sid]);
+ session_commit();
+ } else if (isset($pid) && $pid > 0) {
+ // Izbrišemo profil in nastavimo privzetega
+ $stringUpdate = "DELETE FROM srv_zoom_profiles WHERE id = ".$pid;
+ $updated = sisplet_query($stringUpdate);
+ sisplet_query("COMMIT");
+ }
+ # nastavimo privzet profil
+ self::getProfiles();
+ self::SetDefaultProfile('0');
+ }
+
+ static function displayZoomConditions($showDiv = true) {
+ global $lang;
+
+ $vars = self::$profiles[self::$currentProfileId]['vars'];
+
+ $all_spr = Cache::cache_all_srv_spremenljivka(self::$sid);
+
+ if (is_countable($vars) && count($vars) > 0) {
+ $conditions = self::$profiles[self::$currentProfileId]['conditions'];
+ if ($showDiv == true) {
+ echo '<div id="div_zoom_condition" '.(self::$showVariables == false ? ' style="display:none"' : '').'>';
+ }
+ echo '<span class="" style="display:inline-block; width:100%">';
+ echo '<b>'.$lang['srv_zoom'].'</b>';
+ echo '&nbsp;"'.self::$profiles[self::$currentProfileId]['name'].'"';
+ echo '<span class="as_link spaceLeft" onclick="showZoomSettings();">'.$lang['srv_profile_edit'].'</span>';
+ echo '<span class="as_link spaceLeft" id="span_zoom_condition_remove" onclick="removeZoomProfile();">'.$lang['srv_profile_remove'].'</span>';
+
+ # dodamo še +/- za razpiranje variabel
+ echo '<span class="floatRight spaceLeft">';
+ echo '<span id="zoomSpritesMinus" class="'.(self::$extended == true ? '' : ' displayNone').'">';
+ echo '<span class="pointer faicon icon-blue minus" onClick="toggleAllZoom(\'1\')" >&nbsp;</span>';
+ echo '</span>';
+ echo '<span id="zoomSpritesPlus" class="'.(self::$extended == true ? ' displayNone' : '').'">';
+ echo '<span class="pointer faicon icon-blue plus" onClick="toggleAllZoom(\'0\')">&nbsp;</span>';
+ echo '</span>';
+ echo '</span>';
+
+ echo '</span>';
+ echo '<br/>';
+ echo '<span class="floatLeft'.( self::$extended == false ? ' displayNone': '').'" >';
+ echo '<ul >';
+ IF (count($vars) > 0 && is_array($vars)) {
+ foreach ($vars AS $_spr) {
+ $_spr_tmp = explode('_',$_spr);
+
+ $spr = $_spr_tmp[0];
+ $vre = $_spr_tmp[1];
+ $_conditions = $conditions[$spr];
+
+ if (isset($vre) && $vre > 0) {
+ $sql = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE id='$vre'");
+ $row = mysqli_fetch_assoc($sql);
+ } else {
+ $row = Cache::srv_spremenljivka($spr);
+ }
+ echo '<li id="zoom_var_condition_'.$_spr.'">';
+ echo '<div class="zoom_short_text" title="('.strip_tags($row['variable']).') '.strip_tags($row['naslov']).'">';
+ echo '(<b>'.strip_tags($row['variable']).'</b>) ';
+ echo strip_tags($row['naslov']);
+ echo '</div>';
+ echo '<div class="zoom_short_text">';
+ #echo '<div class="zoom_short_text'.( self::$extended == false ? ' displayNone': '').'">';
+
+ if (isset($vre) && $vre > 0) {
+ # imamo multigride polovimo grids
+ $sql = sisplet_query("SELECT id, naslov, variable FROM srv_grid WHERE spr_id='$spr' AND other = 0 ORDER BY vrstni_red");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ echo '<label title="'.strip_tags($row['variable']).' - '.strip_tags($row['naslov']).'">';
+ echo '<input name="zoom_cond_'.$spr.'[]" id="zoom_cond_'.$spr.'_'.$vre.'_'.$row['id'].'" value="'.$spr.'_'.$vre.'_'.$row['id'].'" type="checkbox" onchange="changeZoomCheckbox(); return false;"';
+ if (is_array($_conditions) && isset($_conditions[(int)$vre])) {
+ if (in_array($row['id'],$_conditions[(int)$vre])) {
+ echo 'checked="checekd"';
+ }
+ }
+ echo ' autocomplete="off">';
+
+ echo strip_tags($row['variable']).' - '.strip_tags($row['naslov']).'</label>';
+ echo "<br>";
+ }
+
+ } else {
+ # imamo navaden polovimo vrednosti
+ $sql = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$spr' AND other = 0 ORDER BY vrstni_red");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ echo '<label title="'.strip_tags($row['variable']).' - '.strip_tags($row['naslov']).'">';
+ echo '<input neme="zoom_cond_'.$spr.'[]" id="zoom_cond_'.$spr.'_'.$vre.'_'.$row['id'].'" value="'.$spr.'_'.$vre.'_'.$row['id'].'" type="checkbox" onchange="changeZoomCheckbox(); return false;"';
+ if (is_array($_conditions) && isset($_conditions[(int)$vre])) {
+ if (in_array($row['id'],$_conditions[(int)$vre])) {
+ echo 'checked="checekd"';
+ }
+ }
+ echo '>';
+ echo strip_tags($row['variable']).' - '.strip_tags($row['naslov']).'</label>';
+ echo "<br>";
+ }
+ }
+ echo '</div>';
+ echo '</li>';
+ }
+ }
+
+ echo '</ul>';
+ echo '</span>';
+
+ if ($showDiv == true) {
+ echo '</div>';
+ }
+
+ }
+ }
+
+ function removeZoomCheckbox() {
+ #odstranimo if
+ $if_id=(int)self::$profiles[self::$currentProfileId]['if_id'];
+ if ( $if_id> 0)
+ {
+ if(self::$currentProfileId == -1)
+ {
+ session_start();
+ $_SESSION['surveyZoom'][self::$sid]['if_id'] = 0;
+ $_SESSION['surveyZoom'][self::$sid]['conditions'] = null;
+ }
+ else
+ {
+ $update = "UPDATE srv_zoom_profiles SET if_id = 0, conditions='' where id='".self::$currentProfileId."'";
+ $sql = sisplet_query($update);
+ sisplet_query("COMMIT");
+ }
+
+ if ((int)$if_id > 0)
+ {
+ $delStr = "DELETE FROM srv_if WHERE id = '$if_id'";
+ sisplet_query($delStr);
+ sisplet_query("COMMIT");
+ }
+ }
+ }
+
+ function changeZoomCheckbox()
+ {
+ if (isset($_POST['vars']) && is_array($_POST['vars']) && count($_POST['vars']) > 0 )
+ {
+ $spr_groups = array();
+ foreach ($_POST['vars'] AS $tmpvar) {
+ $_var = explode('_',$tmpvar);
+ # med posameznimi sub grupami imamo OR pogoje med grupami pa AND
+ #zgrupiramo po spremenljivkah in grupah
+ if (isset($_var[1]) && $_var[1]!=null) {
+
+ $spr_groups[$_var[0]][$_var[1]][] = $_var[2];
+ } else {
+ $spr_groups[$_var[0]][0][] = $_var[2];
+ }
+ }
+ self::createZoomCondition($spr_groups);
+ # še shranimo checkboxe
+ session_start();
+ #če seja ne obstaja nastavimo privzet porfil na 0 - default
+ if(self::$currentProfileId == -1) {
+ session_start();
+ $_SESSION['surveyZoom'][self::$sid]['conditions'] = $spr_groups;
+ } else {
+ $conditions = serialize($spr_groups);
+ $update = "UPDATE srv_zoom_profiles SET conditions = '$conditions' where id='".self::$currentProfileId."'";
+ $sql = sisplet_query($update);
+ sisplet_query("COMMIT");
+ }
+ } else {
+ #odstranimo if
+ $if_id=(int)self::$profiles[self::$currentProfileId]['if_id'];
+ if ( $if_id> 0) {
+ if(self::$currentProfileId == -1) {
+ session_start();
+ $_SESSION['surveyZoom'][self::$sid]['if_id'] = 0;
+ } else {
+ $update = "UPDATE srv_zoom_profiles SET if_id = 0, conditions='' where id='".self::$currentProfileId."'";
+ $sql = sisplet_query($update);
+ sisplet_query("COMMIT");
+ }
+ if ((int)$if_id > 0) {
+ $delStr = "DELETE FROM srv_if WHERE id = '$if_id'";
+ sisplet_query($delStr);
+ sisplet_query("COMMIT");
+ }
+ }
+
+ }
+ SurveyAnalysis::Init(self::$sid);
+ SurveyAnalysis::Display();
+
+ }
+
+ function createZoomCondition($spr_groups) {
+ global $lang,$global_user_id;
+
+ #najprej skreiramo nov if če še ne obstaja
+ if ((int)self::$profiles[self::$currentProfileId]['if_id'] > 0) {
+ $if_id = (int)self::$profiles[self::$currentProfileId]['if_id'];
+ # preverimo dejanski obstoj ifa
+ if ((int)$if_id > 0) {
+ $chks1 = "SELECT id FROM srv_if WHERE id='$if_id'";
+ $chkq1 = sisplet_query($chks1);
+ if (mysqli_num_rows($chkq1) == 0) {
+ $if_id = 0;
+ }
+ }
+ }
+
+ if ( (int)$if_id == 0 || $if_id == null) {
+ // if še ne obstaja, skreiramo novga
+ $sql = sisplet_query("INSERT INTO srv_if (id) VALUES ('')");
+ $if_id = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+ }
+
+ if ((int)$if_id > 0) {
+ # updejtamo še zoom profil
+ self::$profiles[self::$currentProfileId]['if_id'] = (int)$if_id;
+ if ((int)self::$currentProfileId > 0 ) {
+ # v bazi
+ $updateString = "UPDATE srv_zoom_profiles SET if_id=".(int)$if_id." WHERE id='".(int)self::$currentProfileId."'";
+ $sql = sisplet_query($updateString);
+ sisplet_query("COMMIT");
+ } else {
+ # v seji
+ session_start();
+ $_SESSION['surveyZoom'][self::$sid]['if_id'] = (int)$if_id;
+ }
+
+
+ #poiščemo katere condition_id-je lahko obdržimo, ostale pobrišemo
+ if (is_array($spr_groups) &&count($spr_groups ) > 0 ) {
+ $spr_vre = array();
+ foreach ($spr_groups AS $spr_id => $spr_group) {
+ $cids = array();
+ foreach($spr_group AS $key => $values) {
+ $cids[] = (int)$key;
+ }
+ # pobrišemo predhodne ife
+ if (count($cids) > 0) {
+ $spr_vre[] = "(spr_id = '$spr_id' AND vre_id IN (".implode(',',$cids)."))";
+ }
+ }
+ $delStr = "DELETE FROM srv_condition WHERE if_id = '$if_id' AND NOT (".implode(' OR ',$spr_vre).")";
+ sisplet_query($delStr);
+ sisplet_query("COMMIT");
+
+ # dodamo pogoje za posamezne skupine spremenljivk
+ $vrstni_red = 1;
+ foreach ($spr_groups AS $spr_id => $spr_group) {
+ $vrstni_red = self::createSubCondition($if_id,$spr_id,$spr_group,$vrstni_red);
+ }
+ } else {
+ $delStr = "DELETE FROM srv_condition WHERE if_id = '$if_id'";
+ sisplet_query($delStr);
+ sisplet_query("COMMIT");
+ }
+ }
+ }
+
+ function createSubCondition($if_id,$spr_id,$spr_group,$vrstni_red) {
+ foreach($spr_group AS $key => $values) {
+ # če imamo vrednosti
+ if ((int)$key == 0) {
+ # preverimo ali že obstaja condition id
+ $sStr = "SELECT id FROM srv_condition WHERE if_id='$if_id' AND spr_id='$spr_id'";
+ $sQry = sisplet_query($sStr);
+ if (mysqli_num_rows($sQry) > 0) {
+ # cond_id že obstaja uporabimo obstoječega
+ $sRow = mysqli_fetch_assoc($sQry);
+ $cond_id = $sRow['id'];
+ } else {
+ #vstavimo nov pogoj
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red) VALUES ('$if_id', '$spr_id', '$vrstni_red')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr_id', vrstni_red = '$vrstni_red'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+
+ # pobrišemo vrednosti
+ if ($cond_id > 0) {
+ $delStr = "DELETE FROM srv_condition_vre WHERE cond_id = '$cond_id'";
+ sisplet_query($delStr);
+ }
+ foreach ($values AS $value) {
+ if ((int)$value > 0 || (int)$cond_id > 0) {
+ $istr = "INSERT INTO srv_condition_vre (cond_id, vre_id) VALUES ('$cond_id', '$value')";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+ } else {
+ # če imamo grupe
+ # preverimo ali že obstaja condition id
+ $sStr = "SELECT id FROM srv_condition WHERE if_id='$if_id' AND spr_id='$spr_id' AND vre_id='$key'";
+ $sQry = sisplet_query($sStr);
+ if (mysqli_num_rows($sQry) > 0) {
+ # cond_id že obstaja uporabimo obstoječega
+ $sRow = mysqli_fetch_assoc($sQry);
+ $cond_id = $sRow['id'];
+ } else {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vre_id, vrstni_red) VALUES ('$if_id', '$spr_id', '$key', '$vrstni_red')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$spr_id', vrstni_red = '$vrstni_red'";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+ # pobrišemo gride
+ if ($cond_id > 0) {
+ $delStr = "DELETE FROM srv_condition_grid WHERE cond_id = '$cond_id'";
+ sisplet_query($delStr);
+ }
+
+ foreach ($values AS $value) {
+ if ((int)$value > 0 || (int)$cond_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$value."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+ }
+ sisplet_query("COMMIT");
+ $vrstni_red++;
+ }
+
+ return $vrstni_red;
+ }
+
+ function togleExtended() {
+ session_start();
+
+ if (isset($_POST['what']) && $_POST['what'] == 1) {
+ $_SESSION['surveyZoom'][self::$sid]['extended'] = false;
+ } else {
+ $_SESSION['surveyZoom'][self::$sid]['extended'] = true;
+ }
+ }
+ function toggleShowZoomVariables() {
+ session_start();
+
+ if (isset($_POST['what']) && $_POST['what'] == 1) {
+ $_SESSION['surveyZoom'][self::$sid]['showVariables'] = false;
+ } else {
+ $_SESSION['surveyZoom'][self::$sid]['showVariables'] = true;
+ }
+ }
+
+ function renameProfile() {
+ $pid = $_POST['pid'];
+ $name = $_POST['name'];
+ if (isset($pid) && $pid > 0 && isset($name) && trim($name) != "") {
+ // popravimo podatek za variables
+ $stringUpdate = "UPDATE srv_zoom_profiles SET name = '".$name."' WHERE id = '".$pid."'";
+ $updated = sisplet_query($stringUpdate);
+ sisplet_query("COMMIT");
+ return $updated;
+ } else {
+ return -1;
+ }
+
+ }
+
+
+
+ static function generateAwkCondition() {
+ global $global_user_id;
+
+ $zoom_if_id = (int)self::$profiles[self::$currentProfileId]['if_id'];
+
+ if ($zoom_if_id > 0 ) {
+ SurveyConditionProfiles :: Init(self::$sid, $global_user_id);
+ return SurveyConditionProfiles:: generateAwkCondition($zoom_if_id);
+ } else {
+ return null;
+ }
+ }
+
+ static function getConditionString() {
+ global $lang;
+
+# $condition_label = self::$profiles[self::$currentProfileId]['condition_label'];
+ ob_start();
+ $b = new Branching(self::$sid );
+ $if_id = (int)self::$profiles[self::$currentProfileId]['if_id'];
+ $b->display_if_label($if_id);
+ #$condition_label = mysqli_escape_string(ob_get_contents());
+ $condition_label = ob_get_contents();
+ ob_end_clean();
+
+ if ( $if_id > 0 && $condition_label != '') {
+ echo '<div id="conditionProfileNote" class="segmenti">';
+ echo '<span class="floatLeft spaceRight">';
+ # dodamo še +/- za razpiranje variabel
+ echo '<span id="zoomSpritesMinus1" class="'.(self::$showVariables == true ? '' : ' displayNone').'">';
+ echo '<span class="pointer faicon icon-blue minus" onClick="toggleShowZoomVariables(\'1\')" >&nbsp;</span>';
+ echo '</span>';
+ echo '<span id="zoomSpritesPlus1" class="'.(self::$showVariables == true ? ' displayNone' : '').'">';
+ echo '<span class="pointer faicon icon-blue plus" onClick="toggleShowZoomVariables(\'0\')">&nbsp;</span>';
+ echo '</span>';
+ echo '</span >';
+
+ echo '<span class="floatLeft">'.$lang['srv_zoom_filter_note'].'</span>';
+ echo '<span class="floatLeft spaceLeft">'.$condition_label.'</span>';
+/*
+ // ali imamo napake v ifu
+ if ((int)self::$profiles[self :: $currentProfileId]['condition_error'] != 0) {
+ echo '<br>';
+ echo '<span style="border:1px solid #009D91; background-color: #34D0B6; padding:5px; width:auto;"><img src="img_0/error.png" /> ';
+ echo '<span class="red strong">'.$lang['srv_profile_condition_has_error'].'</span>';
+ echo '</span>';
+ }
+ */
+ echo '<span class="as_link spaceLeft" onclick="showZoomSettings();">'.$lang['srv_profile_edit'].'</span>';
+ echo '<span class="as_link spaceLeft" onclick="removeZoomCheckbox();">'.$lang['srv_profile_remove'].'</span>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ return true;
+ }
+
+ return false;
+ }
+
+ function doZoomFromInspect() {
+ global $lang;
+ # polovimo id-je variabel iz inspect profila in nastavimo zoom profil
+ $SI = new SurveyInspect(self::$sid);
+ $variables_to_add = $SI->getInspectVariables();
+
+ session_start();
+ # shranjujenmo v sejo
+ # dodamo profil in ga izberemo za privzetega
+
+ $_SESSION['surveyZoom'][self::$sid] = array('id'=>-1, 'name'=>$lang['srv_zoom_profile_session'],'vars'=>$variables_to_add, 'conditions'=> '', 'if_id'=>0);
+ self::$profiles[-1] = array('id'=>$pid, 'sid'=>self::$sid, 'uid'=>self::$uid, 'name'=>$lang['srv_zoom_profile_session'], 'vars'=>$variables_to_add,'conditions'=>'');
+ self::SetDefaultProfile(-1);
+ self::$currentProfileId = -1;
+ session_commit();
+
+
+ # prikažemo segmente
+ $showDiv = ((int)$_POST['showDiv'] == 1)?true:false;
+ self::displayZoomConditions($showDiv);
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.Timer.php b/admin/survey/classes/class.Timer.php
new file mode 100644
index 0000000..f659a02
--- /dev/null
+++ b/admin/survey/classes/class.Timer.php
@@ -0,0 +1,50 @@
+<?php
+/**
+* @author Gorazd Veselič
+* @date Julij 2010
+* @desc Namenjen merjenju časa izvajanja posameznih funkcij
+*
+*/
+
+class Timer {
+
+ static private $timer = array(); # timer
+ static private $_timer_output = true; # ali timer izpiše output
+
+ static private $_decimals = 7; # Število decimalk
+ static private $_decimals_delimit = ','; # decimalno ločilo
+
+ /** Starta tajmer
+ *
+ */
+ static public function StartTimer($grups=0) {
+ # v header dodomo userid
+ $mtime = explode(" ",microtime());
+ self::$timer[$grups]['start'] = $mtime[1] + $mtime[0];
+ }
+
+ /** Vrne čas izvajanja skripte
+ *
+ */
+ static public function GetTimer($grups=0) {
+ global $lang;
+ # v header dodomo userid
+ $mtime = explode(" ",microtime());
+ self::$timer[$grups]['end'] = $mtime[1] + $mtime[0];
+ if (self::$_timer_output == true && isset(self::$timer[$grups]['start'] )) {
+ $_time = number_format((self::$timer[$grups]['end']-self::$timer[$grups]['start']), self::$_decimals , self::$_decimals_delimit, ' ');
+ printf($lang['srv_timer_output'],$grups,$_time);
+ }
+ return number_format((self::$timer[$grups]['end']-self::$timer[$grups]['start']), self::$_decimals , self::$_decimals_delimit, ' ');
+ }
+
+ /**
+ *
+ * @param unknown_type $out
+ */
+ static public function setTimerOutput($out=true) {
+ self::$_timer_output = $out;
+ return $out;
+ }
+
+}
diff --git a/admin/survey/classes/class.User.php b/admin/survey/classes/class.User.php
new file mode 100644
index 0000000..2d73f55
--- /dev/null
+++ b/admin/survey/classes/class.User.php
@@ -0,0 +1,165 @@
+<?php
+/***************************************
+ * Description:
+ * Autor: Robert Šmalc
+ * Created date: 16.03.2018
+ *****************************************/
+
+class User {
+
+ private static $_instance;
+
+ private $user;
+
+ public function __construct($user_id = null)
+ {
+
+ if(is_null($user_id)){
+ global $global_user_id;
+ $user_id = $global_user_id;
+ }
+
+ $this->user = sisplet_query("SELECT * FROM users WHERE id='" . $user_id. "'", "obj");
+ }
+
+ public static function getInstance($user_id = null)
+ {
+ if (!self::$_instance) {
+ self::$_instance = new User($user_id);
+ }
+ return self::$_instance;
+ }
+
+ /**
+ * Vrne polje vseh emailov s statusom kateri je aktivni
+ *
+ * @return array
+ */
+ public function allEmails($without_master = FALSE)
+ {
+ $emails = $this->emails();
+
+ if ($without_master) {
+ unset($emails['master']);
+ }
+
+ return $emails;
+ }
+
+ private function emails()
+ {
+ $alternative_email_sql = sisplet_query("SELECT id, email, active FROM user_emails WHERE user_id='" . $this->user->id . "'", "obj");
+
+
+ // Če ni akternativnih emailov vrni primarnega
+ if (empty($alternative_email_sql)) {
+ return [
+ 'master' => (object) [
+ 'id' => NULL,
+ 'email' => $this->user->email,
+ 'active' => '1',
+ ],
+ ];
+ }
+
+ if (!empty($alternative_email_sql->email)) {
+ $alternative_email[] = $alternative_email_sql;
+ } elseif ($alternative_email_sql) {
+ $alternative_email = $alternative_email_sql;
+ }
+
+ $alternative_email['master'] = (object) [
+ 'id' => NULL,
+ 'email' => $this->user->email,
+ 'active' => '1',
+ ];
+
+ return $alternative_email;
+ }
+
+ /**
+ * Pridobimo primarni email, ki ga uporabnik uporablja
+ *
+ * @return mixed
+ */
+ public function primaryEmail()
+ {
+ $emails = $this->emails();
+
+ foreach ($emails as $email) {
+ if ($email->active == 1) {
+ return $email->email;
+ }
+ }
+ }
+
+ public static function findByEmail($email = null){
+
+ $user_id = sisplet_query("SELECT id FROM users WHERE email='".$email."'", "obj");
+ if(!empty($user_id)){
+ return $user_id->id;
+ }
+
+ // Preverimo, če uporablja alternativni email
+ $alternativni = sisplet_query("SELECT user_id FROM user_emails WHERE email='".$email."'", "obj");
+ if(!empty($alternativni)){
+ return $alternativni->user_id;
+ }
+
+ return null;
+ }
+
+ public function insertAlternativeEmail($email = NULL, $active = 0)
+ {
+ if (is_null($email) || !validEmail($email) || !unikatenEmail($email)) {
+ return NULL;
+ }
+
+ // Preverimo če email obstaja me duporabniki
+ sisplet_query("INSERT INTO user_emails (user_id, email, active, created_at) VALUES ('" . $this->user->id . "', '" . $email . "', '" . $active . "', NOW())");
+
+ return true;
+ }
+
+ /**
+ * Vrnemo dodatne opcije, ki so vezane na uporabnika
+ *
+ * @param null $user
+ * @param null $name
+ *
+ * @return null
+ */
+ public static function option($user = null, $name = null){
+ $option = sisplet_query("SELECT option_value FROM user_options WHERE user_id='".$user."' AND option_name='".$name."'", "obj");
+
+ if(!empty($option))
+ return $option->option_value;
+
+ return null;
+ }
+
+ public function setOption($name = null, $value = null)
+ {
+ if(is_null($name) || is_null($value))
+ return null;
+
+ $option = sisplet_query("SELECT id FROM user_options WHERE user_id='".$this->user->id ."' AND option_name='".$name."'", "obj");
+
+ if(!empty($option)){
+ sisplet_query("UPDATE user_options SET option_value='".$value."' WHERE user_id='".$this->user->id."' AND id='".$option->id."'");
+ }else{;
+ sisplet_query("INSERT INTO user_options (user_id, option_name, option_value, created_at) VALUES ('".$this->user->id."', '".$name."', '".$value."', NOW())");
+ }
+ }
+
+ // Vrnemo polje userja
+ public function getSetting($setting){
+
+ if(isset($this->user->$setting))
+ return $this->user->$setting;
+ else {
+ return false;
+ }
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/class.UserSetting.php b/admin/survey/classes/class.UserSetting.php
new file mode 100644
index 0000000..58f9488
--- /dev/null
+++ b/admin/survey/classes/class.UserSetting.php
@@ -0,0 +1,149 @@
+<?php
+/**
+ * Created on 12.6.2009
+ *
+ * @author: Gorazd Vesleič
+ *
+ * @desc: za uporabnikove nastavitve prikaza vmesnika,
+ * nastavlja globalne nastavitve za vse ankete.
+ * Uporablja tabelo: srv_user_setting
+ *
+ * -- usr_id # user ID
+ * # za izpis folderjev
+ * -- survey_list_order # vrstni red stolpcev v Direktoriju
+ * -- survey_list_order_by # sortiranje po stolpcu
+ * -- survey_list_rows_per_page # koliko zapisov na stran (25)
+ * -- survey_list_visible # kateri stolpci so vidni
+ * -- survey_list_widths # širine posameznih stolpcev
+ *
+ * # vizualizacija
+ * -- icons_always_on # ali so ikonice vedno vidne
+ * -- full_screen_edit # ali privzeto editira vprašanja v full screen načinu
+ *
+ */
+
+ class UserSetting
+{
+ static private $instance; # instanca razreda
+
+ static private $userId = null; # user ID
+ static private $inited = false; # ali je razred inizializiran
+ static private $user_setting = array(); # array z uporabniškimi nastavitvami;
+ static private $changed = array(); # katera polja so bila spremenjena, uporabimo pri vpisovanju v bazo
+
+ protected function __construct() {}
+
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new UserSetting();
+ }
+ return self::$instance;
+ }
+
+ /** napolnimo podatke
+ *
+ */
+ static function Init($_userId = null)
+ {
+ global $global_user_id;
+ if (self::$inited) {
+ return true;
+ } else {
+ if ($_userId == null) { // ce slucajno ni user_id-ja
+ $_userId = $global_user_id;
+ }
+ if ($_userId != null) {
+ self::$userId = $_userId;
+ $selectSql = "SELECT * FROM srv_user_setting WHERE usr_id = '".self::$userId."'";
+ $sqlUserSetting = sisplet_query($selectSql);
+ if ( mysqli_num_rows( $sqlUserSetting ) > 0 ) {
+ self::$user_setting = mysqli_fetch_assoc($sqlUserSetting);
+ self::$inited=true;
+ return true;
+ } else {
+
+ // uporabnik se nima svojih nastavitev. preberemo iz sistemskih
+ // TODO
+
+ //zaenkrat kar direkt nastavimo privzete nastavitve
+ self::$user_setting['icons_always_on'] = 0;
+ self::$user_setting['full_screen_edit'] = 0;
+
+ self::$user_setting['autoActiveSurvey'] = 0;
+ self::$user_setting['lockSurvey'] = 1;
+
+ self::$user_setting['activeComments'] = 0;
+
+ self::$user_setting['showIntro'] = 1;
+ self::$user_setting['showConcl'] = 1;
+ self::$user_setting['showSurveyTitle'] = 1;
+
+ self::$inited=true;
+ return true;
+ }
+ }
+ else {
+ return false;
+ }
+
+ }
+ }
+
+ static function getUserId() { return self::$userId; }
+ static function getUserSetting($what) {
+ return self::$user_setting[$what];
+ }
+
+ /** @desc ponastavi nastavitev in shrani v bazo
+ *
+ */
+ static function setUserSetting($what, $value) {
+ if (isset($what) && isset($value)) {
+ self::$changed[$what] = $value;
+ self::$user_setting[$what] = $value;
+ }
+ else
+ return false;
+ }
+
+ /** @desc v bazi popravimo vse spremenjene zapise zapis
+ *
+ */
+ static function saveUserSetting()
+ {
+ if (self::$inited && is_countable(self::$changed) && count(self::$changed) > 0 ) {
+
+ $str_insert_fields = 'usr_id';
+ $str_insert_values = "'".self::$userId."'";
+ $str_update_text = '';
+ $str_update_prefix = '';
+
+ foreach (self::$changed as $what => $value) {
+ if (isset(self::$user_setting[$what])) {
+ $str_insert_fields .= ', '.$what;
+ $str_insert_values .= ", '".self::$user_setting[$what]."'";
+ $str_update_text .= $str_update_prefix . $what."='".self::$user_setting[$what]."'";
+ $str_update_prefix = ', ';
+
+ }
+ unset(self::$changed[$what]);
+ }
+
+ // sestavimo mysql insert string
+ $insertString = 'INSERT INTO srv_user_setting ('.$str_insert_fields.') VALUES ('.$str_insert_values.') ON DUPLICATE KEY UPDATE '.$str_update_text;
+ self::$changed = array();
+ $insert = sisplet_query($insertString);
+ return mysqli_affected_rows($GLOBALS['connect_db']);
+ } else { // manjkajo podatki za vpis v bazo
+ return false;
+ }
+ }
+}
+?>
diff --git a/admin/survey/classes/class.Vprasanje.php b/admin/survey/classes/class.Vprasanje.php
new file mode 100644
index 0000000..50ba1b6
--- /dev/null
+++ b/admin/survey/classes/class.Vprasanje.php
@@ -0,0 +1,8062 @@
+<?php
+
+/**
+*
+* Nov, fullscreen nacin urejanja vprasanj
+*
+*/
+
+class Vprasanje {
+
+ var $anketa; // trenutna anketa
+ var $spremenljivka; // spremenljivka ki jo urejamo
+
+ var $db_table = '';
+ var $expanded = 0;
+
+ /**
+ * konstruktor
+ *
+ * @param mixed $anketa
+ * @return Vprasanje
+ */
+ function __construct ($anketa = 0) {
+
+ if (isset ($_GET['anketa']))
+ $this->anketa = $_GET['anketa'];
+ elseif (isset ($_POST['anketa']))
+ $this->anketa = $_POST['anketa'];
+ elseif ($anketa != 0)
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('expanded') == 1)
+ $this->expanded = 1;
+ }
+
+ /**
+ * izrise ogrodje urejanja vprasanja
+ *
+ */
+ function display () {
+
+ $this->tabs();
+
+ echo '<div id="vprasanje_edit">';
+ $this->vprasanje_edit();
+ echo '</div>';
+
+ $this->edit_buttons();
+ }
+
+ /**
+ * izrise tabe pri urejanju vprasanja
+ *
+ */
+ function tabs () {
+ global $lang;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $rows = SurveyInfo::getInstance()->getSurveyRow();
+
+ echo '<div id="vprasanje_tabs">';
+
+ echo '<a href="#" class="tab_link active" id="tab_link_0" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'0\'); return false;">'.$lang['srv_osnovno'].'</a>';
+
+ if ($this->spremenljivka > 0 && !Demografija::getInstance()->isDemografija($row['variable']) ) {
+
+ // Tab napredno
+ echo '<a href="#" class="tab_link" id="tab_link_1" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'1\'); return false;">'.$lang['srv_napredno'].'</a>';
+
+ // Tab pogoji
+ echo '<a href="#" class="tab_link" id="tab_link_2" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'2\'); return false;">'.$lang['srv_condition'].'</a>';
+
+ // Tab validacija
+ echo '<a href="#" class="tab_link" id="tab_link_7" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'7\'); return false;">'.$lang['srv_validation'].'</a>';
+
+ // Tab opomba
+ echo '<a href="#" class="tab_link" id="tab_link_3" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'3\'); return false;">'.$lang['srv_note'].($row['note']!=''?'*':'').'</a>';
+
+ // Tab tracking sprememb na vprašanju
+ if (($admin_type == 0 || $admin_type == 1) && $rows['vprasanje_tracking'] > 0){
+ echo '<div class="tab_link_tracking">';
+ echo '<a href="#" class="tab_link" id="tab_link_6" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'6\'); return false;" title="'.$lang['hour_archive'].'"><span>'.$lang['hour_archive'].'</span></a>';
+ echo '</div>';
+ }
+ }
+ else {
+
+ $star = '';
+ if ($this->spremenljivka == -1) {
+ if ($rows['thread_intro']!=0 || $rows['intro_note']!='') $star = '*';
+ } else {
+ if ($rows['thread_concl']!=0 || $rows['concl_note']!='') $star = '*';
+ }
+
+ echo '<a href="#" class="tab_link" id="tab_link_3" onclick="vprasanje_tab(\''.$this->spremenljivka.'\', \'3\'); return false;">'.$lang['srv_note'].$star.'</a>';
+ }
+
+ echo '</div>';
+ }
+
+ /**
+ * urejanje vprasanja
+ *
+ */
+ function vprasanje_edit () {
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<form name="vprasanje_edit" onsubmit="vprasanje_save(); return false;">';
+
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'" />';
+ echo '<input type="hidden" name="spremenljivka" value="'.$this->spremenljivka.'" />';
+
+ echo '<div id="tab_0" class="tab" style="display:block">';
+ $this->vprasanje_osnovno();
+ echo '</div>';
+
+ if ($this->spremenljivka > 0) {
+
+ echo '<div id="tab_1" class="tab" style="display:none">';
+ $this->vprasanje_napredno();
+ echo '</div>';
+
+ echo '<div id="tab_2" class="tab" style="display:none">';
+ $this->vprasanje_pogoji();
+ echo '</div>';
+
+ echo '<div id="tab_7" class="tab" style="display:none">';
+ $this->vprasanje_validation();
+ echo '</div>';
+
+ echo '<div id="tab_6" class="tab" style="display:none">';
+ $this->vprasanje_display_tracking();
+ echo '</div>';
+ }
+
+ echo '<div id="tab_3" class="tab" style="display:none">';
+ $this->vprasanje_komentarji();
+ echo '</div>';
+
+ echo '</form>';
+
+ echo '<span id="vprasanje_edit_bottom_placeholder"></span>';
+ }
+
+ /**
+ * osnovno urejanje vprasanja
+ *
+ */
+ function vprasanje_osnovno () {
+ global $lang;
+ global $site_url;
+
+ //uvod
+ if ($this->spremenljivka == -1) {
+ $this->edit_uvod();
+
+ //zakljucek
+ } elseif ($this->spremenljivka == -2) {
+ $this->edit_zakljucek();
+
+ //statistika
+ } elseif($this->spremenljivka == -3) {
+ $this->edit_statistika();
+
+ } else {
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ // demografija
+ if (Demografija::getInstance()->isDemografija($row['variable'])) {
+
+ // variabla na vrhu in izbira druge demografije
+ $this->variable();
+
+ // izbira tipa demografije
+ echo '<fieldset><legend>'.$lang['srv_question_type'].'</legend>';
+ echo '<p><span class="title">'.$lang['srv_select_type'].':</span><span class="content"><select style="width:150px" name="tip" id="spremenljivka_tip_' . $row['id'] . '" size="1" spr_id="' . $row['id'] . '" onChange="change_demografija(\'' . $row['id'] . '\', $(this).val());" data-ajax="true">';
+
+ foreach (Demografija::getInstance()->getSeznam($row['variable']) AS $variabla) {
+ echo '<option value="'.Demografija::getInstance()->getSpremenljivkaID($variabla).'" '.($row['variable'] == $variabla?'selected':'').'>'.$variabla.'</option>';
+ }
+
+ echo '</select></span></p>';
+
+ echo '<script type="text/javascript">';
+ echo '$(document).ready(function() { ';
+ echo '$("#spremenljivka_tip_' . $row['id'] . '").selectbox();'; // kreira custom dropdown z možnostjo predogleda vprašanja
+ echo '});';
+ echo '</script>';
+
+ echo '<p><strong>'.$lang[$row['variable']].'</strong></p>';
+
+ echo '</fieldset>';
+
+ // reminder
+ $this->edit_reminder();
+
+
+ }
+ // navadno vprasanje
+ else {
+
+ // variabla na vrhu
+ $this->variable(1);
+
+ // prikaz vprasanja - postavitev
+ if ( in_array($row['tip'], array(1, 2, 3, 6, 7, 16, 17, 20, 9, 26, 27)) ) {
+ $this->edit_subtip();
+ }
+
+ // Nastavitev za postavitev texbox za besedilo, number, datum - vodoravno ob ali pod vprasanjem
+ if ( in_array($row['tip'], array(21, 7, 8)) ) {
+
+ // Ce nimamo slider-ja
+ if($row['tip'] != 7 || $row['ranking_k'] != 1){
+ $this->edit_orientation();
+ }
+ }
+
+ // datum-min/max date
+ if ( in_array($row['tip'], array(8)) ) {
+ $this->edit_date_range();
+ $this->edit_date_withTime();
+ }
+
+ // Lokacija
+ if ( in_array($row['tip'], array(26)) ) {
+ $this->edit_input_type_map();
+ $this->fokus_mape();
+ $this->userLocation();
+ $this->markerPodvprasanje();
+ $this->naslov_podvprasanja_map();
+ $this->st_markerjev();
+ $this->dodaj_SearchBox();
+ }
+
+ // pri nagovoru ni smiselno dodajat opozoril
+ if ( ! in_array($row['tip'], array(5)) ) {
+ $this->edit_reminder();
+ }
+
+ // opomba na vprasanje
+ $this->edit_opomba();
+
+ if (($row['tip'] == 7 || $row['tip'] == 20) && $row['ranking_k'] == 1) {
+
+ echo '<fieldset><legend>'.$lang['slider_properties_note'].'</legend>';
+ $this->edit_sliders_settings();
+ echo '</fieldset>';
+ }
+
+ // Hotspot
+ if( in_array($row['tip'], array(1, 2, 6, 17)) ){
+ $this->edit_hot_spot_settings();
+ }
+
+ if ( in_array($row['tip'], array(6, 16, 19, 20)) ) {
+
+ if ($row['ranking_k'] != 1){
+ echo '<fieldset><legend>'.$lang['srv_kategorije_odgovorov'].'</legend>';
+ }
+ if ( in_array($row['tip'], array(6, 16)) ) {
+ $this->edit_grid_subtitle();
+ }
+
+ $this->edit_grid();
+
+ // Uporaba label
+ $this->edit_column_labels();
+
+ // Ponovi glavo v gridu vsakih x vrstic
+ if ( in_array($row['tip'], array(6, 16)) )
+ $this->edit_grid_repeat_header();
+
+ $this->edit_drag_and_drop_new_look();
+
+ if ($row['ranking_k'] != 1){
+ echo '</fieldset>';
+ }
+
+ // Merska lestvica (ordinalna ali nominalna)
+ if ($row['tip'] == 6){
+ $this->edit_skala_new();
+ }
+
+ echo '<fieldset><legend>'.$lang['srv_manjkajoce_vrednosti2'].' '.Help::display('srv_missing_values').'</legend>';
+ $this->edit_grid_missing();
+ echo '</fieldset>';
+ }
+
+ // kategorije vprasanj
+ if ( in_array($row['tip'], array(1, 2, 3, 6, 16, 17, 18, 19, 20, 24)) ) {
+
+ if ( in_array($row['tip'], array(1, 2, 3, 17, 18)) ){
+ echo '<fieldset class="kategorije_odgovorov" id="kategorije_odgovorov_'.$row['id'].'"><legend>'.$lang['srv_kategorije_odgovorov'].'</legend>';
+ }
+ else{
+ echo '<fieldset><legend>'.$lang['srv_podvprasanja'].'</legend>';
+ }
+
+ if ( in_array($row['tip'], array(24)) ) {
+ $this->edit_multiple_subtitle();
+ }
+
+ if ( in_array($row['tip'], array(6, 16, 19, 18, 20, 24)) ) {
+ $this->edit_grid_width();
+
+ if ( in_array($row['tip'], array(6, 16, 19, 20, 24)) ) {
+ $this->edit_grid_align();
+ }
+ }
+
+ // kategorije vprasanja - hitro dodajanje
+ $this->edit_vrednost();
+
+ // razvrscanje
+ if(!in_array($row['orientation'], [9,11])) {
+ $this->edit_random();
+ }
+
+ if ( in_array($row['tip'], array(1, 2, 3, 6, 16)) ) {
+ $this->edit_selectbox_size();
+ }
+
+ // Slikice namesto radio gumbov (smiley, thumbs up...) - $row['orientation'] == 9
+ if(in_array($row['tip'], array(1, 2))){
+ $this->edit_custom_picture_radio();
+ }
+
+ if(in_array($row['tip'], array(1, 6))){
+ $this->edit_visual_analog_scale();
+ }
+
+
+ // razvrscanje - moznosti
+ if ( in_array($row['tip'], array(17)) ) {
+ $this->edit_ranking_moznosti();
+ }
+
+ echo '</fieldset>';
+ }
+
+ // Merska lestvica (ordinalna ali nominalna)
+ if ($row['tip'] == 1 || $row['tip'] == 3){
+ $this->edit_skala_new();
+ }
+ // manjkajoce vrednosti
+ if ($row['tip'] <= 3) {
+ echo '<fieldset><legend>'.$lang['srv_manjkajoce_vrednosti2'].' '.Help::display('srv_missing_values').'</legend>';
+ $this->edit_missing();
+ echo '</fieldset>';
+ }
+
+ // editiranje vrednosti pri datumu
+ if ( in_array($row['tip'], array(8)) ) {
+
+ echo '<fieldset><legend>'.$lang['srv_manjkajoce_vrednosti2'].' '.Help::display('srv_missing_values').'</legend>';
+
+ $this->edit_vrednost_datum();
+
+ // naknaden prikaz missinga ne vem ob opozorilu (samo ce imamo vklopljeno opozorilo in missing ne vem)
+ $this->edit_alert_show_missing();
+
+ echo '</fieldset>';
+ }
+
+
+
+ if ( in_array($row['tip'], array(7, 19, 20, 21)) ) {
+
+ $captcha = ($spremenljivkaParams->get('captcha') ? $spremenljivkaParams->get('captcha') : 0);
+
+ //ce ni elektronski podpis, upload ali captcha
+ if($row['signature'] != 1 && $row['upload'] < 1 && $captcha != 1){
+ $displayFieldset = 'display: block';
+ }
+ else{
+ $displayFieldset = 'display: none';
+ }
+
+ echo '<fieldset style="'.$displayFieldset.'" class="kategorije_odgovorov" id="kategorijeOdgovorov_'.$this->spremenljivka.'"><legend>'.$lang['srv_kategorije_odgovorov'].'</legend>';
+
+ if ( in_array($row['tip'], array(21)) ) {
+ $this->edit_textboxes();
+ }
+
+ if ( in_array($row['tip'], array(7)) ) {
+ if ($row['ranking_k'] == 0){ //ce je izbrano stevilo in ne drsnik
+ $this->edit_num_size();
+ $this->edit_num_enota();
+ }
+ }
+
+ if ($row['ranking_k'] == 0){ //ce je izbrano stevilo in ne drsnik
+ $this->edit_width();
+ }
+
+ echo '</fieldset>';
+
+
+ // Poseben segment za upload datoteke
+ if($row['upload'] == 1){
+ $displayFieldset = 'display: block';
+ }
+ else{
+ $displayFieldset = 'display: none';
+ }
+
+ echo '<fieldset style="'.$displayFieldset.'" class="upload_info"><legend>'.$lang['srv_vprasanje_upload_limit_title'].' '.Help::display('srv_upload_limit').'</legend>';
+ echo '<p>'.$lang['srv_vprasanje_upload_limit'].'</p>';
+ echo '<p>'.$lang['srv_vprasanje_upload_limit_type'].'</p>';
+ echo '</fieldset>';
+ }
+
+ // manjkajoce vrednosti - besedilo
+ if ( in_array($row['tip'], array(21)) ) {
+ echo '<fieldset><legend>'.$lang['srv_manjkajoce_vrednosti2'].' '.Help::display('srv_missing_values').'</legend>';
+ $this->edit_vrednost_besedilo();
+
+ // naknaden prikaz missinga ne vem ob opozorilu (samo ce imamo vklopljeno opozorilo in missing ne vem)
+ $this->edit_alert_show_missing();
+ echo '</fieldset>';
+ }
+
+ // Sirina polja "drugo" (ce je v vprasanju)
+ if (in_array($row['tip'], array(1,2,3,6,16,19,20,24)))
+ $this->edit_other_field();
+
+ if ( in_array($row['tip'], array(7, 18, 20)) ) {
+
+ if ($row['ranking_k'] == 0){ //ce je izbrano stevilo in ne drsnik
+ $this->edit_number();
+ }
+
+ if ($row['tip'] == 7) {
+ echo '<fieldset><legend>'.$lang['srv_manjkajoce_vrednosti2'].' '.Help::display('srv_missing_values').'</legend>';
+ $this->edit_vrednost_number();
+
+ // naknaden prikaz missinga ne vem ob opozorilu (samo ce imamo vklopljeno opozorilo in missing ne vem)
+ $this->edit_alert_show_missing();
+
+ echo '</fieldset>';
+ }
+ }
+
+ if ( in_array($row['tip'], array(22)) ) {
+ $this->edit_compute();
+ }
+
+ if ( in_array($row['tip'], array(9)) ) {
+ $this->edit_name_generator();
+ }
+
+ if ( in_array($row['tip'], array(7,18,20, 21)) ) {
+ if ($row['ranking_k'] == 0){ //ce je izbrano stevilo in ne drsnik
+ $this->edit_limit();
+ }
+ }
+
+ // Crta pod nagovorom
+ if ($row['tip'] == 5) {
+ $this->edit_nagovor_line();
+ }
+ }
+ }
+ }
+
+ function edit_sliders_settings(){
+ global $lang;
+ global $admin_type;
+ global $default_grid_values; //privzete default vmesne opisne labele
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $slider_handle = ($spremenljivkaParams->get('slider_handle') ? $spremenljivkaParams->get('slider_handle') : 0); //za checkbox
+ $slider_window_number = ($spremenljivkaParams->get('slider_window_number') ? $spremenljivkaParams->get('slider_window_number') : 0); //za checkbox
+
+ $slider_MinMaxNumLabelNew = ($spremenljivkaParams->get('slider_MinMaxNumLabelNew') ? $spremenljivkaParams->get('slider_MinMaxNumLabelNew') : 0);
+ $slider_MinMaxLabel = ($spremenljivkaParams->get('slider_MinMaxLabel') ? $spremenljivkaParams->get('slider_MinMaxLabel') : 0);
+ $slider_VmesneNumLabel = ($spremenljivkaParams->get('slider_VmesneNumLabel') ? $spremenljivkaParams->get('slider_VmesneNumLabel') : 0);
+ $slider_VmesneDescrLabel = ($spremenljivkaParams->get('slider_VmesneDescrLabel') ? $spremenljivkaParams->get('slider_VmesneDescrLabel') : 0);
+ $slider_VmesneCrtice = ($spremenljivkaParams->get('slider_VmesneCrtice') ? $spremenljivkaParams->get('slider_VmesneCrtice') : 0);
+ $slider_handle_step = ($spremenljivkaParams->get('slider_handle_step') ? $spremenljivkaParams->get('slider_handle_step') : 1);
+ $slider_MinLabel= ($spremenljivkaParams->get('slider_MinLabel') ? $spremenljivkaParams->get('slider_MinLabel') : "Minimum");
+ $slider_MaxLabel= ($spremenljivkaParams->get('slider_MaxLabel') ? $spremenljivkaParams->get('slider_MaxLabel') : "Maximum");
+ $slider_MinNumLabel = ($spremenljivkaParams->get('slider_MinNumLabel') ? $spremenljivkaParams->get('slider_MinNumLabel') : 0);
+ $slider_MaxNumLabel = ($spremenljivkaParams->get('slider_MaxNumLabel') ? $spremenljivkaParams->get('slider_MaxNumLabel') : 100);
+ $slider_MinNumLabelTemp = ($spremenljivkaParams->get('slider_MinNumLabelTemp') ? $spremenljivkaParams->get('slider_MinNumLabelTemp') : 0);
+ $slider_MaxNumLabelTemp = ($spremenljivkaParams->get('slider_MaxNumLabelTemp') ? $spremenljivkaParams->get('slider_MaxNumLabelTemp') : 100);
+
+ $slider_NumofDescrLabels = ($spremenljivkaParams->get('slider_NumofDescrLabels') ? $spremenljivkaParams->get('slider_NumofDescrLabels') : 5);
+ $slider_DescriptiveLabel_defaults = ($spremenljivkaParams->get('slider_DescriptiveLabel_defaults') ? $spremenljivkaParams->get('slider_DescriptiveLabel_defaults') : 0);
+
+ $slider_StevLabelPodrocij = ($spremenljivkaParams->get('slider_StevLabelPodrocij') ? $spremenljivkaParams->get('slider_StevLabelPodrocij') : 3);
+
+ $slider_nakazi_odgovore = ($spremenljivkaParams->get('slider_nakazi_odgovore') ? $spremenljivkaParams->get('slider_nakazi_odgovore') : 0); //za checkbox
+ $slider_labele_podrocij = ($spremenljivkaParams->get('slider_labele_podrocij') ? $spremenljivkaParams->get('slider_labele_podrocij') : 0); //za checkbox
+
+ $displayDescriptiveLabels = ($slider_VmesneDescrLabel == 0) ? ' style="display:none;"' : '';
+ $displayStevLabelPodrocij = ($slider_labele_podrocij == 0) ? ' style="display:none;"' : '';
+
+ $disable_slider_handle_hidden = ($slider_handle == 0) ? 'disabled' : '';
+ $disable_slider_MinMaxNumLabelNew_hidden = ($slider_MinMaxNumLabelNew == 0) ? 'disabled' : '';
+ $disable_slider_VmesneCrtice_hidden = ($slider_VmesneCrtice == 1) ? 'disabled' : '';
+ //$disable_slider_VmesneCrtice = ($slider_VmesneCrtice == 0) ? 'disabled' : '';
+
+ $disable_slider_VmesneDescrLabel_hidden = ($slider_VmesneDescrLabel == 1) ? 'disabled' : '';
+ $disable_slider_VmesneNumLabel_hidden = ($slider_VmesneNumLabel == 1) ? 'disabled' : '';
+ $disable_slider_MinMaxLabel_hidden = ($slider_MinMaxLabel == 1) ? 'disabled' : '';
+ $disable_slider_window_number_hidden = ($slider_window_number == 0) ? 'disabled' : '';
+ $disable_slider_handle_step = ($slider_VmesneDescrLabel == 1) ? 'disabled' : '';
+
+ $disable_slider_nakazi_odgovore_hidden = ($slider_nakazi_odgovore == 1) ? 'disabled' : '';
+ $disable_slider_labele_podrocij_hidden = ($slider_labele_podrocij == 1) ? 'disabled' : '';
+
+ //za pravilno osivitev koraka sliderja
+ if ($disable_slider_handle_step == 'disabled'){
+ $slider_handle_step_opacity = 0.5;
+ }else{
+ $slider_handle_step_opacity = 1;
+ }
+
+ //za pravilno osivitev nastavitve za vmesne crtice
+ if ($disable_slider_nakazi_odgovore_hidden == 'disabled'){
+ $slider_VmesneCrtice_opacity = 0.5;
+ $disable_slider_VmesneCrtice = 'disabled';
+ }else{
+ $slider_VmesneCrtice_opacity = 1;
+ $disable_slider_VmesneCrtice = '';
+ }
+
+ //echo '<input type="hidden" name="MinMaxLabelsDefaultFlag" value="1" />';
+
+ // Polje size moramo imeti - drugace se pobrise vse iz srv_vrednost in se ne shranjuje vec
+ echo '<input type="hidden" value="1" name="size" id="num_size">';
+
+ //Drsna rocica
+ echo '<label for="slider_handle_'.$this->spremenljivka.'"><div class="dropsliderhandle" >'; //drsna rocica
+ echo '<p><span class="title" >'.$lang['slider_handle_note'].':</span>';
+ //echo $slider_handle;
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="0" name="slider_handle" '.( $slider_handle == 0 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_handle_'.$this->spremenljivka.'">';
+
+ //echo '<input type="hidden" value="1" name="slider_handle" id="slider_handle_hidden_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_handle_hidden.' type="hidden" value="1" name="slider_handle" id="slider_handle_hidden_'.$this->spremenljivka.'">';
+
+ //echo '<input type="checkbox" value="1" name="slider_handle" '.( $slider_handle == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_handle_'.$this->spremenljivka.'">';
+
+ //echo '<input type="hidden" value="0" name="slider_handle" id="slider_handle_hidden_'.$this->spremenljivka.'">';
+
+ echo '</span></p>';
+ echo '</div></label>';
+
+ //Stevilka nad izbrano tocko
+ echo '<label for="slider_window_number_'.$this->spremenljivka.'"><div class="dropsliderwindownumber" >';
+ echo '<p><span class="title" >'.$lang['slider_window_number_title'].':</span>';
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="0" name="slider_window_number" '.( $slider_window_number == 0 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_window_number_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_window_number_hidden.' type="hidden" value="1" name="slider_window_number" id="slider_window_number_hidden_'.$this->spremenljivka.'">';
+ //echo '<input '.$disable_slider_window_number_hidden.' value="1" name="slider_window_number" id="slider_window_number_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div></label>';
+
+ if ($admin_type == 0){
+ //Nakazi mozne odgovore
+ echo '<label for="slider_nakazi_odgovore_'.$this->spremenljivka.'"><div class="dropslidernakaziodgovore" >';
+ echo '<p><span class="title" >'.$lang['srv_slider_nakazi_odgovore'].':</span>';
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="slider_nakazi_odgovore" '.( $slider_nakazi_odgovore == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_nakazi_odgovore_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_nakazi_odgovore_hidden.' type="hidden" value="0" name="slider_nakazi_odgovore" id="slider_nakazi_odgovore_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div></label>';
+ }
+
+
+
+
+ //Korak drsnika
+ $viewMinMaxNumLabels = ($slider_VmesneDescrLabel == 1) ? '; display:none;' : '';
+ echo '<div class="dropsliderhandle_step_'.$this->spremenljivka.'" style="opacity: '.$slider_handle_step_opacity.''.$viewMinMaxNumLabels.'">'; //korak drsnika
+ echo '<p><span class="title" >'.$lang['slider_handle_step_note'].':</span>';
+ echo '<span class="content"><select name="slider_handle_step" id="slider_handle_step_'.$this->spremenljivka.'" '.$disable_slider_handle_step.'>';
+ for($i=1; $i<=10; $i++){
+ echo '<option value="'.$i.'"'.($slider_handle_step == $i ? ' selected="true"' : '') . '>'.$i.'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+ //Min in max vrednosti
+ $viewMinMaxNumLabels = ($slider_VmesneDescrLabel == 1) ? ' style="display:none;"' : '';
+ echo '<div class="MinMaxNumLabels_'.$this->spremenljivka.'" '.$viewMinMaxNumLabels.'>'; //ureditev min in max stevilk
+ echo '<p>';
+ echo $lang['srv_num_min'] . '<input type="text" name="slider_MinNumLabel" id="slider_MinNumLabel_'.$this->spremenljivka.'" value="' . $slider_MinNumLabel . '" size="8" onkeyup="checkNumber(this, 6, 2); sliderCopytoMinNumLabelTemp('.$this->spremenljivka.');"></input> ';
+ echo $lang['srv_num_limit'] . '<input type="text" name="slider_MaxNumLabel" id="slider_MaxNumLabel_'.$this->spremenljivka.'" value="' . $slider_MaxNumLabel . '" size="8" onkeyup="checkNumber(this, 6, 2); sliderCopytoMaxNumLabelTemp('.$this->spremenljivka.');"></input> ';
+ echo '</p>';
+ echo '</div>';
+
+ //temp Min in Max style="display: none"
+ echo '<div class="MinMaxNumLabelsTemp" style="display: none" >'; //ureditev temp min in max stevilk, za vrnitev stevilskih label, ki so bile prej izbrane
+ echo '<p>';
+ echo $lang['srv_num_min'] . '<input type="text" name="slider_MinNumLabelTemp" id="slider_MinNumLabelTemp_'.$this->spremenljivka.'" value="' . $slider_MinNumLabelTemp . '" size="8" onkeyup="checkNumber(this, 6, 2);"></input> ';
+ echo $lang['srv_num_limit'] . '<input type="text" name="slider_MaxNumLabelTemp" id="slider_MaxNumLabelTemp_'.$this->spremenljivka.'" value="' . $slider_MaxNumLabelTemp . '" size="8" onkeyup="checkNumber(this, 6, 2);"></input> ';
+ echo '</p>';
+ echo '</div>';
+ //temp Min in Max - konec
+
+ //Vmesne crtice
+ echo '<label class="slider_VmesneCrtice_'.$this->spremenljivka.'" for="slider_VmesneCrtice_'.$this->spremenljivka.'"><div class="dropVmesneCrtice" style="opacity: '.$slider_VmesneCrtice_opacity.'">'; //ureditev prikazovanja in skrivanja vmesnih crtic
+ echo '<p><span class="title" >'.$lang['slider_VmesneCrtice_note'].':</span>';
+ echo '<span class="content">';
+ echo '<input '.$disable_slider_VmesneCrtice.' type="checkbox" value="1" name="slider_VmesneCrtice" '.( $slider_VmesneCrtice == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_VmesneCrtice_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_VmesneCrtice_hidden.' type="hidden" value="0" name="slider_VmesneCrtice" id="slider_VmesneCrtice_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div></label>';
+
+ //Stevilske labele
+ //echo '<p><span class="title" >'.$lang['slider_NumLabel_note'].':</span></p>';
+
+ echo '<div class="dropNumLabelNew">';
+
+ echo '<label for="slider_VmesneNumLabel_'.$this->spremenljivka.'"><p><span class="title" >'.$lang['slider_NumLabel_note'].':</span>'; //ureditev prikazovanja in skrivanja stevilskih vmesnih label
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="slider_VmesneNumLabel" '.( $slider_VmesneNumLabel == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_VmesneNumLabel_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_VmesneNumLabel_hidden.' type="hidden" value="0" name="slider_VmesneNumLabel" id="slider_VmesneNumLabel_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p></label>';
+
+ echo '<label for="slider_MinMaxNumLabelNew_'.$this->spremenljivka.'"><p><span class="title" >'.$lang['slider_MinMaxNumLabel_note'].':</span>';
+ echo '<span class="content">'; //ureditev prikazovanja in skrivanja stevilskih label za min in max na sliderju s pips-i
+ echo '<input type="checkbox" value="0" name="slider_MinMaxNumLabelNew" '.( $slider_MinMaxNumLabelNew == 0 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_MinMaxNumLabelNew_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_MinMaxNumLabelNew_hidden.' type="hidden" value="1" name="slider_MinMaxNumLabelNew" id="slider_MinMaxNumLabelNew_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p></label>';
+
+ echo '</div>';
+
+ //Opisne labele
+ echo '<div class="dropDescriptiveLabel" >';
+
+ echo '<label for="slider_MinMaxLabel_'.$this->spremenljivka.'"><p><span class="title">'.$lang['slider_MinMaxLabel_note'].'</span></label>';
+ echo '<span class="content">'; //ureditev prikazovanja in skrivanja opisnih label za min in max
+ echo '<input type="checkbox" value="1" name="slider_MinMaxLabel" '.( $slider_MinMaxLabel == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_MinMaxLabel_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_MinMaxLabel_hidden.' type="hidden" value="0" name="slider_MinMaxLabel" id="slider_MinMaxLabel_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+
+ echo '<label for="slider_VmesneDescrLabel_'.$this->spremenljivka.'"><p><span class="title">'.$lang['slider_VmesneLabel_note'].'</span></label>'; //ureditev prikazovanja in skrivanja opisnih vmesnih label
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="slider_VmesneDescrLabel" '.( $slider_VmesneDescrLabel == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_VmesneDescrLabel_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_VmesneDescrLabel_hidden.' type="hidden" value="0" name="slider_VmesneDescrLabel" id="slider_VmesneDescrLabel_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+
+ echo '</div>';
+
+ // prikaz dropdowna za default vrednosti opisnih vmesnih label
+ echo '<p class="slider_DescriptiveLabel_defaults" '.$displayDescriptiveLabels.'>'; //echo '<p class="grid_defaults" '.$display.'>';
+ echo '<span class="title">'.$lang['srv_defaultDescrLabel'].':</span>';
+ echo '<span class="content"><select name="slider_DescriptiveLabel_defaults" id="slider_DescriptiveLabel_defaults_'.$this->spremenljivka.'" style="width:100px" onChange="slider_defaultDescrLabels_value('.$this->spremenljivka.', this.value); switchSliderOpisneLabeleEditMode('.$this->spremenljivka.', \'\');">';
+ //echo '<span class="content"><select name="slider_DescriptiveLabel_defaults" id="slider_DescriptiveLabel_defaults_'.$this->spremenljivka.'" style="width:100px" onChange="slider_defaultDescrLabels_value('.$this->spremenljivka.', this.value);">';
+ echo '<option value="0">'.$lang['s_without'].'</option>';
+ foreach($default_grid_values AS $key => $value){
+ //echo '<option value="'.$key.'">'.$value['name'].'</option>';
+ echo '<option value="'.$key.'"'.($slider_DescriptiveLabel_defaults == $key ?' selected':'').'>'.$value['name'].'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+
+ echo '<div class="dropNumofDescrLabels" '.$displayDescriptiveLabels.'>';
+ echo '<p><span class="title" >'.$lang['srv_NumDescrLabels_note'].':</span>';
+ echo '<span class="content"><select name="slider_NumofDescrLabels" id="slider_NumofDescrLabels_'.$this->spremenljivka.'" onChange="slider_checkbox_prop('.$this->spremenljivka.');">';
+ echo '<option value="2"'.($slider_NumofDescrLabels =='2'?' selected':'').'>2</option>';
+ echo '<option value="3"'.($slider_NumofDescrLabels =='3'?' selected':'').'>3</option>';
+ echo '<option value="4"'.($slider_NumofDescrLabels =='4'?' selected':'').'>4</option>';
+ echo '<option value="5"'.($slider_NumofDescrLabels =='5'?' selected':'').'>5</option>';
+ echo '<option value="6"'.($slider_NumofDescrLabels =='6'?' selected':'').'>6</option>';
+ echo '<option value="7"'.($slider_NumofDescrLabels =='7'?' selected':'').'>7</option>';
+ echo '<option value="8"'.($slider_NumofDescrLabels =='8'?' selected':'').'>8</option>';
+ echo '<option value="9"'.($slider_NumofDescrLabels =='9'?' selected':'').'>9</option>';
+ echo '<option value="10"'.($slider_NumofDescrLabels =='10'?' selected':'').'>10</option>';
+ echo '<option value="11"'.($slider_NumofDescrLabels =='11'?' selected':'').'>11</option>';
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+ //Labele podrocij
+ echo '<label for="slider_labele_podrocij_'.$this->spremenljivka.'"><div class="check_slider_labele_podrocij" >';
+ echo '<p><span class="title" >'.$lang['srv_slider_labele_podrocij'].':</span>';
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="slider_labele_podrocij" '.( $slider_labele_podrocij == 1 ? ' checked="checked"' : '') .' onChange="slider_checkbox_prop('.$this->spremenljivka.');" id="slider_labele_podrocij_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_slider_labele_podrocij_hidden.' type="hidden" value="0" name="slider_labele_podrocij" id="slider_labele_podrocij_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div></label>';
+
+ //Labele podrocij - prikaz dropdowna z moznimi stevilkami podrocij
+ echo '<div class="drop_slider_stevilo_label_podrocij" '.$displayStevLabelPodrocij.'>';
+ echo '<p><span class="title" >'.$lang['srv_slider_stevilo_label_podrocij'].':</span>';
+ echo '<span class="content"><select name="slider_StevLabelPodrocij" id="slider_StevLabelPodrocij_'.$this->spremenljivka.'" onChange="slider_checkbox_prop('.$this->spremenljivka.');">';
+ echo '<option value="1"'.($slider_StevLabelPodrocij =='1'?' selected':'').'>1</option>';
+ echo '<option value="2"'.($slider_StevLabelPodrocij =='2'?' selected':'').'>2</option>';
+ echo '<option value="3"'.($slider_StevLabelPodrocij =='3'?' selected':'').'>3</option>';
+ echo '<option value="4"'.($slider_StevLabelPodrocij =='4'?' selected':'').'>4</option>';
+ echo '<option value="5"'.($slider_StevLabelPodrocij =='5'?' selected':'').'>5</option>';
+ echo '<option value="6"'.($slider_StevLabelPodrocij =='6'?' selected':'').'>6</option>';
+ echo '<option value="7"'.($slider_StevLabelPodrocij =='7'?' selected':'').'>7</option>';
+ echo '<option value="8"'.($slider_StevLabelPodrocij =='8'?' selected':'').'>8</option>';
+ echo '<option value="9"'.($slider_StevLabelPodrocij =='9'?' selected':'').'>9</option>';
+ echo '<option value="10"'.($slider_StevLabelPodrocij =='10'?' selected':'').'>10</option>';
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+ }
+
+ function edit_hot_spot_settings(){
+ global $lang;
+ global $admin_type;
+ global $default_grid_values; //privzete default vmesne opisne labele
+
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $hotspot_image = ($spremenljivkaParams->get('hotspot_image') ? $spremenljivkaParams->get('hotspot_image') : "");
+ $hotspot_region_visibility_option = ($spremenljivkaParams->get('hotspot_region_visibility_option') ? $spremenljivkaParams->get('hotspot_region_visibility_option') : 0); //za checkbox
+ $hotspot_region_visibility = ($spremenljivkaParams->get('hotspot_region_visibility') ? $spremenljivkaParams->get('hotspot_region_visibility') : 1); //za radio "vedno" in "ob mouseover"
+ $hotspot_tooltips_option = ($spremenljivkaParams->get('hotspot_tooltips_option') ? $spremenljivkaParams->get('hotspot_tooltips_option') : 0);
+ $hotspot_region_color = ($spremenljivkaParams->get('hotspot_region_color') ? $spremenljivkaParams->get('hotspot_region_color') : "");
+ $hotspot_visibility_color = ($spremenljivkaParams->get('hotspot_visibility_color') ? $spremenljivkaParams->get('hotspot_visibility_color') : "");
+ $disable_hotspot_region_visibility_option_hidden = ($hotspot_region_visibility_option == 1) ? 'disabled' : '';
+ $spr_id = $row['id'];
+
+ //prikazovanje/skrivanje nastavitev za osvetljevanje
+ if($hotspot_region_visibility_option){
+ $hotspot_visibility_display = 'style=""';
+ }
+ else{
+ $hotspot_visibility_display = 'style="display:none"';
+ }
+ //prikazovanje/skrivanje nastavitev za osvetljevanje - konec
+
+ //preveri, ce je kaksno obmocje shranjeno v bazi
+ $sqlR = sisplet_query("SELECT region_index, vre_id, region_name FROM srv_hotspot_regions WHERE spr_id = $spr_id");
+
+ if($row['tip'] == 1 || $row['tip'] == 2){
+ $enota_orientation = $row['orientation'];
+ }
+ else if($row['tip'] == 6){
+ $enota_orientation = $row['enota'];
+ }
+ else if($row['tip'] == 17){
+ $enota_orientation = $row['design'];
+ }
+ ?>
+ <script>
+ $(document).ready(function(){
+ //show_hot_spot_settings (<?=$row['id']?>, <?=$row['enota']?>, <?=$row['tip']?>, '<?=$hotspot_image?>');
+ show_hot_spot_settings (<?=$row['id']?>, <?=$enota_orientation?>, <?=$row['tip']?>, '<?=$hotspot_image?>');
+ //init_colorPicker(<?=$row['id']?>, 'region'); //init za region
+ //init_colorPicker(<?=$row['id']?>, 'visibility'); //init za visibility
+ init_colorPicker(<?=$row['id']?>);
+ });
+ </script>
+
+ <?
+
+ $display_regions_menu = ( ($row['tip'] == 6 && $row['enota'] == 10) || ($row['tip'] == 1 && $row['orientation'] == 10) || ($row['tip'] == 17 && $row['design'] == 3) ) ? '' : 'style="display:none;"';
+
+ if($row['tip'] == 6 || $row['tip'] == 17){ //ce je radio grid ali razvrscanje, pokazi naslov kot "Obmocja"
+ echo '<fieldset id="hot_spot_fieldset_'.$row['id'].'" '.$display_regions_menu.'><legend>'.$lang['srv_hot_spot_regions_menu'].'</legend>';
+ }
+ elseif($row['tip'] == 1 || $row['tip'] == 2){ //ce je radio ali checkbox, pokazi naslov kot "Obmocja - Kategorije odgovorov"
+ echo '<fieldset id="hot_spot_fieldset_'.$row['id'].'" '.$display_regions_menu.'><legend>'.$lang['srv_hot_spot_regions_menu'].' - '.$lang['srv_kategorije_odgovorov'].'</legend>';
+ }
+
+ //Sporocilo ob odsotnosti slike
+ echo '<p id="hotspot_message"><span class="title" >'.$lang['srv_hotspot_message'].'</span></p>';
+
+ if (mysqli_num_rows($sqlR) != 0){
+ //pokazi shranjena obmocja
+ while ($rowR = mysqli_fetch_array($sqlR)) {
+ echo '<div id="hotspot_region_'.$rowR['region_index'].'" class="hotspot_region"><div id="hotspot_region_name_'.$rowR['region_index'].'" vre_id="'.$rowR['vre_id'].'" region_index = "'.$rowR['region_index'].'" class="hotspot_vrednost_inline" contenteditable="true">'.$rowR['region_name'].'</div><span class="faicon edit2 inline_hotspot_edit_region"></span><span class="faicon delete_circle icon-orange_link inline_hotspot_delete_region"></span><br /></div>';
+ }
+ }
+
+
+ //Dodajanje območja - gumb
+ echo '<p><span class="title" ><button id="hot_spot_regions_add_button" type="button" onclick=" hotspot_edit_regions('.$row['id'].', 0)">'.$lang['srv_hot_spot_regions'].'</button></span></p>';
+
+ //Izbira barve izbranega obmocja
+ //if($row['tip'] != 6) //ce ni grid, torej radio ali checkbox dodaj nastavitev za barvo izbranega obmocja
+ if($row['tip'] != 6 && $row['tip'] != 17) //ce ni grid in ni razvrscanje, torej radio ali checkbox dodaj nastavitev za barvo izbranega obmocja
+ {
+ if ($hotspot_region_color == '') {
+ $value = '#000000';
+ //echo '<span class="title">'.$lang['srv_hotspot_region_color_text'].': <a href="#" onclick="$(\'#color-region-'.$row['id'].'\').show(); $(this).parent().hide(); return false;" title="'.$lang['edit4'].'">'.$lang['srv_te_default'].' <span class="sprites edit"></span></a></span>';
+ echo '<span class="title">'.$lang['srv_hotspot_region_color_text'].':<span id="help_hotspot_region_color" class="spaceLeft">'.Help::display('srv_hotspot_region_color').' </span> <a href="#" onclick="$(\'#color-region-'.$row['id'].'\').show(); $(this).parent().hide(); return false;" title="'.$lang['edit4'].'">'.$lang['srv_te_default'].' <span class="faicon edit"></span></a></span>';
+ }else{
+ $value = $hotspot_region_color;
+ }
+
+ echo '<span class="title" id="color-region-'.$row['id'].'" '.($hotspot_region_color==''?'style="display:none;"':'').'>'.$lang['srv_hotspot_region_color_text'].': <span id="help_hotspot_region_color" class="spaceLeft">'.Help::display('srv_hotspot_region_color').' </span>';
+ echo '<input type="text" id="color-region'.$row['id'].'" class="colorwell auto-save" name="hotspot_region_color" value="'.$value.'" data-id="'.$row['id'].'" data-type="'.$type.'" >';
+ echo '</span>';
+
+ //echo '<div id="picker"></div>';
+ }
+ //Izbira barve izbranega obmocja - konec
+
+ //Regions visibility options **********************************************
+
+ //checkbox za "Osvetljevanje"
+ echo '<label for="hotspot_region_visibility_options_' . $row['id'] . '"><div class="hotspot_region_visibility_option_class">';
+ //echo '<div class="hotspot_region_visibility_option_class">';
+ echo '<p><span class="title" >'.$lang['srv_hotspot_visibility_options_title'].':<span id="help_hotspot_visibility" class="spaceLeft">'.Help::display('srv_hotspot_visibility').' </span></span>'; //vprasajcek za help ob osvetilitvi
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="hotspot_region_visibility_option" '.( $hotspot_region_visibility_option == 1 ? ' checked="checked"' : '') .' onChange="hotspot_region_visibility_option_checkbox_prop('.$row['id'].');" id="hotspot_region_visibility_options_' . $row['id'] . '">';
+ echo '<input '.$disable_hotspot_region_visibility_option_hidden.' type="hidden" value="0" name="hotspot_region_visibility_option" id="hotspot_region_visibility_option_'.$row['id'].'">';
+ echo '</span></p>';
+ echo '</div></label>';
+ //echo '</div>';
+ //checkbox za "Osvetljevanje" - konec
+
+ //radio za nastavitve osvetljevanja (vedno, ob mouseover)
+ echo '<p id="hotspot_region_visibility_'.$row['id'].'" '.$hotspot_visibility_display.'>';
+ echo '<input type="radio" name="hotspot_region_visibility" id="hotspot_region_visibility_0" value="1" '.(($hotspot_region_visibility == 1 || $hotspot_region_visibility == -1) ? ' checked="checked" ' : '').' onClick="" /><label for="hotspot_region_visibility_0" class="spaceRight">'.$lang['srv_hotspot_visibility_options_4'].'</label>';
+ echo '<input type="radio" name="hotspot_region_visibility" id="hotspot_region_visibility_1" value="2" '.(($hotspot_region_visibility == 2) ? ' checked="checked" ' : '').' onClick="" /><label for="hotspot_region_visibility_1">'.$lang['srv_hotspot_visibility_options_5'].'</label>';
+ //echo '</p>';
+ //radio za nastavitve osvetljevanja (vedno, ob mouseover) - konec
+
+ //Izbira barve osvetljevanja obmocja
+ if ($hotspot_visibility_color == '') {
+ $value = '#000000';
+ echo '<br /><span class="title">'.$lang['srv_hotspot_visibility_color_text'].': <span id="help_hotspot_visibility_color" class="spaceLeft">'.Help::display('srv_hotspot_visibility_color').' </span> <a href="#" onclick="$(\'#color-visibility-'.$row['id'].'\').show(); $(this).parent().hide(); return false;" title="'.$lang['edit4'].'">'.$lang['srv_te_default'].' <span class="faicon edit"></span></a></span>';
+ }else{
+ $value = $hotspot_visibility_color;
+ }
+
+ echo '<br /><span class="title" id="color-visibility-'.$row['id'].'" '.($hotspot_visibility_color==''?'style="display:none;"':'').'>'.$lang['srv_hotspot_visibility_color_text'].': <span id="help_hotspot_visibility_color" class="spaceLeft">'.Help::display('srv_hotspot_visibility_color').' </span>';
+ echo '<input type="text" id="color-visibility'.$row['id'].'" class="colorwell auto-save" name="hotspot_visibility_color" value="'.$value.'" data-id="'.$row['id'].'" data-type="'.$type.'" >';
+ echo '</span>';
+
+ echo '<div id="picker"></div>';
+ //Izbira barve osvetljevanja obmocja - konec
+
+ echo '</p>';
+
+ //Regions visibility options - konec ****************************************************************
+
+ //Tooltips options
+ if($row['tip'] == 1 || $row['tip'] == 2){ //ce je radio ali checkbox
+ $srv_hotspot_tooltip = 'srv_hotspot_tooltip';
+ }
+ else if($row['tip'] == 6 ||$row['tip'] == 17){
+ $srv_hotspot_tooltip = 'srv_hotspot_tooltip_grid';
+ }
+
+ echo '<p><span class="title">'.$lang['srv_hotspot_tooltips_options_title'].':<span id="help_hotspot_namig" class="spaceLeft">'.Help::display($srv_hotspot_tooltip).' </span></span>';
+ echo '<span class="title"><select id="hotspot_tooltips_options_' . $row['id'] . '" spr_id="'.$row['id'].'" name="hotspot_tooltips_option" onChange="">';
+ echo '<option value="0" '.(($hotspot_tooltips_option == 0) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_tooltips_options_0'].'</option>';
+ if($row['tip'] == 1 || $row['tip'] == 2){ //ce je radio ali checkbox
+ echo '<option value="1" '.(($hotspot_tooltips_option == 1) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_tooltips_options_1'].'</option>';
+ }
+ //if($row['tip'] == 6){ //ce je radio grid
+ if($row['tip'] == 6 ||$row['tip'] == 17){ //ce je radio grid ali razvrscanje
+ echo '<option value="2" '.(($hotspot_tooltips_option == 2) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_tooltips_options_2'].'</option>';
+ }
+
+ echo '</select>';
+ echo '</span></p>';
+
+ echo '</fieldset>';
+ }
+
+ function edit_orientation() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ if($row['signature'] != 1){ //ce ni elektronski podpis
+ $displayOrientation = 'display: block';
+ }else{
+ $displayOrientation = 'display: none';
+ }
+ //echo '<p>';
+ echo '<p id="orientation_'.$this->spremenljivka.'" style="'.$displayOrientation.' ">';
+ echo '<span class="title" >'.$lang['srv_orientacija'].': </span>';
+
+ //echo (int)$row['orientation'];
+ echo '<span class="content"><select name="orientation" id="spremenljivka_orientation_' . $row['id'] . '" spr_id="'.$row['id'].'">';
+
+ echo '<option value="1"' . (($row['orientation'] == 1 || $row['orientation'] == 2) ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_horizontalna_2'].'</option>';
+ //echo '<option value="1"' . ($row['orientation'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_vertikalna'].'</option>';
+ echo '<option value="0"' . ($row['orientation'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_horizontalna'].'</option>';
+ if($row['tip'] == 21)
+ echo '<option value="3"' . (($row['orientation'] == 3 || $row['orientation'] == 3) ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_vertikalna'].'</option>';
+
+ echo '</select></span>';
+
+ echo '</p>';
+ }
+
+
+ function edit_date_range() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $newParams = new enkaParameters($row['params']);
+ $min = $newParams->get('date_range_min');
+ $max = $newParams->get('date_range_max');
+
+ echo '<p>';
+ echo '<span class="title" >'.$lang['srv_vprasanje_date_range_min'].': </span>'.Help::display('edit_date_range');
+ echo '<span class="content">';
+ echo '<input type="number" value="'.$min.'" name="date_range_min" id="date_range_min_' . $row['id'] . '" spr_id="'.$row['id'].'" size="4" style="margin-top:-12px;" />';
+ echo '</span>';
+ echo '</p>';
+
+ echo '<p>';
+ echo '<span class="title" >'.$lang['srv_vprasanje_date_range_max'].': </span>'.Help::display('edit_date_range');
+ echo '<span class="content">';
+ echo '<input type="number" min="0" value="'.$max.'" name="date_range_max" id="date_range_max_' . $row['id'] . '" spr_id="'.$row['id'].'" size="4" style="margin-top:-12px;" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+ function edit_date_withTime() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $newParams = new enkaParameters($row['params']);
+ $withTime = $newParams->get('date_withTime');
+
+ echo '<p>';
+ echo '<span class="title"><label for="date_withTime_' . $row['id'] . '">'.$lang['srv_vprasanje_date_withTime'].'</label>: </span>';
+ echo '<span class="content"><input type="hidden" name="date_withTime" value="0">';
+ echo '<input type="checkbox" value="1" '.(($withTime == 1) ? 'checked' : '').' name="date_withTime" id="date_withTime_' . $row['id'] . '" spr_id="'.$row['id'].'" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+
+ /**
+ * Tip multilokacija
+ *
+ * Doloci najvisjo stevilo dovoljenih vnosov - markerjev
+ * @global type $lang
+ */
+ function st_markerjev() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+
+ //$min = $newParams->get('date_range_min');
+ $max = $newParams->get('max_markers') ? $newParams->get('max_markers') : 1;
+ $input = $newParams->get('multi_input_type') ? $newParams->get('multi_input_type') : 'marker';
+
+ echo '<p id="max_markers_map" '. (($row['enota'] == 2 && $input =='marker') ? '' : 'style="display: none;"').'>';
+ echo '<span class="title">'.$lang['srv_vprasanje_max_marker_map'].': '.Help::display('srv_vprasanje_max_marker_map').'</span>';
+ echo '<span class="content">';
+
+ //roleta
+ echo '<select name="max_markers" id="max_markers_' . $row['id'] . '" spr_id="'.$row['id'].'">';
+ echo '<option value="1" '.(($max == 1) ? ' selected="true" ' : '').'>1</option>';
+ echo '<option value="2" '.(($max == 2) ? ' selected="true" ' : '').'>2</option>';
+ echo '<option value="3" '.(($max == 3) ? ' selected="true" ' : '').'>3</option>';
+ echo '<option value="4" '.(($max == 4) ? ' selected="true" ' : '').'>4</option>';
+ echo '<option value="5" '.(($max == 5) ? ' selected="true" ' : '').'>5</option>';
+ echo '<option value="6" '.(($max == 6) ? ' selected="true" ' : '').'>6</option>';
+ echo '<option value="7" '.(($max == 7) ? ' selected="true" ' : '').'>7</option>';
+ echo '<option value="8" '.(($max == 8) ? ' selected="true" ' : '').'>8</option>';
+ echo '<option value="9" '.(($max == 9) ? ' selected="true" ' : '').'>9</option>';
+ echo '<option value="10" '.(($max == 10) ? ' selected="true" ' : '').'>10</option>';
+
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ /**
+ * vrstica za fokusiranje mape (text kraja, lokacije)
+ */
+ function fokus_mape() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+ $fokus = $newParams->get('fokus_mape'); //dobi fokus mape
+
+ echo '<p id="fokus_mape" '.($row['enota'] == 3 ? 'style="display: none;"' : '').'>';
+ echo '<span class="title" >'.$lang['srv_vprasanje_fokus_map'].': </span>';
+ echo '<span class="content">';
+ echo '<input type="text" value="'.$fokus.'" name="fokus_mape" id="fokus_mape_' . $row['id'] . '" spr_id="'.$row['id'].'" size="20" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+ /**
+ * vrstica za naslov podvprasanja v oblacek markerja
+ */
+ function naslov_podvprasanja_map() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+
+ $naslov = $newParams->get('naslov_podvprasanja_map'); //dobi naslov podvprasanja mape
+ $marpod = $newParams->get('marker_podvprasanje'); //ali dodam podvprasanje v infowindow
+
+ echo '<p id="naslov_podvprasanja_map" '.(($marpod == 1 || $row['enota'] == 3) ? '' : 'style="display: none;"').'>';
+ echo '<span class="title" >'.$lang['srv_vprasanje_naslov_podvprasanja_map'].': '.Help::display('naslov_podvprasanja_map').'</span>';
+ echo '<span class="content">';
+ echo '<input type="text" value="'.$naslov.'" name="naslov_podvprasanja_map" id="naslov_podvprasanja_map_' . $row['id'] . '" spr_id="'.$row['id'].'" size="25" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+ /**
+ * vrstica za poizvedovanje trenutne lokacije
+ */
+ function userLocation() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+ $usrloc = $newParams->get('user_location'); //ali se poizve trenutna lokacija
+ $input = $newParams->get('multi_input_type') ? $newParams->get('multi_input_type') : 'marker';
+
+ echo '<p id="user_location_map" '. ((($row['enota'] == 2 && $input !== 'marker') || $row['enota'] == 3) ? 'style="display: none;"' : '').'>';
+ echo '<label for="user_location_' . $row['id'] . '" class="title">'.$lang['srv_vprasanje_user_location_map'].': '.Help::display('user_location_map').'</label>';
+ echo '<span class="content"><input type="hidden" name="user_location" value="0">';
+ echo '<input type="checkbox" value="1" '.(($usrloc == 1) ? 'checked' : '').' name="user_location" id="user_location_' . $row['id'] . '" spr_id="'.$row['id'].'" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+ /**
+ * vrstica za podvprasanje v markerju - infowindow
+ */
+ function markerPodvprasanje() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+ $marpod = $newParams->get('marker_podvprasanje'); //ali dodam podvprasanje v infowindow
+ $input = $newParams->get('multi_input_type') ? $newParams->get('multi_input_type') : 'marker';
+
+ echo '<p id="marker_podvprasanje" '. ((($row['enota'] == 3) || $input !== 'marker') ? 'style="display: none;"' : '').' >';
+ echo '<label for="marker_podvprasanje_' . $row['id'] . '" class="title">'.$lang['srv_vprasanje_marker_podvpr_map'].': '.Help::display('marker_podvprasanje').'</label>';
+
+ echo '<span class="content"><input type="hidden" name="marker_podvprasanje" value="0">';
+ echo '<input type="checkbox" value="1" '.(($marpod == 1) ? 'checked' : '' ). ' onChange="show_infowindow_map();"'.
+ ' name="marker_podvprasanje" id="marker_podvprasanje_' . $row['id'] . '" spr_id="'.$row['id'].'" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+ /**
+ * vrstica za podvprasanje v markerju - infowindow
+ */
+ function dodaj_SearchBox() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+ $marpod = $newParams->get('dodaj_searchbox'); //ali dodam podvprasanje v infowindow
+ $input = $newParams->get('multi_input_type') ? $newParams->get('multi_input_type') : 'marker';
+
+ echo '<p id="dodaj_searchbox" '.($row['enota'] == 3 || $input != 'marker' ? 'style="display: none;"' : '').'>';
+ echo '<label for="dodaj_searchbox_' . $row['id'] . '" class="title">'.$lang['srv_vprasanje_show_searchbox_map'].': '
+ .Help::display('dodaj_searchbox').'</label>';
+ echo '<span class="content"><input type="hidden" name="dodaj_searchbox" value="0">';
+ echo '<input type="checkbox" value="1" '.(($marpod == 1) ? 'checked' : '').
+ ' name="dodaj_searchbox" id="dodaj_searchbox_' . $row['id'] . '" spr_id="'.$row['id'].'" />';
+ echo '</span>';
+ echo '</p>';
+ }
+
+
+ /**
+ * napredno urejanje vprasanja
+ *
+ */
+ function vprasanje_napredno () {
+ global $lang;
+ global $global_user_id;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ //echo '<h2>'.$row['variable'].' - '.$lang['srv_napredno_urejanje'].'</h2>';
+ $this->variable();
+
+
+ // Spremenljivka
+ echo '<fieldset><legend>'.$lang['srv_spremenljivka'].'</legend>';
+ $this->edit_variable();
+ $this->edit_label();
+ echo '</fieldset>';
+
+
+ // Lastnosti
+ echo '<fieldset><legend>'.$lang['srv_lastnosti'].'</legend>';
+ $this->edit_sistem();
+
+ //echo '<p class="heading">'.$lang['srv_prikaz_vprasanja'].'</p>';
+ $this->edit_visible();
+
+ // Disabled vprasanje - vprasanje je onemogoceno za respondente (zaenkrat samo osnovni radio, dropdown in text)
+ if(in_array($row['tip'], array(1,3,4,21)))
+ $this->edit_disabled();
+
+ // Vprasanje lahko zaklene samo admin, manager ali avtor (drugace ga lahko zaklene sam sebi in potem ne more vec urejat)
+ $author = SurveyInfo::getInstance()->getSurveyColumn("insert_uid");
+ if($admin_type == 0 || $admin_type == 1 || $global_user_id == $author)
+ $this->edit_locked();
+
+ $this->edit_timer();
+
+ if ($row['tip'] <= 2 )
+ $this->edit_stolpci();
+
+ if($row['tip'] == 2) {
+ $this->edit_checkbox_max_limit();
+ $this->edit_checkbox_min_limit();
+ }
+
+ if($row['tip'] <= 3)
+ $this->edit_stat();
+
+ if ($row['tip'] == 6)
+ $this->edit_grid_dynamic();
+
+ if ($row['tip'] == 1 || $row['tip'] == 6) {
+ $this->edit_onchange_submit();
+ }
+
+ if ($row['tip'] == 1 || $row['tip'] == 3)
+ $this->edit_inline_edit();
+
+ if ($row['tip'] != 5)
+ $this->edit_showOnAllPages();
+
+ if ($row['tip'] == 1 || $row['tip'] == 2 && (in_array($row['orientation'], array(0,1,2))))
+ $this->edit_hideRadio();
+
+ if($row['tip'] == 1 || $row['tip'] == 2 || $row['tip'] == 6)
+ $this->edit_presetValue();
+
+ // Nastavitev za prikaz prejsnjih odgovorov pod text vprasanjem
+ if ($row['tip'] == 21)
+ $this->edit_show_prevAnswers();
+
+ echo '</fieldset>';
+
+ // Posebni tipi text vprasanja (signature, captcha, upload, email)
+ if ($row['tip'] == 21){
+ echo '<fieldset><legend>'.$lang['srv_advanced_subtype'].'</legend>';
+
+ $this->edit_upload();
+ $this->edit_signature();
+ $this->edit_captcha();
+ $this->edit_email_verify();
+
+ echo '</fieldset>';
+ }
+ }
+
+ /**
+ * poskrbi za prikaz pogojev v vprasanju
+ *
+ */
+ function vprasanje_pogoji () {
+ global $lang;
+ global $global_user_id;
+
+ $b = new Branching($this->anketa);
+
+ $rows = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $this->variable();
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+ if(!$userAccess->checkUserAccess($what='if')){
+
+ $userAccess->displayNoAccess($what='if');
+ return;
+ }
+
+ $sql = sisplet_query("SELECT parent FROM srv_branching WHERE element_spr = '$this->spremenljivka'");
+ $row = mysqli_fetch_array($sql);
+
+ if ($row['parent'] > 0) {
+ $sql1 = sisplet_query("SELECT COUNT(*) AS count FROM srv_branching WHERE parent = '$row[parent]'");
+ $row1 = mysqli_fetch_array($sql1);
+ $count = $row1['count'];
+ } else $count = 0;
+
+ // $count pove koliko elementov je v parent ifu
+ if ($row['parent'] == 0 || $count > 1) {
+
+ // naredimo isto kot s klikom na ikono IF na vprasanju
+ $r['spr'] = $this->spremenljivka;
+ $r['if'] = 0;
+ $r['endif'] = 1;
+
+ echo '<p id="if_preview">'.$lang['srv_question_no_if'].'</p>';
+
+ echo '<p id="if_preview_link"><a href="#" onclick="if_new(\''.$r['spr'].'\', \''.$r['if'].'\', \''.$r['endif'].'\', \'0\'); return false;"><span class="bold">'.$lang['srv_add_condition_question'].'</span></a></p>';
+
+ if ($count > 1) {
+ $parents = $b->get_parents($this->spremenljivka);
+ if ($parents != '') {
+ echo '<p><b>'.$lang['srv_question_no_if_in_nested_if'].':</b> ';
+ $parents = explode(' ', $parents);
+ foreach ($parents AS $p) {
+ $p = str_replace('p_', '', $p);
+ echo '<br />';
+ $b->conditions_display($p);
+ }
+ echo '</p>';
+ }
+ }
+
+ } else {
+
+ //echo '<h2>'.$rows['variable'].' - '.$lang['srv_edit_condition_question'].'</h2>';
+
+ echo '<p id="if_preview">';
+
+ $b->conditions_display($row['parent']);
+ echo '</p>';
+
+ echo '<p><a href="#" onclick="condition_editing(\''.$row['parent'].'\'); return false;">'.$lang['srv_if_edit'].'</a></p>';
+
+ if ($row['parent'] != 0) {
+
+ $parents = $b->get_parents(0, $row['parent']);
+ if ($parents != '') {
+ echo '<p><b>'.$lang['srv_question_in_if_in_nested_if'].':</b> ';
+ $parents = explode(' ', $parents);
+ foreach ($parents AS $p) {
+ $p = str_replace('p_', '', $p);
+ echo '<br />';
+ $b->conditions_display($p);
+ }
+ echo '</p>';
+ }
+ }
+
+ }
+ }
+
+ /**
+ * prikaze opcije za validacijo
+ *
+ */
+ function vprasanje_validation () {
+ global $lang;
+ global $global_user_id;
+
+ $rows = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $this->variable();
+
+ $sql = sisplet_query("SELECT if_id, reminder, reminder_text FROM srv_validation v WHERE v.spr_id='$this->spremenljivka'");
+ if (mysqli_num_rows($sql) > 0) {
+
+ echo '<input type="hidden" value="1" name="validationedit">';
+
+ $b = new Branching($this->anketa);
+
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<fieldset>';
+ echo '<p><a href="#" onclick="validation_edit(\''.$this->spremenljivka.'\', \''.$row['if_id'].'\'); return false;" title="'.$lang['srv_if_edit'].'">';
+ $b->conditions_display($row['if_id']);
+ echo '</a></p>';
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_alert_type'].':</span>';
+
+ echo '<span class="content">';
+ echo '<select name="validation-'.$row['if_id'].'-reminder">';
+ echo '<option value="0" '.($row['reminder']==0?'selected':'').'>'.$lang['srv_reminder_off2'].'</option>';
+ echo '<option value="1" '.($row['reminder']==1?'selected':'').'>'.$lang['srv_reminder_soft2'].'</option>';
+ echo '<option value="2" '.($row['reminder']==2?'selected':'').'>'.$lang['srv_reminder_hard2'].'</option>';
+ echo '</select>';
+ echo '</span>';
+
+ echo '</p>';
+ echo '<p><span class="title">'.$lang['srv_alert_text'].':</span>';
+
+ echo '<span class="content"><input type="text" name="validation-'.$row['if_id'].'-reminder_text" value="'.$row['reminder_text'].'"></span>';
+
+ echo '</p>';
+
+ echo '<p class="floatLeft spaceRight bold"><a href="#" onclick="validation_if_remove(\''.$this->spremenljivka.'\', \''.$row['if_id'].'\'); return false;">'.$lang['srv_validation_remove'].'</a></p>';
+
+ echo '</fieldset>';
+ }
+
+ } else {
+ echo '<p>'.$lang['srv_validation_no'].'</p>';
+ }
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik - drugace skrijemo gumb za dodajanje validacije
+ $userAccess = UserAccess::getInstance($global_user_id);
+ if(!$userAccess->checkUserAccess($what='validation')){
+ $userAccess->displayNoAccess($what='validation');
+ }
+ else{
+ echo '<p><a href="#" onclick="validation_new(\''.$this->spremenljivka.'\'); return false;"><span class="bold">'.$lang['srv_validation_new'].'</span></a></p>';
+ }
+ }
+
+ /**
+ * prikaze komentarje na vprasanje
+ *
+ */
+ function vprasanje_komentarji () {
+ global $lang;
+ global $admin_type;
+ global $global_user_id;
+
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+
+ if ($this->spremenljivka > 0) {
+ $rows = Cache::srv_spremenljivka($this->spremenljivka);
+ $this->variable();
+ }
+ else {
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ if ($this->spremenljivka == -1) {
+ $rows['variable'] = $lang['srv_intro_label'];
+ $rows['note'] = $row['intro_note'];
+ $rows['thread'] = $row['thread_intro'];
+
+ echo '<h2>'.$rows['variable'].'</h2>';
+ }
+ elseif ($this->spremenljivka == -2) {
+ $rows['variable'] = $lang['srv_end_label'];
+ $rows['note'] = $row['concl_note'];
+ $rows['thread'] = $row['thread_concl'];
+
+ echo '<h2>'.$rows['variable'].'</h2>';
+ }
+ }
+
+
+ $question_note_view = SurveySetting::getInstance()->getSurveyMiscSetting('question_note_view');
+ $question_note_write = SurveySetting::getInstance()->getSurveyMiscSetting('question_note_write');
+
+ if ($question_note_view == '' || $question_note_view >= $admin_type) {
+
+ if ($question_note_write == '' || $question_note_write >= $admin_type) {
+ echo '<p>'.$lang['srv_note'];
+ //echo '<span class="red pointer" onclick="this.style.display=\'none\'; create_editor(\'note\');"> - '.$lang['srv_editor'].'</span>';
+ echo '<a href="#" title="'.$lang['srv_editor_title'].'" onmouseover="this.style.display=\'none\'; create_editor(\'note\');"><span class="faicon edit spaceLeft"></span></a>';
+ echo '<textarea name="note" id="note" style="width:99%; height:150px">'.$rows['note'].'</textarea></p>';
+ } else {
+ echo '<p>'.$lang['srv_note'].'';
+ echo '<textarea name="note" id="note" style="width:99%; height:150px" disabled>'.$rows['note'].'</textarea></p>';
+ }
+ }
+
+ // tukaj prikazujemo samo se opombo
+ return;
+
+ $question_comment = SurveySetting::getInstance()->getSurveyMiscSetting('question_comment');
+ //$question_comment = 4; // vedno prikazemo
+ $question_resp_comment = SurveySetting::getInstance()->getSurveyMiscSetting('question_resp_comment');
+ $question_resp_comment_viewadminonly = SurveySetting::getInstance()->getSurveyMiscSetting('question_resp_comment_viewadminonly');
+ $question_comment_viewadminonly = SurveySetting::getInstance()->getSurveyMiscSetting('question_comment_viewadminonly');
+ $question_comment_viewauthor = SurveySetting::getInstance()->getSurveyMiscSetting('question_comment_viewauthor');
+ $sortpostorder = SurveySetting::getInstance()->getSurveyMiscSetting('sortpostorder');
+ $addfieldposition = SurveySetting::getInstance()->getSurveyMiscSetting('addfieldposition');
+
+ if (($admin_type <= $question_comment && $question_comment != '') || $question_resp_comment==1) {
+
+ $f = new Forum;
+
+ $spremenljivka = $this->spremenljivka;
+ $type = 1;
+ $view = 3;
+
+ echo '<div id="survey_comment_'.$spremenljivka.'_'.$view.'">';
+ echo '<div style="width:45%; float:left">';
+ echo '<h3 class="red"><b>'.$lang['comments'].'</b>';
+ echo '<span class="sprites '.($sortpostorder==1?'up':'down').'" style="float:right" title="'.($sortpostorder==1?$lang['forum_desc']:$lang['forum_asc']).'"></span>';
+ echo '</h3>';
+
+ if ($addfieldposition == 1) {
+ $b = new BranchingAjax($this->anketa);
+ $b->add_comment_field($spremenljivka, $type, $view, false);
+ echo '<br /><br />';
+ }
+
+ // komentarji na vprašanje
+ if ($rows['thread'] > 0) {
+
+ $tid = $rows['thread'];
+
+ $orderby = $sortpostorder == 1 ? 'DESC' : 'ASC' ;
+
+ if ($admin_type <= $question_comment_viewadminonly) { // vidi vse komentarje
+ $sql = sisplet_query("SELECT * FROM post WHERE tid='$tid' ORDER BY time $orderby, id $orderby");
+ } elseif ($question_comment_viewauthor == 1) { // vidi samo svoje komentarje
+ $sql = sisplet_query("SELECT * FROM post WHERE tid='$tid' AND uid='$global_user_id' ORDER BY time $orderby, id $orderby");
+ } else { // ne vidi nobenih komentarjev
+ $sql = sisplet_query("SELECT * FROM post WHERE 1=0");
+ }
+
+ if (mysqli_num_rows($sql) > 0) {
+ $i = 0;
+ while ($row = mysqli_fetch_array($sql)) {
+ if (($i != 0 && $sortpostorder==0) || ($i < $rowss-1 && $sortpostorder==1)) {
+ if ($row['ocena'] == 0) echo '<span style="color:black">';
+ elseif ($row['ocena'] == 1) echo '<span style="color:darkgreen">';
+ elseif ($row['ocena'] == 2) echo '<span style="color:lightgray">';
+ elseif ($row['ocena'] == 3) echo '<span style="color:lightgray">';
+ else echo '<span>';
+
+ echo '<b>'.$f->user($row['uid']).'</b> ('.$f->datetime1($row['time']).'):';
+ echo '<br/>'.$row['vsebina'].'<hr>';
+
+ echo '</span>';
+ }
+ $i++;
+ }
+ }
+
+ }
+
+ if ($addfieldposition == '' || $addfieldposition == 0) {
+ $b = new BranchingAjax($this->anketa);
+ $b->add_comment_field($spremenljivka, $type, $view, false);
+ }
+
+ echo '</div>';
+ echo '</div>';
+
+ if ($admin_type <= $question_resp_comment_viewadminonly) {
+ $sql = sisplet_query("SELECT d.*, u.time_edit FROM srv_data_text".$this->db_table." d, srv_user u WHERE d.spr_id='0' AND d.vre_id='$this->spremenljivka' AND u.id=d.usr_id ORDER BY d.id ASC");
+
+ // komentarji respondentov
+ $sql = sisplet_query("SELECT d.*, u.time_edit FROM srv_data_text".$this->db_table." d, srv_user u WHERE d.spr_id='0' AND d.vre_id='$this->spremenljivka' AND u.id=d.usr_id ORDER BY d.id ASC");
+ if (mysqli_num_rows($sql) > 0) {
+
+ echo '<div style="width:45%; float:right">';
+ echo '<h3 class="red"><b>'.$lang['srv_repondent_comment'].'</b></h3>';
+
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['text2'] == 0) echo '<span style="color:black">';
+ elseif ($row['text2'] == 1) echo '<span style="color:darkgreen">';
+ elseif ($row['text2'] == 2) echo '<span style="color:lightgray">';
+ elseif ($row['text2'] == 3) echo '<span style="color:lightgray">';
+ else echo '<span>';
+
+ echo $f->datetime1($row['time_edit']).':<br />'.$row['text'].'<hr>';
+
+ echo '</span>';
+ }
+
+ echo '</div>';
+
+ }
+ }
+ }
+ }
+
+ /**
+ * urejanje label za manjkajoče vrednosti za vprašanje
+ *
+ */
+ function vprasanje_manjkajoce () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $vmv = new RecodeValues($this->anketa,$this->spremenljivka);
+
+ $this->variable();
+
+ echo '<span id="vprasanje_edit_mv">';
+ echo $vmv->DisplayMissingValuesForQuestion();
+ echo '</span>';
+ }
+
+
+
+ /**
+ * urejanje label za grafe
+ *
+ */
+ /*function vprasanje_grafi () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ //echo '<h2>'.$row['variable'].' - '.$lang['srv_grafi_urejanje'].'</h2>';
+ $this->variable();
+
+ // Enable/disable editiranje label posebej za grafe
+ $this->edit_graf();
+
+ // Gumb za kopiranje besedila iz osnovnega urejanja
+ echo '<div class="chart_copy" '.($row['edit_graf'] == 0 ? ' style="display: none;"' : '').'><p>';
+ echo $lang['srv_edit_chart_copy'].': ';
+ echo '<input type="button" name="copy_graf" value="'.$lang['srv_edit_chart_copyB'].'" onClick="copy_chart();" />';
+
+ //echo '<a class="ovalbutton ovalbutton_gray" onclick="copy_chart();" href="#">
+ // <span>'.$lang['srv_edit_chart_copyB'].'</span>
+ // </a>';
+
+ echo '</p></div>';
+
+ $show = ($row['edit_graf'] == 0) ? ' style="display:none;"' : '';
+
+ echo '<div class="chart_editing" '.$show.'>';
+
+ // Urejanje naslova spremenljivke
+ $text = $row['naslov_graf'] == '<p></p>' ? $row['naslov'] : $row['naslov_graf'];
+ if (strtolower(substr($text, 0, 3)) == '<p>' && strtolower(substr($text, -4)) == '</p>' && strrpos($text, '<p>') == 0) {
+ $text = substr($text, 3);
+ $text = substr($text, 0, -4);
+ }
+ echo '<p>';
+ echo '<textarea style="width:99%; height:60px;" name="naslov_graf" id="naslov_graf" class="chart_label">'.$text.'</textarea>';
+ echo '</p>';
+
+ // Urejanje naslovov variabel
+ $sql1 = sisplet_query("SELECT id, naslov, naslov_graf, variable, other FROM srv_vrednost WHERE spr_id = '$this->spremenljivka' ORDER BY vrstni_red ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo '<input type="hidden" name="edit_vrednost_graf" value="1" />';
+
+ echo '<div id="vrednosti_holder"><ul class="vrednost_sort">';
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ $text = $row1['naslov_graf'] == '' ? $row1['naslov'] : $row1['naslov_graf'];
+
+ echo '<li id="vrednost_'.$vrednost.'" '.($row1['other'] == 1 ? 'class="li_other"' : '').'>';
+
+ $gridWidth = 42;
+
+ echo '<textarea name="vrednost_graf_'.$row1['id'].'" id="'.$row1['variable'].'_graf" class="vrednost_textarea chart_label" style="width:'.$gridWidth.'%;">'.$text.'</textarea> ';
+ echo '['.$row1['variable'].']</span>';
+ if ($row1['other'] == 1) echo ' <input type="text" disabled style="width:40px" />';
+
+ echo '</li>';
+ }
+
+ echo '</ul>';
+
+ echo '</div>';
+
+
+ // Urejanje label za gride
+ //if($row['tip'] == 6 || $row['tip'] == 16 || $row['tip'] == 19 || $row['tip'] == 20){
+ if($row['tip'] == 6 || $row['tip'] == 16 || $row['tip'] == 19 || $row['tip'] == 20 || $row['tip'] == 2){
+
+ echo '<div class="grid_settings">';
+ echo '<input type="hidden" name="edit_grid_graf" value="1" />';
+
+ echo '<table id="grids" style="width:100%">';
+
+ echo '<tr>';
+ for ($i=1; $i<=$row['grids']; $i++) {
+ echo '<td>'.$i.'</td>';
+ }
+
+ //dodatne vrednosti (ne vem, zavrnil...)
+ if (count($already_set_mv) > 0 ) {
+ echo '<td></td>';
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ if (isset($already_set_mv[$mv_key])) {
+ echo '<td>'.$mv_key.'</td>';
+ }
+ }
+ }
+ }
+ echo '</tr>';
+
+ echo '<tr>';
+ for ($i=1; $i<=$row['grids']; $i++) {
+ $sql1 = sisplet_query("SELECT naslov, naslov_graf FROM srv_grid WHERE id='$i' AND spr_id='$this->spremenljivka'");
+ $row1 = mysqli_fetch_array($sql1);
+ $text = $row1['naslov_graf'] == '' ? $row1['naslov'] : $row1['naslov_graf'];
+ echo '<td><input type="text" name="grid_graf_'.$i.'" id="grid_naslov_'.$i.'_graf" class="chart_label" value="'.$text.'" /></td>';
+ }
+
+ //dodatne vrednosti (ne vem, zavrnil...)
+ if (count($already_set_mv) > 0 ) {
+ echo '<td></td>';
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ if (isset($already_set_mv[$mv_key])) {
+ echo '<td><input type="text" name="grid_'.$mv_key.'_graf" class="chart_label" value="'.$already_set_mv[$mv_key].'" /></td>';
+ }
+ }
+ }
+ }
+ echo '</tr>';
+
+ echo '</table>';
+ echo '</div>';
+ }
+
+ echo '</div>';
+
+
+ // sirina labele grafa (navadna ali 50%)
+ //$this->wide_graf();
+ }*/
+
+ /**
+ * prikaz trackinga sprememb spremenljivke
+ *
+ */
+ function vprasanje_display_tracking () {
+ global $lang;
+ global $admin_type;
+
+ $rows = SurveyInfo::getInstance()->getSurveyRow();
+ if ($rows['vprasanje_tracking'] == 0) return;
+
+ $row1 = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $this->variable();
+
+ $sql = sisplet_query("SELECT * FROM srv_spremenljivka_tracking s, users u WHERE s.spr_id='$this->spremenljivka' AND s.tracking_uid=u.id ORDER BY s.tracking_time DESC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ echo '<div class="pointer" onmouseover="show_tip_preview_toolbox(\'0\', \''.$row['tracking_id'].'\', \'1\');" onmouseout="$(\'#tip_preview\').hide();" copy="'.$row['tracking_id'].'"><p><span title="'.$row['email'].'">'.$row['name'].'</span> - '.datetime($row['tracking_time']).'</p></div>';
+ }
+ }
+
+ // ali urejamo labele za graf ali uporabimo default labele
+ function edit_graf() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo $lang['srv_edit_chart'].':<br /><br />';
+ echo '<input type="radio" name="edit_graf" value="0" '.(($row['edit_graf'] == 0) ? ' checked="checked" ' : '').' onClick="edit_chart(0);" />'.$lang['srv_edit_chart_0'].'<br />';
+ echo '<input type="radio" name="edit_graf" value="1" '.(($row['edit_graf'] == 1) ? ' checked="checked" ' : '').' onClick="edit_chart(1);" />'.$lang['srv_edit_chart_1'];
+ echo '</p>';
+ }
+
+ // sirina grafa - (navadna ali sirse labele -> 50%)
+ function wide_graf() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_wide_chart'].':</span>';
+ echo '<input type="radio" name="wide_graf" value="0" '.(($row['wide_graf'] == 0) ? ' checked="checked" ' : '').' />'.$lang['srv_wide_chart0'];
+ echo '<input type="radio" name="wide_graf" value="1" '.(($row['wide_graf'] == 1) ? ' checked="checked" ' : '').' />'.$lang['srv_wide_chart1'];
+ echo '</p>';
+ }
+
+
+ function edit_tip () {
+ global $lang;
+ global $admin_type;
+ global $global_user_id;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $sa = new SurveyAdmin();
+ $this->survey_type = $sa->getSurvey_type($this->anketa);
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+
+ // demografija ima svojo roleto
+ if (Demografija::getInstance()->isDemografija($row['variable'])) {
+
+ }
+ // obicna roleta za tip
+ else {
+
+ echo '<span class="content"><select name="tip" id="spremenljivka_tip_' . $row['id'] . '" size="1" spr_id="' . $row['id'] . '" onChange="change_tip(\'' . $row['id'] . '\', $(this).val());">';
+ echo '<option value="1"' . ($row['tip'] == 1 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_radio'] . '</option>';
+ echo '<option value="2"' . ($row['tip'] == 2 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_checkbox'] . '</option>';
+
+ if($this->survey_type != 0){
+
+ if ($row['tip'] == 3) // star tip, ostane samo za kompatibilnost, ce je kje ostal se star tip
+ //echo '<option value="3"' . ($row['tip'] == 3 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_dropdown'] . '</option>';
+ if ($row['info']){
+ echo '<option value="3"' . ($row['tip'] == 3 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_checkbox'] .'</option>';
+ }
+ else{
+ echo '<option value="3"' . ($row['tip'] == 3 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_radio'] .'</option>';
+ }
+
+ echo '<option value="6"' . ($row['tip'] == 6 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_multigrid'] . '</option>';
+ echo '<option value="16"' . ($row['tip'] == 16 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_multicheckbox'] . '</option>';
+ echo '<option value="19"' . ($row['tip'] == 19 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_multitext'] . '</option>';
+ echo '<option value="20"' . ($row['tip'] == 20 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_multinumber'] . '</option>';
+
+ if($userAccess->checkUserAccess($what='question_type_multitable'))
+ echo '<option value="24"' . ($row['tip'] == 24 ? ' selected="true"' : '') . '>' . $lang['srv_survey_table_multiple'] . '</option>';
+
+ echo '<option value="21"' . ($row['tip'] == 21 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_text'] . '</option>';
+
+ if ($row['tip'] == 4) // star tip, ostane samo za kompatibilnost, ce je kje ostal se star tip
+ echo '<option value="4"' . ($row['tip'] == 4 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_text'] . '</option>';
+
+ echo '<option value="7"' . ($row['tip'] == 7 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_number'] . '</option>';
+ echo '<option value="5"' . ($row['tip'] == 5 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_label'] . '</option>';
+
+ if($userAccess->checkUserAccess($what='question_type_location'))
+ echo '<option value="26"' . ($row['tip'] == 26 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_location'] . '</option>';
+
+ // heatmap - sedaj lahko vsi to uporabljajo
+ if($userAccess->checkUserAccess($what='question_type_heatmap'))
+ echo '<option value="27"' . ($row['tip'] == 27 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_heatmap'] . '</option>';
+
+ echo '<option value="8"' . ($row['tip'] == 8 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_datum'] . '</option>';
+
+ if($userAccess->checkUserAccess($what='question_type_ranking'))
+ echo '<option value="17"' . ($row['tip'] == 17 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_ranking'] . '</option>';
+
+ if($userAccess->checkUserAccess($what='question_type_sum'))
+ echo '<option value="18"' . ($row['tip'] == 18 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_vsota'] . '</option>';
+
+ if ($row['tip'] == 22) // star tip, ostane samo za kompatibilnost, ce je kje ostal se star tip
+ echo '<option value="22"' . ($row['tip'] == 22 ? ' selected="true"' : '') . '>' . $lang['srv_vprasanje_tip_22'] . '</option>';
+ }
+
+ if (SurveyInfo::getInstance()->checkSurveyModule('social_network')) {
+ echo '<option disabled="disabled">-------------------------------</option>';
+ echo '<option value="9"' . ($row['tip'] == 9 ? ' selected="true"' : '') . '>'.$lang['srv_vprasanje_tip_9'].'</option>';
+ }
+
+ echo '</select></span>';
+ //echo '</p>';
+
+
+ echo '<script type="text/javascript">';
+ echo '$(document).ready(function() { ';
+ echo '$("#spremenljivka_tip_' . $row['id'] . '").selectbox();'; // kreira custom dropdown z možnostjo predogleda vprašanja
+ echo '});';
+ echo '</script>';
+ }
+ }
+
+ /**
+ * urejanje tipa vprašanja
+ */
+ function edit_subtip () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $sa = new SurveyAdmin();
+ $this->survey_type = $sa->getSurvey_type($this->anketa);
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+
+ //editiranje podtipa pri radio (hor., ver., dropdown)
+ if($row['tip'] == 1 || ($row['tip'] == 3 && !$row['info'])){
+ $this->edit_radio_subtype();
+ }
+
+ //editiranje orientacije pri checkboxu (hor., ver.)
+ if($row['tip'] == 2 || ($row['tip'] == 3 && $row['info'])){
+ $this->edit_checkbox_subtype();
+ }
+
+ //editiranje podtipa pri razvrscanju (prestavljanje, ostevilcevanje...)
+ if($row['tip'] == 17){
+ $this->edit_ranking();
+ }
+
+ //editiranje podtipa pri multigridu (navadno, dropdown, sem.dif.)
+ if($row['tip'] == 6 || $row['tip'] == 16){
+ $this->edit_grid_subtype();
+ }
+
+ if ($row['tip'] == 7) {
+ $this->edit_subtype_number();
+ return;
+ }
+
+ if ($row['tip'] == 20) {
+ $this->edit_subtype_multinumber();
+ return;
+ }
+
+ if ($row['tip'] == 9) {
+ $this->edit_name_generator_design();
+ }
+
+ //podtip lokacija - moja lokacija
+ if ($row['tip'] == 26) {
+ $this->edit_subtype_map();
+ }
+
+ //podtip heatmap
+ if ($row['tip'] == 27) {
+ $this->edit_heatmap_settings();
+ }
+
+ echo '<script type="text/javascript">';
+ echo ' $(document).ready(function() {';
+ echo ' $("#spremenljivka_podtip_' . $row['id'] . '").selectbox();'; // kreira custom dropdown z možnostjo predogleda vprašanja
+ echo ' });';
+ echo '</script>';
+ }
+
+ /**
+ * urejanje naslova
+ *
+ */
+ function edit_naslov($editor = true) {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // ce je ena vrstica pobrisemo <p> in </p>
+ if (strtolower(substr($row['naslov'], 0, 3)) == '<p>' && strtolower(substr($row['naslov'], -4)) == '</p>' && strrpos($row['naslov'], '<p>') == 0) {
+ $row['naslov'] = substr($row['naslov'], 3);
+ $row['naslov'] = substr($row['naslov'], 0, -4);
+ }
+
+ echo '<p>';
+ if ($editor)
+ echo '<span class="red pointer" onmouseover="this.style.display=\'none\'; create_editor(\'naslov\');">'.$lang['srv_editor'].'</span><br />';
+ echo '<textarea name="naslov" id="naslov">'.$row['naslov'].'</textarea>';
+ echo '</p>';
+ }
+
+ /**
+ * urejanje variable
+ *
+ */
+ function edit_variable () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ #'email','ime','priimek','telefon','naziv','drugo'
+ if ( in_array($row['variable'], array('email','telefon','ime','priimek','naziv','drugo')) && $row['sistem']==1 )
+ $disabled = true; else $disabled = false;
+
+ echo '<p><span class="title">'.$lang['srv_variable'].': '.Help::display('edit_variable').'</span><span class="content"><input type="text" name="variable" value="'.$row['variable'].'" onkeyup="vprasanje_check_variable(this);" '.($disabled?'disabled':'').' maxlength="10" /></span></p>';
+
+ //echo '<p><span class="title">'.$lang['srv_datapiping'].': '.Help::display('DataPiping').'</span> '.$lang['srv_datapiping_txt'].'</p>';
+
+ }
+
+ /**
+ * urejanje variable
+ *
+ */
+ function edit_label () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ #'email','ime','priimek','telefon','naziv','drugo'
+
+ echo '<p><span class="title">'.$lang['srv_label'].':</span><span class="content"><input type="text" name="label" value="'.$row['label'].'" maxlength="80" /></span></p>';
+ }
+
+ /**
+ * variablo urejamo inline v naslovu
+ *
+ */
+ function variable ($edit_tip = 0) {
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ //echo '<h2><div contenteditable="true" onkeyup="vprasanje_check_variable(this); $(\'#spremenljivka_content_'.$row['id'].' .variable_name\').html( $(this).html() );" onblur="inline_variable(\''.$row['id'].'\', this);" class="editable" style="display:inline-block; width:115px; overflow:hidden; cursor:text">'.$row['variable'].'</div>';
+ echo '<h2>'.$row['variable'].'';
+ if ($edit_tip == 1) $this->edit_tip();
+ echo '</h2>';
+
+ }
+
+ //edit opombe
+ function edit_opomba() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p style="margin-bottom: 32px"><label for="_info" class="title">'.$lang['srv_note2'].':</label>';
+ //echo '<span class="content"><textarea name="info" style="width:200px">'.$row['info'].'</textarea></span>';
+ //echo '<span class="content"><input type="radio" name="info" value="" '.($row['info']==''?' checked':'').'>'.$lang['no'].'';
+ //echo '<input type="radio" name="info" value="'.($row['info']!=''?$row['info']:$lang['note']).'" id="radiothis" '.($row['info']!=''?' checked':'').'>'.$lang['yes'].'</span>';
+ echo '<span class="content"><input type="hidden" name="info" value="">';
+ echo '<input type="checkbox" id="_info" name="info" value="'.($row['info']!=''?$row['info']:$lang['note']).'" '.($row['info']!=''?' checked':'').'></span>';
+ echo '</p>';
+
+ // ob spremembi opombe, damo drug value tudi na radio Da, da se ob shranjevanju desnega menija shrani nova opomba, ce je bila spremenenjena
+ ?><script> $('div.spremenljivka_info.info_inline[spr_id=<?=$this->spremenljivka?>]').live('blur', function() { $('#_info').val( $(this).html() ); }) </script><?
+ }
+
+ //editiranje naslova uvoda
+ function edit_uvod() {
+ global $lang;
+ global $admin_type;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ echo '<h2>'.$lang['srv_intro_label'].'</h2>';
+
+ if ($row['introduction'] == '') {
+ $lang_admin = SurveyInfo::getInstance()->getSurveyColumn('lang_admin');
+ $lang_resp = SurveyInfo::getInstance()->getSurveyColumn('lang_resp');
+
+ // nastavimo na jezik za respondentov vmesnik
+ $file = '../../lang/'.$lang_resp.'.php';
+ include($file);
+
+ $text = $lang['srv_intro'];
+ $lang_srv_nextpage_uvod = $lang['srv_nextpage_uvod'];
+
+ // nastavimo nazaj na admin jezik
+ $file = '../../lang/'.$lang_admin.'.php';
+ include($file);
+ }
+ else {
+ $text = $row['introduction'];
+ }
+
+ if (strtolower(substr($text, 0, 3)) == '<p>' && strtolower(substr($text, -4)) == '</p>' && strrpos($text, '<p>') == 0) {
+ $text = substr($text, 3);
+ $text = substr($text, 0, -4);
+ }
+
+ // Opomba
+ $opomba = $row['intro_opomba'];
+ echo '<p>'.$lang['note'].' ('.$lang['srv_internal'].'): ';
+ echo '<textarea name="intro_opomba" class="texteditor info" >'.$opomba.'</textarea>';
+ echo '</p>';
+
+ /*if ($row['user_base'] == 1 && (int)$row['individual_invitation'] > 0) {
+ $disabled = 'disabled';
+ } else*/ $disabled = '';
+
+ // Prikaz uvoda
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_show_intro'].': </span>';
+ echo '<input type="radio" name="show_intro" value="0" id="show_intro_0" '.(($row['show_intro'] == 0) ? ' checked="checked" ' : '').' '.$disabled.' onClick="$(\'.intro_static_setting\').hide();" /><label for="show_intro_0">'.$lang['no1'].'</label>';
+ echo '<input type="radio" name="show_intro" value="1" id="show_intro_1" '.(($row['show_intro'] == 1) ? ' checked="checked" ' : '').' '.$disabled.' onClick="$(\'.intro_static_setting\').show();" /><label for="show_intro_1">'.$lang['yes'].'</label>';
+ echo '</p>';
+
+ // Staticen uvod, ki ne ustvari userja (user se ustvari sele na naslednji strani) - za recimo embeddane ankete...
+ //if($admin_type == 0){
+ echo '<p class="intro_static_setting" '.($row['show_intro'] == 0 ? ' style="display:none;"' : '').'>';
+ echo '<span class="title">'.$lang['srv_show_intro_static'].': </span>';
+ echo '<input type="radio" name="intro_static" id="intro_static_0" value="0" '.(($row['intro_static'] == 0) ? ' checked="checked" ' : '').' '.$disabled.' /><label for="intro_static_0">'.$lang['srv_show_intro_static_0'].'</label>';
+ echo '<input type="radio" name="intro_static" id="intro_static_1" value="1" '.(($row['intro_static'] == 1) ? ' checked="checked" ' : '').' '.$disabled.' /><label for="intro_static_1">'.$lang['srv_show_intro_static_1'].'</label>';
+ echo '<input type="radio" name="intro_static" id="intro_static_2" value="2" '.(($row['intro_static'] == 2) ? ' checked="checked" ' : '').' '.$disabled.' /><label for="intro_static_2">'.$lang['srv_show_intro_static_2'].'</label>';
+ echo '</p>';
+ //}
+
+ //dodaten naslov gumba za naprej
+ SurveySetting::getInstance()->Init($this->anketa);
+ $srv_nextpage_uvod = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_srv_nextpage_uvod');
+ if ($srv_nextpage_uvod != '')
+ $text = $srv_nextpage_uvod;
+ else
+ $text = $lang_srv_nextpage_uvod;
+ echo '<p><label for="srv_nextpage_uvod">'.$lang['srv_nextpage_uvod'].':</label> <input type="text" name="srv_nextpage_uvod" id="srv_nextpage_uvod" value="'.$text.'" style="width:200px"></span></p>';
+ }
+
+ //editiranje naslova zakljucka in osnovnih nastavitev (skok na url...)
+ function edit_zakljucek() {
+ global $lang;
+ global $site_url;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+ SurveySetting::getInstance()->Init($this->anketa);
+
+ echo '<h2>'.$lang['srv_end_label'].'</h2>';
+
+ if ($row['conclusion'] == '') {
+ $lang_admin = SurveyInfo::getInstance()->getSurveyColumn('lang_admin');
+ $lang_resp = SurveyInfo::getInstance()->getSurveyColumn('lang_resp');
+
+ // nastavimo na jezik za respondentov vmesnik
+ $file = '../../lang/'.$lang_resp.'.php';
+ include($file);
+
+ $text = $lang['srv_end'];
+ $lang_srv_prevpage = $lang['srv_prevpage'];
+ $lang_srv_konec = $lang['srv_konec'];
+
+ // nastavimo nazaj na admin jezik
+ $file = '../../lang/'.$lang_admin.'.php';
+ include($file);
+ }
+ else {
+ $text = $row['conclusion'];
+ }
+
+ if (strtolower(substr($text, 0, 3)) == '<p>' && strtolower(substr($text, -4)) == '</p>' && strrpos($text, '<p>') == 0) {
+ $text = substr($text, 3);
+ $text = substr($text, 0, -4);
+ }
+
+ // opomba
+ $opomba = $row['concl_opomba'];
+
+ echo '<p>'.$lang['note'].' ('.$lang['srv_internal'].'): ';
+ echo '<textarea name="concl_opomba" class="texteditor info" >'.$opomba.'</textarea>';
+ echo '</p>';
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_show_concl'].': </span>';
+ echo '<input type="radio" id="show_concl_0" name="show_concl" value="0" '.(($row['show_concl'] == 0) ? ' checked="checked" ' : '').' /><label for="show_concl_0">'.$lang['no1'].'</label>';
+ echo '<input type="radio" id="show_concl_1" name="show_concl" value="1" '.(($row['show_concl'] == 1) ? ' checked="checked" ' : '').' /><label for="show_concl_1">'.$lang['yes'].'</label>';
+ echo '</p>';
+
+
+ //dodatne nastaitve (skok na url ...)
+ echo '<fieldset><legend>'.$lang['srv_concl_link'].'</legend>';
+
+ if ($row['url'] != '')
+ $url = $row['url'];
+ else
+ $url = $site_url;
+
+ echo '<p>';
+ echo '<input type="radio" id="concl_link_1" name="concl_link" value="1" '.($row['concl_link'] == 0 ? ' checked' : '').' onclick="$(\'#srv_concl_link_go\').hide()"><label for="concl_link_1">'.$lang['srv_concl_link_close'].'</label> ';
+ // Rekurzivno - samo pri navadni anketi
+ if($row['survey_type'] > 1)
+ echo '<br /><input type="radio" id="concl_link_2" name="concl_link" value="2" '.($row['concl_link'] == 2 ? ' checked' : '').' onclick="$(\'#srv_concl_link_go\').hide()"><label for="concl_link_2">'.$lang['srv_concl_link_rec'].'</label> ';
+ echo '<br /><input type="radio" id="concl_link_0" name="concl_link" value="0" '.($row['concl_link'] == 1 ? ' checked' : '').' onclick="$(\'#srv_concl_link_go\').show()"><label for="concl_link_0">'.$lang['srv_concl_link_go'].'</label> ';
+ echo '</p>';
+
+ // Ce skocimo na custom url prikazemo urejanje url-ja in dodatne nastavitve za parametre v url (usr_id, status...)
+ echo '<div id="srv_concl_link_go" '.($row['concl_link'] == 0 || $row['concl_link'] == 2 ?' style="display:none"':'').'">';
+
+ // URL
+ echo '<p><label for="url">'.$lang['srv_url'].':</label> <input type="text" name="url" id="url_concl_sett" value="'.$url.'" style="width:200px"></p>';
+
+
+ // Parametri
+ echo '<p>';
+ echo $lang['srv_concl_link_params'].':<br />';
+ $concl_url_usr_id = SurveySetting::getInstance()->getSurveyMiscSetting('concl_url_usr_id');
+ echo '<input type="hidden" name="concl_url_usr_id" value="0">';
+ echo '<span class="spaceLeft spaceright"><input type="checkbox" name="concl_url_usr_id" id="concl_url_usr_id" value="1" '.($concl_url_usr_id==1 ? ' checked="checked"' : '').'> <label for="concl_url_usr_id">'.$lang['srv_concl_link_usr_id'].'</label></span>';
+ echo '<br />';
+ $concl_url_status = SurveySetting::getInstance()->getSurveyMiscSetting('concl_url_status');
+ echo '<input type="hidden" name="concl_url_status" value="0">';
+ echo '<span class="spaceLeft"><input type="checkbox" name="concl_url_status" id="concl_url_status" value="1" '.($concl_url_status==1 ? ' checked="checked"' : '').'> <label for="concl_url_status">'.$lang['srv_concl_link_status'].'</label></span>';
+ echo '<br />';
+ $concl_url_recnum = SurveySetting::getInstance()->getSurveyMiscSetting('concl_url_recnum');
+ echo '<input type="hidden" name="concl_url_recnum" value="0">';
+ echo '<span class="spaceLeft"><input type="checkbox" name="concl_url_recnum" id="concl_url_recnum" value="1" '.($concl_url_recnum==1 ? ' checked="checked"' : '').'> <label for="concl_url_recnum">'.$lang['srv_concl_link_recnum'].'</label></span>';
+ echo '</p>';
+
+
+ // Text za datapiping v url-ju
+ echo '<p>'.$lang['srv_concl_link_datapiping'].'</p>';
+
+ echo '</div>';
+
+ echo '</fieldset>';
+
+
+ echo '<fieldset><legend>'.$lang['srv_extra_settings'].'</legend>';
+
+ echo '<p><label for="concl_back_button">'.$lang['srv_concl_back_button_show'].'</label><span class="content"><input type="checkbox" id="concl_back_button" name="concl_back_button" value="1" '.($row['concl_back_button'] == 1 ? ' checked' : '').' onclick=" if (this.checked) { $(\'#srv_prevpage_span\').show(); } else { $(\'#srv_prevpage_span\').hide(); }" /></span>';
+
+ // dodaten naslov gumba zakljucek
+ $srv_prevpage = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_srv_prevpage');
+ if ($srv_prevpage != '')
+ $text = $srv_prevpage;
+ else
+ $text = $lang_srv_prevpage;
+ echo '<br /><span id="srv_prevpage_span"'.($row['concl_back_button']==0?' style="display:none"':'').'> <label for="srv_prevpage">'.$lang['srv_prevpage'].':</label> <span class="content"><input type="text" name="srv_prevpage" id="srv_prevpage" value="'.$text.'" style="width:190px"></span></span></p>';
+
+
+ echo '<p><label for="concl_end_button">'.$lang['srv_concl_end_button_show'].'</label><span class="content"><input type="checkbox" id="concl_end_button" name="concl_end_button" value="1" '.($row['concl_end_button'] == 1 ? ' checked' : '').' onclick=" if (this.checked) { $(\'#srv_konec_span\').show(); } else { $(\'#srv_konec_span\').hide(); }" /></span>';
+
+ // dodaten naslov gumba zakljucek
+ $srv_konec = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_srv_konec');
+ if ($srv_konec != '')
+ $text = $srv_konec;
+ else
+ $text = $lang_srv_konec;
+ echo '<br /><span id="srv_konec_span"'.($row['concl_end_button']==0?' style="display:none"':'').'> <label for="srv_konec">'.$lang['srv_konec'].':</label> <span class="content"><input type="text" name="srv_konec" id="srv_konec" value="'.$text.'" style="width:190px"></span></span></p>';
+
+ // Povezava za naknadno urejanje
+ echo '<p><label for="concl_return_edit">'.$lang['srv_concl_return_edit'].'</label><span class="content"><input type="checkbox" id="concl_return_edit" name="concl_return_edit" value="1" '.($row['concl_return_edit'] == 1 ? ' checked' : '').'/></span></p>';
+
+ // Povezava na pdf
+ echo '<p><label for="concl_PDF_link">'.$lang['srv_concl_PDF_link'].'</label><span class="content"><input type="checkbox" id="concl_PDF_link" name="concl_PDF_link" value="1" '.($row['concl_PDF_link'] == 1 ? ' checked' : '').'/></span>'.Help :: display('srv_concl_PDF_link').'</p>';
+
+
+ // link na urejanje texta ce je anketa ze zakljucena
+ echo '<p>';
+ echo $lang['srv_concl_deactivation_text'].' '.Help::display('srv_concl_deactivation_text').'<br />';
+
+ $value = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_srv_survey_non_active');
+ if ($value == '') $value = $lang['srv_survey_non_active'];
+
+ echo '<textarea name="srvlang_srv_survey_non_active" id="srvlang_srv_survey_non_active" style="width:260px; height:30px;">'.$value.'</textarea>';
+ echo '<span class="faicon edit icon-as_link small" onclick="vprasanje_jezik_edit_zakljucek(\'srvlang_srv_survey_non_active\');" style="float: right; margin-top: 1px;"></span>';
+ echo '</p>';
+
+
+ echo '</fieldset>';
+ }
+
+ //editiranje naslova statistike
+ function edit_statistika() {
+ global $lang;
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ echo '<h2>'.$lang['srv_statistic_label'].'</h2>';
+
+ $text = $row['statistics'];
+
+ if (strtolower(substr($text, 0, 3)) == '<p>' && strtolower(substr($text, -4)) == '</p>' && strrpos($text, '<p>') == 0) {
+ $text = substr($text, 3);
+ $text = substr($text, 0, -4);
+ }
+
+ // text
+ echo '<p><span class="title">Besedilo statistike:</span>';
+ echo '<textarea name="statistics">'.$text.'</textarea>';
+ echo '</p>';
+ }
+
+ // navadna/sistemska spr
+ function edit_sistem() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ if ( in_array($row['variable'], array('email','telefon','ime','priimek','naziv','drugo')) && $row['sistem']==1 )
+ $disabled = true; else $disabled = false;
+
+ echo '<p>';
+ echo '<label for="sistem" class="title">'.$lang['srv_sistemska'].': '.Help::display('srv_sistemska_edit').'</label>';
+ echo '<span class="content"><input type="hidden" name="sistem" value="0" />';
+ echo '<input type="checkbox" id="sistem" name="sistem" value="1" '.(($row['sistem'] == 1) ? ' checked="checked" ' : '').' '.($disabled?'disabled':'').' />';
+ echo '</span></p>';
+ }
+
+ // skrito/vidno vprasanje
+ function edit_visible() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<label for="visible" class="title">'.$lang['srv_visible'].': </label>';
+ //echo '<span class="content"><input type="radio" name="visible" value="0" '.(($row['visible'] == 0) ? ' checked="checked" ' : '').' />'.$lang['no1'];
+ //echo '<input type="radio" name="visible" value="1" '.(($row['visible'] == 1) ? ' checked="checked" ' : '').' />'.$lang['yes'];
+ echo '<span class="content"><input type="hidden" name="visible" value="0" />';
+ echo '<input type="checkbox" id="visible" name="visible" value="1" '.(($row['visible'] == 1) ? ' checked="checked" ' : '').' onClick="show_dostop(this.checked);" />';
+ echo '</span></p>';
+
+ echo '<div id="dostop" '.($row['visible'] == 1 ? '' : ' style="display:none;"').'><p>';
+ echo '<span class="title">'.$lang['srv_visible_dostop'].': </span>';
+ echo '<span class="content"><select name="dostop">';
+ echo '<option value="4"'.($row['dostop']==4?' selected':'').'>'.$lang['see_everybody'].'</option>';
+ echo '<option value="3"'.($row['dostop']==3?' selected':'').'>'.$lang['see_registered'].'</option>';
+ echo '<option value="2"'.($row['dostop']==2?' selected':'').'>'.$lang['see_member'].'</option>';
+ echo '<option value="1"'.($row['dostop']==1?' selected':'').'>'.$lang['see_manager'].'</option>';
+ echo '<option value="0"'.($row['dostop']==0?' selected':'').'>'.$lang['see_admin'].'</option>';
+ echo '</select></span>';
+ echo '</p></div>';
+ }
+
+ // odklenjeno/zaklenjeno vprasanje
+ function edit_locked() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<label for="locked" class="title">'.$lang['srv_locked'].': '.Help::display('srv_spremenljivka_lock').'</label>';
+ echo '<span class="content"><input type="hidden" name="locked" value="0" />';
+ echo '<input type="checkbox" id="locked" name="locked" value="1" '.(($row['locked'] == 1) ? ' checked="checked" ' : '').' />';
+ echo '</span></p>';
+ }
+
+ // omogoceno/onemogoceno vprasanje pri resevanju
+ function edit_disabled() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $disabled_vprasanje = ($spremenljivkaParams->get('disabled_vprasanje') ? $spremenljivkaParams->get('disabled_vprasanje') : 0);
+
+ echo '<p>';
+ echo '<label for="disabled_vprasanje" class="title">'.$lang['srv_disabled'].': '.Help::display('srv_disabled_question').'</label>';
+ echo '<span class="content"><input type="hidden" name="disabled_vprasanje" value="0" />';
+ echo '<input type="checkbox" id="disabled_vprasanje" name="disabled_vprasanje" value="1" '.(($disabled_vprasanje == 1) ? ' checked="checked" ' : '').' />';
+ echo '</span></p>';
+ }
+
+ /**
+ * editiranje grida
+ */
+ function edit_grid () {
+ global $lang;
+ global $default_grid_values;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $rowA = SurveyInfo::getInstance()->getSurveyRow();
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $diferencial_trak = ($spremenljivkaParams->get('diferencial_trak') ? $spremenljivkaParams->get('diferencial_trak') : 0); //za checkbox
+
+ $display_1 = ( ($row['tip'] == 6 && ($row['enota'] == 4 || $row['enota'] == 5)) || ($row['tip'] == 6 && $row['enota'] == 8) || ($row['tip'] == 20 && $row['ranking_k'] == 1)) ? ' style="display:none;"' : '';
+ $display = ( ($row['tip'] == 6 && ($row['enota'] == 4 || $row['enota'] == 5 || ($row['enota'] == 1 && $diferencial_trak == 1) || ($row['enota'] == 0 && $diferencial_trak == 1)) ) || ($row['tip'] == 6 && $row['enota'] == 8) || ($row['tip'] == 20 && $row['ranking_k'] == 1)) ? ' style="display:none;"' : '';
+
+
+ echo '<div class="drop_grids_num" '.$display_1.'>';
+ echo '<p><span class="title" >'.$lang['srv_odgovorov'].':</span>';
+ echo '<span class="content"><select name="grids_count" id="grids_count" onChange="change_selectbox_size(\'' . $row['id'] . '\', $(this).val(), \'' . $lang['srv_select_box_vse'] . '\'); change_trak_num_of_titles(\'' . $row['id'] . '\', $(this).val());">';
+
+ // Vedno imamo najmanj 2 grida (drugace so stvari cudne v analizah) - namesto 1 se uporabi navaden radio tip vprasanja
+ // Pri number sliderju se rabi 1 (mogoče še kje - npr checkbox itd.... ) analize morajo delati tudi v tem primeru :P
+ echo '<option value="1"'.($row['grids']=='1'?' selected':'').'>1</option>';
+ echo '<option value="2"'.($row['grids']=='2'?' selected':'').'>2</option>';
+ echo '<option value="3"'.($row['grids']=='3'?' selected':'').'>3</option>';
+ echo '<option value="4"'.($row['grids']=='4'?' selected':'').'>4</option>';
+ echo '<option value="5"'.($row['grids']=='5'?' selected':'').'>5</option>';
+ echo '<option value="6"'.($row['grids']=='6'?' selected':'').'>6</option>';
+ echo '<option value="7"'.($row['grids']=='7'?' selected':'').'>7</option>';
+
+ if($row['enota'] != 11) {
+ echo '<option value="8"' . ($row['grids'] == '8' ? ' selected' : '') . '>8</option>';
+ echo '<option value="9"' . ($row['grids'] == '9' ? ' selected' : '') . '>9</option>';
+ echo '<option value="10"' . ($row['grids'] == '10' ? ' selected' : '') . '>10</option>';
+ echo '<option value="11"' . ($row['grids'] == '11' ? ' selected' : '') . '>11</option>';
+ echo '<option value="12"' . ($row['grids'] == '12' ? ' selected' : '') . '>12</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+ // Slikovni tip
+ if($row['tip'] == 6){
+ //if($row['enota'] == 12) {
+ $this->edit_custom_picture_radio();
+ //}
+
+ $this->edit_trak_tabela();
+ }
+
+ // prikaz dropdowna za default vrednosti gridov
+ if ($row['tip'] == 6 /*&& $row['grids'] == 5*/){
+ //echo '<p class="grid_defaults">';
+ echo '<p class="grid_defaults_class" '.$display.'>';
+ echo '<span class="title">'.$lang['srv_defaultGrid'].':</span>';
+ echo '<span class="content"><select name="grid_defaults" id="grid_defaults" style="width:100px">';
+ //echo '<span class="content"><select name="grid_defaults" id="grid_defaults" style="width:100px" onChange="vprasanje_save(true)">';
+ echo '<option value="0">'.$lang['s_without'].'</option>';
+ foreach($default_grid_values AS $key => $value){
+ echo '<option value="'.$key.'">'.$value['name'].'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ if ($row['ranking_k'] != 1){
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $grid_var = ($spremenljivkaParams->get('grid_var') ? $spremenljivkaParams->get('grid_var') : 0);
+
+ echo '<p class="grid_var_class" '.$display.'><label for="grid_var" class="title">'.$lang['srv_edit_values'].':</label>';
+ echo ' '.Help::display('srv_grid_var');
+ echo '<span class="content">';
+ echo '<input type="hidden" name="grid_var" value="0">';
+ echo '<input type="checkbox" id="grid_var" name="grid_var" value="1" '.($grid_var == 1 ? ' checked="checked"' : '').'></span></p>';
+ }
+ }
+
+ /**
+ * editiranje podnaslova grida (pri double gridu)
+ */
+ function edit_grid_missing () {
+ global $lang;
+
+ //dodatne missing vrednosti (ne vem, zavrnil...)
+ # preberemo iz class.SurveyMissingValues
+ $smv = new SurveyMissingValues($this->anketa);
+ # katere missinge imamo na voljo
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+
+ #kateri missingi so nastavljeni
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_grid WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+ echo '<p>';
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ echo '<input type="checkbox" '.(isset($already_set_mv[$mv_key]) ? ' checked' : '').' name="missing_value_checkbox[]" id="missing_value_'.$mv_key.'" value="'.$mv_key.'" title="'.$mv_text.'""></input> '; // ,\''.$mv_key.'\',\''.$mv_text.'\'
+ echo '<label for="missing_value_'.$mv_key.'" class="pointer">'.$mv_text.'</label>';
+ }
+ }
+ echo '</p>';
+ }
+
+ /**
+ * editiranje podnaslova grida (pri double gridu)
+ */
+ function edit_grid_subtitle () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $rowA = SurveyInfo::getInstance()->getSurveyRow();
+
+ $display = ($row['enota'] == 3 ? '' : 'display: none;');
+
+
+ echo '<div class="grid_subtitle" style="'.$display.'">';
+
+ echo '<p><span class="title">'.$lang['srv_grid_subtitle1'].':</span><span class="content"><input type="text" size="23" name="grid_subtitle1" value="'.$row['grid_subtitle1'].'" /></span></p>';
+ echo '<p><span class="title">'.$lang['srv_grid_subtitle2'].':</span><span class="content"><input type="text" size="23" name="grid_subtitle2" value="'.$row['grid_subtitle2'].'" /></span></p>';
+
+ echo '</div>';
+ }
+
+
+ /**
+ * navadno editiranje vrednosti
+ *
+ */
+ function edit_vrednost () {
+ global $lang;
+ global $admin_type;
+ global $default_grid_values;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ //Če gre za vizualno skalo ali slikovni tip potem opcij ne prikazujemo. Še vedno pa izpišemo, da delujejo če nekdo zamenja tip vprašanaj
+ $displayNone = '';
+ if(in_array($row['orientation'], [9,11]))
+ $displayNone = 'style="display:none";';
+
+ // Prednastavljene vrednosti odgovorov (dropdown)
+ if ($row['tip'] == 1) {
+
+ echo '<p class="radio_defaults_class">';
+ echo '<span class="title">'.$lang['srv_defaultGrid'].':</span>';
+ echo '<span class="content"><select name="radio_defaults" id="radio_defaults" style="width:100px">';
+ echo '<option value="0">'.$lang['s_without'].'</option>';
+ foreach($default_grid_values AS $key => $value){
+ echo '<option value="'.$key.'">'.$value['name'].'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // inline urejanje variabel vrednosti
+ if ( in_array($row['tip'], array(1,2,3))) {
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $grid_var = ($spremenljivkaParams->get('grid_var') ? $spremenljivkaParams->get('grid_var') : 0);
+
+ echo '<p '.$displayNone.'><label for="grid_var" class="title">'.$lang['srv_edit_values'].':</label>';
+ echo ' '.Help::display('srv_grid_var');
+ echo '<span class="content">';
+ echo '<span class="content"><input type="hidden" name="grid_var" value="0" />';
+ echo '<input type="checkbox" id="grid_var" name="grid_var" value="1" '.($grid_var == 1 ? 'checked="checked"' : '').'></span></p>';
+
+ // Obratni vrstni red vrednosti
+ if($row['tip'] == 1 || $row['tip'] == 3){
+
+ $reverse_var = ($spremenljivkaParams->get('reverse_var') ? $spremenljivkaParams->get('reverse_var') : 0);
+
+ echo '<p '.$displayNone.'><label for="reverse_var" class="title">'.$lang['srv_reverse_values'].':</label>';
+ echo '<span class="content">';
+ echo '<span class="content"><input type="hidden" name="reverse_var" value="0" />';
+ echo '<input type="checkbox" '.($reverse_var == '1' ? ' checked="checked" ': '').' value="1" id="reverse_var" name="reverse_var"></span></p>';
+ }
+ }
+
+ // besedilo za vsoto
+ if ($row['tip'] == 18) {
+ //echo '<div style="width:60%; height: 1px; border-top: 1px black solid;"></div>';
+
+ if($row['vsota'] == '')
+ $vsotaText = $lang['srv_vsota_text'];
+ else
+ $vsotaText = $row['vsota'];
+
+ // echo '<p id="vrednost_'.$row['id'].'" class="vrednost_vsota">';
+ // echo '<textarea name="vsota">'.$vsotaText.'</textarea>';
+ // echo '</p>';
+ }
+
+
+ echo '<p '.$displayNone.'><span onclick="vrednost_fastadd(\''.$this->spremenljivka.'\'); return false;" class="pointer"><span class="sprites paste_word"></span> ';
+
+ if ( in_array($row['tip'], array(6, 16, 19, 20)) )
+ echo $lang['srv_question_fastadd'].' '.Help::display('srv_question_fastadd');
+ else
+ echo $lang['srv_vrednost_fastadd'].' '.Help::display('srv_vrednost_fastadd');
+
+ echo '</span></p>';
+
+
+ // inline hitro dodajanje slik - zaenkrat samo radio in checkbox - v testiranju, zato samo za admine
+ if (in_array($row['tip'], array(1,2)) && $row['orientation'] == 1) {
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $quickImage = ($spremenljivkaParams->get('quickImage') ? $spremenljivkaParams->get('quickImage') : 0);
+
+ echo '<p><label for="quickImage" class="title">'.$lang['srv_edit_quick_image'].':</label>';
+ echo '<span class="content">';
+ echo '<span class="content"><input type="hidden" value="0" name="quickImage" />';
+ echo '<input type="checkbox" id="quickImage" name="quickImage" value="1" '.($quickImage == 1 ? ' checked="checked"' : '').'></span></p>';
+ }
+ }
+
+ /**
+ * Urejanje manjkajocih vrednosti
+ *
+ */
+ function edit_missing () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ if ($row['tip'] <= 3) {
+
+ //echo '<p class="vrednost_new">';
+ echo '<p>';
+
+ //dodatne missing vrednosti (ne vem, zavrnil...)
+ # preberemo iz class.SurveyMissingValues
+ $smv = new SurveyMissingValues($this->anketa);
+ # katere missinge imamo na voljo
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+
+ #kateri missingi so nastavljeni
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+ //echo '<span class="floatRight">';
+ if (count($missing_values) > 0) {
+
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ echo '<span class="floatLeft">';
+ echo '<input type="checkbox" '.(isset($already_set_mv[$mv_key]) ? ' checked="checked"' : '').' onChange="vrednost_new_dodatne(\'' . $row['id'] . '\', \''.$mv_key.'\', \''.$row['tip'].'\', this.checked); show_alert_missing();" id="missing_value_'.$mv_key.'">';
+ echo '<label for="missing_value_'.$mv_key.'" class="pointer">'. $mv_text . '</label> ';
+ //echo '<br/>';
+ echo '</span>';
+ }
+ }
+ //echo '</span>';
+
+ echo '<span class="clr"></span>';
+
+ //echo '</p></div>';
+ echo '</p>';
+
+ // naknaden prikaz missinga ne vem ob opozorilu (samo ce imamo vklopljeno opozorilo in missing ne vem)
+ if ($row['tip'] <= 2)
+ $this->edit_alert_show_missing();
+ }
+ }
+
+ /**
+ * vrstica vrednosti
+ *
+ */
+ function edit_vrednost_li ($vrednost, $row=null) {
+
+ if ($row == null) {
+ $sql = sisplet_query("SELECT * FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+ }
+
+ echo '<li id="vrednost_'.$vrednost.'" '.($row['other'] == 1 ? 'class="li_other"' : '').'>';
+ $this->edit_vrednost_li_content($vrednost, $row);
+ echo '</li>';
+ }
+
+ /**
+ * ta je locena od zgornje funkcije, ker se z ajaxom refresha samo vsebina (pri urejanju vrstice)
+ *
+ */
+ function edit_vrednost_li_content($vrednost, $row=null) {
+ global $lang;
+
+ $rowS = Cache::srv_spremenljivka($this->spremenljivka);
+
+ if($rowS['tip'] == 6 || $rowS['tip'] == 16 || $rowS['tip'] == 19 || $rowS['tip'] == 20){
+ $spremenljivkaParams = new enkaParameters($rowS['params']);
+ $gridWidth = ($spremenljivkaParams->get('gridWidth') ? $spremenljivkaParams->get('gridWidth') : 20);
+ $gridWidth = ($gridWidth == -1 ? 20 : $gridWidth);
+ }
+ else
+ $gridWidth = 42;
+
+ if ($row == null) {
+ $sql = sisplet_query("SELECT id, naslov, naslov2, variable, other, if_id, random FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+ }
+
+ echo ' <span class="faicon move_updown move"></span> <textarea name="vrednost_naslov_'.$row['id'].'" id="'.$row['variable'].'" class="vrednost_textarea" style="width:'.$gridWidth.'%;">'.$row['naslov'].'</textarea> ';
+ echo '['.$row['variable'].'] <span class="faicon edit2 pointer" onclick="vrednost_edit(\''.$row['id'].'\'); return false;"></span> <span class="faicon delete_circle icon-orange_link" onclick="vrednost_delete(\''.$rowS['id'].'\', \''.$row['id'].'\', \''.$rowS['tip'].'\', \''.$row['variable'].'\');"></span>';
+ if ($row['other'] == 1) echo ' <input type="text" disabled style="width:40px" />';
+
+ if ($row['if_id'] > 0) {
+ echo ' * ';
+ $b = new Branching($this->anketa);
+ if ($b->condition_check($row['if_id']) != 0)
+ echo ' <span class="faicon warning icon-orange" title="'.$lang['srv_check_pogoji_spremenljivka'].'"></span>';
+ }
+
+ //polje pri diferencialu
+ if($rowS['tip'] == 6 && $rowS['enota'] == 1){
+ echo '<textarea name="vrednost_naslov2_'.$row['id'].'" id="'.$row['variable'].'_2" style="float: right; width:20%">'.$row['naslov2'].'</textarea>';
+ }
+
+ switch ($row['random']) {
+ //case 0 : echo $lang['srv_random_off'];
+ //break;
+ case 1 : echo ' '.$lang['srv_random_on'];
+ break;
+ case 2 : echo ' '.$lang['srv_sort_asc'];
+ break;
+ case 3 : echo ' '.$lang['srv_sort_desc'];
+ break;
+
+ }
+ }
+
+ /**
+ * urejanje vrednosti, ki se odpre v popupu
+ *
+ */
+ function vrednost_edit ($vrednost) {
+ global $lang;
+
+ $lang_id = $_POST['lang_id'];
+
+ $sql = sisplet_query("SELECT id, spr_id, variable, naslov, random, other, if_id FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+
+ $rows = Cache::srv_spremenljivka($row['spr_id']);
+
+ echo '<form name="vrednost_edit" onsubmit="vrednost_save(); return false;">';
+
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'">';
+ echo '<input type="hidden" name="spremenljivka" value="'.$row['spr_id'].'">';
+ echo '<input type="hidden" name="vrednost" value="'.$vrednost.'">';
+ echo '<input type="hidden" name="lang_id" value="'.$lang_id.'">';
+
+
+ if ($lang_id > 0) {
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+ save('lang_id', $lang_id);
+
+ $naslov = \App\Controllers\LanguageController::getInstance()->srv_language_vrednost($vrednost);
+ if ($naslov != '') $row['naslov'] = $naslov;
+ echo '<p>'.$lang['srv_vprasanje_text'].': <textarea id="vrednost_naslov" name="vrednost_naslov" style="width:99%">'.$row['naslov'].'</textarea></p>';
+ ?><script>
+ create_editor('vrednost_naslov', false);
+ </script><?
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="vrednost_save_lang(\''.$vrednost.'\'); return false;"><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vrednost_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';
+ }
+ else {
+ echo '<div class="popup_close"><a href="#" onClick="vrednost_cancel(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_kategorije_odgovorov_title'].'</h2>';
+
+ echo '<div class="left-float"><span class="title">'.(in_array($rows['tip'], array(2,6,16,19,20))?$lang['srv_spremenljivka']:$lang['srv_vrednost']).':</span> <input type="text" name="vrednost_variable" value="'.$row['variable'].'" '.(in_array($rows['tip'], array(2,6,16,19,20)) ? ' onkeyup="vprasanje_check_variable(this);"' : '').'></div>';
+
+ // RAZVRSTI odgovore
+ echo '<div class="left-float"><span class="title">'.$lang['sort'].':</span> ';
+ echo '<select name="vrednost_random">';
+ echo '<option value="0"'.($row['random']==0?' selected':'').'>'.$lang['srv_random_off2'].'</option>';
+ echo '<option value="1"'.($row['random']==1?' selected':'').'>'.$lang['srv_random_on2'].'</option>';
+ echo '<option value="2"'.($row['random']==2?' selected':'').'>'.$lang['srv_sort_asc2'].'</option>';
+ echo '<option value="3"'.($row['random']==3?' selected':'').'>'.$lang['srv_sort_desc2'].'</option>';
+ echo '</select>';
+ echo '</div>';
+
+ echo '<div style="clear:both;"></div>';
+
+ echo '<div>'.$lang['srv_vprasanje_text'].' <span onmouseover="$(this).hide(); create_editor(\'vrednost_naslov\');" class="red pointer"> - '.$lang['srv_editor'].'</span>: <textarea id="vrednost_naslov" name="vrednost_naslov" style="width:99%">'.$row['naslov'].'</textarea></div>';
+
+ echo '<p>';
+ if ($row['if_id'] > 0) {
+ echo $lang['srv_podif_edit'].': ';
+ echo '<a href="#" onclick="vrednost_condition_editing(\''.$vrednost.'\'); return false;">';
+ $b = new Branching($this->anketa);
+ $b->conditions_display($row['if_id'], 0, 1);
+ echo '</a>';
+ } else {
+ echo $lang['srv_podif_new'].': ';
+ echo '<span class="faicon odg_if_not inline inline_if_not" onclick="vrednost_condition_editing(\''.$vrednost.'\'); return false;" title="'.$lang['srv_podif_edit'].'" style="cursor: pointer;"></span>';
+ }
+ echo '</p>';
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="vrednost_save(\''.$vrednost.'\'); return false;"><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vrednost_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';
+ }
+
+ echo '</form>';
+ }
+
+ /**
+ * hiter upload slike, ki se odpre v popupu - V DELU
+ *
+ */
+ function vrednost_insert_image ($vrednost) {
+ global $lang;
+
+ $lang_id = $_POST['lang_id'];
+
+ $sql = sisplet_query("SELECT spr_id, naslov, variable FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+
+ echo '<form name="vrednost_insert_image_form" onsubmit="vrednost_insert_image_save(); return false;">';
+
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'">';
+ echo '<input type="hidden" name="spremenljivka" value="'.$row['spr_id'].'">';
+ echo '<input type="hidden" name="vrednost" value="'.$vrednost.'">';
+ echo '<input type="hidden" name="vrednost_variable" value="'.$row['variable'].'">';
+ echo '<input type="hidden" name="lang_id" value="'.$lang_id.'">';
+
+ // Textovno polje in naložena vsebina
+ echo '<br />';
+ echo '<textarea name="vrednost_naslov" id="hitro-nalaganje-slike">'.$row['naslov'].'</textarea>';
+
+ echo '<br /><br />';
+
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vrednost_insert_image_save ('.$vrednost.'); return false;"><span>'.$lang['srv_potrdi'].'</span></a>'."\n\r";
+ echo '</span>';
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vrednost_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';
+
+ echo '</form>';
+ }
+
+ /**
+ * urejanje slike in obmocij za hotspot, ki se odpre v popupu
+ *
+ */
+
+ function hotspot_edit ($spr_id) {
+ global $lang;
+
+ $lang_id = $_POST['lang_id'];
+ $spr_id = $_POST['spr_id'];
+
+ //$sql = sisplet_query("SELECT * FROM srv_vrednost WHERE id = '$vrednost'");
+ $sql = sisplet_query("SELECT id, tip, enota, params, orientation, design FROM srv_spremenljivka WHERE id = '$spr_id'");
+ $row = mysqli_fetch_array($sql);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $hotspot_image = ($spremenljivkaParams->get('hotspot_image') ? $spremenljivkaParams->get('hotspot_image') : "");
+ //$rows = Cache::srv_spremenljivka($row['spr_id']);
+
+ if($row['tip'] == 1 || $row['tip'] == 2){
+ $enota_orientation = $row['orientation'];
+ }else if($row['tip'] == 6){
+ $enota_orientation = $row['enota'];
+ }else if($row['tip'] == 17){
+ $enota_orientation = $row['design'];
+ }
+
+
+ echo '<form name="hotspot_image_edit" onsubmit="hotspot_image_save(); return false;">';
+
+ echo '<input type="hidden" name="spremenljivka" value="'.$spr_id.'">';
+
+ echo '<div style="clear:both;"></div>';
+
+ //izris editorja s sliko
+ echo '<div><textarea id="hotspot_image" name="hotspot_image" style="width:99%">'.$hotspot_image.'</textarea></div>';
+ //izris editorja s sliko - konec
+
+ echo '<br />';
+
+ //gumb Potrdi
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="hotspot_image_save(\''.$row['id'].'\'); hotspot_image_resize(\''.$row['id'].'\'); show_hot_spot_settings_from_editor (\''.$row['id'].'\', \''.$enota_orientation.'\', \''.$row['tip'].'\'); hotspot_image_button_update(\''.$row['id'].'\', \''.$lang['srv_hot_spot_load_image'].'\', \''.$lang['srv_hot_spot_edit_image'].'\'); return false; "><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+ //gumb Potrdi - konec
+
+ //gumb Zapri
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vrednost_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';
+ //gumb Zapri - konec
+
+ echo '</form>';
+
+ }
+
+ function hotspot_edit_regions () {
+ global $lang;
+
+ $lang_id = $_POST['lang_id'];
+
+ $vrednost = $_POST['vrednost'];
+ $sql = sisplet_query("SELECT id, spr_id, naslov FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+
+ $rows = Cache::srv_spremenljivka($row['spr_id']);
+ $spremenljivkaParams = new enkaParameters($rows['params']);
+ $hotspot_image = ($spremenljivkaParams->get('hotspot_image') ? $spremenljivkaParams->get('hotspot_image') : "");
+
+ $src_image = $_POST['src_image'];
+ $hotspot_image_height = $_POST['hotspot_image_height'];
+ $hotspot_image_width = $_POST['hotspot_image_width'];
+ $spr_id = $rows['id'];
+ //$region_name = $_POST['region_name'];
+
+ //echo $vrednost;
+ //poberi iz baze, kateri je zadnji vneseni indeks obmocja $last_hotspot_region_index
+ //$sqlR = sisplet_query("SELECT * FROM srv_hotspot_regions WHERE spr_id = $spr_id order by region_index DESC LIMIT 1");
+ $sqlR = sisplet_query("SELECT region_index FROM srv_hotspot_regions WHERE spr_id = $spr_id order by region_index DESC LIMIT 1");
+ //$sqlR2 = sisplet_query("SELECT * FROM srv_hotspot_regions WHERE spr_id = $spr_id AND vre_id = $vrednost");
+ $sqlR2 = sisplet_query("SELECT region_coords, region_name, region_index FROM srv_hotspot_regions WHERE spr_id = $spr_id AND vre_id = $vrednost");
+ //$sqlR3 = sisplet_query("SELECT * FROM srv_hotspot_regions WHERE spr_id= $spr_id ");
+ $sqlR3 = sisplet_query("SELECT region_coords, vre_id FROM srv_hotspot_regions WHERE spr_id= $spr_id ");
+
+ $rowR = mysqli_fetch_array($sqlR);
+ $rowR2 = mysqli_fetch_array($sqlR2);
+
+ if(mysqli_num_rows($sqlR) == 0){
+ $last_hotspot_region_index = -1;
+ }else{
+ $last_hotspot_region_index = $rowR['region_index'];
+ }
+
+ if(mysqli_num_rows($sqlR2) != 0){
+ $hotspot_image_coords = $rowR2['region_coords'];
+ $region_name = $rowR2['region_name'];
+ $hotspot_region_index = $rowR2['region_index'];
+ }else{
+ $region_name = "";
+ $hotspot_region_index = -2;
+ }
+
+
+ echo '<form name="hotspot_region_edit" onsubmit="hotspot_save_regions(); return false;">';
+ //echo '$last_hotspot_region_index: '.$last_hotspot_region_index;
+ //echo '$hotspot_region_index: '.$hotspot_region_index;
+
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'">';
+ echo '<input type="hidden" name="spremenljivka" value="'.$row['spr_id'].'">';
+ echo '<input type="hidden" name="vrednost" value="'.$vrednost.'">';
+ echo '<input type="hidden" name="lang_id" value="'.$lang_id.'">';
+
+ echo '<div><p id="slika_'.$row['spr_id'].'" style="width:99%; display: none;">'.$row['naslov'].'</p></div>';
+
+ echo '<div id="slika_'.$row['spr_id'].'_container" >';
+
+ //********* za prikazovanje obstojecih obmocij @ urejanju/dodajanju novega obmocja ********
+
+ $findme = 'img';
+ $pos = strpos($hotspot_image, $findme);
+ if($pos === false) { //string NOT present
+
+ }
+ else { //string present
+ $usemap = 'id="hotspot_'.$row['id'].'_image" usemap="#hotspot_'.$row['id'].'_usemap" style="z-index: 1; height:'.$hotspot_image_height.'px; width: '.$hotspot_image_width.'px; position: relative; top: 15px;"'; //z-index: 1, da bo slika pod canvas in prave dimenzije in na pravi poziciji
+ //v $hotspot_image je potrebno dodati usemap="#hotspot_image_'.$row['id'].'" za identificiranje mape
+ $hotspot_image = substr_replace($hotspot_image, $usemap, 5, 0); //dodaj zeleni string v $hotspot_image
+ }
+
+ //prikaz slike
+ echo $hotspot_image;
+
+ //ureditev map
+ if(mysqli_num_rows($sqlR3) != 0){ //ce je kaksno obmocje v bazi
+ echo '<map id="hotspot_'.$row['id'].'_map" name="hotspot_'.$row['id'].'_usemap">';
+ while ($rowR3 = mysqli_fetch_array($sqlR3)) {
+ echo '<area coords="'.$rowR3['region_coords'].'" name="'.$rowR3['vre_id'].'" shape="poly" href="#">';
+ }
+ echo '</map>';
+ }
+
+ ?>
+ <script>
+ $(document).ready(function () {
+ mapinit_editor(<?=$row['id']?>); //uredi delovanje imagemapster in prikazovanja obmocij ter tooltip-ov
+ });
+ </script>
+ <?
+
+ //********* za prikazovanje obstojecih obmocij @ urejanju/dodajanju novega obmocja - konec *********
+
+ echo '<div style="clear:both;"></div>';
+
+ echo '
+ <script language="javascript" type="text/javascript" src="./script/jquery/jquery.canvasAreaDraw.js"></script>
+ <textarea id="hotspot_region_coords_'.$row['spr_id'].'" style="display: none;" rows=3 name="hotspot_region_coords_'.$row['spr_id'].'" class="canvas-area" disabled
+ placeholder="Shape Coordinates"
+ data-image-url="'.$src_image.'" data-canvas-id="canvas_'.$row['spr_id'].'" data-spr-id="'.$row['spr_id'].'" image-height="'.$hotspot_image_height.'" image-width="'.$hotspot_image_width.'" image-coords="'.$hotspot_image_coords.'" clear_button="'.$lang['srv_hotspot_clear_region_points'].'"></textarea>
+ ';
+
+ echo '</div>';
+
+ echo '<br />';
+
+
+ //polje za vnos imena obmocja
+ echo '<span class="buttonwrapper spaceRight">';
+ echo $lang['srv_hot_spot_region_name'].': ';
+ echo '<input name="hotspot_region_name" value="'.$region_name.'">';
+ echo '</span>';
+ //polje za vnos imena obmocja - konec
+
+ echo '<br />';
+ echo '<br />';
+
+
+ //gumb Potrdi
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="hotspot_save_regions('.$row['spr_id'].', '.$last_hotspot_region_index.', '.$vrednost.', '.$hotspot_region_index.'); return false; "><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+ //gumb Potrdi - konec
+
+ //gumb Zapri - konec
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="hotspot_region_cancel('.$row['spr_id'].', '.$vrednost.'); vrednost_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';
+ //gumb Zapri - konec
+
+ //tekst z navodili
+ echo '<br />';
+ echo '<br />'.$lang['srv_hotspot_edit_region_msg'];
+ echo '<div id="hotspot_tips_'.$row['spr_id'].'" style="display:none">'.$lang['srv_hotspot_edit_region_tip_delete'].' <br />
+ '.$lang['srv_hotspot_edit_region_tip_move'].'</div>';
+ //tekst z navodili - konec
+
+
+ echo '</form>';
+ }
+
+ /**
+ * hitro dodajanje vrednosti preko textarea
+ *
+ */
+ function vrednost_fastadd() {
+ global $lang;
+
+ echo '<h2>'.$lang['srv_vrednost_fastadd'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="vrednost_cancel(); return false;">✕</a></div>';
+
+ echo '<form name="vrednost_fastadd_form" onsubmit="vrednost_fastadd_save(); return false;">';
+
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'" />';
+ echo '<input type="hidden" name="spremenljivka" value="'.$this->spremenljivka.'" />';
+
+ echo '<p><textarea name="fastadd" style="width:99%; height:100px"></textarea></p>';
+
+ echo '<p>'.$lang['srv_vrednost_fastadd_txt'].'</p>';
+
+ echo '<span class="buttonwrapper floatRight">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="vrednost_fastadd_save(\''.$this->spremenljivka.'\'); return false;"><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper spaceRight floatRight">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vrednost_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';
+
+ echo '</form>';
+
+ ?><script> $('textarea[name=fastadd]').focus(); </script><?php
+ }
+
+ //editiranje vrednosti pri besedilu
+ function edit_vrednost_besedilo(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $taSize = ($spremenljivkaParams->get('taSize') ? $spremenljivkaParams->get('taSize') : 1);
+ $taWidth = ($spremenljivkaParams->get('taWidth') ? $spremenljivkaParams->get('taWidth') : -1);
+
+ //default sirina
+ if($taWidth == -1)
+ $taWidth = 30;
+
+ echo '<input type="hidden" name="edit_vrednost_besedilo" value="1" />';
+
+ # manjkajoče vrednosti
+ //dodatne missing vrednosti (ne vem, zavrnil...)
+ # preberemo iz class.SurveyMissingValues
+ $smv = new SurveyMissingValues($this->anketa);
+ # katere missinge imamo na voljo
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+
+ #kateri missingi so nastavljeni
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+
+
+ echo '<p>';
+
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ echo '<input type="checkbox" '.(isset($already_set_mv[$mv_key]) ? ' checked="checked"' : '').' onChange="vrednost_new_dodatne(\'' . $row['id'] . '\', \''.$mv_key.'\', \''.$row['tip'].'\', this.checked); show_alert_missing();" id="missing_value_'.$mv_key.'">';
+ echo '<label for="missing_value_'.$mv_key.'" class="pointer">'.$mv_text.'</label>';
+ }
+ }
+ echo '</p>';
+ }
+
+ //editiranje vrednosti pri number
+ function edit_vrednost_number(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $taWidth = ($spremenljivkaParams->get('taWidth') ? $spremenljivkaParams->get('taWidth') : -1);
+ //default sirina
+ if($taWidth == -1)
+ $taWidth = 10;
+
+ echo '<input type="hidden" name="edit_vrednost_number" value="1" />';
+
+
+ //dodatne missing vrednosti (ne vem, zavrnil...)
+ # preberemo iz class.SurveyMissingValues
+ $smv = new SurveyMissingValues($this->anketa);
+ # katere missinge imamo na voljo
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+
+ #kateri missingi so nastavljeni
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+
+
+ echo '<p>';
+
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ echo '<input type="checkbox" '.(isset($already_set_mv[$mv_key]) ? ' checked="checked"' : '').' onChange="vrednost_new_dodatne(\'' . $row['id'] . '\', \''.$mv_key.'\', \''.$row['tip'].'\', this.checked); show_alert_missing();" id="missing_value_'.$mv_key.'">';
+ echo '<label for="missing_value_'.$mv_key.'" class="pointer">'.$mv_text.'</label>';
+ }
+ }
+ echo '</p>';
+ }
+
+ //editiranje vrednosti pri datumu
+ function edit_vrednost_datum(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ # manjkajoče vrednosti
+
+ //dodatne missing vrednosti (ne vem, zavrnil...)
+ # preberemo iz class.SurveyMissingValues
+ $smv = new SurveyMissingValues($this->anketa);
+ # katere missinge imamo na voljo
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+
+ #kateri missingi so nastavljeni
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+
+
+ echo '<p>';
+
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ echo '<input type="checkbox" '.(isset($already_set_mv[$mv_key]) ? ' checked="checked"' : '').' onChange="vrednost_new_dodatne(\'' . $row['id'] . '\', \''.$mv_key.'\', \''.$row['tip'].'\', this.checked); show_alert_missing();" id="missing_value_'.$mv_key.'">';
+ echo '<label for="missing_value_'.$mv_key.'" class="pointer">'.$mv_text.'</label>';
+ }
+ }
+ echo '</p>';
+
+ }
+
+ function edit_grid_subtype(){
+ global $lang;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+
+ $prikazi_vas_ali_slikovni_tip = 'show_custom_picture_radio(\''.$row['id'].'\', this.value);';
+
+ echo '<p><span class="title">'.$lang['srv_orientacija'].':</span>';
+ //echo '<span class="content"><select id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" name="enota" onChange="change_diferencial(\'' . $row['id'] . '\', this.value); show_selectbox_size(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_nastavitve_tabela_da_ne(\'' . $row['id'] . '\', this.value); max_diff_labels(\'' . $row['id'] . '\', this.value, \'' . $lang['srv_maxdiff_label1'] . '\',\'' . $lang['srv_maxdiff_label2'] . '\',\'' . $lang['srv_new_grid'] . '\'); show_hot_spot_settings(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_preset_value(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_drag_and_drop_new_look_option(\'' . $row['id'] . '\', this.value);">';
+ echo '<span class="content"><select id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" name="enota" onChange="change_diferencial(\'' . $row['id'] . '\', this.value); show_selectbox_size(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_nastavitve_tabela_da_ne(\'' . $row['id'] . '\', this.value); max_diff_labels(\'' . $row['id'] . '\', this.value, \'' . $lang['srv_maxdiff_label1'] . '\',\'' . $lang['srv_maxdiff_label2'] . '\',\'' . $lang['srv_new_grid'] . '\'); show_hot_spot_settings(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_preset_value(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_drag_and_drop_new_look_option(\'' . $row['id'] . '\', this.value); '.$prikazi_vas_ali_slikovni_tip.'">';
+
+ echo '<option value="0" '.(($row['enota'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_classic'].'</option>';
+ //te izbire niso mozne pri multicheckboxu
+ if($row['tip'] == 6){
+ echo '<option value="1" '.(($row['enota'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_diferencial2'].'</option>';
+ echo '<option value="2" '.(($row['enota'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_dropdown'].'</option>';
+ echo '<option value="4" '.(($row['enota'] == 4) ? ' selected="true" ' : '').'>'.$lang['srv_one_against_another'].'</option>';
+ echo '<option value="5" '.(($row['enota'] == 5) ? ' selected="true" ' : '').'>'.$lang['srv_max_diff'].'</option>';
+ echo '<option value="8"' . ($row['enota'] == 8 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_tabela_da_ne'].'</option>';
+ //echo '<option value="6" '.(($row['enota'] == 6) ? ' selected="true" ' : '').'>'.$lang['srv_select-box_radio'].'</option>';
+ //echo '<option value="9"' . ($row['enota'] == 9 ? ' selected="true"' : '') . '>'.$lang['srv_drag_drop'].'</option>';
+ echo '<option value="10"' . ($row['enota'] == 10 ? ' selected="true"' : '') . '>'.$lang['srv_hot_spot'].'</option>';
+ echo '<option value="11"' . ($row['enota'] == 11 ? ' selected="true"' : '') . '>'.$lang['srv_visual_analog_scale'].'</option>';
+ echo '<option value="12"' . ($row['enota'] == 12 ? ' selected="true"' : '') . '>'.$lang['srv_custom-picture_radio'].'</option>';
+ }
+
+ # dvonji grid je na voljo samo za mgrid, dokler se ne uredi še za checkbox - CHECKBOX DELA VREDU?
+ //if($row['tip'] == 6){
+ echo '<option value="3" '.(($row['enota'] == 3) ? ' selected="true" ' : '').'>'.$lang['srv_double_grid'].'</option>';
+ echo '<option value="6" '.(($row['enota'] == 6) ? ' selected="true" ' : '').'>'.$lang['srv_select-box_radio'].'</option>';
+ echo '<option value="9"' . ($row['enota'] == 9 ? ' selected="true"' : '') . '>'.$lang['srv_drag_drop'].'</option>';
+ //}
+ if ($admin_type == 0){
+ //echo '<option value="6" '.(($row['enota'] == 6) ? ' selected="true" ' : '').'>'.$lang['srv_select-box_radio'].'</option>';
+ //echo '<option value="9"' . ($row['enota'] == 9 ? ' selected="true"' : '') . '>'.$lang['srv_drag_drop'].'</option>';
+ if($row['tip'] == 6){
+ //echo '<option value="10"' . ($row['enota'] == 10 ? ' selected="true"' : '') . '>'.$lang['srv_hot_spot'].'</option>';
+ }
+ }
+
+ echo '</select>';
+ echo '</span></p>';
+ }
+
+ function edit_grid_dynamic () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // dinamicen multigrid
+ if($row['tip'] == 6){
+ echo '<p><label class="title">'.$lang['srv_dynamic_multigrid'].':</label>';
+ echo '<span class="content"><input type="hidden" name="dynamic_mg" value="0" />';
+
+ echo '<select id="dynamic_mg" name="dynamic_mg" onChange="onchange_submit_show(this.value);">';
+ echo '<option value="0" '.(($row['dynamic_mg'] == 0) ? ' selected="true" ' : '').'>'.$lang['no'].'</option>';
+ echo '<option value="1" '.(($row['dynamic_mg'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_orientacija_horizontalna_3'].'</option>';
+ echo '<option value="3" '.(($row['dynamic_mg'] == 3) ? ' selected="true" ' : '').'>'.$lang['srv_orientacija_horizontalna_3'].'_2</option>';
+ echo '<option value="5" '.(($row['dynamic_mg'] == 5) ? ' selected="true" ' : '').'>'.$lang['srv_orientacija_horizontalna_3'].'_3</option>';
+ echo '<option value="2" '.(($row['dynamic_mg'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_orientacija_vertikalna'].'</option>';
+ echo '<option value="4" '.(($row['dynamic_mg'] == 4) ? ' selected="true" ' : '').'>'.$lang['srv_orientacija_vertikalna'].'_2</option>';
+ echo '<option value="6" '.(($row['dynamic_mg'] == 6) ? ' selected="true" ' : '').'>'.$lang['srv_orientacija_vertikalna'].'_3</option>';
+ echo '</select>';
+
+ //echo '<input type="checkbox" id="dynamic_mg" name="dynamic_mg" value="1" '.($row['dynamic_mg'] == '1' ?' checked' : '').'></span>';
+ echo '</span></p>';
+ }
+ }
+
+ // nastavitev reminderja
+ function edit_reminder() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_reminder'].':</span>';
+ echo '<span class="content"><select name="reminder" id="reminder" onChange="show_alert_missing();">';
+ echo '<option value="0" '.(($row['reminder'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_reminder_off'].'</option>';
+ echo '<option value="1" '.(($row['reminder'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_reminder_soft'].'</option>';
+ echo '<option value="2" '.(($row['reminder'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_reminder_hard'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // Nastavitev za naknaden prikaz odgovora ne vem
+ function edit_alert_show_missing(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ if($row['reminder'] == 0)
+ $show = array('97'=>false, '98'=>false, '99'=>false);
+ else
+ $show = array('97'=>true, '98'=>true, '99'=>true);
+
+ // Imamo missing v gridu
+ if(in_array($row['tip'], array(6,16,19,20,24))){
+
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_grid WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+
+ if(!isset($already_set_mv['-97']))
+ $show['97'] = false;
+
+ if(!isset($already_set_mv['-98']))
+ $show['98'] = false;
+
+ if(!isset($already_set_mv['-99']))
+ $show['99'] = false;
+ }
+ // Imamo missing variablo
+ else{
+
+ $already_set_mv = array();
+ $sql_grid_mv = sisplet_query("SELECT naslov, other FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ while ($row_grid_mv = mysqli_fetch_array($sql_grid_mv)) {
+ $already_set_mv[$row_grid_mv['other']] = $row_grid_mv['naslov'];
+ }
+
+ if(!isset($already_set_mv['-97']))
+ $show['97'] = false;
+
+ if(!isset($already_set_mv['-98']))
+ $show['98'] = false;
+
+ if(!isset($already_set_mv['-99']))
+ $show['99'] = false;
+ }
+
+ echo '<div id="alert_show_missing">';
+
+ // Prikaz -97 (neustrezno) ob opozorilu
+ echo '<p><label for="alert_show_97" class="title"><span id="alert_show_97_text" class="'.($show['97']?'':' gray').'">'.$lang['srv_alert_show_missing_97'].':</span></label> '.Help::display('srv_alert_show_97');
+ echo '<span class="content"><input type="hidden" name="alert_show_97" value="0" />';
+ echo '<input type="checkbox" id="alert_show_97" name="alert_show_97" value="1" '.($row['alert_show_97']=='1'?' checked':'').' '.($show['97'] ? '' : ' disabled="disabled"').'></span>';
+ echo '</p>';
+ // Prikaz -98 (Zavrnil) ob opozorilu
+ echo '<p><label for="alert_show_98" class="title"><span id="alert_show_98_text" class="'.($show['98']?'':' gray').'">'.$lang['srv_alert_show_missing_98'].':</span></label> '.Help::display('srv_alert_show_98');
+ echo '<span class="content"><input type="hidden" name="alert_show_98" value="0" />';
+ echo '<input type="checkbox" id="alert_show_98" name="alert_show_98" value="1" '.($row['alert_show_98']=='1'?' checked':'').' '.($show['98'] ? '' : ' disabled="disabled"').'></span>';
+ echo '</p>';
+ // Prikaz -99 (ne vem) ob opozorilu
+ echo '<p><label for="alert_show_99" class="title"><span id="alert_show_99_text" class="'.($show['99']?'':' gray').'">'.$lang['srv_alert_show_missing'].':</span></label> '.Help::display('srv_alert_show_99');
+ echo '<span class="content"><input type="hidden" name="alert_show_99" value="0" />';
+ echo '<input type="checkbox" id="alert_show_99" name="alert_show_99" value="1" '.($row['alert_show_99']=='1'?' checked':'').' '.($show['99'] ? '' : ' disabled="disabled"').'></span>';
+ echo '</p>';
+
+ echo '</div>';
+ }
+
+ // nastavitev ravrscanja vrednosti spr
+ /**
+ * 0 = sort po vrstnem redu
+ * 1 = sort random
+ * 2 = sort po abecedi naraščajoče
+ * 3 = sort po abecedi padajoče
+ */
+ function edit_random() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+
+ if ( in_array($row['tip'], array(6, 16, 19, 20)) )
+ echo '<span class="title">'.$lang['srv_sort_grid'].': </span>';
+ else
+ echo '<span class="title">'.$lang['srv_sort'].': </span>';
+
+ echo '<span class="content"><select name="random">';
+ echo '<option value="0" '.(($row['random'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_random_off2'].'</option>';
+ echo '<option value="1" '.(($row['random'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_random_on2'].'</option>';
+ echo '<option value="2" '.(($row['random'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_sort_asc2'].'</option>';
+ echo '<option value="3" '.(($row['random'] == 3) ? ' selected="true" ' : '').'>'.$lang['srv_sort_desc2'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // nastavitev stevila stolpcev v prikazu
+ function edit_stolpci () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ if ($row['orientation'] != 1)
+ return;
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $stolpci = ($spremenljivkaParams->get('stolpci') ? $spremenljivkaParams->get('stolpci') : 1);
+
+ echo '<p><span class="title">'.$lang['srv_stolpci'].': </span>';
+ echo '<span class="content"><select name="stolpci">';
+ echo '<option value="1" '.(($stolpci == 1) ? ' selected="true" ' : '').'>'.$lang['no'].'</option>';
+ echo '<option value="2" '.(($stolpci == 2) ? ' selected="true" ' : '').'>2</option>';
+ echo '<option value="3" '.(($stolpci == 3) ? ' selected="true" ' : '').'>3</option>';
+ echo '<option value="4" '.(($stolpci == 4) ? ' selected="true" ' : '').'>4</option>';
+ echo '<option value="5" '.(($stolpci == 5) ? ' selected="true" ' : '').'>5</option>';
+ echo '</select></span>';
+ echo '</p>';
+
+ }
+
+ // nastavitev skale
+ function edit_skala_new() {
+ global $lang;
+
+ $value = Common::getSpremenljivkaSkala($this->spremenljivka);
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ # v bazi je privzeto -1
+ # skala - 1 Nominalna
+ # skala - 0 Ordinalna - računamo povprečja
+ //$display = (($row['tip'] == 6 && $row['enota'] == 8)) ? ' style="display:none;"' : '';
+
+ //echo '<fieldset '.$display.'><legend>'.$lang['srv_measurment_scale'].' '.Help::display('srv_skala_edit').'</legend>';
+ echo '<fieldset><legend>'.$lang['srv_measurment_scale'].' '.Help::display('srv_skala_edit').'</legend>';
+
+ echo '<p>';
+ echo '<input type="radio" name="skala" id="skala_0" value="0" '.(($value == 0 || $value == -1) ? ' checked="checked" ' : '').' onClick="show_scale_text(0)" /><label for="skala_0" class="spaceRight">'.$lang['srv_skala_0'].'</label>';
+ echo '<input type="radio" name="skala" id="skala_1" value="1" '.(($value == 1) ? ' checked="checked" ' : '').' onClick="show_scale_text(1)" /><label for="skala_1">'.$lang['srv_skala_1'].'</label>';
+ echo '</p>';
+
+ echo '<span id="skala_text_ord" class="spaceLeft" '.($value==0 || $value == -1 ? '' : ' style="display:none;"').'>'.$lang['srv_measurment_scale_ord'].' '.Help::display('srv_skala_text_ord').'</span>';
+ echo '<span id="skala_text_nom" class="spaceLeft" '.($value==1 ? '' : ' style="display:none;"').'>'.$lang['srv_measurment_scale_nom'].' '.Help::display('srv_skala_text_nom').'</span>';
+
+ echo '</fieldset>';
+ }
+
+ // prikaz checkboxa
+ function edit_checkboxhide() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<label for="checkboxhide" class="title">'.$lang['srv_checkboxhide_enabled'].':</label>';
+ //echo '<input type="radio" name="checkboxhide" value="1" '.(($row['checkboxhide'] == 1) ? ' checked="checked" ' : '').' />'.$lang['yes'];
+ //echo '<input type="radio" name="checkboxhide" value="0" '.(($row['checkboxhide'] == 0) ? ' checked="checked" ' : '').' />'.$lang['no1'];
+ echo '<span class="content"><input type="hidden" name="checkboxhide" value="1" />';
+ echo '<input type="checkbox" id="checkboxhide" name="checkboxhide" value="0" '.(($row['checkboxhide'] == 0) ? ' checked="checked" ' : '').' />';
+ echo '</span></p>';
+ }
+
+ //bivsa edit_checkbox_limit()
+ function edit_checkbox_max_limit() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $checkbox_limit = ($spremenljivkaParams->get('checkbox_limit') ? $spremenljivkaParams->get('checkbox_limit') : 0);
+
+ $sqlc = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id='$this->spremenljivka'");
+ $rowc = mysqli_fetch_array($sqlc);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_checkbox_max_limit'].':</span>';
+ echo '<span class="content"><select name="checkbox_limit" id="checkbox_limit_'.$this->spremenljivka.'" onChange="checkCheckboxLimits(\'' . $row['id'] . '\', $(this).val(), \'checkbox_limit\');">';
+ echo '<option value="0" '.(($checkbox_limit == 0) ? ' selected="true" ' : '').'>'.$lang['no'].'</option>';
+ for ($i=1; $i<=$rowc['count']; $i++) {
+ echo '<option value="'.$i.'" '.(($checkbox_limit == $i) ? ' selected="true" ' : '').'>'.$i.'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+
+ function edit_checkbox_min_limit() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $checkbox_min_limit = ($spremenljivkaParams->get('checkbox_min_limit') ? $spremenljivkaParams->get('checkbox_min_limit') : 0);
+
+ $sqlc = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id='$this->spremenljivka'");
+ $rowc = mysqli_fetch_array($sqlc);
+ //$maxNumberOfAnswers = $rowc['count'] - 1;
+ $maxNumberOfAnswers = $rowc['count'];
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_checkbox_min_limit'].':</span>';
+ echo '<span class="content"><select name="checkbox_min_limit" id="checkbox_min_limit_'.$this->spremenljivka.'" onChange="checkCheckboxLimits(\'' . $row['id'] . '\', $(this).val(), \'checkbox_min_limit\'); toggleCheckboxMinLimitReminder(\'' . $row['id'] . '\', $(this).val());">';
+ echo '<option value="0" '.(($checkbox_min_limit == 0) ? ' selected="true" ' : '').'>'.$lang['no'].'</option>';
+ for ($i=1; $i<=$maxNumberOfAnswers; $i++) {
+ echo '<option value="'.$i.'" '.(($checkbox_min_limit == $i) ? ' selected="true" ' : '').'>'.$i.'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+
+ $this->edit_reminder_min_checkbox($checkbox_min_limit);
+ }
+
+ // nastavitev reminderja za minimalno stevilo izbranih checkbox-ox
+ function edit_reminder_min_checkbox($checkbox_min_limit) {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $checkbox_min_limit_reminder = ($spremenljivkaParams->get('checkbox_min_limit_reminder') ? $spremenljivkaParams->get('checkbox_min_limit_reminder') : 0);
+
+ if($checkbox_min_limit){
+ $displayReminder = " ";
+ }else{
+ $displayReminder = "none";
+ }
+
+ echo '<p id="checkboxLimitReminder_'.$row['id'].'" style="display:'.$displayReminder.'">';
+ echo '<span class="title">'.$lang['srv_checkbox_min_limit_reminder'].':</span>';
+ //echo '<span class="content"><select name="reminder" id="reminder" onChange="show_alert_missing();">';
+ echo '<span class="content"><select name="checkbox_min_limit_reminder" id="checkbox_min_limit_reminder">';
+ echo '<option value="0" '.(($checkbox_min_limit_reminder == 0) ? ' selected="true" ' : '').'>'.$lang['srv_reminder_off2'].'</option>';
+ echo '<option value="1" '.(($checkbox_min_limit_reminder == 1) ? ' selected="true" ' : '').'>'.$lang['srv_reminder_soft2'].'</option>';
+ echo '<option value="2" '.(($checkbox_min_limit_reminder == 2) ? ' selected="true" ' : '').'>'.$lang['srv_reminder_hard2'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // editiranje radio tipa (1) - navaden, horizontalen, dropdown, semanticni diferencial
+ function edit_radio_subtype() {
+ global $lang;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title" >'.$lang['srv_orientacija'].': </span>';
+ echo '<span class="content"><select name="orientation" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" onChange="getOrientation(this.value); show_selectbox_size(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_preset_value(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_custom_picture_radio(\''.$row['id'].'\', this.value); show_hot_spot_settings(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\');">';
+ echo '<option value="1"' . ($row['orientation'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_vertikalna'].'</option>';
+ echo '<option value="7"' . ($row['orientation'] == 7 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_vertikalna_2'].'</option>';
+ echo '<option value="0"' . ($row['orientation'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_horizontalna'].'</option>';
+ echo '<option value="2"' . ($row['orientation'] == 2 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_horizontalna_2'].'</option>';
+ echo '<option value="4"' . ($row['tip'] == 3 ? ' selected="true"' : '') . '>'.$lang['srv_dropdown'].'</option>';
+ echo '<option value="6"' . ($row['orientation'] == 6 ? ' selected="true"' : '') . '>'.$lang['srv_select-box_radio'].'</option>';
+ echo '<option value="8"' . ($row['orientation'] == 8 ? ' selected="true"' : '') . '>'.$lang['srv_drag_drop'].'</option>';
+ echo '<option value="9"' . ($row['orientation'] == 9 ? ' selected="true"' : '') . '>'.$lang['srv_custom-picture_radio'].'</option>'; // Custom picture za radio tip
+ echo '<option value="10"' . ($row['orientation'] == 10 ? ' selected="true"' : '') . '>'.$lang['srv_hot_spot'].'</option>'; //image hotspot
+ echo '<option value="11"' . ($row['orientation'] == 11 ? ' selected="true"' : '') . '>'.$lang['srv_visual_analog_scale'].'</option>'; //vizualna analaogna skala - smeški
+ echo '<option value="5"' . ($row['hidden_default'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_potrditev'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // editiranje orientacije chackboxa
+ function edit_checkbox_subtype() {
+ global $lang;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_orientacija'].':</span>';
+ //echo '<span class="content"><select name="orientation" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" onChange="getOrientation(this.value); show_selectbox_size(\'' . $row['id'] . '\', this.value);">';
+ echo '<span class="content"><select name="orientation" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" onChange="getOrientation(this.value); show_selectbox_size(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_preset_value(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\'); show_hot_spot_settings(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\');">';
+ echo '<option value="1"' . ($row['orientation'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_vertikalna'].'</option>';
+ echo '<option value="7"' . ($row['orientation'] == 7 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_vertikalna_2'].'</option>';
+ echo '<option value="0"' . ($row['orientation'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_horizontalna'].'</option>';
+ echo '<option value="2"' . ($row['orientation'] == 2 ? ' selected="true"' : '') . '>'.$lang['srv_orientacija_horizontalna_2'].'</option>';
+ echo '<option value="6"' . ($row['orientation'] == 6 ? ' selected="true"' : '') . '>'.$lang['srv_select-box_check'].'</option>';
+ echo '<option value="8"' . ($row['orientation'] == 8 ? ' selected="true"' : '') . '>'.$lang['srv_drag_drop'].'</option>';
+ echo '<option value="10"' . ($row['orientation'] == 10 ? ' selected="true"' : '') . '>'.$lang['srv_hot_spot'].'</option>'; //image hotspot
+ if ($admin_type == 0){
+ //echo '<option value="6"' . ($row['orientation'] == 6 ? ' selected="true"' : '') . '>'.$lang['srv_select-box_check'].'</option>';
+
+ }
+ //echo '<option value="6"' . ($row['orientation'] == 6 ? ' selected="true"' : '') . '>'.$lang['srv_mutliselect-box'].'</option>';
+ echo '</select>';
+ echo '</span></p>';
+ }
+
+ // navaden number ali slider
+ function edit_subtype_number () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_number_insert'].':</span>';
+ // //echo '<span class="content"><select name="ranking_k" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" class="no_submit" onchange="change_subtype_number(\''.$row['id'].'\');">';
+ // echo '<span class="content"><select name="ranking_k" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" class="no_submit" onchange="change_subtype_number(\''.$row['id'].'\'); show_slider_prop(\''.$row['id'].'\',this.value)">';
+ // echo '<option value="0"' . ($row['ranking_k'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_0'].'</option>';
+ // echo '<option value="1"' . ($row['ranking_k'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_1'].'</option>';
+ // echo '</select>';
+ //echo '<p>';
+ echo '<span class="content">';
+ echo '<input type="radio" name="ranking_k" id="select_num_0" value="0" '.(($row['ranking_k'] == 0) ? ' checked="checked" ' : '').' onClick="change_subtype_number(\''.$row['id'].'\'); show_slider_prop(\''.$row['id'].'\',this.value)" /><label for="select_num_0">'.$lang['srv_number_insert_0_new'].'</label>';
+ echo '<input type="radio" name="ranking_k" id="select_num_1" value="1" '.(($row['ranking_k'] == 1) ? ' checked="checked" ' : '').' onClick="change_subtype_number(\''.$row['id'].'\'); show_slider_prop(\''.$row['id'].'\',this.value)"/><label for="select_num_1">'.$lang['srv_number_insert_1'].'</label>';
+
+ //echo '</p>';
+ echo '</span></p>';
+ }
+
+ // navaden number ali slider
+ function edit_subtype_multinumber () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_number_insert'].':</span>';
+ // echo '<span class="content"><select name="ranking_k" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" class="no_submit" onchange="change_subtype_number(\''.$row['id'].'\');">';
+ // echo '<option value="0"' . ($row['ranking_k'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_0'].'</option>';
+ // echo '<option value="1"' . ($row['ranking_k'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_1'].'</option>';
+ // echo '<option value="2"' . ($row['ranking_k'] == 2 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_2'].'</option>';
+ // echo '<option value="3"' . ($row['ranking_k'] == 3 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_3'].'</option>';
+ // echo '<option value="4"' . ($row['ranking_k'] == 4 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_4'].'</option>';
+ // echo '<option value="5"' . ($row['ranking_k'] == 5 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_5'].'</option>';
+ // echo '<option value="6"' . ($row['ranking_k'] == 6 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_6'].'</option>';
+ //echo '<option value="7"' . ($row['ranking_k'] == 7 ? ' selected="true"' : '') . '>'.$lang['srv_number_insert_7'].'</option>';
+ //echo '</select>';
+ //echo '</span></p>';
+ echo '<input type="radio" name="ranking_k" value="0" '.(($row['ranking_k'] == 0) ? ' checked="checked" ' : '').' onChange="change_subtype_number(\''.$row['id'].'\'); show_slider_prop(\''.$row['id'].'\',this.value)" /><label for="skala_0" class="spaceRight">'.$lang['srv_number_insert_0_new'].'</label>';
+ echo '<input type="radio" name="ranking_k" value="1" '.(($row['ranking_k'] == 1) ? ' checked="checked" ' : '').' onChange="change_subtype_number(\''.$row['id'].'\'); show_slider_prop(\''.$row['id'].'\',this.value)"/><label for="skala_1">'.$lang['srv_number_insert_1'].'</label>';
+ echo '</p>';
+
+ }
+
+ // prikaz statistike
+ function edit_stat() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<label for="stat" class="title">'.$lang['srv_stat_on'].': '.Help::display('srv_statistika').'</label>';
+ //echo '<span class="content"><input type="radio" name="stat" value="0" '.(($row['stat'] == 0) ? ' checked="checked" ' : '').' />'.$lang['no1'];
+ //echo '<input type="radio" name="stat" value="1" '.(($row['stat'] == 1) ? ' checked="checked" ' : '').' />'.$lang['yes'];
+ echo '<span class="content"><input type="hidden" name="stat" value="0" />';
+ echo '<input type="checkbox" id="stat" name="stat" value="1" '.(($row['stat'] == 1) ? ' checked="checked" ' : '').' />';
+ echo '</span></p>';
+ }
+
+ // upload pri tekstovnem polju
+ function edit_upload() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $captcha = ($spremenljivkaParams->get('captcha') ? $spremenljivkaParams->get('captcha') : 0);
+ $emailVerify = ($spremenljivkaParams->get('emailVerify') ? $spremenljivkaParams->get('emailVerify') : 0);
+
+ $disabled = ($row['signature']==1 || $captcha==1 || $emailVerify==1) ? ' disabled="disabled"' : '';
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_vprasanje_upload_type'].':</span>';
+
+ //novo, dropdown s fotografijami onChange="change_upload(\'' . $row['id'] . '\', this.value);"
+ echo '<span class="content"><select name="upload" id="spremenljivka_upload_' . $row['id'] . '" spr_id="'.$row['id'].'" '.$disabled.' onChange="textSubtypeToggle(\'upload\', this.value);">';
+ echo ' <option value="0" '.(($row['upload'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_upload_no'].'</option>';
+ echo ' <option value="1" '.(($row['upload'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_upload_yes'].'</option>';
+ echo ' <option value="2" '.(($row['upload'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_upload_fotografija'].'</option></select>';
+ echo '</p>';
+ }
+
+ // podpis pri tekstovnem polju
+ function edit_signature() {
+ global $lang;
+ global $global_user_id;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // Podpis je na voljo samo v 3. paketu
+ $userAccess = UserAccess::getInstance($global_user_id);
+ if(!$userAccess->checkUserAccess($what='question_type_signature') && $row['signature'] != 1)
+ return;
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $captcha = ($spremenljivkaParams->get('captcha') ? $spremenljivkaParams->get('captcha') : 0);
+ $emailVerify = ($spremenljivkaParams->get('emailVerify') ? $spremenljivkaParams->get('emailVerify') : 0);
+
+ $disabled = ($row['upload']>0 || $captcha==1 || $emailVerify==1) ? ' disabled="disabled"' : '';
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_tip_standard_996'].':</span>';
+
+ echo '<span class="content">';
+ echo '<input type="radio" id="signature_'.$this->spremenljivka.'_0" name="signature" '.$disabled.' onclick="signatureProp('.$this->spremenljivka.'); textSubtypeToggle(\'signature\', this.value);" value="0" '.(($row['signature'] == 0) ? ' checked="checked" ' : '').' /><label for="signature_'.$this->spremenljivka.'_0">'.$lang['no1'].'</label>';
+ echo '<input type="radio" id="signature_'.$this->spremenljivka.'" name="signature" '.$disabled.' onclick="signatureProp('.$this->spremenljivka.'); textSubtypeToggle(\'signature\', this.value);" value="1" '.(($row['signature'] == 1) ? ' checked="checked" ' : '').' /><label for="signature_'.$this->spremenljivka.'">'.$lang['yes'].'</label>';
+ echo '</span>';
+
+ echo '</p>';
+ }
+
+ // nastavitev timerja
+ function edit_timer() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<label for="_timer" class="title">Timer:</label>';
+ echo '<span class="content"><input type="hidden" name="timer" value="0" />';
+ echo '<input type="checkbox" id="_timer" name="timer" value="1" '.(($row['timer'] > 0) ? ' checked="checked" ' : '').' onchange="show_timer(this.value);" />';
+ echo '</span></p>';
+
+ echo '<p id="timer" '.(($row['timer'] == 0) ? 'style="display: none;"' : '').'>';
+ echo '<span class="title">&nbsp;</span><span class="content">';
+ echo '<select name="timer2">';
+
+ # od 1-15 mamo za vsako sekundo
+ for ($t = 1; $t <= 15; $t += 1){
+ echo '<option value="'.$t.'" '.(($t == $row['timer']) ? ' selected' : '').'>';
+ echo $t . $lang['srv_seconds'];
+ echo '</option>';
+ }
+
+ # dodatna opcija za 20s 30s in 45s
+ echo '<option value="20"' . ((20 == $row['timer']) ? ' selected' : '') . '>';
+ echo '20' . $lang['srv_seconds'];
+ echo '</option>';
+
+ echo '<option value="30"' . ((30 == $row['timer']) ? ' selected' : '') . '>';
+ echo '30' . $lang['srv_seconds'];
+ echo '</option>';
+
+ echo '<option value="45"' . ((45 == $row['timer']) ? ' selected' : '') . '>';
+ echo '45' . $lang['srv_seconds'];
+ echo '</option>';
+
+ #od 60 do 600 mamo na 15s
+ for ($t = 60; $t <= 600; $t += 15){
+ echo '<option value="' . $t . '"' . (($t == $row['timer']) ? ' selected' : '') . '>';
+ echo floor(bcdiv($t, 60)) . $lang['srv_minutes'] . ' ';
+ echo (bcmod($t, 60)) . $lang['srv_seconds'] . '';
+ echo '</option>';
+ }
+
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // nastavitev celih in decimalnih mest (number, multinumber, vsota)
+ function edit_number() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<fieldset><legend>'.$lang['srv_num_limits'].'</legend>';
+ echo '<p><span class="title">';
+
+ echo $lang['srv_cela'].':</span><span class="content">';
+ echo '<select name="cela">';
+ for ($i = 1; $i <= 10; $i++)
+ echo '<option value="' . $i . '"' . ($row['cela'] == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ echo '</select></span>';
+ echo '</p><p>';
+ echo '<span class="title">'.$lang['srv_decimalna'].':</span><span class="content">';
+ echo '<select name="decimalna">';
+ for ($i = 0; $i <= 10; $i++)
+ echo '<option value="' . $i . '"' . ($row['decimalna'] == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ echo '</select></span>';
+
+ echo '</p>';
+ echo '</fieldset>';
+
+ }
+
+ // nastavitev za obliko generatorja imen
+ function edit_name_generator_design(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // Design generatorja
+ echo '<p><label class="title">'.$lang['srv_design'].':</label>';
+ echo '<span class="content"><input type="hidden" name="sn_design" value="0" />';
+ echo '<select id="spremenljivka_podtip_' . $row['id'] . '" name="sn_design" spr_id="'.$row['id'].'" onChange="show_SN_count(this.value)">';
+ echo '<option value="0" '.(($row['design'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_sn_design_1'].'</option>';
+ echo '<option value="1" '.(($row['design'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_sn_design_2'].'</option>';
+ echo '<option value="2" '.(($row['design'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_sn_design_3'].'</option>';
+ echo '<option value="3" '.(($row['design'] == 3) ? ' selected="true" ' : '').'>'.$lang['srv_sn_design_4'].'</option>';
+ echo '</select>';
+ echo '</span></p>';
+ }
+
+ // nastavitve za generator imen
+ function edit_name_generator(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+
+ // Max odgovorov - samo pri 2. designu
+ echo '<div id="SN_count" class="SN_hidable_settings" '.($row['design'] != 1 ? ' style="display:none;"' : '').'>';
+
+ echo '<p><label class="title">'.$lang['srv_design_count'].':</label>';
+ echo '<span class="content"><input type="hidden" name="size" value="0" />';
+ echo '<select id="size" name="size">';
+ for($i=1; $i<=20; $i++){
+ echo '<option value="'.$i.'" '.(($row['size'] == $i) ? ' selected="true" ' : '').'>'.$i.'</option>';
+ }
+ echo '</select>';
+ echo '</span></p>';
+
+ echo '</div>';
+
+
+ // Antonuccijev krog
+ echo '<p><label class="title">'.$lang['srv_antonucci'].':</label>';
+ echo '<span class="content"><input type="hidden" name="antonucci" value="0" />';
+ echo '<select id="antonucci" name="antonucci">';
+ echo '<option value="0" '.(($row['antonucci'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_none'].'</option>';
+ echo '<option value="1" '.(($row['antonucci'] == 1) ? ' selected="true" ' : '').'>1.</option>';
+ echo '<option value="2" '.(($row['antonucci'] == 2) ? ' selected="true" ' : '').'>2.</option>';
+ echo '<option value="3" '.(($row['antonucci'] == 3) ? ' selected="true" ' : '').'>3.</option>';
+ echo '</select>';
+ echo '</span></p>';
+
+
+ if($spremenljivkaParams->get('NG_cancelButton') == '1'){
+ $cancelText = $spremenljivkaParams->get('NG_cancelText');
+ $cancelButton = 1;
+ $hidden = '';
+ }
+ else{
+ $cancelText = $lang['srv_NG_cancelText'];
+ $cancelButton = 0;
+ $hidden = ' style="display:none;"';
+ }
+
+ // Text za dodajanje nove osebe
+ $addText = ($spremenljivkaParams->get('NG_addText') ? $spremenljivkaParams->get('NG_addText') : $lang['srv_NG_addText']);
+ echo '<div id="SN_add_text" class="SN_hidable_settings" '.($row['design'] != 0 ? ' style="display:none;"' : '').'>';
+
+ echo '<p>';
+ echo $lang['srv_NG_addText_setting'] . ': <input type="text" name="NG_addText" value="' . $addText . '" size="30" />';
+ echo '</p>';
+
+ echo '</div>';
+
+
+ // Pri vnosu stevila polj imamo opcijo za urejanje texta "Število polj za vnos"
+ $countText = ($spremenljivkaParams->get('NG_countText') ? $spremenljivkaParams->get('NG_countText') : $lang['srv_design_count']);
+ echo '<div id="SN_count_text" class="SN_hidable_settings" '.($row['design'] != 3 ? ' style="display:none;"' : '').'>';
+
+ echo '<p>';
+ echo $lang['srv_NG_countText_setting'] . ': <input type="text" name="NG_countText" value="' . $countText . '" size="30" />';
+ echo '</p>';
+
+ echo '</div>';
+
+
+ // Gumb za preskok generatorja imen
+ echo '<p>';
+
+ echo $lang['srv_NG_cancelText_setting'] . ': ';
+ echo '<input type="radio" '.($cancelButton == 0 ? ' checked' : '').' name="NG_cancelButton" value="0" onClick="change_NG_cancelButton(this.value);">'.$lang['no'].'</input> ';
+ echo '<input type="radio" '.($cancelButton == 1 ? ' checked' : '').' name="NG_cancelButton" value="1" onClick="change_NG_cancelButton(this.value);">'.$lang['yes'].'</input> ';
+
+ echo '&nbsp;&nbsp;&nbsp;<input type="text" '.$hidden.' name="NG_cancelText" id="NG_cancelText" value="' . $cancelText . '" size="30" />';
+ echo '</p>';
+ }
+
+ // nastavitev omejitve vnessenega stevila (number, vsota)
+ function edit_limit() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+
+ //omejitev za number
+ if($row['tip'] == 7 || $row['tip'] == 21){
+ $onkeyup = $row['tip'] == 21 ? ' onkeyup="checkNumber(this, 4, 0, true);"' : '';
+
+ echo '<fieldset><legend>'.$lang['srv_num_reminder'].'</legend>';
+ echo '<input type="hidden" name="edit_number_limit" value="1" />';
+
+ echo '<p>';
+ echo '<span class="clr" id="num_limit_label" '.($row['size']==2 ? '' : ' style="display:none;"').'>'.$lang['srv_num_field1'].':</span>';
+
+ //spodnji limit
+ echo '<input type="checkbox" value="1" id="num_useMin" name="num_useMin" '.($row['num_useMin']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'vsota_min\',this.checked)">';
+ echo $lang['srv_num_min'] . '<input type="text" name="vsota_min" id="vsota_min"'.$onkeyup.' value="' . $row['vsota_min'] . '" size="8" '.($row['num_useMin'] == 0 ? ' disabled' : '').'></input> ';
+ //zgornji limit
+ echo '&nbsp;&nbsp;<input type="checkbox" value="1" id="num_useMax" name="num_useMax" '.($row['num_useMax']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'vsota_limit\',this.checked)">';
+ echo $lang['srv_num_limit'] . '<input type="text" name="vsota_limit" id="vsota_limit"'.$onkeyup.' value="' . $row['vsota_limit'] . '" size="8" '.($row['num_useMax'] == 0 ? ' disabled' : '').'></input> ';
+ echo '</p>';
+
+ // Omejitve za 2. polje (ce ga imamo)
+ echo '<div id="num_limit2" '.($row['size'] == 2 ? '' : ' style="display:none;"').'>';
+ echo '<p>';
+ echo '<span class="clr">'.$lang['srv_num_field2'].':</span>';
+ //spodnji limit
+ echo '<input type="checkbox" value="1" id="num_useMin2" name="num_useMin2" '.($row['num_useMin2']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'num_min2\',this.checked)">';
+ echo $lang['srv_num_min'] . '<input type="text" name="num_min2" id="num_min2" value="' . $row['num_min2'] . '" size="8" '.($row['num_useMin2'] == 0 ? ' disabled' : '').'></input> ';
+ //zgornji limit
+ echo '&nbsp;&nbsp;<input type="checkbox" value="1" id="num_useMax2" name="num_useMax2" '.($row['num_useMax2']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'num_max2\',this.checked)">';
+ echo $lang['srv_num_limit'] . '<input type="text" name="num_max2" id="num_max2" value="' . $row['num_max2'] . '" size="8" '.($row['num_useMax2'] == 0 ? ' disabled' : '').'></input> ';
+ echo '</p>';
+ echo '</div>';
+
+ // prikaz omejitve
+ echo '<p><span class="title"><label for="vsota_show">'.$lang['srv_num_limit_show'] . '</label></span><span class="content"><input type="checkbox" name="vsota_show" id="vsota_show" value="1" '.($row['vsota_show']==1?'checked':'').' /></span></p>';
+
+ // opozorilo za preseg limita (mehko, trdo)
+ echo '<p><span class="title">'.$lang['srv_num_limit_reminder'].': </span>';
+ echo '<span class="content"><select name="vsota_reminder">';
+ echo '<option value="0"' . ($row['vsota_reminder'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_off2'].'</option>';
+ echo '<option value="1"' . ($row['vsota_reminder'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_soft2'].'</option>';
+ echo '<option value="2"' . ($row['vsota_reminder'] == 2 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_hard2'].'</option>';
+ echo '</select></span></p>';
+ echo '</fieldset>';
+ }
+
+ // grid number
+ if ($row['tip'] == 20 && $row['ranking_k'] != 1) {
+
+ // zaenkrat sam za slider
+ //if ($row['ranking_k'] != 1) return;
+
+ echo '<fieldset><legend>'.$lang['srv_num_reminder'].'</legend>';
+ echo '<input type="hidden" name="edit_number_limit" value="1" />';
+
+ echo '<p>';
+ echo '<span class="clr" id="num_limit_label" '.($row['size']==2 ? '' : ' style="display:none;"').'>'.$lang['srv_num_field1'].':</span>';
+
+ //spodnji limit
+ echo '<input type="checkbox" value="1" id="num_useMin" name="num_useMin" '.($row['num_useMin']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'vsota_min\',this.checked)">';
+ echo $lang['srv_num_min'] . '<input type="text" name="vsota_min" id="vsota_min" value="' . $row['vsota_min'] . '" size="8" '.($row['num_useMin'] == 0 ? ' disabled' : '').'></input> ';
+ //zgornji limit
+ echo '&nbsp;&nbsp;<input type="checkbox" value="1" id="num_useMax" name="num_useMax" '.($row['num_useMax']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'vsota_limit\',this.checked)">';
+ echo $lang['srv_num_limit'] . '<input type="text" name="vsota_limit" id="vsota_limit" value="' . $row['vsota_limit'] . '" size="8" '.($row['num_useMax'] == 0 ? ' disabled' : '').'></input> ';
+ echo '</p>';
+
+ // Omejitve za 2. polje (ce ga imamo)
+ echo '<div id="num_limit2" '.($row['size'] == 2 ? '' : ' style="display:none;"').'>';
+ echo '<p>';
+ echo '<span class="clr">'.$lang['srv_num_field2'].':</span>';
+ //spodnji limit
+ echo '<input type="checkbox" value="1" id="num_useMin2" name="num_useMin2" '.($row['num_useMin2']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'num_min2\',this.checked)">';
+ echo $lang['srv_num_min'] . '<input type="text" name="num_min2" id="num_min2" value="' . $row['num_min2'] . '" size="8" '.($row['num_useMin2'] == 0 ? ' disabled' : '').'></input> ';
+ //zgornji limit
+ echo '&nbsp;&nbsp;<input type="checkbox" value="1" id="num_useMax2" name="num_useMax2" '.($row['num_useMax2']==1 ? ' checked="checked"' : '').' onClick="num_limit(\'num_max2\',this.checked)">';
+ echo $lang['srv_num_limit'] . '<input type="text" name="num_max2" id="num_max2" value="' . $row['num_max2'] . '" size="8" '.($row['num_useMax2'] == 0 ? ' disabled' : '').'></input> ';
+ echo '</p>';
+ echo '</div>';
+
+ // prikaz omejitve
+ echo '<p><span class="title"><label for="vsota_show">'.$lang['srv_num_limit_show'] . '</label></span><span class="content"><input type="checkbox" name="vsota_show" id="vsota_show" value="1" '.($row['vsota_show']==1?'checked':'').' /></span></p>';
+
+ // opozorilo za preseg limita (mehko, trdo)
+ echo '<p><span class="title">'.$lang['srv_num_limit_reminder'].': </span>';
+ echo '<span class="content"><select name="vsota_reminder">';
+ echo '<option value="0"' . ($row['vsota_reminder'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_off2'].'</option>';
+ echo '<option value="1"' . ($row['vsota_reminder'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_soft2'].'</option>';
+ echo '<option value="2"' . ($row['vsota_reminder'] == 2 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_hard2'].'</option>';
+ echo '</select></span></p>';
+ echo '</fieldset>';
+ }
+
+ // grid slider
+ if ($row['tip'] == 20 && $row['ranking_k'] == 1) {
+
+ echo '<fieldset><legend>'.$lang['srv_num_reminder'].'</legend>';
+ echo '<input type="hidden" name="edit_number_limit" value="1" />';
+
+ echo '<p>';
+ //spodnji limit
+ echo $lang['srv_num_min'] . '<input type="text" name="vsota_min" id="vsota_min" value="' . $row['vsota_min'] . '" size="8"></input> ';
+ //zgornji limit
+ echo '&nbsp;&nbsp;';
+ echo $lang['srv_num_limit'] . '<input type="text" name="vsota_limit" id="vsota_limit" value="' . $row['vsota_limit'] . '" size="8"></input> ';
+ echo '</p>';
+
+
+ echo '</fieldset>';
+
+ }
+
+ //omejitev za vsoto
+ if($row['tip'] == 18){
+ echo '<fieldset><legend>'.$lang['srv_vsota_reminder'].'</legend>';
+ echo '<input type="hidden" name="edit_vsota_limit" value="1" />';
+ echo '<p>';
+ //nastavitev tocne vsote
+ if($row['vsota_min'] == $row['vsota_limit'])
+ $val = $row['vsota_min'];
+
+ echo $lang['srv_vsota_exact'] . '<input type="text" '.($row['vsota_limittype'] == 1 ? ' disabled' : '').' name="vsota_exact" id="vsota_exact" value="' . $val . '" size="8"></input> ';
+ echo '</p>';
+
+ echo '<p>';
+ echo $lang['srv_vsota_both'] . '<input type="checkbox" '.($row['vsota_limittype'] == 1 ? ' checked' : '').' name="vsota_limittype" value="1" onClick="change_limittype(this.checked)"></input> ';
+ echo '</p>';
+
+ echo '<p>';
+ //spodnji limit vsote
+ echo $lang['srv_vsota_min'] . '<input type="text" '.($row['vsota_limittype'] == 0 ? ' disabled' : '').' name="vsota_min" id="vsota_min" value="' . $row['vsota_min'] . '" size="8"></input> ';
+ //zgornji limit vsote
+ echo $lang['srv_vsota_limit'] . '<input type="text" '.($row['vsota_limittype'] == 0 ? ' disabled' : '').' name="vsota_limit" id="vsota_limit" value="' . $row['vsota_limit'] . '" size="8"></input> ';
+
+ echo '</p>';
+
+ // prikaz omejitve
+ echo '<p>'.$lang['srv_vsota_show'] . '<input type="checkbox" name="vsota_show" id="vsota_show" value="1" '.($row['vsota_show']==1?'checked':'').' /></p>';
+
+ // opozorilo za preseg limita (mehko, trdo)
+ echo '<p>';
+ echo $lang['srv_vsota_reminder'].': ';
+ echo '<select name="vsota_reminder">';
+ echo '<option value="0"' . ($row['vsota_reminder'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_off'].'</option>';
+ echo '<option value="1"' . ($row['vsota_reminder'] == 1 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_soft'].'</option>';
+ echo '<option value="2"' . ($row['vsota_reminder'] == 2 ? ' selected="true"' : '') . '>'.$lang['srv_reminder_hard'].'</option>';
+ echo '</select>';
+
+ echo '</p>';
+ echo '</fieldset>';
+ }
+
+
+ }
+
+ // nastavitev poravnave celic v gridih
+ function edit_grid_align() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $display = ( ($row['tip'] == 2)) ? ' style="display:none;"' : '';
+ echo '<p '.$display.'>';
+
+ $gridAlign = ($spremenljivkaParams->get('gridAlign') ? $spremenljivkaParams->get('gridAlign') : -1);
+ echo '<span class="title">'.$lang['srv_gridAlign'].'</span>';
+
+ echo '<span class="content"><select name="gridAlign" id="gridAlign">';
+
+ echo '<option value="0"' . ($gridAlign == 0 ? ' selected="true"' : '') . '>'.$lang['srv_gridAlign_center'].'</option>';
+ echo '<option value="1"' . ($gridAlign == 1 ? ' selected="true"' : '') . '>'.$lang['srv_gridAlign_left'].'</option>';
+ echo '<option value="2"' . ($gridAlign == 2 ? ' selected="true"' : '') . '>'.$lang['srv_gridAlign_right'].'</option>';
+
+ echo '</select></span>';
+
+ echo '</p>';
+ }
+
+ // nastavitev sirine text polja (besedilo*, multitext, multinumber, number)
+ function edit_width() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ echo '<p>';
+
+ $taWidth = ($spremenljivkaParams->get('taWidth') ? $spremenljivkaParams->get('taWidth') : -1);
+ $taHeight = ($spremenljivkaParams->get('taHeight') ? $spremenljivkaParams->get('taHeight') : 1);
+ echo $lang['srv_textAreaWidth'].': ';
+
+ //sirina za multitext in multinumber
+ if($row['tip'] == 19 || $row['tip'] == 20){
+ $size = $row['grids'];
+ $missing_count = 0;
+ # če imamo missinge size povečamo za 1 + številomissingov
+ $sql_grid_mv = sisplet_query("SELECT * FROM srv_grid WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ $missing_count = mysqli_num_rows($sql_grid_mv);
+ if ($missing_count > 0) {
+ $size += $missing_count + 1;
+ }
+
+ echo '<select name="taWidth" id="width">';
+ $maxWidth = round(50 / $size);
+
+ echo '<option value="-1"' . ($taWidth == -1 ? ' selected="true"' : '') . '>'.$lang['default'].'</option>';
+ for($i=1; $i<$maxWidth; $i++){
+ echo '<option value="'.$i.'"' . ($taWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select>';
+
+ // multitext ima tudi nastavitev visine
+ if ($row['tip'] == 19) {
+
+ echo '<span class="content">'.$lang['srv_textAreaHeight'].': ';
+ echo '<select name="taHeight" class="no-margin" id="taHeight">';
+ $maxHeight = 10;
+
+ for($i=1; $i<=$maxHeight; $i++){
+ echo '<option value="'.$i.'"' . ($taHeight == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select></span>';
+ }
+ }
+
+ //sirina za number
+ elseif($row['tip'] == 7){
+ $sql1 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = '$this->spremenljivka' ORDER BY vrstni_red ASC");
+ $row1 = mysqli_fetch_array($sql1);
+ $id1 = $row1['id'];
+ $row1 = mysqli_fetch_array($sql1);
+ $id2 = $row1['id'];
+
+ echo '<select name="taWidth" id="width" onchange="change_number(\'1\', \'2\');">';
+
+ echo '<option value="-1"' . ($taWidth == -1 ? ' selected="true"' : '') . '>'.$lang['default'].' (10)</option>';
+ for($i=5; $i<50; $i+=5){
+ echo '<option value="'.$i.'"' . ($taWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ for($i=50; $i<=100; $i+=10){
+ echo '<option value="'.$i.'"' . ($taWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select>';
+ }
+
+ //sirina za besedilo*
+ elseif($row['tip'] == 21){
+ echo '<select name="taWidth" id="width">';
+
+ echo '<option value="-1"' . ($taWidth == -1 ? ' selected="true"' : '') . '>'.$lang['default'].' (30)</option>';
+ for($i=5; $i<50; $i+=5){
+ echo '<option value="'.$i.'"' . ($taWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ for($i=50; $i<=100; $i+=10){
+ echo '<option value="'.$i.'"' . ($taWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select>';
+
+ $this->edit_height();
+ }
+
+ echo '</p>';
+ }
+
+ // nastavitev visine text polja (besedilo*)
+ function edit_height() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ //echo '<p>';
+
+ $taSize = ($spremenljivkaParams->get('taSize') ? $spremenljivkaParams->get('taSize') : 1);
+ echo '<span class="content">'.$lang['srv_textAreaSize'].'';
+ echo '<select name="taSize" class="no-margin" id="height">';
+ echo '<option value="1"' . ($taSize == 1 ? ' selected="true"' : '') . '>' . $lang['srv_textArea1line'] . '</option>';
+ echo '<option value="2"' . ($taSize == 2 ? ' selected="true"' : '') . '>' . $lang['srv_textArea2line'] . '</option>';
+ echo '<option value="3"' . ($taSize == 3 ? ' selected="true"' : '') . '>' . $lang['srv_textArea3line'] . '</option>';
+ echo '<option value="5"' . ($taSize == 5 ? ' selected="true"' : '') . '>' . $lang['srv_textArea5line'] . '</option>';
+ echo '<option value="7"' . ($taSize == 7 ? ' selected="true"' : '') . '>' . $lang['srv_textArea7line'] . '</option>';
+ echo '<option value="10"' . ($taSize == 10 ? ' selected="true"' : '') . '>' . $lang['srv_textArea10line'] . '</option>';
+ echo '<option value="20"' . ($taSize == 20 ? ' selected="true"' : '') . '>' . $lang['srv_textArea20line'] . '</option>';
+ echo '<option value="30"' . ($taSize == 30 ? ' selected="true"' : '') . '>' . $lang['srv_textArea30line'] . '</option>';
+ echo '</select></span>';
+
+ //echo '</p>';
+ }
+
+ /**
+ * Prikazovanje podnaslovov na multiple tabelah
+ */
+ function edit_multiple_subtitle () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<input type="hidden" value="" name="multiple_subtitle">';
+ echo '<p><label class="title" for="multiple_subtitle">';
+ echo $lang['srv_multiple_subtitle'].':</label><span class="content">';
+ echo '<input id="multiple_subtitle" type="checkbox" name="multiple_subtitle" value="1" '.($row['grid_subtitle1']==1?'checked':'').'></span>';
+
+ echo '</p>';
+
+ }
+
+ // nastavitev sirina levih polj pri gridih
+ function edit_grid_width() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $display = ( ($row['tip'] == 2)) ? ' style="display:none;"' : '';
+ echo '<p '.$display.'><span class="title">';
+
+ $gridWidth = ($spremenljivkaParams->get('gridWidth') ? $spremenljivkaParams->get('gridWidth') : 1);
+ echo $lang['srv_gridAreaSize'].':</span><span class="content">';
+ echo '<select name="gridWidth" id="gridWidth" onChange="change_grid_width(this.value);">';
+ echo '<option value="-1"' . ($gridWidth == -1 ? ' selected="true"' : '') . '>'.$lang['default'].' (30%)</option>';
+ // 0 bo podrla zdruzljivost za nazaj (0 = -1, default!!!!!!)
+ echo '<option value="-2"' . ($gridWidth == -2 ? ' selected="true"' : '') . '>'.$lang['srv_gridAreaHidden'].' (0%)</option>';
+ for($i=1; $i<=16; $i++){
+ echo '<option value="'.$i * 5 .'"' . ($gridWidth == $i * 5 ? ' selected="true"' : '') . '>' . $i * 5 . '%</option>';
+ }
+ echo '</select></span>';
+
+ echo '</p>';
+ }
+
+ // nastavitve za besedilo* (st. kosov in polozaj besedila)
+ function edit_textboxes() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ //stevilo kosov
+ echo '<span class="title">'.$lang['srv_kosov'].': ';
+ echo '<select name="text_kosov" id="kosov">';
+ echo '<option value="1"' . ($row['text_kosov'] == 1 ? ' selected="true"' : '') . '>1</option>';
+ echo '<option value="2"' . ($row['text_kosov'] == 2 ? ' selected="true"' : '') . '>2</option>';
+ echo '<option value="3"' . ($row['text_kosov'] == 3 ? ' selected="true"' : '') . '>3</option>';
+ echo '<option value="4"' . ($row['text_kosov'] == 4 ? ' selected="true"' : '') . '>4</option>';
+ echo '</select></span>';
+
+ //polozaj besedila
+ echo '<span class="content">'.$lang['srv_polozaj'].': ';
+ echo '<select name="text_orientation" class="no-margin" id="position">';
+ echo '<option value="0"' . ($row['text_orientation'] == 0 ? ' selected="true"' : '') . '>' . $lang['srv_polozaj_off'] . '</option>';
+ echo '<option value="1"' . ($row['text_orientation'] == 1 ? ' selected="true"' : '') . '>' . $lang['srv_polozaj_side'] . '</option>';
+ echo '<option value="3"' . ($row['text_orientation'] == 3 ? ' selected="true"' : '') . '>' . $lang['srv_polozaj_above'] . '</option>';
+ echo '<option value="2"' . ($row['text_orientation'] == 2 ? ' selected="true"' : '') . '>' . $lang['srv_polozaj_bottom'] . '</option>';
+ echo '</select></span>';
+
+ echo '</p>';
+
+
+ }
+
+ // nastavitve za number (st. polj)
+ function edit_num_size() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $sql1 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = '$this->spremenljivka' ORDER BY vrstni_red ASC");
+ $row1 = mysqli_fetch_array($sql1);
+ $id1 = $row1['id'];
+ $row1 = mysqli_fetch_array($sql1);
+ $id2 = $row1['id'];
+
+ echo '<p><span class="title">';
+
+ echo $lang['srv_kategorij'].': ';
+ echo '<select id="num_size" name="size" onchange="change_number(\'1\', \'2\'); toggle_num_limits(this.value);">';
+ echo '<option value="1"' . ($row['size'] == 1 ? ' selected="true"' : '') . '>1</option>';
+ echo '<option value="2"' . ($row['size'] == 2 ? ' selected="true"' : '') . '>2</option>';
+ echo '</select></span>';
+ }
+
+ // nastavitve za number (enota/brez enote)
+ function edit_num_enota() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $sql1 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = '$this->spremenljivka' ORDER BY vrstni_red ASC");
+ $row1 = mysqli_fetch_array($sql1);
+ $id1 = $row1['id'];
+ $row1 = mysqli_fetch_array($sql1);
+ $id2 = $row1['id'];
+
+
+
+ //polje za enoto
+ echo '<span class="content">'.$lang['srv_enota'].': ';
+ echo '<select id="num_enota" name="enota" class="no-margin" onchange="change_number(\'1\', \'2\');">';
+ echo '<option value="0"' . ($row['enota'] == 0 ? ' selected="true"' : '') . '>' . $lang['no1'] . '</option>';
+ echo '<option value="1"' . ($row['enota'] == 1 ? ' selected="true"' : '') . '>' . $lang['left'] . '</option>';
+ echo '<option value="2"' . ($row['enota'] == 2 ? ' selected="true"' : '') . '>' . $lang['right'] . '</option>';
+ echo '</select></span>';
+
+ echo '</p>';
+ }
+
+ // nastavitev za ranking (moznosti)
+ function edit_ranking() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_ranking_type'].':</span>';
+ echo '<span class="content"><select name="design" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" class="ranking_k" onchange="show_ranking_k(this.value); show_hot_spot_settings(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\');">';
+ echo '<option value="0" '.(($row['design'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_ranking_prestavljanje'].'</option>';
+ echo '<option value="1" '.(($row['design'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_ranking_ostevilcevanje'].'</option>';
+ echo '<option value="2" '.(($row['design'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_ranking_premikanje'].'</option>';
+ echo '<option value="3" '.(($row['design'] == 3) ? ' selected="true" ' : '').'>'.$lang['srv_ranking_hotspot'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ // nastavitev za ranking (moznosti)
+ function edit_ranking_moznosti() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $sqls = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id='$this->spremenljivka'");
+ $count = mysqli_num_rows($sqls);
+
+ echo '<div id="ranking_k" '.(($row['design'] == 2) ? 'style="display: none;"' : '').'>';
+ echo '<p><span class="title">'.$lang['srv_ranking_k'].':</span>';
+ echo '<span class="content"><select name="ranking_k" class="ranking_k">';
+ echo '<option value="0"' . ($row['ranking_k'] == 0 ? ' selected="true"' : '') . '>'.$lang['srv_vsi'].'</option>';
+ for ($i=1; $i<$count; $i++) {
+ echo '<option value="' . $i . '"' . ($row['ranking_k'] == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select></span>';
+ echo '</p></div>';
+ }
+
+ // nastavitev za nagovor - crta za vprasanjem
+ function edit_nagovor_line(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $nagovorLine = ($spremenljivkaParams->get('nagovorLine') ? $spremenljivkaParams->get('nagovorLine') : 0);
+ echo '<p><span class="title">'.$lang['srv_nagovorLine'].':</span>';
+ echo '<span class="content"><select name="nagovorLine" id="nagovorLine">';
+ echo '<option value="0"' . ($nagovorLine == 0 ? ' selected="true"' : '') . '>' . $lang['srv_default'] . '</option>';
+ echo '<option value="1"' . ($nagovorLine == 1 ? ' selected="true"' : '') . '>' . $lang['no1'] . '</option>';
+ echo '<option value="2"' . ($nagovorLine == 2 ? ' selected="true"' : '') . '>' . $lang['yes'] . '</option>';
+ echo '</select></span></p>';
+ }
+
+ /**
+ * prikaze gumbe
+ */
+ function edit_buttons () {
+ global $lang;
+
+ echo '<div id="vprasanje_buttons">';
+
+ echo '<span class="buttonwrapper spaceLeft floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="#" onclick="vprasanje_save(); return false;"><span>'.$lang['srv_zapri'].'</span></a>';
+ echo '</span>';
+
+ /*echo '<span class="buttonwrapper spaceLeft floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="vprasanje_cancel(); return false;"><span>'.$lang['srv_close_profile'].'</span></a>'."\n\r";
+ echo '</span>';*/
+
+ echo '<span class="buttonwrapper spaceLeft floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" href="#" onclick="brisi_spremenljivko(\''.$this->spremenljivka.'\', undefined, \'0\'); return false;"><span>'.$lang['srv_brisispremenljivko'].'</span></a>'."\n\r";
+ echo '</span>';
+
+ //echo '<div id="arrows_more_vprasanje" onclick=" $(\'#vprasanje_edit\').animate({ scrollTop: $(\'#vprasanje_edit\').attr(\'scrollHeight\') }, 2000); "><img src="img_0/bullet_arrow_down.png" /> '.$lang['srv_more'].'</div>';
+
+ echo '</div>';
+ }
+
+ /**
+ * kalkulacija
+ *
+ */
+ function edit_compute () {
+ global $lang;
+
+ $b = new Branching($this->anketa);
+
+ echo '<p>'.$lang['srv_vprasanje_tip_22'].': ';
+
+ echo '<a href="#" onclick="calculation_editing(\'-'.$this->spremenljivka.'\'); return false;">';
+ $calc = $b->calculations_display( - $this->spremenljivka); // za spremenljivke je v srv_calculation, v cnd_id zapisan id spremenljivke kot minus (plus je za kalkulacije v ifih)
+ echo $calc != '' ? $calc : $lang['srv_editcalculation'];
+ echo '</a></p>';
+
+ }
+
+ function edit_inline_edit() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p><label for="inline_edit" class="title">'.$lang['srv_inline_edit'].':</label> '.Help::display('srv_dropdown_quickedit');
+ echo '<span class="content"><input type="hidden" value="0" name="inline_edit" />';
+ echo '<input type="checkbox" value="1" id="inline_edit" name="inline_edit" '.($row['inline_edit']==1?' checked="checked"':'').' /></span></p>';
+
+ }
+
+ function edit_onchange_submit() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // pri multigridu ga prikazemo samo ce imamo vklopljeno postopno resevanje
+ echo '<div id="onchange_submit_div" '.($row['dynamic_mg']==0 && $row['tip']!=1 && $row['orientation']>2 ? ' style="display:none;"':'').'>';
+
+ echo '<p><label for="onchange_submit" class="title">'.$lang['srv_onchange_submit'].':</label>';
+ //echo '<span class="content"><input type="radio" value="0" name="onchange_submit" '.($row['onchange_submit']==0?' checked="checked"':'').' />'.$lang['no'];
+ //echo '<input type="radio" value="1" name="onchange_submit" '.($row['onchange_submit']==1?' checked="checked"':'').' />'.$lang['yes'].'</span></p>';
+ echo '<span class="content"><input type="hidden" value="0" name="onchange_submit" />';
+ echo '<input type="checkbox" value="1" id="onchange_submit" name="onchange_submit" '.($row['onchange_submit']==1?' checked="checked"':'').' /></span></p>';
+
+ echo '</div>';
+ }
+
+ function edit_hidden_default() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p><span class="title">'.$lang['srv_hidden_default'].':</span><input type="radio" value="0" name="hidden_default" '.($row['hidden_default']==0?' checked="checked"':'').' />'.$lang['no'].'<input type="radio" value="1" name="hidden_default" '.($row['hidden_default']==1?' checked="checked"':'').' />'.$lang['yes'].'</p>';
+
+ }
+
+ function edit_captcha () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $captcha = ($spremenljivkaParams->get('captcha') ? $spremenljivkaParams->get('captcha') : 0);
+ $emailVerify = ($spremenljivkaParams->get('emailVerify') ? $spremenljivkaParams->get('emailVerify') : 0);
+
+ $disabled = ($row['upload']>0 || $row['signature']==1 || $emailVerify==1) ? ' disabled="disabled"' : '';
+
+ echo '<p><span class="title">'.$lang['srv_captcha_edit'].':</span><span class="content">';
+ echo '<input type="radio" value="0" name="captcha" id="captcha_0" '.($captcha==0?' checked="checked"':'').' '.$disabled.' onClick="textSubtypeToggle(\'captcha\', this.value);" /><label for="captcha_0">'.$lang['no'].'</label>';
+ echo '<input type="radio" value="1" name="captcha" id="captcha_1" '.($captcha==1?' checked="checked"':'').' '.$disabled.' onClick="textSubtypeToggle(\'captcha\', this.value);" /><label for="captcha_1">'.$lang['yes'].'</label>';
+ echo '</span><br>'.$lang['srv_captcha_edit_note'].'</p>';
+
+ }
+
+ function edit_email_verify () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $emailVerify = ($spremenljivkaParams->get('emailVerify') ? $spremenljivkaParams->get('emailVerify') : 0);
+ $captcha = ($spremenljivkaParams->get('captcha') ? $spremenljivkaParams->get('captcha') : 0);
+
+ $disabled = ($row['upload']>0 || $row['signature']==1 || $captcha==1) ? ' disabled="disabled"' : '';
+
+ echo '<p><span class="title">'.$lang['srv_email_edit'].':</span><span class="content">';
+ echo '<input type="radio" value="0" name="emailVerify" id="emailVerify_0" '.($emailVerify==0?' checked="checked"':'').' '.$disabled.' onClick="textSubtypeToggle(\'emailVerify\', this.value);" /><label for="emailVerify_0">'.$lang['no'].'</label>';
+ echo '<input type="radio" value="1" name="emailVerify" id="emailVerify_1" '.($emailVerify==1?' checked="checked"':'').' '.$disabled.' onClick="textSubtypeToggle(\'emailVerify\', this.value);" /><label for="emailVerify_1">'.$lang['yes'].'</label>';
+ echo '</span><br>'.$lang['srv_email_edit_note'].'</p>';
+ }
+
+ function edit_showOnAllPages () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ echo '<p><label for="showOnAllPages" class="title">'.$lang['srv_showOnAllPages_edit'].':</label>';
+ echo '<span class="content"><input type="hidden" value="0" name="showOnAllPages" />';
+ echo '<input type="checkbox" value="1" id="showOnAllPages" name="showOnAllPages" '.($row['showOnAllPages']==1?' checked="checked"':'').' /></span></p>';
+
+ }
+
+ function edit_hideRadio () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $hideRadio = ($spremenljivkaParams->get('hideRadio') ? $spremenljivkaParams->get('hideRadio') : 0);
+
+ echo '<p><label for="hideRadio" class="title">'.$lang['srv_hideRadio_edit_'.$row['tip']].':</label>';
+ echo '<span class="content"><input type="hidden" value="0" name="hideRadio" />';
+ echo '<input type="checkbox" value="1" id="hideRadio" name="hideRadio" '.($hideRadio==1?' checked="checked"':'').' /></span></p>';
+
+ }
+
+ // Prednastavljena vrednost (pri radio ali tabela - radio)
+ function edit_presetValue () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // Pri tabelah je prednastavljena vrednost srv_grid
+ if($row['tip'] == 6 || $row['tip'] == 16){
+ $sqlV = sisplet_query("SELECT id, naslov, variable FROM srv_grid WHERE spr_id='$this->spremenljivka' ORDER BY vrstni_red ASC");
+ }
+ // Pri navadnih vprasanjih je prednastavljena vrednost srv_vrednost
+ else{
+ $sqlV = sisplet_query("SELECT id, naslov, variable FROM srv_vrednost WHERE spr_id='$this->spremenljivka' ORDER BY vrstni_red ASC");
+ }
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $presetValue = ($spremenljivkaParams->get('presetValue') ? $spremenljivkaParams->get('presetValue') : 0);
+
+ $show = ' style="display:none;"';
+ if(($row['tip'] == 1 && in_array($row['orientation'], array(0,1,2,7)))
+ || ($row['tip'] == 2 && in_array($row['orientation'], array(0,1,2,7)))
+ || ($row['tip'] == 6 && in_array($row['enota'], array(0,1,8))))
+ $show = '';
+ echo '<p class="presetValue" '.$show.'><label class="title">'.$lang['srv_vrednost_default'].':</label>';
+
+ echo '<span class="content"><select id="presetValue" name="presetValue" style="width:120px; text-overflow:ellipsis;">';
+ echo ' <option value="0">'.$lang['no'].'</option>';
+ while($rowV = mysqli_fetch_array($sqlV)){
+
+ $naslov = (strlen($rowV['naslov']) > 20) ? substr($rowV['naslov'], 0, 20).'...' : $rowV['naslov'];
+ $naslov = strip_tags($naslov);
+ $naslov = ($naslov == '') ? '' : '('.$naslov.')';
+
+
+ echo ' <option value="'.$rowV['id'].'" '.($presetValue == $rowV['id'] ? ' selected="selected"' : '').'>'.$rowV['variable'].' '.$naslov.'</option>';
+ }
+ echo '</select></span>';
+
+ echo '</p>';
+ }
+
+ // Urejanje velikosti polja drugo
+ function edit_other_field () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // Ce imamo kaken odgovor drugo
+ $sql = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$row[id]' AND other='1'");
+ //if(mysqli_num_rows($sql) > 0){
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $otherWidth = ($spremenljivkaParams->get('otherWidth') ? $spremenljivkaParams->get('otherWidth') : -1);
+ $otherHeight = ($spremenljivkaParams->get('otherHeight') ? $spremenljivkaParams->get('otherHeight') : 1);
+
+ //echo '<fieldset><legend>'.$lang['srv_other_size'].'</legend>';
+ //echo '<fieldset id = '.$row['id'].'><legend>'.$lang['srv_other_size'].'</legend>';
+ //echo '<fieldset id = fieldset'.$row['id'].' ><legend onclick="$(\'#fieldset'.$row['id'].'\').hide()">'.$lang['srv_other_size'].'</legend>';
+ if(mysqli_num_rows($sql) > 0){ //ce je prisotna moznost Drugo,
+ echo '<fieldset id = fieldset'.$row['id'].'><legend>'.$lang['srv_other_size'].'</legend>'; //pokazi fieldset
+ }
+ else{ //drugace
+ echo '<fieldset id = fieldset'.$row['id'].' hidden><legend>'.$lang['srv_other_size'].'</legend>'; //skrij fieldset
+ }
+ //echo '<fieldset id = fieldset'.$row['id'].' ><legend onclick="console.log(\'Tralala\');">'.$lang['srv_other_size'].'</legend>';
+
+ echo '<p>';
+
+ echo $lang['srv_textAreaWidth'].': ';
+ echo '<select name="otherWidth" id="width">';
+ echo '<option value="-1"' . ($otherWidth == -1 ? ' selected="true"' : '') . '>'.$lang['default'].'</option>';
+ for($i=5; $i<61; $i+=5){
+ echo '<option value="'.$i.'"' . ($otherWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select>';
+
+ echo '<span class="content">'.$lang['srv_textAreaSize'].'';
+ echo '<select name="otherHeight" class="no-margin" id="height">';
+ echo '<option value="1"' . ($otherHeight == 1 ? ' selected="true"' : '') . '>' . $lang['srv_textArea1line'] . '</option>';
+ echo '<option value="3"' . ($otherHeight == 3 ? ' selected="true"' : '') . '>' . $lang['srv_textArea3line'] . '</option>';
+ echo '<option value="5"' . ($otherHeight == 5 ? ' selected="true"' : '') . '>' . $lang['srv_textArea5line'] . '</option>';
+ echo '<option value="7"' . ($otherHeight == 7 ? ' selected="true"' : '') . '>' . $lang['srv_textArea7line'] . '</option>';
+ echo '<option value="10"' . ($otherHeight == 10 ? ' selected="true"' : '') . '>' . $lang['srv_textArea10line'] . '</option>';
+ echo '<option value="20"' . ($otherHeight == 20 ? ' selected="true"' : '') . '>' . $lang['srv_textArea20line'] . '</option>';
+ echo '<option value="30"' . ($otherHeight == 30 ? ' selected="true"' : '') . '>' . $lang['srv_textArea30line'] . '</option>';
+ echo '</select></span>';
+
+ echo '</p>';
+
+ echo '</fieldset>';
+ //}
+ }
+
+ /**
+ * editiranje stevila vidnih moznosti selectbox
+ */
+ function edit_selectbox_size () {
+ global $lang;
+
+ $sql1 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = '$this->spremenljivka'");
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $prvaVrstica = ($spremenljivkaParams->get('prvaVrstica') ? $spremenljivkaParams->get('prvaVrstica') : 1);
+ $prvaVrstica_roleta = ($spremenljivkaParams->get('prvaVrstica_roleta') ? $spremenljivkaParams->get('prvaVrstica_roleta') : 1);
+ $sbSizeVse = mysqli_num_rows($sql1); //stevilo vnesenih moznih odgovorov
+
+ echo '<span class="content"><select name="sbSizeVse" id="selectboxSizeVse'.$this->spremenljivka.'" style="display:none;">';
+ echo '<option>'.$sbSizeVse.'</option>';
+ echo '</select>';
+
+ // Nastavimo prikaz nastavitve za stevilo vidnih moznosti v select box - ce imamo selectbox je ta moznost vidna, drugace ni
+ if (($row['tip'] == 6 || $row['tip'] == 16) && $row['enota'] != 2){
+ $display = (($row['tip'] == 6 || $row['tip'] == 16) && $row['enota'] != 6 && $row['enota'] != 8) ? ' style="display:none;"' : '';
+ $displayprvavrstica_roleta =' style="display:none;"';
+ $sbSizeVse = $row['grids'];
+ }
+ elseif($row['tip'] == 1 || $row['tip'] == 2){
+ $display = (($row['tip'] == 1 || $row['tip'] == 2) && $row['orientation'] != 6) ? ' style="display:none;"' : '';
+ $displayprvavrstica_roleta =' style="display:none;"';
+ }
+ elseif($row['tip'] == 3 || ($row['tip'] == 6 && $row['enota'] == 2)){
+ $display = ' style="display:none;"';
+ $displayprvavrstica_roleta = ' ';
+ }
+
+ $sbSize = ($spremenljivkaParams->get('sbSize') ? $spremenljivkaParams->get('sbSize') : $sbSizeVse);
+
+ echo '<div class="dropselectboxsize" '.$display.'>';
+ echo '<p><span class="title" >'.$lang['srv_stevilo_odgovorov_selectbox'].':</span>';
+ echo '<span class="content"><select name="sbSize" id="selectboxSize'.$this->spremenljivka.'">';
+
+ for($i=2; $i<$sbSizeVse; $i++){
+ echo '<option value="'.$i.'"'.($sbSize == $i ? ' selected="true"' : '') . '>'.$i.'</option>';
+ }
+ echo '<option value="'.$sbSizeVse.'"'.($sbSize == $sbSizeVse ? ' selected="true"' : '') . '>'.$lang['srv_select_box_vse'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+
+ echo '<div class="dropselectboxsizeprvavrstica" '.$display.'>';
+ echo '<p><span class="title" >'.$lang['srv_select_box_prva_vrstica'].':</span>';
+ echo '<span class="content"><select name="prvaVrstica" id="prvaVrstica'.$this->spremenljivka.'">'; //echo '<span class="content"><select name="prvaVrstica" id="prvaVrstica">';
+
+ echo '<option value="1"'.($prvaVrstica == 1 ? ' selected="true"' : '') . '>'.$lang['srv_select_box_prva_vrstica_1'].'</option>';
+ echo '<option value="2"'.($prvaVrstica == 2 ? ' selected="true"' : '') . '>'.$lang['srv_select_box_prva_vrstica_2'].'</option>';
+ echo '<option value="3"'.($prvaVrstica == 3 ? ' selected="true"' : '') . '>'.$lang['srv_select_box_prva_vrstica_3'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+
+ echo '<div class="dropselectboxsizeprvavrstica_roleta" '.$displayprvavrstica_roleta.'>';
+ echo '<p><span class="title" >'.$lang['srv_select_box_prva_vrstica'].':</span>';
+ echo '<span class="content"><select name="prvaVrstica_roleta" id="prvaVrstica_roleta'.$this->spremenljivka.'">'; //echo '<span class="content"><select name="prvaVrstica" id="prvaVrstica">';
+
+ echo '<option value="1"'.($prvaVrstica_roleta == 1 ? ' selected="true"' : '') . '>'.$lang['srv_select_box_prva_vrstica_2'].'</option>';
+
+ echo '<option value="3"'.($prvaVrstica_roleta == 3 ? ' selected="true"' : '') . '>'.$lang['srv_select_box_prva_vrstica_3'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+
+ }
+
+ // Nastavitev text vprasanja, da se pod njim prikazejo odgovori prejsnjih respondentov
+ private function edit_show_prevAnswers(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $prevAnswers = ($spremenljivkaParams->get('prevAnswers') ? $spremenljivkaParams->get('prevAnswers') : 0);
+
+ echo '<p>';
+ echo '<label for="prevAnswers" class="title">'.$lang['srv_setting_prevAnswers'].': </label>';
+ echo '<span class="content"><input type="hidden" name="prevAnswers" value="0" />';
+ echo '<input type="checkbox" id="prevAnswers" name="prevAnswers" value="1" '.(($prevAnswers == 1) ? ' checked="checked" ' : '').' />';
+ echo '</span></p>';
+ }
+
+ /**
+ * CUSTOM PICTURE RADIO
+ * Nastavitve za slikovni tip radio gumbov (smiley, thumbs up...)
+ */
+ function edit_custom_picture_radio(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $displayCustomRadio = ($row['orientation'] == 9 || $row['tip'] == 6 && $row['enota'] == 12) ? '' :' style="display:none;"';
+
+ $customRadioNumber = ($spremenljivkaParams->get('customRadioNumber') ? $spremenljivkaParams->get('customRadioNumber') : '5');
+ $customRadio = $spremenljivkaParams->get('customRadio');
+
+ echo '<div class="custom-picture-radio" '.$displayCustomRadio.'>';
+ echo '<p><span class="title" >'.$lang['srv_custom-picture_radio_label'].':</span>';
+ echo '<span class="content"><select name="customRadio" id="customRadioSelect'.$this->spremenljivka.'">';
+ echo '<option value="star" '.($customRadio == "star" ? 'selected="selected"' : '').'>'.$lang['srv_custom-picture_radio_star'].'</option>';
+ echo '<option value="smiley" '.($customRadio == "smiley" ? 'selected="selected"' : '').'>'.$lang['srv_custom-picture_radio_smiley'].'</option>';
+ echo '<option value="thumb" '.($customRadio == 'thumb' ? 'selected="selected"' : '').'>'.$lang['srv_custom-picture_radio_thumb'].'</option>';
+ echo '<option value="heart" '.($customRadio == 'heart' ? 'selected="selected"' : '').'>'.$lang['srv_custom-picture_radio_heart'].'</option>';
+ echo '<option value="flag" '.($customRadio == 'flag' ? 'selected="selected"' : '').'>'.$lang['srv_custom-picture_radio_flag'].'</option>';
+ echo '<option value="user" '.($customRadio == 'user' ? 'selected="selected"' : '').'>'.$lang['srv_custom-picture_radio_user'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+
+ $preveriOdgovore = sisplet_query("SELECT spr_id FROM srv_data_vrednost" . $this->db_table. " WHERE spr_id='".$this->spremenljivka."'");
+ $stOdgovorov=1;
+ if(mysqli_num_rows($preveriOdgovore)){
+ $stOdgovorov = $customRadioNumber;
+ }
+
+ if($row['tip'] != 6) {
+ echo '<p><span class="title" >' . $lang['srv_custom-picture_number_label'] . ':</span>';
+ echo '<span class="content"><select name="customRadioNumber" id="customRadioNumberSelect' . $this->spremenljivka . '">';
+ for ($n = $stOdgovorov ; $n < 13; $n++) {
+ echo '<option value="' . $n . '" ' . (($customRadioNumber == $n) ? 'selected="selected"' : '') . '>' . $n . '</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ }
+ echo '</div>';
+ }
+
+ /**
+ * Funkcija prikaže izbir število odgovorov
+ */
+ function edit_visual_analog_scale(){
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $displayAnalognoSkalo = ($row['orientation'] == 11) ? '' :' style="display:none;"';
+
+ $vizualnaSkalaNumber = ($spremenljivkaParams->get('vizualnaSkalaNumber') ? $spremenljivkaParams->get('vizualnaSkalaNumber') : '5');
+
+ echo '<div class="vizualna-analogna-skala" '.$displayAnalognoSkalo.'><p><span class="title" >'.$lang['srv_custom-picture_number_label'].':</span>';
+ echo '<span class="content"><select name="vizualnaSkalaNumber" id="vizualnaSkalaNumberSelect'.$this->spremenljivka.'">';
+ for($n=2; $n<8; $n++){
+ echo '<option value="'.$n.'" '.(($vizualnaSkalaNumber == $n) ? 'selected="selected"' : '').'>'.$n.'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+ }
+
+ // nastavitev za lokacijo podtip
+ function edit_subtype_map() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_vprasanje_podtip_map'].':</span>';
+ echo '<span class="content">';
+ echo '<select name="podtip_lokacija" id="spremenljivka_podtip_' . $row['id'] . '" spr_id="'.$row['id'].'" onChange="change_map(this.value, '.$this->spremenljivka.');">';
+ echo '<option value="1" '.(($row['enota'] == 1) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_mylocation'].'</option>';
+ echo '<option value="2" '.(($row['enota'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_multilocation'].'</option>';
+ echo '<option value="3" '.(($row['enota'] == 3) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_chooselocation'].'</option>';
+
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ /**
+ * Tip multilokacija
+ * nastavitev za lokacijo input type
+ * @global type $lang
+ */
+ function edit_input_type_map() {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+ $input = $newParams->get('multi_input_type') ? $newParams->get('multi_input_type') : 'marker';
+
+ echo '<p id="multi_input_type_map" '. ($row['enota'] == 2 ? '' : 'style="display: none;"').'>';
+ echo '<span class="title" >'.$lang['srv_vprasanje_input_type_map'].': </span>';
+ echo '<span class="content">';
+
+ //roleta
+ echo '<select name="multi_input_type" id="multi_input_type_' . $row['id'] . '" spr_id="'.$row['id'].'" onChange="change_input_map(this.value, '.$this->spremenljivka.');">';
+ echo '<option value="marker" '.(($input == 'marker') ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_marker'].'</option>';
+ echo '<option value="polyline" '.(($input == 'polyline') ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_line'].'</option>';
+ echo '<option value="polygon" '.(($input == 'polygon') ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_polygon'].'</option>';
+
+ echo '</select></span>';
+ echo '</p>';
+ }
+
+ /**
+ * spremeni tip vprašanja
+ * static je, da se lažje kliče še iz ostalih classov
+ */
+ public static function change_tip ($spremenljivka, $tip, $podtip = null) {
+ global $lang;
+
+ if ($spremenljivka <= 0) return;
+
+ sisplet_query("UPDATE srv_spremenljivka SET tip = '$tip' WHERE id='$spremenljivka'");
+
+ Cache::clear_cache();
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ if (isset ($_GET['anketa']))
+ $anketa = $_GET['anketa'];
+ elseif (isset ($_POST['anketa']))
+ $anketa = $_POST['anketa'];
+ elseif ($anketa != 0)
+ $anketa = $anketa;
+
+ /* TODO
+ * tukaj se doda se dodatne stvari, ki jih je treba narediti za vsak tip posebej ob spremembi
+ */
+
+
+ // checkbox ima zraven default opombo - nastavimo na ustreznen jezik - uposteva se jezik za respondente in ne admin!
+ $lang_admin = SurveyInfo::getInstance()->getSurveyColumn('lang_admin');
+ $lang_resp = SurveyInfo::getInstance()->getSurveyColumn('lang_resp');
+
+ // nastavimo na jezik za respondentov vmesnik
+ $file = '../../lang/'.$lang_resp.'.php';
+ include($file);
+
+ // checkbox ima zraven default opombo
+ if ($tip == 2 && $row['orientation'] != 6) {
+ $s = sisplet_query("UPDATE srv_spremenljivka SET info='$lang[srv_info_checkbox]' WHERE id = '$spremenljivka'");
+ }
+ // checkbox s selectbox ima zraven default opombo
+ elseif($tip == 2 && $row['orientation'] == 6){
+ $s = sisplet_query("UPDATE srv_spremenljivka SET info='$lang[srv_info_selectbox]' WHERE id = '$spremenljivka'");
+ }
+ // grid s checkboxi ima zraven default opombo
+ elseif ($tip == 16 && $row['enota'] != 6) {
+ $s = sisplet_query("UPDATE srv_spremenljivka SET info='$lang[srv_info_checkbox]' WHERE id = '$spremenljivka'");
+ }
+ //grid s selectboxi ima zraven default opombo
+ elseif($tip == 16 && $row['enota'] == 6){
+ $s = sisplet_query("UPDATE srv_spremenljivka SET info='$lang[srv_info_selectbox]' WHERE id = '$spremenljivka'");
+ }
+ else {
+ $s = sisplet_query("SELECT info FROM srv_spremenljivka WHERE id = '$spremenljivka'");
+ $r = mysqli_fetch_array($s);
+ // if ($r['info'] == $lang['srv_info_checkbox'])
+ $s = sisplet_query("UPDATE srv_spremenljivka SET info='' WHERE id = '$spremenljivka'");
+ }
+
+ // nastavimo nazaj na admin jezik
+ $file = '../../lang/'.$lang_admin.'.php';
+ include($file);
+
+
+ //besedilo* - pobrisemo odvecne vrednosti
+ if ($tip == 21){
+ sisplet_query("UPDATE srv_spremenljivka SET size=text_kosov WHERE id='$spremenljivka'");
+ $row['size'] = $row['text_kosov']; // ker se spodaj bere se size
+ sisplet_query("DELETE FROM srv_vrednost WHERE vrstni_red > '$row[text_kosov]' AND spr_id='$spremenljivka' AND other = 0");
+ sisplet_query("UPDATE srv_vrednost SET naslov='$lang[srv_new_text]', naslov_graf='$lang[srv_new_text]' WHERE spr_id='$spremenljivka' AND other = 0");
+
+ //fotografiranje ima svojo variablo
+ if($podtip != null && $podtip == 7){
+ $sql1 = sisplet_query("SELECT s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' AND s.tip='21' AND s.upload=2 AND s.id!='$spremenljivka'");
+ if (!$sql1) echo 'err453'.mysqli_error($GLOBALS['connect_db']);
+ $c = 0;
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ $row1['variable'] = (int)str_replace('FOTO', '', $row1['variable']);
+ if ($row1['variable'] > $c)
+ $c = $row1['variable'];
+ }
+ $c++;
+ $variable = 'FOTO'.$c;
+ sisplet_query("UPDATE srv_spremenljivka SET variable='$variable', variable_custom='1' WHERE id = '$spremenljivka'");
+ }
+ }
+
+ // number ima na zacetku size 1 in enoto 0
+ if ($row['tip'] == 7) {
+ sisplet_query("UPDATE srv_spremenljivka SET size='1', enota='0' WHERE id = '$spremenljivka'");
+ $row['size'] = 1;
+ sisplet_query("DELETE FROM srv_vrednost WHERE vrstni_red > '".$row['size']."' AND spr_id='$spremenljivka' AND other = 0");
+ sisplet_query("UPDATE srv_vrednost SET naslov='$lang[srv_new_text]', naslov_graf='$lang[srv_new_text]' WHERE spr_id='$spremenljivka' AND other = 0");
+ }
+
+ //multigrid ima na zacetku enoto 0 (subtype)
+ if ($row['tip'] == 6 || $row['tip'] == 16) {
+ sisplet_query("UPDATE srv_spremenljivka SET enota='0' WHERE id = '$spremenljivka'");
+ }
+ //lokacija ima na zacetku enoto 1 (subtype) in parametre - moja lokacija
+ if ($row['tip'] == 26) {
+ sisplet_query("UPDATE srv_spremenljivka SET enota='1' WHERE id = '$spremenljivka'");
+ }
+
+ // kalkulacija ima svojo variablo in 2 decimalki
+ if ($tip == 22) {
+
+ $sql1 = sisplet_query("SELECT s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' AND s.tip='22' AND s.id!='$spremenljivka'");
+ if (!$sql1) echo 'err453'.mysqli_error($GLOBALS['connect_db']);
+ $c = 0;
+ $row['size'] = 1;
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ $row1['variable'] = (int)str_replace('C', '', $row1['variable']);
+ if ($row1['variable'] > $c)
+ $c = $row1['variable'];
+ }
+ $c++;
+ $variable = 'C'.$c;
+
+ sisplet_query("UPDATE srv_spremenljivka SET naslov='$lang[srv_vprasanje_tip_22]', variable='C$c', variable_custom='1', sistem='1', decimalna='2' WHERE id = '$spremenljivka'");
+ }
+
+ // Kvota ima svojo variablo
+ if ($tip == 25) {
+ $sql1 = sisplet_query("SELECT s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' AND s.tip='25' AND s.id!='$spremenljivka'");
+ if (!$sql1) echo 'err453'.mysqli_error($GLOBALS['connect_db']);
+ $c = 0;
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ $row1['variable'] = (int)str_replace('QU', '', $row1['variable']);
+ if ($row1['variable'] > $c)
+ $c = $row1['variable'];
+ }
+ $c++;
+ $variable = 'QU'.$c;
+
+ sisplet_query("UPDATE srv_spremenljivka SET naslov='$lang[srv_vprasanje_tip_25]', variable='QU$c', variable_custom='1', sistem='1' WHERE id = '$spremenljivka'");
+ }
+
+ // generator imen ima svojo variablo in velikost 20 (max imen je 20)
+ if ($tip == 9) {
+
+ $sql1 = sisplet_query("SELECT s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' AND s.tip='9' AND s.id!='$spremenljivka'");
+ if (!$sql1) echo 'err453'.mysqli_error($GLOBALS['connect_db']);
+ $c = 0;
+ while ($row1 = mysqli_fetch_array($sql1)) {
+ $row1['variable'] = (int)str_replace('G', '', $row1['variable']);
+ if ($row1['variable'] > $c)
+ $c = $row1['variable'];
+ }
+ $c++;
+ $variable = 'G'.$c;
+
+ sisplet_query("UPDATE srv_spremenljivka SET naslov='$lang[srv_vprasanje_tip_long_9]', variable='$variable', size='20', label='$lang[srv_name_generator]' WHERE id = '$spremenljivka'");
+
+ $row['size'] = 20;
+ }
+
+ // radio, checkbox, dropdown, vse tabele (tudi multiple), razvrscanje, vsota, besedilo, number, SN-imena
+ if ($row['tip']<=3 || $row['tip']==6 || $row['tip']==16 || $row['tip']==19 || $row['tip']==20 || $row['tip'] == 24 || $row['tip']==17 || $row['tip']==18 || $row['tip'] == 7 || $row['tip'] == 9 || $row['tip'] == 21 || $row['tip'] == 22) {
+ // pri spremembi tipa (npr. iz radio v checkbox) ne smemo se enkrat dodat v srv_vrednost
+ $sqlc = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id='$spremenljivka'");
+ $rowc = mysqli_fetch_array($sqlc);
+ $rowc['count']++; // da pri novem ne zacnemo z 0, ker so potem napacne labele variabel
+ $values = "";
+ for ($i = $rowc['count']; $i <= $row['size']; $i++) {
+ if ($values != "") $values .= ",";
+ if ($row['tip']==21 || $row['tip']==7 || $row['tip']==22) $def_naslov = $lang['srv_new_text']; else $def_naslov = $lang['srv_new_vrednost'].' '.$i;
+ $values .= " ('$spremenljivka', '$i', '$def_naslov', '$i', '$def_naslov') ";
+ }
+ $sql1 = sisplet_query("INSERT INTO srv_vrednost (spr_id, variable, naslov, vrstni_red, naslov2) VALUES $values");
+ } else {
+ sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$spremenljivka'");
+ }
+
+ // tabele imajo zapis v srv_grid - razen multiple tabela
+ //if ($row['tip'] == 6 || $row['tip'] == 16 || $row['tip'] == 19 || $row['tip'] == 20) {
+ if ($row['tip'] == 6 || $row['tip'] == 16 || $row['tip'] == 19 || $row['tip'] == 20 || ($row['tip'] == 2)) {
+ // tukaj ni problema, ce ob spremembi tipa se enkrat naredimo INSERT, ker so nastavljeni kljuci in se ne da 2x vnest
+ $values = "";
+ for ($i=1; $i<=$row['grids']; $i++) {
+ if ($values != "") $values .= ", ";
+ $values .= " ('$i', '$spremenljivka', '$lang[srv_new_grid]', '$i', '$i') ";
+ }
+ $sql1 = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable) VALUES $values");
+
+ } else {
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id = '$spremenljivka'");
+ }
+
+ // multiple tabela
+ if ($row['tip'] == 24) {
+ // zaenkrat nic
+ } else {
+ // pri brisanju multiple grid vprasanja, moramo pobrisate tudi vse child spremenljivke (ker kljuci niso nastavljeni)
+ $sqld = sisplet_query("SELECT spr_id FROM srv_grid_multiple WHERE parent='$spremenljivka'");
+ while ($rowd = mysqli_fetch_array($sqld)) {
+ sisplet_query("DELETE FROM srv_spremenljivka WHERE id='$rowd[spr_id]'");
+ }
+ sisplet_query("DELETE FROM srv_grid_multiple WHERE parent = '$spremenljivka' AND ank_id = '$anketa'");
+ }
+
+ Cache::clear_cache();
+
+ }
+
+ /**
+ * nastavi vprasanje na tip captcha
+ *
+ */
+ function set_captcha () {
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $newParams = new enkaParameters($row['params']);
+
+ $newParams->set('captcha', 1);
+
+ $params = $newParams->getString();
+ $update .= ", params = '$params' ";
+
+ sisplet_query("UPDATE srv_spremenljivka SET tip='21', reminder='2' $update WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi multigrid na datum
+ *
+ */
+ function set_datum () {
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $newParams = new enkaParameters($row['params']);
+
+ $newParams->set('multigrid-datum', 1);
+
+ $params = $newParams->getString();
+ $update .= ", params = '$params' ";
+
+ sisplet_query("UPDATE srv_spremenljivka SET tip='19' $update WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip email
+ *
+ */
+ function set_email ($reminder=2) {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+ $newParams->set('emailVerify', 1);
+
+ $params = $newParams->getString();
+ $update .= ", params = '$params' ";
+
+ sisplet_query("UPDATE srv_spremenljivka SET variable='email', variable_custom='1', info='(".$lang['srv_email_example'].")', tip='21', reminder='".$reminder."' $update WHERE id = '$this->spremenljivka'");
+ //sisplet_query("UPDATE srv_spremenljivka SET info = '(".$lang['srv_email_example'].")' WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip url
+ *
+ */
+ function set_url () {
+ global $lang;
+
+ sisplet_query("UPDATE srv_spremenljivka SET info = '(".$lang['srv_url_example'].")' WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip upload
+ *
+ */
+ function set_upload () {
+ global $lang;
+
+ sisplet_query("UPDATE srv_spremenljivka SET upload = '1' WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip fotografija
+ *
+ */
+ function set_fotografija () {
+ global $lang;
+
+ sisplet_query("UPDATE srv_spremenljivka SET upload = '2' WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip signature
+ *
+ */
+ function set_signature () {
+ global $lang;
+ sisplet_query("UPDATE srv_spremenljivka SET signature = '1' $update WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip GDPR
+ *
+ */
+ function set_GDPR () {
+ global $lang;
+
+ $lang_admin = SurveyInfo::getInstance()->getSurveyColumn('lang_admin');
+ $lang_resp = SurveyInfo::getInstance()->getSurveyColumn('lang_resp');
+
+ // nastavimo na jezik za respondentov vmesnik
+ $file = '../../lang/'.$lang_resp.'.php';
+ include($file);
+
+
+ $user_settings = GDPR::getSurveySettings($this->anketa);
+
+ // GDPR je radio (da / ne) tip vprasanja z predefiniranim textom
+ $naslov = GDPR::getSurveyIntro($this->anketa);
+
+ // Poporavimo naslov vprasanja
+ sisplet_query("UPDATE srv_spremenljivka SET variable='gdpr', variable_custom='1', naslov='".$naslov."', tip='1', reminder='2' WHERE id = '$this->spremenljivka'");
+
+ // Pobrisemo odvecne variable
+ sisplet_query("DELETE FROM srv_vrednost WHERE spr_id = '$this->spremenljivka' AND vrstni_red > '2'");
+
+ // Popravimo text variabel
+ sisplet_query("UPDATE srv_vrednost SET naslov='".$lang['srv_gdpr_intro_no']."' WHERE spr_id = '$this->spremenljivka' AND vrstni_red = '1'");
+ sisplet_query("UPDATE srv_vrednost SET naslov='".$lang['srv_gdpr_intro_yes']."' WHERE spr_id = '$this->spremenljivka' AND vrstni_red = '2'");
+
+ // Popravimo, da ima anketa vklopljen gdpr
+ sisplet_query("INSERT INTO srv_gdpr_anketa (ank_id) VALUES ('".$this->anketa."')");
+
+
+ // nastavimo nazaj na admin jezik
+ $file = '../../lang/'.$lang_admin.'.php';
+ include($file);
+ }
+
+ /**
+ * nastavi na tip text box
+ *
+ */
+ function set_box () {
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $newParams = new enkaParameters($row['params']);
+
+ $newParams->set('taSize', 5);
+ $newParams->set('taWidth', 50);
+
+ $params = $newParams->getString();
+ $update .= ", params = '$params' ";
+
+ sisplet_query("UPDATE srv_spremenljivka SET tip='21' $update WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip mape
+ *
+ */
+ function set_map ($podtip) {
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $newParams = new enkaParameters($row['params']);
+
+ //multi lokacija
+ if($podtip == 2){
+ $newParams->set('user_location', 0);
+ $newParams->set('fokus_mape', 'Slovenija');
+ $newParams->set('marker_podvprasanje', 0);
+ $newParams->set('max_markers', 3);
+ $newParams->set('dodaj_searchbox', 1);
+ $newParams->set('multi_input_type', 'marker');
+ }
+ //moja lokacija
+ elseif($podtip == 1){
+ $newParams->set('user_location', 1);
+ $newParams->set('fokus_mape', 'Slovenija');
+ $newParams->set('marker_podvprasanje', 0);
+ $newParams->set('max_markers', 3);
+ $newParams->set('dodaj_searchbox', 1);
+ $newParams->set('multi_input_type', 'marker');
+ }
+
+ $params = $newParams->getString();
+ $update .= ", params = '$params' ";
+
+ sisplet_query("UPDATE srv_spremenljivka SET enota = '$podtip' $update WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi text nagovoru za aktivacijo chata
+ *
+ */
+ function set_chat() {
+ global $lang;
+
+ $title = '<p>'.$lang['srv_chat_question_text'].'</p><div class="tawk-chat-activation button">'.$lang['srv_chat_turn_on'].'</div>';
+
+ sisplet_query("UPDATE srv_spremenljivka SET naslov = '".$title."' WHERE id = '$this->spremenljivka'");
+ }
+
+ /**
+ * nastavi vprasanje na tip slider
+ *
+ */
+ function set_slider () {
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET ranking_k='1', vsota_min='0', vsota_limit='100', num_useMin='1', num_useMax='1' WHERE id = '$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+
+ /**
+ * pohendla ajax klice za vprasanje
+ *
+ */
+ function ajax () {
+
+ if (isset($_POST['spremenljivka'])) $this->spremenljivka = $_POST['spremenljivka'];
+
+ $ajax = 'ajax_' . $_GET['a'];
+
+ if ( method_exists('Vprasanje', $ajax) )
+ $this->$ajax();
+ else
+ echo 'method '.$ajax.' does not exist';
+ }
+
+ function ajax_vprasanje_fullscreen () {
+ $this->display();
+ }
+
+ function ajax_vprasanje_tab () {
+ $this->vprasanje_edit();
+ }
+
+ function ajax_vprasanje_save () {
+ global $lang;
+ global $default_grid_values;
+
+ if ($this->spremenljivka < -3) return; // -1, -2, -3 so uvod, zakljucek in statistika
+
+ $lang_id = $_POST['lang_id'];
+
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $update = '';
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $diferencial_trak = ($spremenljivkaParams->get('diferencial_trak') ? $spremenljivkaParams->get('diferencial_trak') : 0); //za checkbox
+
+ // urejanje grida
+ if (isset($_POST['edit_grid'])) {
+
+ //na zacetku pobrisemo missing gride (ker jih na koncu dodamo)
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND vrstni_red > '$i' AND other != '0'");
+
+ $vrstni_red = 0;
+ $i = 0;
+ foreach ($_POST as $key => $v) {
+
+ if (substr($key, 0, 12) == 'grid_naslov_') {
+ $vrstni_red++;
+
+ $grid = substr($key, 12);
+ $naslov = $_POST['grid_naslov_'.$grid];
+ $variable = $grid;
+ $id= $vrstni_red;
+
+ $other = '0';
+
+ # manjkoajoče vrednosti (ne vem, zavrnil ...
+ if (isset($_POST['missing_value_checkbox']) && is_array($_POST['missing_value_checkbox'])) {
+
+ if (in_array($grid, $_POST['missing_value_checkbox'])) {
+ # grid je manjkajoča vrednost
+ $other = $grid.'';
+ $id = $grid;
+ }
+ else {
+ # grid je normalna vrednost
+ $i++;
+ }
+ }
+ else {
+ # grid je normalna vrednost
+ $i++;
+ }
+
+ // ne sme bit replace into, ker najprej zbrise in nato inserta, in pobrise vse tabele, ki se navezujejo s foreign keyi
+ // v update ni variable, ker se variable vpise samo v insertu, potem ga pa spreminjamo samo spodaj rocno - _variable_edit
+ $s = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable, other, part) VALUES ('$id', '$this->spremenljivka', '$naslov', '$vrstni_red', '$variable', '$other', '1') ON DUPLICATE KEY UPDATE naslov=VALUES(naslov), vrstni_red=VALUES(vrstni_red), other=VALUES(other), part='1'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // pri double gridih podvojimo vnose -> part=2
+ if($row['enota'] == 3){
+ $vrstni_red2 = $vrstni_red + ((int) $_POST['grids_count']);
+ $id = $vrstni_red2;
+
+ $s = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable, other, part) VALUES ('$id', '$this->spremenljivka', '$naslov', '$vrstni_red2', '$variable', '$other', 2) ON DUPLICATE KEY UPDATE naslov=VALUES(naslov), vrstni_red=VALUES(vrstni_red), other=VALUES(other), part=2");
+ }
+ }
+ }
+
+ //popravimo st gridov ce imamo posebne vrednosti
+ $update .= ", grids = '$i' ";
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND vrstni_red > '$i' AND other = '0' AND part = '1'");
+
+ if($row['enota'] == 3){
+ $i *= 2;
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND vrstni_red > '$i' AND other = '0' AND part = '2'");
+ }
+ else{
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND part = '2'");
+ }
+ }
+
+ if (isset($_POST['edit_grid_variable_edit']) && $_POST['edit_grid_variable_edit'] == 1) {
+
+ $s = sisplet_query("SELECT id FROM srv_grid WHERE spr_id = '$this->spremenljivka'");
+ while ($r = mysqli_fetch_array($s)) {
+
+ if (isset($_POST['edit_grid_variable_'.$r['id']]))
+ sisplet_query("UPDATE srv_grid SET variable='{$_POST['edit_grid_variable_'.$r['id']]}' WHERE spr_id='$this->spremenljivka' AND id='$r[id]'");
+
+ }
+ }
+
+ // urejanje vrednosti
+ if (isset($_POST['edit_vrednost'])) {
+
+ $i = 1;
+
+ foreach ($_POST as $key => $v) {
+ //shranimo drugo polje ce imamo diferencial
+ if (substr($key, 0, 17) == 'vrednost_naslov2_') {
+ $vrednost = substr($key, 17);
+
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov2='".$_POST['vrednost_naslov2_'.$vrednost]."' WHERE id = '$vrednost'");
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ if (substr($key, 0, 16) == 'vrednost_naslov_') {
+ $vrednost = substr($key, 16);
+
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov='".$_POST['vrednost_naslov_'.$vrednost]."', vrstni_red='$i' WHERE id = '$vrednost'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $i++;
+ }
+ }
+
+ //sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND naslov=''");
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ // odstranimo default vrednosti - ( v primeru da vsaj 1 ni vec default )
+ if (true) {
+
+ $_default = true;
+ $s = sisplet_query("SELECT id, naslov FROM srv_vrednost WHERE spr_id='$this->spremenljivka'");
+ while ($r = mysqli_fetch_array($s)) {
+ if ( strpos($r['naslov'], $lang['srv_new_vrednost']) === false ) $_default = false;
+ }
+
+ if ($_default == false) {
+ mysqli_data_seek($s, 0);
+ while ($r = mysqli_fetch_array($s)) {
+ if ( strpos($r['naslov'], $lang['srv_new_vrednost']) !== false ) {
+ sisplet_query("DELETE FROM srv_vrednost WHERE id = '$r[id]'");
+ }
+ }
+ }
+
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ // shrani stevilo gridov in jih doda/pobrise iz srv_grid
+ if (isset($_POST['grids_count'])) {
+
+ // Shranimo stare naslove missing gridov da jih ne povozimo kasneje
+ $sqlM = sisplet_query("SELECT id, naslov, other FROM srv_grid WHERE spr_id='$this->spremenljivka' AND other!='0'");
+ $missing_old_vals = array();
+ while($rowM = mysqli_fetch_array($sqlM)){
+ $missing_old_vals[$rowM['other']]['naslov'] = $rowM['naslov'];
+
+ // Shranimo se preveden naslov ce ga imamo
+ $sqlL = sisplet_query("SELECT lang_id, naslov, podnaslov FROM srv_language_grid WHERE spr_id='$this->spremenljivka' AND grd_id='".$rowM['id']."'");
+ while($rowL = mysqli_fetch_array($sqlL)){
+ $missing_old_vals[$rowM['other']]['translations'][] = $rowL;
+ }
+ }
+
+ //na zacetku pobrisemo missing gride in podvojene gride (dvojna tabela) - ker jih na koncu dodamo
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND (other != '0' OR part != '1')");
+
+ // Pri multigrid tipih max diff in one against another popravimo stevilo gridov na 2
+ if($row['tip'] == 6 && ($_POST['enota'] == 4 || $_POST['enota'] == 5 || $_POST['enota'] == 8)){
+ $count = 2;
+ }
+ elseif ($row['tip'] == 20 && $row['ranking_k'] == 1){
+ $count = 1;
+ }
+ else{
+ $count = $_POST['grids_count'];
+ }
+
+ $countAll = (isset($_POST['missing_value_checkbox']) && is_array($_POST['missing_value_checkbox'])) ? $count + count($_POST['missing_value_checkbox']) : $count;
+
+ //pobrisemo gride ki so prevec
+ sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND vrstni_red > '$count' AND other = '0' AND part = '1'");
+
+ for($i=1; $i<=$count; $i++){
+
+ $id = $i;
+ $vrstni_red = $i;
+ $variable = $i;
+
+ //dodamo grid
+ if($row['grids'] < $i){
+
+ $s = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable, other, part) VALUES ('$id', '$this->spremenljivka', '$lang[srv_new_grid]', '$vrstni_red', '$variable', '$other', '1') ON DUPLICATE KEY UPDATE naslov=VALUES(naslov), vrstni_red=VALUES(vrstni_red), other=VALUES(other), part=2");
+
+ if ($diferencial_trak == 1){ //ce je trak, se morajo vrednosti ustrezno posodobiti,saj so se pred tem v bazi spremenile
+ $this->ajax_diferencial_trak_skrite_vrednosti($this->spremenljivka, $count, $_POST['diferencial_trak_starting_num']);
+ }
+ }
+
+ //dodamo podvojen grid pri dvojni tabeli
+ if($_POST['enota'] == 3){
+
+ $sqlN = sisplet_query("SELECT naslov FROM srv_grid WHERE spr_id='$this->spremenljivka' AND id = '$id'");
+ $rowN = mysqli_fetch_array($sqlN);
+ $naslov2 = $rowN['naslov'];
+
+ $vrstni_red2 = $vrstni_red + $countAll;
+ $id = $vrstni_red2;
+
+ $s = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable, other, part) VALUES ('$id', '$this->spremenljivka', '$naslov2', '$vrstni_red2', '$variable', '$other', 2)");
+ }
+ }
+
+ # napolnimo/pobrisemo manjkajoče vrednosti (ne vem, zavrnil ...
+ if (isset($_POST['missing_value_checkbox']) && is_array($_POST['missing_value_checkbox'])) {
+
+ $vrstni_red = $count;
+
+ foreach($_POST['missing_value_checkbox'] as $key => $missing){
+
+ # popravimi za missing vrednosi
+ # katere missinge imamo na voljo
+ $smv = new SurveyMissingValues($this->anketa);
+
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+ $naslov = addslashes($missing_values[$missing]);
+ $other = $missing;
+
+ // Popravimo naslov missing gridov ce samo zapremo edit (da ga ne povozimo)
+ if(isset($missing_old_vals[$other]))
+ $naslov = $missing_old_vals[$other]['naslov'];
+
+ $vrstni_red++;
+ $id = $vrstni_red;
+ $variable = $id;
+
+ $s = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable, other, part) VALUES ('$id', '$this->spremenljivka', '$naslov', '$vrstni_red', '$variable', '$other', '1') ON DUPLICATE KEY UPDATE naslov=VALUES(naslov), vrstni_red=VALUES(vrstni_red), other=VALUES(other), part=2");
+
+ // Insertamo se prevedene naslove missing gridov ce obstajajo
+ if(isset($missing_old_vals[$other]['translations'])){
+
+ foreach($missing_old_vals[$other]['translations'] as $translation){
+
+ $sl = sisplet_query("INSERT INTO srv_language_grid
+ (ank_id, spr_id, grd_id, lang_id, naslov, podnaslov)
+ VALUES
+ ('".$this->anketa."', '".$this->spremenljivka."', '".$id."', '".$translation['lang_id']."', '".$translation['naslov']."', '".$translation['podnaslov']."')");
+ }
+ }
+
+
+ //dodamo podvojen grid pri dvojni tabeli
+ if($_POST['enota'] == 3){
+
+ $vrstni_red2 = $vrstni_red + $countAll;
+ $id = $vrstni_red2;
+
+ $s = sisplet_query("INSERT INTO srv_grid (id, spr_id, naslov, vrstni_red, variable, other, part) VALUES ('$id', '$this->spremenljivka', '$naslov', '$vrstni_red2', '$variable', '$other', 2)");
+ }
+ }
+ }
+
+ $update .= ", grids = '$count' ";
+ }
+
+ // napolni default vrednosti v gride
+ if(isset($_POST['grid_defaults'])){
+
+ $grid_defaults = $_POST['grid_defaults'];
+
+ $grids_count = 5;
+
+ if($row['tip'] == 6 && ($_POST['enota'] == 4 || $_POST['enota'] == 5 || $_POST['enota'] == 8)){//dodal pogoj, ker drugace ne kaze pravilno label
+ $grids_count = 2;
+ }
+ else{
+ $grids_count = $_POST['grids_count'];
+ }
+
+ // Ce imamo nastavljene dolocene default vrednosti gridov jih napolnimo
+ if($grid_defaults > 0){
+
+ // Napolnimo prave vrednosti
+ $values = $default_grid_values[$grid_defaults];
+
+ $indexArray = array(
+ 2 => array(2, 6),
+ 3 => array(2, 4, 6),
+ 4 => array(1, 2, 6, 7),
+ 5 => array(1, 2, 4, 6, 7),
+ 6 => array(1, 2, 3, 5, 6, 7),
+ 7 => array(1, 2, 3, 4, 5, 6, 7)
+ );
+
+ for($i=1; $i<=$grids_count; $i++){
+
+ // Ce imamo samo en grid
+ if($grids_count == 1 && $i == 1){
+ $index = 2;
+ $naslov = $values[2];
+ }
+ // Ce imamo vec kot 7 gridov - prvih 7 zapisemo normalno, ostali so prazni
+ else if($grids_count > 7){
+ if($i <= 7){
+ $index = $indexArray[7][$i-1];
+ $naslov = $values[$index];
+ }
+ else
+ break;
+ }
+ // Ce imamo 2 - 7 gridov jih izpisemo v skladu z $indexArray
+ else{
+ $index = $indexArray[$grids_count][$i-1];
+ $naslov = $values[$index];
+ }
+
+ //$lang['srv_grid_defaults_'.$grid_defaults.'_'.$i];
+ $s = sisplet_query("UPDATE srv_grid SET naslov='".$naslov."' WHERE spr_id='$this->spremenljivka' AND vrstni_red = '$i'");
+ }
+ }
+ }
+
+ // napolni default vrednosti v radio tip
+ if(isset($_POST['radio_defaults'])){
+
+ $radio_defaults = $_POST['radio_defaults'];
+
+ // Preberemo stevilo vrednosti
+ $sqlVCnt = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND other='0' ORDER BY vrstni_red ASC");
+ $vrednost_count = (mysqli_num_rows($sqlVCnt) > 0) ? mysqli_num_rows($sqlVCnt) : 5;
+
+ // Ce imamo nastavljene dolocene default vrednosti gridov jih napolnimo
+ if($radio_defaults > 0){
+
+ // Napolnimo prave vrednosti
+ $values = $default_grid_values[$radio_defaults];
+
+ $indexArray = array(
+ 2 => array(2, 6),
+ 3 => array(2, 4, 6),
+ 4 => array(1, 2, 6, 7),
+ 5 => array(1, 2, 4, 6, 7),
+ 6 => array(1, 2, 3, 5, 6, 7),
+ 7 => array(1, 2, 3, 4, 5, 6, 7)
+ );
+
+ $sqlV = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND other='0' ORDER BY vrstni_red ASC");
+ $i=1;
+ if(mysqli_num_rows($sqlV) > 0){
+ while($rowV = mysqli_fetch_array($sqlV)){
+
+ // Ce imamo samo eno vrednost
+ if($vrednost_count == 1 && $i == 1){
+ $index = 2;
+ $naslov = $values[2];
+ }
+ // Ce imamo vec kot 7 vrednosti - prvih 7 zapisemo normalno, ostali so prazni
+ else if($vrednost_count > 7){
+ if($i <= 7){
+ $index = $indexArray[7][$i-1];
+ $naslov = $values[$index];
+ }
+ else
+ break;
+ }
+ // Ce imamo 2 - 7 gridov jih izpisemo v skladu z $indexArray
+ else{
+ $index = $indexArray[$vrednost_count][$i-1];
+ $naslov = $values[$index];
+ }
+
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov='".$naslov."' WHERE spr_id='$this->spremenljivka' AND id='".$rowV['id']."'");
+ $i++;
+ }
+ }
+ }
+ }
+
+
+ // urejanje vrednosti pri besedilu*
+ if (isset($_POST['edit_vrednost_besedilo'])) {
+
+ # pogledamo koliko kosov rabimo
+ $kosov = $_POST['text_kosov'];
+
+ $j = 0;
+ for ($j = 1; $j <= $kosov; $j++) {
+ $vrstni_red = $j;
+ //$naslov = $_POST['vrednost_naslov_'.$vrstni_red];
+ $naslov = $lang['srv_new_text'];
+ $size = $_POST['vrednost_size_'.$vrstni_red];
+
+ //$s = sisplet_query("UPDATE srv_vrednost SET naslov='".$_POST['vrednost_naslov_'.$j]."', size='".$_POST['vrednost_size_'.$j]."' WHERE vrstni_red='$j' AND other = '0' AND spr_id='$this->spremenljivka'");
+ $s = sisplet_query("UPDATE srv_vrednost SET size='".$_POST['vrednost_size_'.$j]."' WHERE vrstni_red='$j' AND other = '0' AND spr_id='$this->spremenljivka'");
+
+ $s = sisplet_query("SELECT id FROM srv_vrednost WHERE vrstni_red='$vrstni_red' AND spr_id='$this->spremenljivka' AND other = 0");
+ if(mysqli_num_rows($s) == 0){
+ $i = sisplet_query("INSERT INTO srv_vrednost (id, spr_id, naslov, size, vrstni_red) VALUES ('', '$this->spremenljivka', '$naslov', '$size', '$vrstni_red')");
+ }
+
+ unset($_POST['vrednost_naslov_'.$j]);
+ unset($_POST['vrednost_size_'.$j]);
+ }
+
+ # popravimo polja drugo, nevem...
+ foreach ($_POST as $key => $v) {
+ if (substr($key, 0, 16) == 'vrednost_naslov_') {
+ $vrednost = substr($key, 16);
+ //$naslov = $_POST['vrednost_naslov_'.$vrednost]; // naslov spreminjamo zdaj v inlineu
+ //$s = sisplet_query("UPDATE srv_vrednost SET naslov='$naslov', vrstni_red='$j' WHERE id='$vrednost' AND spr_id='$this->spremenljivka'");
+ $s = sisplet_query("UPDATE srv_vrednost SET vrstni_red='$j' WHERE id='$vrednost' AND spr_id='$this->spremenljivka'");
+
+ $j++;
+ }
+ }
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ // urejanje vrednosti pri number
+ if (isset($_POST['edit_vrednost_number'])) {
+
+ $kosov = (int)$_POST['size'];
+ $j = 0;
+
+ for ($j = 1; $j <= $kosov; $j++) {
+ $vrstni_red = $j;
+ //$naslov = $_POST['vrednost_naslov_'.$vrstni_red];
+ $naslov = $lang['srv_new_text'];
+ $size = $_POST['vrednost_size_'.$vrstni_red];
+
+ //$s = sisplet_query("UPDATE srv_vrednost SET naslov='".$_POST['vrednost_naslov_'.$j]."', size='".$_POST['vrednost_size_'.$j]."' WHERE vrstni_red='$j' AND other = '0' AND spr_id='$this->spremenljivka'");
+ $s = sisplet_query("UPDATE srv_vrednost SET size='".$_POST['vrednost_size_'.$j]."' WHERE vrstni_red='$j' AND other = '0' AND spr_id='$this->spremenljivka'");
+
+ $s = sisplet_query("SELECT id FROM srv_vrednost WHERE vrstni_red='$vrstni_red' AND spr_id='$this->spremenljivka' AND other = 0");
+ if(mysqli_num_rows($s) == 0){
+ $i = sisplet_query("INSERT INTO srv_vrednost (id, spr_id, naslov, size, vrstni_red) VALUES ('', '$this->spremenljivka', '$naslov', '$size', '$vrstni_red')");
+ }
+
+ unset($_POST['vrednost_naslov_'.$j]);
+ unset($_POST['vrednost_size_'.$j]);
+ }
+ # pobrišemo morebitne odvečne variable
+ $s1 = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND other = '0'");
+ if (mysqli_num_rows($s1) > $kosov) {
+ sisplet_query("DELETE FROM srv_vrednost WHERE vrstni_red > '$kosov' AND spr_id='$this->spremenljivka' AND other = 0");
+ }
+
+ # popravimo polja drugo, nevem...
+ foreach ($_POST as $key => $v) {
+ if (substr($key, 0, 16) == 'vrednost_naslov_') {
+ $vrednost = substr($key, 16);
+ //$naslov = $_POST['vrednost_naslov_'.$vrednost];
+ //$s = sisplet_query("UPDATE srv_vrednost SET naslov='$naslov', vrstni_red='$j' WHERE id='$vrednost' AND spr_id='$this->spremenljivka'");
+ $s = sisplet_query("UPDATE srv_vrednost SET vrstni_red='$j' WHERE id='$vrednost' AND spr_id='$this->spremenljivka'");
+ $j++;
+ }
+ }
+
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ // shrani naslov
+ if (isset($_POST['naslov'])) {
+ $naslov = $_POST['naslov'];
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($naslov, -4) == '<br>') {
+ $naslov = substr($naslov, 0, -4);
+ }
+ if (substr($naslov, -8) == '<br></p>') { // ce je na koncu <br></p>
+ $naslov = substr($naslov, 0, -8).'</p>';
+ }
+
+ // ce nimamo paragrafov jih dodamo
+ if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if ($lang_id == 0) {
+ $update .= ", naslov = '$naslov' ";
+ }
+ else {
+ sisplet_query("INSERT INTO srv_language_spremenljivka (ank_id, spr_id, lang_id, naslov) VALUES ('$this->anketa', '$this->spremenljivka', '$lang_id', '$naslov') ON DUPLICATE KEY UPDATE naslov='$naslov'");
+ }
+ }
+
+ if (isset($_POST['variable'])) {
+
+ if ( in_array($row['variable'], array('email','telefon','ime','priimek','naziv','drugo')) && $row['sistem']==1 ) {
+
+ // tukaj ne pustimo spremeniti
+
+ } else {
+
+ // preverimo, da ni se kje drugje v anekti tako ime spremenljivke
+ $sqlv = sisplet_query("SELECT s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa'");
+ $ok = true;
+ while ($rowv = mysqli_fetch_array($sqlv)) {
+ if ($rowv['variable'] == $_POST['variable']) $ok = false;
+ }
+
+ if ($_POST['variable'] != $row['variable'] && $_POST['variable'] != ''){
+ // Ce imamo unikatno ime shranimo
+ if($ok){
+ $update .= ", variable='$_POST[variable]', variable_custom='1' ";
+ }
+ // Ce se ime ze pojavi v anketi mu dodamo stevilko
+ else{
+ $ok = false;
+ $i = 2;
+ while(!$ok){
+ $ok = true;
+ $variable = $_POST['variable'].'_'.$i;
+
+ $sqlv = sisplet_query("SELECT s.variable, s.id as id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$this->anketa'");
+ while ($rowv = mysqli_fetch_array($sqlv)) {
+ if ($rowv['variable'] == $variable && $this->spremenljivka != $rowv['id']){
+ $ok = false;
+ $i++;
+ }
+ }
+ }
+
+ $update .= ", variable='$variable', variable_custom='1' ";
+ }
+ }
+
+ }
+ }
+
+ if (isset($_POST['label'])) {
+ if ($_POST['label'] != $row['label'])
+ $update .= ", label='$_POST[label]' ";
+ }
+
+ // // shrani opombo
+ if (isset($_POST['info'])) {
+ $update .= ", info = '$_POST[info]' ";
+ }
+
+
+ // shrani uvod
+ if (isset($_POST['introduction'])) {
+
+ $naslov = $_POST['introduction'];
+ if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if ($lang_id == 0) {
+ $s = sisplet_query("UPDATE srv_anketa SET introduction='".$naslov."' WHERE id = '$this->anketa'");
+ }
+ else {
+ if ($naslov!='')
+ sisplet_query("REPLACE INTO srv_language_spremenljivka (ank_id, spr_id, lang_id, naslov) VALUES ('$this->anketa', '-1', '$lang_id', '$naslov')");
+ else
+ sisplet_query("DELETE FROM srv_language_spremenljivka WHERE ank_id='$this->anketa' AND spr_id='-1' AND lang_id='$lang_id'");
+ }
+ }
+
+ // nastavitve uvoda
+ if ( isset($_POST['intro_opomba'])) {
+ if (isset($_POST['intro_opomba'])) {
+ $intro_opomba = $_POST['intro_opomba'];
+ $intro_note = $_POST['note'];
+ $intro = " intro_opomba='".$intro_opomba."', intro_note='$intro_note'";
+ } else $intro = '';
+
+ unset($_POST['note']); // da ne gre shranjevat v srv_spremenljivka
+
+ $s = sisplet_query("UPDATE srv_anketa SET $intro WHERE id = '$this->anketa'");
+ //$s = sisplet_query("UPDATE srv_anketa SET $intro WHERE id = '$this->anketa'");
+ }
+
+ // shrani dodatno ime za gumb za naprej
+ if(isset($_POST['srv_nextpage_uvod'])) {
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveySetting::getInstance()->setSurveyMiscSetting('srvlang_srv_nextpage_uvod', $_POST['srv_nextpage_uvod']);
+ }
+
+ // shrani napredne nastavitve za uvod
+ if (isset($_POST['show_intro'])) {
+ $s = sisplet_query("UPDATE srv_anketa SET show_intro='".$_POST['show_intro']."' WHERE id = '$this->anketa'");
+ }
+
+ // shrani napredne nastavitve za uvod
+ if (isset($_POST['show_intro'])) {
+ $s = sisplet_query("UPDATE srv_anketa SET intro_static='".$_POST['intro_static']."' WHERE id = '$this->anketa'");
+ }
+
+ // shrani zakljucek
+ if (isset($_POST['conclusion'])) {
+
+ $naslov = $_POST['conclusion'];
+ if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ //$naslov = '<p>'.nl2br($naslov).'</p>';
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if ($lang_id == 0) {
+ $s = sisplet_query("UPDATE srv_anketa SET conclusion='".$naslov."' WHERE id = '$this->anketa'");
+ }
+ else {
+ if ($naslov!='')
+ sisplet_query("REPLACE INTO srv_language_spremenljivka (ank_id, spr_id, lang_id, naslov) VALUES ('$this->anketa', '-2', '$lang_id', '$naslov')");
+ else
+ sisplet_query("DELETE FROM srv_language_spremenljivka WHERE ank_id='$this->anketa' AND spr_id='-2' AND lang_id='$lang_id'");
+ }
+ }
+
+ // nastavitve zakljucka
+ if (isset($_POST['concl_opomba'])) {
+ if (isset($_POST['concl_opomba'])) {
+
+ // Shranjevanje kaj se zgodi po koncu ankete (skok na url...)
+ $concl_link = $_POST['concl_link'];
+ if($concl_link == 1)
+ $concl_link = 0;
+ elseif($concl_link == 0)
+ $concl_link =1;
+
+ $url = $_POST['url'];
+
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveySetting::getInstance()->setSurveyMiscSetting('concl_url_usr_id', $_POST['concl_url_usr_id']);
+ SurveySetting::getInstance()->setSurveyMiscSetting('concl_url_status', $_POST['concl_url_status']);
+ SurveySetting::getInstance()->setSurveyMiscSetting('concl_url_recnum', $_POST['concl_url_recnum']);
+
+ $concl_opomba = $_POST['concl_opomba'];
+ $concl_note = $_POST['note'];
+
+ $concl_back_button = $_POST['concl_back_button'];
+ $concl_end_button = $_POST['concl_end_button'];
+
+ // shrani prikaz povezave na zacetek ankete za naknadno urejanje
+ $concl_return_edit = $_POST['concl_return_edit'];
+
+ // shrani prikaz povezave na PDF link na koncu
+ $concl_PDF_link = $_POST['concl_PDF_link'];
+
+ $concl = "concl_opomba='".$concl_opomba."',
+ url='".$url."',
+ concl_back_button='".$concl_back_button."',
+ concl_link='".$concl_link."',
+ concl_end_button='".$concl_end_button."',
+ concl_note='$concl_note',
+ concl_PDF_link='$concl_PDF_link',
+ concl_return_edit='$concl_return_edit'";
+ }
+ else
+ $concl = '';
+
+ unset($_POST['note']); // da ne gre shranjevat v srv_spremenljivka
+
+ $s = sisplet_query("UPDATE srv_anketa SET $concl WHERE id = '$this->anketa'");
+ //$s = sisplet_query("UPDATE srv_anketa SET $concl WHERE id = '$this->anketa'");
+ }
+
+ // shrani napredne nastavitve za zakljucek
+ if (isset($_POST['show_concl'])) {
+ $s = sisplet_query("UPDATE srv_anketa SET show_concl='".$_POST['show_concl']."' WHERE id = '$this->anketa'");
+ }
+
+ // shrani dodatno ime za gumb zakljucek
+ if(isset($_POST['srv_konec'])){
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveySetting::getInstance()->setSurveyMiscSetting('srvlang_srv_konec', $_POST['srv_konec']);
+ }
+
+ // shrani dodatno ime za gumb prejsnja stran
+ if(isset($_POST['srv_prevpage'])){
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveySetting::getInstance()->setSurveyMiscSetting('srvlang_srv_prevpage', $_POST['srv_prevpage']);
+ }
+
+ // shrani text zakljucka po deaktivaciji
+ if(isset($_POST['srvlang_srv_survey_non_active'])){
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveySetting::getInstance()->setSurveyMiscSetting('srvlang_srv_survey_non_active', $_POST['srvlang_srv_survey_non_active']);
+ }
+
+ // shrani statistiko
+ if (isset($_POST['statistics'])) {
+ $naslov = $_POST['statistics'];
+ if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ //$naslov = '<p>'.nl2br($naslov).'</p>';
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ $s = sisplet_query("UPDATE srv_anketa SET statistics='".$naslov."' WHERE id = '$this->anketa'");
+ }
+
+ // shrani dodaten naslov spremenljivke za graf
+ if (isset($_POST['naslov_graf'])) {
+ $naslov = $_POST['naslov_graf'];
+ if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ //$naslov = '<p>'.nl2br($naslov).'</p>';
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ $update .= ", naslov_graf = '$naslov' ";
+ }
+
+ // shrani dodatne naslove variabel za graf
+ if (isset($_POST['edit_vrednost_graf'])) {
+ $i = 1;
+
+ foreach ($_POST as $key => $v) {
+
+ if (substr($key, 0, 14) == 'vrednost_graf_') {
+ $vrednost = substr($key, 14);
+
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov_graf='".$_POST['vrednost_graf_'.$vrednost]."' WHERE id = '$vrednost'");
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ $i++;
+ }
+ }
+ }
+
+ // shrani dodatne naslove gridov za graf
+ if (isset($_POST['edit_grid_graf'])) {
+
+ $vrstni_red = 0;
+ $i = 0;
+ foreach ($_POST as $key => $v) {
+ if (substr($key, 0, 10) == 'grid_graf_') {
+ $vrstni_red++;
+
+ $grid = substr($key, 10);
+ $naslov = $_POST['grid_graf_'.$grid];
+ $variable = $grid;
+ $id= $vrstni_red;
+
+ $other = '0';
+ # manjkoajoče vrednosti (ne vem, zavrnil ...
+ if (isset($_POST['missing_value_checkbox']) && is_array($_POST['missing_value_checkbox'])) {
+ if (in_array($grid, $_POST['missing_value_checkbox'])) {
+ # grid je manjkajoča vrednost
+ $other = $grid.'';
+ $id = $grid;
+ } else {
+ # grid je normalna vrednost
+ $i++;
+ }
+ } else {
+ # grid je normalna vrednost
+ $i++;
+ }
+ $s = sisplet_query("UPDATE srv_grid SET naslov_graf='$naslov' WHERE id='$id' AND spr_id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+ // shrani nastavitev za sistemsko/navadno spr.
+ if (isset($_POST['sistem'])) {
+
+ if ( in_array($row['variable'], array('email','telefon','ime','priimek','naziv','drugo')) && $row['sistem']==1 ) {
+
+ // tukaj ne pustimo spremeniti)
+ } else {
+ $update .= ", sistem = '$_POST[sistem]' ";
+ }
+ }
+
+ // shrani nastavitev za sistemsko/navadno spr.
+ if (isset($_POST['reverse_var'])) {
+
+ $newParams = new enkaParameters($row['params']);
+
+ // Ce je bila vrednost spremenjena
+ if($newParams->get('reverse_var') != $_POST['reverse_var']){
+
+ // Popravimo nastavitev
+ $newParams->set('reverse_var', $_POST['reverse_var']);
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params='".$newParams->getString()."' WHERE id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // Na novo prestevilcimo variable
+ Cache::clear_cache();
+ Common::prestevilci($this->spremenljivka);
+ }
+ }
+
+ // shrani nastavitev za vidno/skrito spr.
+ if (isset($_POST['visible'])) {
+ $update .= ", visible = '$_POST[visible]' ";
+ }
+
+ // shrani nastavitev za odklenjeno/zaklenjeno spr.
+ if (isset($_POST['locked'])) {
+ $update .= ", locked = '$_POST[locked]' ";
+ }
+
+ // shrani nastavitev kdo vidi spr.
+ if (isset($_POST['dostop'])) {
+ $update .= ", dostop = '$_POST[dostop]' ";
+ }
+
+ // shrani nastavitev za reminder
+ if (isset($_POST['reminder'])) {
+ $update .= ", reminder = '$_POST[reminder]' ";
+ }
+
+ // shrani nastavitev za prikaz "neustrezno" ob opozorilu
+ if (isset($_POST['alert_show_97'])) {
+ $update .= ", alert_show_97 = '$_POST[alert_show_97]' ";
+ }
+ // shrani nastavitev za prikaz "zavrnil" ob opozorilu
+ if (isset($_POST['alert_show_98'])) {
+ $update .= ", alert_show_98 = '$_POST[alert_show_98]' ";
+ }
+ // shrani nastavitev za prikaz "ne vem" ob opozorilu
+ if (isset($_POST['alert_show_99'])) {
+ $update .= ", alert_show_99 = '$_POST[alert_show_99]' ";
+ }
+
+ // shrani nastavitev za razvrstitev vrednosti spr
+ if (isset($_POST['random'])) {
+ $random = $_POST['random'];
+ $other = ($random) ? " AND other='0'" : "";
+
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET random = '$random' WHERE id='$this->spremenljivka'");
+ /* kadar spremenimo, povozimo vse vrednosti (ker sicer se nastavlja še vsako opcijo posebej) */
+ if ($row['random'] != $random)
+ $sql1 = sisplet_query("UPDATE srv_vrednost SET random = '$random' WHERE spr_id ='$this->spremenljivka' $other");
+ }
+
+ // shrani nastavitev za skalo
+ if (isset($_POST['skala'])) {
+ $update .= ", skala = '$_POST[skala]' ";
+ }
+
+ // shrani nastavitev za stevilo - st. celih mest
+ if (isset($_POST['cela'])) {
+ $update .= ", cela = '$_POST[cela]' ";
+ }
+
+ // shrani nastavitev za stevilo - st. decimalnih mest
+ if (isset($_POST['decimalna'])) {
+ $update .= ", decimalna = '$_POST[decimalna]' ";
+ }
+
+ // shrani dinamicen multigrid
+ if (isset($_POST['dynamic_mg'])) {
+ $update .= ", dynamic_mg = '$_POST[dynamic_mg]' ";
+ }
+
+ // shrani nastavitve za omejitve vsote
+ if (isset($_POST['edit_vsota_limit'])) {
+
+ if($_POST['vsota_limittype'] == 1){
+ $vsota_limittype = 1;
+ $vsota_min = $_POST['vsota_min'];
+ $vsota_limit = $_POST['vsota_limit'];
+ }
+ else{
+ $vsota_limittype = 0;
+ $vsota_min = $_POST['vsota_exact'];
+ $vsota_limit = $_POST['vsota_exact'];
+ }
+
+ $update .= ", vsota_reminder = '$_POST[vsota_reminder]', vsota_min = '$vsota_min', vsota_limit = '$vsota_limit', vsota_limittype = '$vsota_limittype', vsota_show='$_POST[vsota_show]' ";
+ }
+
+ // shrani nastavitve za omejitve stevila
+ if (isset($_POST['edit_number_limit'])) {
+ $update .= ", vsota_reminder = '$_POST[vsota_reminder]', num_useMin = '$_POST[num_useMin]', num_useMax = '$_POST[num_useMax]', vsota_min = '$_POST[vsota_min]', vsota_limit = '$_POST[vsota_limit]', vsota_show='$_POST[vsota_show]', num_useMin2 = '$_POST[num_useMin2]', num_useMax2 = '$_POST[num_useMax2]', num_min2 = '$_POST[num_min2]', num_max2 = '$_POST[num_max2]'";
+ }
+
+ // shrani nastavitev za razvrscanje - tip
+ if (isset($_POST['design'])) {
+ $update .= ", design = '$_POST[design]' ";
+ }
+
+ // shrani nastavitev za sn generator - tip
+ if (isset($_POST['sn_design'])) {
+ $update .= ", design = '$_POST[sn_design]' ";
+ }
+
+ // shrani nastavitev za razvrscanje - st. moznosti
+ if (isset($_POST['ranking_k'])) {
+ $update .= ", ranking_k = '$_POST[ranking_k]' ";
+ }
+
+ // shrani nastavitev za besedilo* - st. kosov
+ if (isset($_POST['text_kosov'])) {
+
+ $update .= ", text_kosov = '$_POST[text_kosov]' ";
+
+ $sqlc = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND other = '0'");
+ $rowc = mysqli_fetch_array($sqlc);
+ if($rowc['count'] < $_POST['text_kosov']){
+ $rowc['count']++; // da pri novem ne zacnemo z 0, ker so potem napacne labele variabel
+ $values = "";
+ for ($i = $rowc['count']; $i <= $_POST['text_kosov']; $i++) {
+ if ($values != "") $values .= ",";
+ $values .= " ('$this->spremenljivka', '$i', '$i') ";
+ }
+ $sql1 = sisplet_query("INSERT INTO srv_vrednost (spr_id, variable, vrstni_red) VALUES $values");
+ }
+ //pobrisemo odvecne vrednosti
+ else {
+ sisplet_query("DELETE FROM srv_vrednost WHERE vrstni_red > '$_POST[text_kosov]' AND spr_id='$this->spremenljivka' AND other = 0");
+ }
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ // shrani nastavitev za besedilo* - polozaj besedila
+ if (isset($_POST['text_orientation'])) {
+ $update .= ", text_orientation = '$_POST[text_orientation]' ";
+ }
+
+ // shrani nastavitev za number - polozaj enote
+ if (isset($_POST['enota'])) {
+ $update .= ", enota = '$_POST[enota]' ";
+ }
+
+ // shrani nastavitev za number - stevilo polj
+ if (isset($_POST['size'])) {
+ $update .= ", size = '$_POST[size]' ";
+ }
+
+ // shrani nastavitev za prikaz checkboxa
+ if (isset($_POST['checkboxhide'])) {
+ $update .= ", checkboxhide = '$_POST[checkboxhide]' ";
+ }
+
+ // shrani nastavitev za prikaz statistike
+ if (isset($_POST['stat'])) {
+ $update .= ", stat = '$_POST[stat]' ";
+ }
+
+ // shrani nastavitev za timer
+ if (isset($_POST['timer'])) {
+ if($_POST['timer'] == 0)
+ $update .= ", timer = '$_POST[timer]' ";
+ elseif(isset($_POST['timer2']))
+ $update .= ", timer = '$_POST[timer2]' ";
+ }
+
+ // shrani nastavitev za editiranje label grafov
+ if (isset($_POST['edit_graf'])) {
+ $update .= ", edit_graf = '$_POST[edit_graf]' ";
+ }
+ // shrani nastavitev za siroke labele pri grafih
+ if (isset($_POST['wide_graf'])) {
+ $update .= ", wide_graf = '$_POST[wide_graf]' ";
+ }
+
+ // shrani nastavitev za antonuccijev krog pri generatorju imen
+ if (isset($_POST['antonucci'])) {
+ $update .= ", antonucci = '$_POST[antonucci]' ";
+ }
+
+ if ( isset($_POST['taWidth'])
+ || isset($_POST['gridWidth'])
+ || isset($_POST['gridAlign'])
+ || isset($_POST['taSize'])
+ || isset($_POST['taHeight'])
+ || isset($_POST['gridmultiple_width'])
+ || isset($_POST['stolpci'])
+ || isset($_POST['checkbox_limit'])
+ || isset($_POST['checkbox_min_limit'])
+ || isset($_POST['checkbox_min_limit_reminder'])
+ || isset($_POST['reverse_var'])
+ || isset($_POST['grid_var'])
+ || isset($_POST['revers_var'])
+ || isset($_POST['captcha'])
+ || isset($_POST['emailVerify'])
+ || isset($_POST['NG_addText'])
+ || isset($_POST['NG_cancelButton'])
+ || isset($_POST['NG_cancelText'])
+ || isset($_POST['NG_countText'])
+ || isset($_POST['date_range_min'])
+ || isset($_POST['date_range_max'])
+ || isset($_POST['date_withTime'])
+ || isset($_POST['max_markers'])
+ || isset($_POST['multi_input_type'])
+ || isset($_POST['naslov_podvprasanja_map'])
+ || isset($_POST['fokus_mape'])
+ || isset($_POST['user_location'])
+ || isset($_POST['dodaj_searchbox'])
+ || isset($_POST['marker_podvprasanje'])
+ || isset($_POST['customRadio'])
+ || isset($_POST['otherWidth'])
+ || isset($_POST['otherHeight'])
+ || isset($_POST['nagovorLine'])
+ || isset($_POST['sbSize'])
+ || isset($_POST['prvaVrstica'])
+ || isset($_POST['prvaVrstica_roleta'])
+ || isset($_POST['sbSizeVse'])
+ || isset($_POST['prevAnswers'])
+ || isset($_POST['disabled_vprasanje'])
+ || isset($_POST['slider_handle'])
+ || isset($_POST['slider_MinMaxNumLabel'])
+ || isset($_POST['slider_MinMaxLabel'])
+ || isset($_POST['slider_VmesneDescrLabel'])
+ || isset($_POST['slider_VmesneNumLabel'])
+ || isset($_POST['slider_handle_step'])
+ || isset($_POST['slider_MinMaxNumLabelNew'])
+ || isset($_POST['slider_VmesneCrtice'])
+ || isset($_POST['slider_MinLabel'])
+ || isset($_POST['slider_MaxLabel'])
+ || isset($_POST['slider_MinNumLabel'])
+ || isset($_POST['slider_MaxNumLabel'])
+ || isset($_POST['slider_MinNumLabelTemp'])
+ || isset($_POST['slider_MaxNumLabelTemp'])
+ || isset($_POST['slider_window_number'])
+ || isset($_POST['slider_NumofDescrLabels'])
+ || isset($_POST['slider_DescriptiveLabel_defaults'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov1'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov2'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov3'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov4'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov5'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov6'])
+ || isset($_POST['slider_DescriptiveLabel_defaults_naslov7'])
+ || isset($_POST['slider_nakazi_odgovore'])
+ || isset($_POST['slider_labele_podrocij'])
+ || isset($_POST['slider_StevLabelPodrocij'])
+ || isset($_POST['hotspot_image'])
+ || isset($_POST['hotspot_region_visibility_option'])
+ || isset($_POST['hotspot_region_visibility'])
+ || isset($_POST['hotspot_tooltips_option'])
+ || isset($_POST['diferencial_trak'])
+ || isset($_POST['diferencial_trak_starting_num'])
+ || isset($_POST['trak_num_of_titles'])
+ || isset($_POST['display_drag_and_drop_new_look'])
+ || isset($_POST['custom_column_label_option'])
+ || isset($_POST['grid_repeat_header'])
+ || isset($_POST['hotspot_region_color'])
+ || isset($_POST['hotspot_visibility_color'])
+ || isset($_POST['heatmap_click_color'])
+ || isset($_POST['heatmap_click_size'])
+ || isset($_POST['heatmap_click_shape'])
+ || isset($_POST['heatmap_num_clicks'])
+ || isset($_POST['heatmap_show_clicks'])
+ || isset($_POST['heatmap_show_counter_clicks']) ){
+
+ $newParams = new enkaParameters($row['params']);
+
+ if (isset($_POST['taWidth']))
+ $newParams->set('taWidth', $_POST['taWidth']);
+ if (isset($_POST['taHeight']))
+ $newParams->set('taHeight', $_POST['taHeight']);
+ if (isset($_POST['gridmultiple_width']))
+ $newParams->set('gridmultiple_width', $_POST['gridmultiple_width']);
+ if (isset($_POST['taSize']))
+ $newParams->set('taSize', $_POST['taSize']);
+ if (isset($_POST['gridWidth']))
+ $newParams->set('gridWidth', $_POST['gridWidth']);
+ if (isset($_POST['gridAlign']))
+ $newParams->set('gridAlign', $_POST['gridAlign']);
+ if (isset($_POST['stolpci']))
+ $newParams->set('stolpci', $_POST['stolpci']);
+ if (isset($_POST['checkbox_limit']))
+ $newParams->set('checkbox_limit', $_POST['checkbox_limit']);
+ if (isset($_POST['checkbox_min_limit']))
+ $newParams->set('checkbox_min_limit', $_POST['checkbox_min_limit']);
+ if (isset($_POST['checkbox_min_limit_reminder']))
+ $newParams->set('checkbox_min_limit_reminder', $_POST['checkbox_min_limit_reminder']);
+ if (isset($_POST['reverse_var']))
+ $newParams->set('reverse_var', $_POST['reverse_var']);
+ if (isset($_POST['grid_var']))
+ $newParams->set('grid_var', $_POST['grid_var']);
+ if (isset($_POST['captcha']))
+ $newParams->set('captcha', $_POST['captcha']);
+ if (isset($_POST['emailVerify']))
+ $newParams->set('emailVerify', $_POST['emailVerify']);
+ if (isset($_POST['NG_addText']))
+ $newParams->set('NG_addText', $_POST['NG_addText']);
+ if (isset($_POST['NG_cancelButton']))
+ $newParams->set('NG_cancelButton', $_POST['NG_cancelButton']);
+ if (isset($_POST['NG_cancelText']))
+ $newParams->set('NG_cancelText', $_POST['NG_cancelText']);
+ if (isset($_POST['NG_countText']))
+ $newParams->set('NG_countText', $_POST['NG_countText']);
+ if (isset($_POST['date_range_min']))
+ $newParams->set('date_range_min', $_POST['date_range_min']);
+ if (isset($_POST['date_range_max']))
+ $newParams->set('date_range_max', $_POST['date_range_max']);
+ if (isset($_POST['date_withTime']))
+ $newParams->set('date_withTime', $_POST['date_withTime']);
+ if (isset($_POST['otherWidth']))
+ $newParams->set('otherWidth', $_POST['otherWidth']);
+ if (isset($_POST['otherHeight']))
+ $newParams->set('otherHeight', $_POST['otherHeight']);
+ if (isset($_POST['nagovorLine']))
+ $newParams->set('nagovorLine', $_POST['nagovorLine']);
+ if (isset($_POST['hideRadio']))
+ $newParams->set('hideRadio', $_POST['hideRadio']);
+ if (isset($_POST['quickImage']))
+ $newParams->set('quickImage', $_POST['quickImage']);
+ if (isset($_POST['presetValue']))
+ $newParams->set('presetValue', $_POST['presetValue']);
+ if (isset($_POST['sbSize']))
+ $newParams->set('sbSize', $_POST['sbSize']);
+ if (isset($_POST['customRadio']))
+ $newParams->set('customRadio', ((in_array($row['tip'], [1,6]) && ($row['enota'] == 12 || $row['orientation'] == 9)) ? $_POST['customRadio'] : ''));
+ if (isset($_POST['customRadioNumber']) && $_POST['customRadioNumber'] > 0) {
+ if ($_POST['tip'] == 6 && $row['enota'] == 12) {
+ $customRadioNumber = $_POST['grids_count'];
+ }else{
+ $customRadioNumber = $_POST['customRadioNumber'];
+ }
+ $newParams->set('customRadioNumber', $customRadioNumber);
+ }
+ if (isset($_POST['vizualnaSkalaNumber']) && $_POST['vizualnaSkalaNumber'] > 0) {
+ if ($_POST['tip'] == 6 && $row['enota'] == 11) {
+ $vizualnaSkalaNumber = ($_POST['grids_count'] > 7 ? 7 : $_POST['grids_count']);
+ }else{
+ $vizualnaSkalaNumber = $_POST['vizualnaSkalaNumber'];
+ }
+ $newParams->set('vizualnaSkalaNumber', $vizualnaSkalaNumber);
+ }
+ if (isset($_POST['prvaVrstica']))
+ $newParams->set('prvaVrstica', $_POST['prvaVrstica']);
+ if (isset($_POST['prvaVrstica_roleta']))
+ $newParams->set('prvaVrstica_roleta', $_POST['prvaVrstica_roleta']);
+ if (isset($_POST['sbSizeVse']))
+ $newParams->set('sbSizeVse', $_POST['sbSizeVse']);
+ if (isset($_POST['prevAnswers']))
+ $newParams->set('prevAnswers', $_POST['prevAnswers']);
+ if (isset($_POST['disabled_vprasanje']))
+ $newParams->set('disabled_vprasanje', $_POST['disabled_vprasanje']);
+ if ( isset($_POST['slider_handle']) )
+ $newParams->set('slider_handle', $_POST['slider_handle']);
+ if (isset($_POST['slider_MinMaxNumLabel']))
+ $newParams->set('slider_MinMaxNumLabel', $_POST['slider_MinMaxNumLabel']);
+ if ( isset($_POST['slider_MinMaxNumLabelNew']) )
+ $newParams->set('slider_MinMaxNumLabelNew', $_POST['slider_MinMaxNumLabelNew']);
+ if ( isset($_POST['slider_MinMaxLabel']) )
+ $newParams->set('slider_MinMaxLabel', $_POST['slider_MinMaxLabel']);
+ if ( isset($_POST['slider_VmesneNumLabel']) )
+ $newParams->set('slider_VmesneNumLabel', $_POST['slider_VmesneNumLabel']);
+ if ( isset($_POST['slider_VmesneDescrLabel']) )
+ $newParams->set('slider_VmesneDescrLabel', $_POST['slider_VmesneDescrLabel']);
+ if ( isset($_POST['slider_VmesneCrtice']) )
+ $newParams->set('slider_VmesneCrtice', $_POST['slider_VmesneCrtice']);
+ if (isset($_POST['slider_handle_step']))
+ $newParams->set('slider_handle_step', $_POST['slider_handle_step']);
+ if (isset($_POST['slider_MinLabel']))
+ $newParams->set('slider_MinLabel', $_POST['slider_MinLabel']);
+ if (isset($_POST['slider_MaxLabel']))
+ $newParams->set('slider_MaxLabel', $_POST['slider_MaxLabel']);
+ if (isset($_POST['slider_MinNumLabel']))
+ $newParams->set('slider_MinNumLabel', $_POST['slider_MinNumLabel']);
+ if (isset($_POST['slider_MaxNumLabel']))
+ $newParams->set('slider_MaxNumLabel', $_POST['slider_MaxNumLabel']);
+ if (isset($_POST['slider_MinNumLabelTemp']))
+ $newParams->set('slider_MinNumLabelTemp', $_POST['slider_MinNumLabelTemp']);
+ if (isset($_POST['slider_MaxNumLabelTemp']))
+ $newParams->set('slider_MaxNumLabelTemp', $_POST['slider_MaxNumLabelTemp']);
+ if ( isset($_POST['slider_window_number']) )
+ $newParams->set('slider_window_number', $_POST['slider_window_number']);
+ if ( isset($_POST['slider_NumofDescrLabels']) )
+ $newParams->set('slider_NumofDescrLabels', $_POST['slider_NumofDescrLabels']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults']) )
+ $newParams->set('slider_DescriptiveLabel_defaults', $_POST['slider_DescriptiveLabel_defaults']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov1']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov1', $_POST['slider_DescriptiveLabel_defaults_naslov1']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov2']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov2', $_POST['slider_DescriptiveLabel_defaults_naslov2']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov3']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov3', $_POST['slider_DescriptiveLabel_defaults_naslov3']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov4']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov4', $_POST['slider_DescriptiveLabel_defaults_naslov4']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov5']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov5', $_POST['slider_DescriptiveLabel_defaults_naslov5']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov6']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov6', $_POST['slider_DescriptiveLabel_defaults_naslov6']);
+ if ( isset($_POST['slider_DescriptiveLabel_defaults_naslov7']) )
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov7', $_POST['slider_DescriptiveLabel_defaults_naslov7']);
+ if ( isset($_POST['slider_nakazi_odgovore']) )
+ $newParams->set('slider_nakazi_odgovore', $_POST['slider_nakazi_odgovore']);
+ if ( isset($_POST['slider_StevLabelPodrocij']) )
+ $newParams->set('slider_StevLabelPodrocij', $_POST['slider_StevLabelPodrocij']);
+ if ( isset($_POST['hotspot_image']) ){
+ $newParams->set('hotspot_image', $_POST['hotspot_image']);
+ $newParams->set('multi_input_type', 'marker');
+ }
+ if ( isset($_POST['slider_labele_podrocij']) ){
+ $newParams->set('slider_labele_podrocij', $_POST['slider_labele_podrocij']);
+ }
+ if ( isset($_POST['fokus_mape']) )
+ $newParams->set('fokus_mape', $_POST['fokus_mape']);
+ if ( isset($_POST['naslov_podvprasanja_map']) )
+ $newParams->set('naslov_podvprasanja_map', $_POST['naslov_podvprasanja_map']);
+ if ( isset($_POST['user_location']) )
+ $newParams->set('user_location', $_POST['user_location']);
+ if ( isset($_POST['dodaj_searchbox']) )
+ $newParams->set('dodaj_searchbox', $_POST['dodaj_searchbox']);
+ if ( isset($_POST['max_markers']) )
+ $newParams->set('max_markers', $_POST['max_markers']);
+ if ( isset($_POST['multi_input_type']) )
+ $newParams->set('multi_input_type', $_POST['multi_input_type']);
+ if ( isset($_POST['marker_podvprasanje']) )
+ $newParams->set('marker_podvprasanje', $_POST['marker_podvprasanje']);
+ if ( isset($_POST['hotspot_region_visibility_option']) ){
+ $newParams->set('hotspot_region_visibility_option', $_POST['hotspot_region_visibility_option']);
+ }
+ if ( isset($_POST['hotspot_region_visibility']) ){
+ $newParams->set('hotspot_region_visibility', $_POST['hotspot_region_visibility']);
+ }
+ if ( isset($_POST['hotspot_region_color']) ){
+ $newParams->set('hotspot_region_color', $_POST['hotspot_region_color']);
+ }
+ if ( isset($_POST['hotspot_visibility_color']) ){
+ $newParams->set('hotspot_visibility_color', $_POST['hotspot_visibility_color']);
+ }
+ if ( isset($_POST['heatmap_click_shape']) ){
+ $newParams->set('heatmap_click_shape', $_POST['heatmap_click_shape']);
+ }
+ if ( isset($_POST['heatmap_click_size']) ){
+ $newParams->set('heatmap_click_size', $_POST['heatmap_click_size']);
+ }
+ if ( isset($_POST['heatmap_click_color']) ){
+ $newParams->set('heatmap_click_color', $_POST['heatmap_click_color']);
+ }
+ if ( isset($_POST['hotspot_tooltips_option']) ){
+ $newParams->set('hotspot_tooltips_option', $_POST['hotspot_tooltips_option']);
+ }
+ if ( isset($_POST['diferencial_trak']) ){
+ $newParams->set('diferencial_trak', $_POST['diferencial_trak']);
+ }
+ if ( isset($_POST['diferencial_trak_starting_num']) ){
+ $newParams->set('diferencial_trak_starting_num', $_POST['diferencial_trak_starting_num']);
+ }
+ if ( isset($_POST['trak_num_of_titles']) ){
+ $newParams->set('trak_num_of_titles', $_POST['trak_num_of_titles']);
+ }
+ if ( isset($_POST['display_drag_and_drop_new_look']) ){
+ $newParams->set('display_drag_and_drop_new_look', $_POST['display_drag_and_drop_new_look']);
+ }
+ if ( isset($_POST['custom_column_label_option']) ){
+ $newParams->set('custom_column_label_option', $_POST['custom_column_label_option']);
+ }
+ if ( isset($_POST['grid_repeat_header']) ){
+ $newParams->set('grid_repeat_header', $_POST['grid_repeat_header']);
+ }
+ if ( isset($_POST['heatmap_num_clicks']) ){
+ $newParams->set('heatmap_num_clicks', $_POST['heatmap_num_clicks']);
+ }
+ if ( isset($_POST['heatmap_show_clicks']) ){
+ $newParams->set('heatmap_show_clicks', $_POST['heatmap_show_clicks']);
+ }
+ if ( isset($_POST['heatmap_show_counter_clicks']) ){
+ $newParams->set('heatmap_show_counter_clicks', $_POST['heatmap_show_counter_clicks']);
+ }
+ if(isset($_POST['slider_DescriptiveLabel_defaults'])){
+
+ $slider_descriptiveLabels_defaults = $_POST['slider_DescriptiveLabel_defaults'];
+ $slider_NumofDescrLabels = ($_POST['slider_NumofDescrLabels'] + 1);
+ $slider_VmesneDescrLabel = $_POST['slider_VmesneDescrLabel'];
+
+ if($slider_VmesneDescrLabel == 1){
+ if($slider_descriptiveLabels_defaults > 0){ //ce so izbrane default opisne labele
+
+ // Napolnimo prave vrednosti
+ $values = $default_grid_values[$slider_descriptiveLabels_defaults];
+
+ $indexArray = array(
+ 2 => array(2, 6),
+ 3 => array(2, 4, 6),
+ 4 => array(1, 2, 6, 7),
+ 5 => array(1, 2, 4, 6, 7),
+ 6 => array(1, 2, 3, 5, 6, 7),
+ 7 => array(1, 2, 3, 4, 5, 6, 7)
+ );
+
+ $naslov = array(); //definicija
+
+ for($i=1; $i<=$slider_NumofDescrLabels; $i++){
+
+ // Ce imamo samo en grid
+ if($slider_NumofDescrLabels == 1 && $i == 1){
+ $index = 2;
+ //$naslov = $values[2]; //slider_DescriptiveLabel_defaults_naslov
+ $slider_DescriptiveLabel_defaults_naslov = $values[2];
+ }
+ // Ce imamo vec kot 7 gridov - prvih 7 zapisemo normalno, ostali so prazni
+ else if($slider_NumofDescrLabels > 7){
+ if($i <= 7){
+ $index = $indexArray[7][$i-1];
+ //$naslov = $values[$index];
+ $slider_DescriptiveLabel_defaults_naslov = $values[$index];
+ //echo $slider_DescriptiveLabel_defaults_naslov;
+ }
+ else
+ break;
+ }
+ // Ce imamo 2 - 7 gridov jih izpisemo v skladu z $indexArray
+ else{
+ $index = $indexArray[$slider_NumofDescrLabels][$i-1];
+ //$naslov = $values[$index];
+ $slider_DescriptiveLabel_defaults_naslov = $values[$index];
+ //echo $slider_DescriptiveLabel_defaults_naslov.'<br />';
+ }
+ //echo $slider_DescriptiveLabel_defaults_naslov;
+ $naslov[$i] = $slider_DescriptiveLabel_defaults_naslov;
+ //echo $naslov[$i].'<br />';
+ }
+ $implodednaslov = implode(";", $naslov); //zdruzi elemente array v string
+ $newParams->set('slider_DescriptiveLabel_defaults_naslov1', $implodednaslov);
+
+
+ }
+ else{ //ce so custom opisne labele
+
+ }
+ }
+ else if($slider_VmesneDescrLabel != 1){
+
+ }
+ }
+
+ //*******************
+ if ($_POST['enota'] == 9){ //ce je postavitev drag and drop
+ $newParams->set('izris_droppable_grid', 0);
+ }
+ //**************************
+
+
+ $params = $newParams->getString();
+ $update .= ", params = '$params' ";
+ }
+
+ // shrani nastavitev za orientacijo
+ if (isset($_POST['orientation'])) {
+
+ # checkbox
+ //if ($row['tip'] == 2 || $row['tip'] == 7 || $row['tip'] == 8 || $row['tip'] == 21) {
+ if ($row['tip'] == 7 || $row['tip'] == 8 || $row['tip'] == 21) {
+ # če je checkbox ne spreminjamo tipa, tudi če je datum, besedilo ali number
+ $update .= ", orientation = '$_POST[orientation]' ";
+
+ } else {
+ # radio, dropdown
+ //dropdown
+ if($_POST['orientation'] == 4)
+ $update .= ", orientation = '1', tip = '3', hidden_default = '0' ";
+ //elseif ($_POST['orientation'] == 6)
+ // $update .= ", orientation = '6', tip = '3', hidden_default = '0' ";
+ //druge opcije orientacije
+ elseif ($_POST['orientation'] == 5)
+ $update .= ", orientation = '1', tip = '1', hidden_default = '1' ";
+ else{
+ if($_POST['tip'] == 2){
+ $update .= ", orientation = '$_POST[orientation]', tip = '2', hidden_default = '0' "; //ce smo preklopli, ko je bilo vprasanje checkbox, naj se vrne checkbox
+ }
+ elseif($_POST['tip'] == 1){
+ $update .= ", orientation = '$_POST[orientation]', tip = '1', hidden_default = '0' "; //ce smo preklopli, ko je bilo vprasanje radio button, naj se vrne kot radio button
+
+ //v kolikor gre za slikovni tip radio buttons potem v tabelo srv_vrednost vstaviti ustrezno št. vrstic
+ if($_POST['orientation'] == 9)
+ $this->slikovni_tip($_POST['customRadioNumber']);
+
+ // vizualno analogno skalo buttons potem v tabelo srv_vrednost vstaviti ustrezno št. vrstic
+ if($_POST['orientation'] == 11)
+ $this->slikovni_tip($_POST['vizualnaSkalaNumber']);
+ }
+ }
+ }
+ }
+
+ if (isset($_POST['note'])) {
+ $update .= ", note = '$_POST[note]' ";
+ }
+
+ // shrani nastavitev za file upload
+ if (isset($_POST['upload'])) {
+ $update .= ", upload = '$_POST[upload]' ";
+ }
+
+ //shrani nastavitev za elektronski podpis
+ if (isset($_POST['signature'])){
+ $update .= ", signature = '$_POST[signature]' ";
+ }
+
+ // shrani enoto - podtip lokacije
+ if (isset($_POST['podtip_lokacija'])) {
+ $update .= ", enota = '$_POST[podtip_lokacija]' ";
+ }
+
+ // shrani podnaslova za dvojni grid
+ if (isset($_POST['grid_subtitle1'])) {
+ $update .= ", grid_subtitle1 = '$_POST[grid_subtitle1]' ";
+ }
+
+ if (isset($_POST['grid_subtitle2'])) {
+ $update .= ", grid_subtitle2 = '$_POST[grid_subtitle2]' ";
+ }
+
+ if (isset($_POST['inline_edit'])) {
+ $update .= ", inline_edit = '$_POST[inline_edit]' ";
+ }
+
+ if (isset($_POST['onchange_submit'])) {
+ $update .= ", onchange_submit = '$_POST[onchange_submit]' ";
+ }
+
+ if (isset($_POST['showOnAllPages'])) {
+ $update .= ", showOnAllPages = '$_POST[showOnAllPages]' ";
+ }
+
+ if (isset($_POST['validationedit'])) {
+
+ foreach ($_POST AS $key => $val) {
+
+ if ( substr($key, 0, 11) == 'validation-' ) {
+
+ $key = explode('-', $key);
+
+ if ( $key[2] == 'reminder' ) {
+
+ $if_id = $key[1];
+ $reminder = $val;
+
+ sisplet_query("UPDATE srv_validation SET reminder='$reminder' WHERE spr_id='$this->spremenljivka' AND if_id='$if_id'");
+
+ } elseif ( $key[2] == 'reminder_text' ) {
+
+ $if_id = $key[1];
+ $reminder_text = $val;
+
+ sisplet_query("UPDATE srv_validation SET reminder_text='$reminder_text' WHERE spr_id='$this->spremenljivka' AND if_id='$if_id'");
+
+ }
+ }
+
+ }
+
+ }
+
+ // shrani nastavitev za multiple subtitle
+ if (isset($_POST['multiple_subtitle'])) {
+ $update .= ", grid_subtitle1 = '$_POST[multiple_subtitle]' ";
+ }
+
+
+ $update = substr($update, 1); // odrezemo prvo vejico
+
+
+ if ($update != '') {
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET $update WHERE id = '$this->spremenljivka' ");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ $this->ajax_vprasanje_refresh();
+
+ self::vprasanje_tracking();
+
+ //echo $update;
+ }
+
+ function slikovni_tip($number){
+
+ //pobrišemo dosedanje vrednosti
+ $dosedanjiVnosi = sisplet_query("SELECT id, naslov, variable, vrstni_red FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' ORDER BY vrstni_red");
+ $st = mysqli_num_rows($dosedanjiVnosi);
+
+ // V koliko povečamo število vnosov od dosedanjega vprašanja
+ if($st < $number) {
+ if($st > 0){
+ $zaporedje = 1;
+ while($row = mysqli_fetch_assoc($dosedanjiVnosi)){
+ sisplet_query("UPDATE srv_vrednost SET naslov=$zaporedje, variable=$zaporedje, vrstni_red=$zaporedje WHERE id=".$row['id']." AND spr_id=".$this->spremenljivka);
+ $zaporedje++;
+ }
+ }
+
+ for ( $i = $st + 1; $i < $number + 1; $i++) {
+ sisplet_query("INSERT INTO srv_vrednost (spr_id, naslov, variable, vrstni_red) VALUES ('$this->spremenljivka', '$i', '$i', '$i')");
+ }
+ }
+ elseif($st > $number) {
+ $preveriOdgovore = sisplet_query("SELECT spr_id FROM srv_data_vrednost" . $this->db_table. " WHERE spr_id='".$this->spremenljivka."'");
+
+ if(mysqli_num_rows($preveriOdgovore) == 0){
+ sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='".$this->spremenljivka."' AND vrstni_red>'".$number."'");
+ }
+ }
+
+
+ // Preštevilčimo naslove v kolikor bi radio tip spremenili in ostanejo v labelah imena namesto številk
+ $zaporedje = 1;
+ while($row = mysqli_fetch_assoc($dosedanjiVnosi)){
+ if(!is_numeric($row['naslov']) || !is_int($row['variable'])) {
+ sisplet_query("UPDATE srv_vrednost SET naslov=$zaporedje WHERE id=".$row['id']." AND spr_id=".$this->spremenljivka);
+ }
+
+ $zaporedje++;
+ }
+ }
+
+
+ /**
+ * prikaze spremenljivko pri skrcenem nacinu
+ *
+ * @param mixed $spremenljivka
+ * @param mixed $naslov
+ * @param mixed $variable
+ * @param mixed $visible
+ * @param mixed $sistem
+ */
+ function spremenljivka_name ($spremenljivka, $naslov=null, $variable=null, $visible=1, $sistem=0) {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($spremenljivka);
+
+ $tip = $row['tip'];
+ $naslov = $row['naslov'];
+ $variable = $row['variable'];
+ $visible = $row['visible'];
+ $sistem = $row['sistem'];
+
+ // barva vprašanja je privzeto modra, če pa je sistemsko ali skrito pa je rdeča
+ $spanred = ($visible == 0 || $sistem == 1 ) ? ' <span class="red">' : '';
+
+ if ($tip != 22) { // navadne spremenljivke
+ echo '<span class="colorvariable">('.$variable.')</span> '.$spanred.skrajsaj(strip_tags($naslov), 80).($spanred!=''?'</span>':'').' <span class="spr_comment">( '.$lang['srv_vprasanje_tip_long_'.$row['tip']].' )</span>';
+
+ } else { // kalkulacija
+ $b = new Branching($this->anketa);
+ echo '<span class="calculationvariable">('.$variable.')</span> '.$b->calculations_display(-$spremenljivka).' <span class="spr_comment">( '.$lang['srv_vprasanje_tip_long_'.$row['tip']].' )</span>';
+
+ }
+ }
+
+ /**
+ * pobrise vrednost
+ *
+ * $API_call = true, ce se klice iz API
+ *
+ */
+ function ajax_vrednost_delete ($vrednost = null, $API_call = false) {
+ global $lang;
+
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $spremenljivka = $this->spremenljivka;
+
+ if($vrednost == null)
+ $vrednost = (int)$_POST['vrednost'];
+
+ if(!$API_call){
+ $confirmed = (int)$_POST['confirmed'];
+ $can_delete_last = (isset($_POST['can_delete_last']) && $_POST['can_delete_last'] == 1) ?
+ true : false;
+ }
+ else
+ $confirmed = '1';
+
+ $return = array();
+
+ // preverimo, ce obstajajo ze podatki za spremenljivko - v tem primeru damo dodaten error
+ if ($confirmed != '1') {
+ $sql = sisplet_query("SELECT count(*) AS count FROM srv_user WHERE ank_id='$this->anketa' AND deleted='0' AND preview='0'");
+ $row = mysqli_fetch_array($sql);
+
+ if ($row['count'] > 0) {
+
+ $return['error'] = 2;
+
+ $return['output'] = '<h2>'.$lang['srv_warning'].'</h2>';
+ $return['output'] .= '<div class="popup_close"><a href="#" onClick="$(\'#dropped_alert\').hide(); $(\'#fade\').fadeOut(); return false;">✕</a></div>';
+
+ $return['output'] .= '<p>'.$lang['spremenljivka_delete_data_vre'].'</p>';
+ $return['output'] .= '<p>'.$lang['srv_brisivrednostconfirm_data'].'</p><br />';
+
+ //ce se spremeni onclick, se prosim spremeni v datoteki vprasanjeInline.js v funkciji inline_vrednost_delete v else if (data.error == 2)
+ $return['output'] .= '<span class="buttonwrapper floatRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inline_vrednost_delete(\''.$spremenljivka.'\', \''.$vrednost.'\', \'1\'); $(\'#dropped_alert\').html(\'\').hide(); $(\'#fade\').fadeOut(); return false;"><span>'.$lang['srv_brisivrednost'].'</span></a></span>';
+ $return['output'] .= '<span class="buttonwrapper floatRight spaceRight"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#dropped_alert\').hide(); $(\'#fade\').fadeOut(); return false;"><span>'.$lang['srv_analiza_arhiviraj_cancle'].'</span></a></span>';
+ //$return['output'] .= '<p><a href="#" id="brisivrednostchecked" onclick="inline_vrednost_delete(\''.$spremenljivka.'\', \''.$vrednost.'\', \'1\'); $(\'#dropped_alert\').html(\'\').hide(); $(\'#fade\').fadeOut(); return false;">'.$lang['srv_brisivrednost'].'</a> <a href="#" onclick="$(\'#dropped_alert\').html(\'\').hide(); $(\'#fade\').fadeOut(); return false;">'.$lang['srv_analiza_arhiviraj_cancle'].'</a></p>';
+
+ echo json_encode($return);
+
+ return;
+ }
+ }
+
+ if(!$API_call && !$can_delete_last){
+ $sql = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id='$spremenljivka' AND id != '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+ if ($row['count'] == 0) return;
+ }
+
+ if ($vrednost <= 0) return;
+
+ $sql = sisplet_query("SELECT spr_id, if_id FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+
+ $sql = sisplet_query("DELETE FROM srv_vrednost WHERE id = '$vrednost'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $spremenljivka = $row['spr_id'];
+
+ // Pobrisemo se pogoj ce je dodan na vrednost
+ if($row['if_id'] > 0){
+
+ $if = $row['if_id'];
+
+ $sqlCV = sisplet_query("SELECT id FROM srv_condition WHERE if_id = '$if'");
+ while ($rowCV = mysqli_fetch_array($sqlCV))
+ sisplet_query("DELETE FROM srv_condition_vre WHERE cond_id='$rowCV[id]'");
+
+ sisplet_query("DELETE FROM srv_condition WHERE if_id = '$if'");
+ sisplet_query("DELETE FROM srv_if WHERE id = '$if'");
+ }
+
+ $rows = Cache::srv_spremenljivka($spremenljivka);
+ if ($rows['tip'] == 24) {
+ $this->repare_grid_multiple($spremenljivka);
+ }
+
+ Common::repareVrednost($spremenljivka);
+ Common::prestevilci($spremenljivka);
+
+ $return['error'] = 0;
+
+ if(!$API_call)
+ echo json_encode($return);
+ else
+ return $return;
+ }
+
+ /**
+ * pobrise vrednost
+ *
+ */
+ function ajax_vrednosti_other_delete () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $spremenljivka = $this->spremenljivka;
+
+ $sql = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id = '$spremenljivka' AND other = '1'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ $spremenljivka = $row['spr_id'];
+
+ Common::repareVrednost($spremenljivka);
+ Common::prestevilci($spremenljivka);
+ }
+
+ /**
+ * funkcija, ki doda novo vrednost
+ *
+ */
+ function vrednost_new ($naslov='', $other=0, $mv = null, $spr_id=null) {
+ global $lang;
+
+ Common::updateEditStamp();
+
+ $anketa = $this->anketa;
+ $spremenljivka = $this->spremenljivka;
+
+ if ($spr_id != null) $spremenljivka = $spr_id;
+
+ $purifier = New Purifier();
+
+ $naslov = $purifier->purify_DB($naslov);
+
+ $sql = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id='$spremenljivka' AND vrstni_red>0");
+ $row = mysqli_fetch_array($sql);
+ $nums = $row['count'];
+ $vrstni_red = $nums +1;
+
+ $variable = -$other; // tole se itak popravi v prestevilci()
+
+ //pri API, se poslje tudi naslov za other
+ if ($other == 1 && $naslov == '') {
+ $naslov = $lang['srv_other'] . ':';
+ }
+ # popravimi za missing vrednosi
+ if ($mv != null) {
+ # katere missinge imamo na voljo
+ $smv = new SurveyMissingValues($this->anketa);
+
+ $missing_values = $smv->GetUnsetValuesForSurvey();
+ $naslov = addslashes($missing_values[$mv]);
+
+ $variable = $mv;
+ $other = $mv;
+ }
+
+ $row1 = Cache::srv_spremenljivka($spremenljivka);
+ $random = $row1['random'];
+
+ if((int)$variable == 0) {
+ $variable = $vrstni_red;
+ }
+ $sql = sisplet_query("INSERT INTO srv_vrednost (id, spr_id, naslov, variable, vrstni_red, random, other) VALUES ('', '$spremenljivka', '$naslov', '$variable', '$vrstni_red', '$random', '$other')");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $vrednost = mysqli_insert_id($GLOBALS['connect_db']);
+
+
+ // dodamo vrednosti -4 za novo variablo k že vpisanim odgovorom
+ // multigridu dodamo vrednost -4
+ if ($row1['tip'] == 6 || $row1['tip'] == 16 || $row1['tip'] == 19 || $row1['tip'] == 20) { // multigrid, multicheckbox, multitext, multinumber
+ //$sql = sisplet_query("SELECT * FROM srv_vrednost WHERE spr_id = '$spremenljivka'");
+ $sql1 = sisplet_query("SELECT id FROM srv_user WHERE ank_id='$anketa'");
+ $values = '';
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+
+ //$s = sisplet_query("INSERT INTO srv_data_grid".$this->db_table." (spr_id, vre_id, usr_id, grd_id) VALUES ('$spremenljivka', '$vrednost', '$row1[id]', '-4')");
+ if ($values != '') $values .= ', ';
+ $values .= "('$spremenljivka', '$vrednost', '$row1[id]', '-4')";
+ }
+ $s = sisplet_query("INSERT INTO srv_data_grid".$this->db_table." (spr_id, vre_id, usr_id, grd_id) VALUES $values");
+
+ }
+
+ if ($row1['tip'] == 24) {
+ $this->repare_grid_multiple($row1['id']);
+ }
+
+ if ($row1['tip'] == 17) { // ranking
+ $sql1 = sisplet_query("SELECT id FROM srv_user WHERE ank_id='$anketa'");
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+ $s = sisplet_query("INSERT INTO srv_data_rating (spr_id, vre_id, usr_id, vrstni_red) VALUES ('$spremenljivka', '$vrednost', '$row1[id]', '-4')");
+ }
+ }
+
+ if($row1['tip'] == 26 && $row1['enota'] == 3){
+ $sql1 = sisplet_query("SELECT id FROM srv_user WHERE ank_id='$anketa'");
+ while ($row1 = mysqli_fetch_assoc($sql1)) {
+ $s = sisplet_query("INSERT INTO srv_data_map (spr_id, vre_id, usr_id, text) VALUES ('$spremenljivka', '$vrednost', '$row1[id]', '-4')");
+ }
+ }
+
+ return $vrednost;
+ }
+
+ /**
+ * doda novo vrednost
+ *
+ */
+ function ajax_vrednost_new () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ global $lang;
+
+ $naslov = '';
+ $other = $_POST['other'];
+ $mv = $_POST['mv'];
+
+ $vrednost = $this->vrednost_new($naslov, $other, $mv);
+
+ Common::prestevilci($this->spremenljivka);
+ $this->edit_vrednost_li($vrednost);
+ }
+
+ function ajax_change_tip () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $tip = $_POST['tip'];
+
+ self::change_tip($this->spremenljivka, $tip);
+
+ $this->display();
+ }
+
+ function ajax_show_tip () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $tip = $_POST['tip'];
+ echo $tip;
+ self::show_tip($tip);
+
+ //$this->display();
+ }
+
+ // spremeni tip vprasanja demografija -- najprej ustvari novo vprasanje za trenutnim, in ga nato se izbrise (trenutnega)
+ function ajax_change_demografija () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $podtip = $_POST['podtip'];
+
+ ob_start();
+ $ba = new BranchingAjax($this->anketa);
+ $ba->ajax_spremenljivka_new($this->spremenljivka, 0, 0, 0, 23, $podtip);
+
+ $sa = new SurveyAdmin();
+ $sa->brisi_spremenljivko($this->spremenljivka);
+ ob_clean();
+
+ echo $ba->spremenljivka;
+ }
+
+ function ajax_change_diferencial ($e = null) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $enota = $_POST['enota'];
+ if ($e !== null) $enota = $e;
+
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET enota = '$enota' WHERE id = '$this->spremenljivka'");
+
+ $this->edit_vrednost();
+ }
+
+ function ajax_vrednost_edit() {
+
+ $vrednost = $_POST['vrednost'];
+ $this->vrednost_edit($vrednost);
+ }
+
+ function ajax_vrednost_insert_image() {
+
+ $vrednost = $_POST['vrednost'];
+ $this->vrednost_insert_image($vrednost);
+ }
+
+ function ajax_hotspot_image_save () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $spr_id = $_POST['spremenljivka'];
+ $naslov = $_POST['hotspot_image'];
+
+ $row = Cache::srv_spremenljivka($spr_id);
+ $newParams = new enkaParameters($row['params']);
+
+ if (strtolower(substr($naslov, 0, 3)) == '<p>' && strtolower(substr($naslov, -4)) == '</p>') {
+ $tmp = substr(substr($naslov, 0, -4), 3);
+
+ if (strpos($tmp, "<p>") === false)
+ $naslov = $tmp;
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if (isset($_POST['hotspot_image'])){
+
+ if ($_POST['hotspot_image'] == ""){
+ $hotspot_image = "";
+ }
+ else{
+ $hotspot_image = $_POST['hotspot_image'];
+ $dimensions_present = strpos($hotspot_image,'style=');
+
+ //ce slika nima dimenzij
+ if($dimensions_present == ""){
+
+ //pobrisi obstojeci parameter hotspot_image
+ $newParams->set('hotspot_image', "");
+ $params = $newParams->getString();
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET params='$params' WHERE id='$spr_id'");
+
+ $length = strlen($hotspot_image); //dobi dolzino celotne html kode za sliko
+ $hotspot_image = substr($hotspot_image, 0, ($length-2)); //izlusci vse razen zadnjih dveh znakov, kjer se zakljuci html koda za sliko
+
+ $hotspot_image = $hotspot_image . 'style="height:'.$_POST['height'].'px; width:'.$_POST['width'].'px;" />';
+ }
+ }
+
+ //vnesi parameter hotspot_image
+ $newParams->set('hotspot_image', $hotspot_image);
+ $params = $newParams->getString();
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET params='$params' WHERE id='$spr_id'");
+ }
+
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo mysql_real_unescape_string($naslov);
+ }
+
+
+ function ajax_hotspot_edit() {
+
+ $vrednost = $_POST['vrednost'];
+ $this->hotspot_edit($vrednost);
+
+ }
+
+ function ajax_hotspot_edit_regions() {
+
+ $vrednost = $_POST['vrednost'];
+ //$src_image = $_POST['src_image'];
+ //$hotspot_image_height = $_POST['hotspot_image_height'];
+ //$hotspot_image_width = $_POST['hotspot_image_width'];
+ //$spr_id = $_POST['spr_id'];
+
+ $this->hotspot_edit_regions($vrednost);
+
+ }
+
+ function ajax_hotspot_save_regions () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $spr_id = $_POST['spr_id'];
+ $vre_id = $_POST['vre_id'];
+ $hotspot_region_name = $_POST['hotspot_region_name'];
+ $hotspot_region_coords = $_POST['hotspot_region_coords'];
+ $last_hotspot_region_index = $_POST['last_hotspot_region_index'];
+ $hotspot_region_index = $_POST['hotspot_region_index'];
+ //$hotspot_region_index = 0;
+
+
+ $purifier = New Purifier();
+ $hotspot_region_name = $purifier->purify_DB($hotspot_region_name);
+
+ $sqlVrednost = sisplet_query("SELECT variable, vrstni_red FROM srv_vrednost WHERE spr_id = $spr_id AND id = $vre_id");
+ $rowVrednost = mysqli_fetch_array($sqlVrednost);
+ $vrstni_red = $rowVrednost['vrstni_red'];
+ $rowSpr = Cache::srv_spremenljivka($spr_id);
+ $variableName = $rowSpr['variable'];
+
+ if($rowSpr['tip'] == 27){ //ce je heatmap vprasanje
+ $variable = $variableName.chr($vrstni_red+96); //spremeni default "variable", da ne bo tezav pri izvozu podatkov v SPSS
+ }else{ //drugace
+ $variable = $rowVrednost['variable']; //poberi "variable" iz tabele srv_vrednost
+ }
+
+
+
+ //preveri, ce je kaksno obmocje shranjeno v bazi
+ $sqlR = sisplet_query("SELECT id FROM srv_hotspot_regions WHERE spr_id = $spr_id AND vre_id = $vre_id");
+ $rowR = mysqli_fetch_array($sqlR);
+
+ if (mysqli_num_rows($sqlR) == 0){ //se ni obmocja v bazi za trenutno spremenljivko in vrednost kategorije odgovora
+
+ //vnesi podatke o obmocju v bazo za trenutno spremenljivko in vrednost kategorije odgovora
+ $sql = sisplet_query("INSERT INTO srv_hotspot_regions (vre_id, spr_id, region_name, region_coords, region_index, variable, vrstni_red) VALUES ('$vre_id', '$spr_id', '$hotspot_region_name', '$hotspot_region_coords', '$last_hotspot_region_index', '$variable', '$vrstni_red')");
+
+ //posodobi podatke o obmocju za njegovo vrednost kategorije
+ $sql_vre = sisplet_query("UPDATE srv_vrednost SET naslov = '$hotspot_region_name', variable = '$variable' WHERE spr_id = '$spr_id' AND id = '$vre_id'");
+
+ //naberi vse identifikatorje kategorij odgovorov drugih obmocij, ki niso trenutnega obmocja
+ $sql_vre_select = sisplet_query("SELECT id, spr_id, variable, vrstni_red FROM srv_vrednost WHERE spr_id = $spr_id AND id != '$vre_id'");
+
+ //za vsako kategorijo odgovora drugih obmocij, ki niso trenutno obmocje
+ while($row_vre_select = mysqli_fetch_array($sql_vre_select)){
+ $variable_select = $row_vre_select['variable'];
+ $vrstni_red_select = $row_vre_select['vrstni_red'];
+ $spr_id_select = $row_vre_select['spr_id'];
+ $vre_id_select = $row_vre_select['id'];
+
+ //posodobi podatke drugih obmocij
+ $sql = sisplet_query("UPDATE srv_hotspot_regions SET variable = '$variable_select', vrstni_red = '$vrstni_red_select' WHERE spr_id = '$spr_id_select' AND vre_id = $vre_id_select");
+ }
+
+ }else{ //obstaja obmocje v bazi za trenutno spremenljivko in vrednost kategorije odgovora
+
+ //posodobi podatke o obmocju za trenutno spremenljivko in vrednost kategorije odgovora
+ $sql = sisplet_query("UPDATE srv_hotspot_regions SET region_name = '$hotspot_region_name', region_coords = '$hotspot_region_coords', region_index = '$hotspot_region_index', variable = '$variable', vrstni_red = '$vrstni_red' WHERE spr_id = '$spr_id' AND vre_id = $vre_id");
+
+ //posodobi podatke o obmocju za njegovo vrednost kategorije
+ $sql_vre = sisplet_query("UPDATE srv_vrednost SET naslov = '$hotspot_region_name' WHERE spr_id = '$spr_id' AND id = '$vre_id'");
+
+ }
+ //poberi vre_id novega polja za shranjevanja imena naslednjega obmocja
+ $sql_vre_id = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = $spr_id order by vrstni_red DESC LIMIT 1");
+ $row_vre_id = mysqli_fetch_array($sql_vre_id);
+
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo mysql_real_unescape_string($hotspot_region_name);
+
+ }
+
+ function ajax_vrednost_save () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $vrednost = $_POST['vrednost'];
+
+ $sql = sisplet_query("SELECT variable, variable_custom FROM srv_vrednost WHERE id = '$vrednost'");
+ $row = mysqli_fetch_array($sql);
+
+ $variable = $_POST['vrednost_variable'];
+ $naslov = $_POST['vrednost_naslov'];
+ $random = $_POST['vrednost_random'];
+
+ if (strtolower(substr($naslov, 0, 3)) == '<p>' && strtolower(substr($naslov, -4)) == '</p>') {
+ //$naslov = '<p>'.nl2br($naslov).'</p>';
+ $tmp = substr(substr($naslov, 0, -4), 3);
+ if (strpos($tmp, "<p>") === false)
+ $naslov = $tmp;
+ }
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if ($variable != $row['variable'] || $row['variable_custom'] == 1)
+ $variable_custom = 1;
+ else
+ $variable_custom = 0;
+
+ $sql = sisplet_query("UPDATE srv_vrednost SET naslov='$naslov', variable='$variable', variable_custom='$variable_custom', random='$random' WHERE id = '$vrednost'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo mysql_real_unescape_string($naslov);
+ }
+
+ function ajax_vrednost_fastadd () {
+
+ $this->vrednost_fastadd();
+
+ }
+
+ function ajax_vrednost_fastadd_save () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ global $lang;
+
+ $fastadd = mysql_real_unescape_string( $_POST['fastadd'] );
+ if ($fastadd == '') return;
+
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND ( naslov='' OR naslov LIKE '%$lang[srv_new_vrednost]%' )");
+ echo ("DELETE FROM srv_vrednost WHERE spr_id='$this->spremenljivka' AND ( naslov='' OR naslov = '$lang[srv_new_vrednost]' )");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $fastadd = explode("\n", $fastadd);
+
+ foreach ($fastadd AS $naslov) {
+ if ($naslov != '') {
+ $this->vrednost_new(trim($naslov), $other);
+ }
+ }
+
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ function ajax_vprasanje_refresh () {
+ global $lang;
+
+ if ($_GET['silentsave'] == 'true')
+ $silentsave = true;
+ else
+ $silentsave = false;
+
+
+ if ($this->expanded || $silentsave) {
+
+ Cache::clear_cache();
+
+ if($this->spremenljivka > 0){
+ $Branching = new Branching($this->anketa);
+ $Branching->vprasanje($this->spremenljivka);
+ }
+ elseif($this->spremenljivka == -1){
+ $Branching = new Branching($this->anketa);
+ $Branching->introduction_conclusion(-1, 0);
+ }
+ elseif($this->spremenljivka == -2){
+ $Branching = new Branching($this->anketa);
+ $Branching->introduction_conclusion(-2, 0);
+ }
+ elseif($this->spremenljivka == -3){
+ $Glasovanje = new Glasovanje($this->anketa);
+ $Glasovanje->edit_statistika();
+ }
+
+ } else {
+
+ /* tole je skopirano iz Branching->spremenljivka_name(), da ne loadamo celga classa za par vrstic */
+
+ // tukaj je treba še enkrat prebrat iz baze, ker se vrednosti spremenijo
+ Cache::clear_cache();
+
+ if ($this->spremenljivka > 0) {
+
+ $this->spremenljivka_name($this->spremenljivka);
+
+ } elseif ($this->spremenljivka == -1) {
+ echo ''.$lang['srv_intro_label'].'';
+
+ } elseif ($this->spremenljivka == -2) {
+ echo ''.$lang['srv_end_label'].'';
+
+ }
+
+ }
+
+ }
+
+ function ajax_vprasanje_tracking () {
+ global $lang;
+
+ self::vprasanje_tracking(1);
+
+ echo $lang['srv_vprasanje_tracking_done'];
+ }
+
+ function ajax_validation_new () {
+
+ $sql = sisplet_query("INSERT INTO srv_if (id) VALUES ('')");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $if_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $s = sisplet_query("INSERT INTO srv_condition (id, if_id, vrstni_red) VALUES ('', '$if_id', '1')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $s = sisplet_query("INSERT INTO srv_validation (spr_id, if_id, reminder) VALUES ('$this->spremenljivka', '$if_id', '1')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ $b = new Branching($this->anketa);
+
+ $b->spremenljivka = $_POST['spremenljivka'];
+ $b->condition_editing($if_id, -4);
+
+ }
+
+ function ajax_validation_edit() {
+
+ $if_id = (int)$_POST['if_id'];
+
+ $b = new Branching($this->anketa);
+
+ $b->spremenljivka = $_POST['spremenljivka'];
+ $b->condition_editing($if_id, -4);
+
+ }
+
+ function ajax_validation_if_close () {
+
+ $this->spremenljivka = $_POST['spremenljivka'];
+
+ $this->vprasanje_validation();
+
+ }
+
+ function ajax_change_subtype_number () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ // slider pri numberju
+ if ( isset($_POST['ranking_k']) && $row['tip']=='7' ) {
+
+ if ($row['num_useMin'] == '0' && $row['num_useMax']=='0') {
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET ranking_k='$_POST[ranking_k]', vsota_min='0', vsota_limit='100', num_useMin='1', num_useMax='1' WHERE id = '$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ /*$s = sisplet_query("SELECT * From srv_spremenljivka WHERE id = '$this->spremenljivka'");
+ $r = mysqli_fetch_assoc($s);
+ print_r($r);*/
+
+ } else {
+ $s = sisplet_query("UPDATE srv_spremenljivka SET ranking_k='$_POST[ranking_k]' WHERE id = '$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+
+ // slider pri multinumberju
+ if ( isset($_POST['ranking_k']) && $row['tip']=='20' ) {
+
+ if ($row['num_useMin'] == '0' || $row['num_useMax']=='0') {
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET ranking_k='$_POST[ranking_k]', vsota_min='0', vsota_limit='100', num_useMin='1', num_useMax='1', grids='1' WHERE id = '$this->spremenljivka'");
+ //$s = sisplet_query("UPDATE srv_spremenljivka SET ranking_k='$_POST[ranking_k]', vsota_min='0', vsota_limit='0', num_useMin='1', num_useMax='1', grids='1' WHERE id = '$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ $s = sisplet_query("DELETE FROM srv_grid WHERE spr_id='$this->spremenljivka' AND vrstni_red > '1'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ } else {
+ $s = sisplet_query("UPDATE srv_spremenljivka SET ranking_k='$_POST[ranking_k]' WHERE id = '$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+
+ }
+
+ /**
+ * manual je, ce rocno pozenemo tracking, sicer se poganja avtomatsko
+ *
+ * @param mixed $manual
+ */
+
+ public static function vprasanje_tracking($manual = 0) {
+ global $global_user_id;
+
+ $anketa = (int)$_REQUEST['anketa'];
+ $spremenljivka = (int)$_REQUEST['spremenljivka'];
+
+ SurveyInfo::getInstance()->SurveyInit($anketa);
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ if ($row['vprasanje_tracking'] == 0) return;
+ if ($row['vprasanje_tracking'] == 2 && $manual==0) return;
+ if ($row['vprasanje_tracking'] == 3 && $_GET['silentsave']!='undefined') return;
+
+ $branching = new Branching($anketa);
+ $tracking_id = $branching->nova_spremenljivka(-1, 0, 0, $spremenljivka);
+
+ sisplet_query("INSERT INTO srv_spremenljivka_tracking (ank_id, spr_id, tracking_id, tracking_uid, tracking_time) VALUES ('$anketa', '$spremenljivka', '$tracking_id', '$global_user_id', NOW())");
+ }
+
+ function ajax_grid_multiple_add () {
+ global $lang;
+
+ echo '<p><b>'.$lang['srv_gridmultiple_choose'].'</b></p>';
+
+ echo '<p><label onclick="grid_multiple_addnew(\''.$this->spremenljivka.'\', \'6\');"><span class="sprites radio3"></span> '.$lang['srv_vprasanje_tip_1'].'</label></p>';
+ echo '<p><label onclick="grid_multiple_addnew(\''.$this->spremenljivka.'\', \'16\');"><span class="sprites checkbox3"></span> '.$lang['srv_vprasanje_tip_2'].'</label></p>';
+ echo '<p><label onclick="grid_multiple_addnew(\''.$this->spremenljivka.'\', \'19\');"><span class="sprites text"></span> '.$lang['srv_vprasanje_tip_21'].'</label></p>';
+ echo '<p><label onclick="grid_multiple_addnew(\''.$this->spremenljivka.'\', \'20\');"><span class="sprites text"></span> '.$lang['srv_vprasanje_tip_7'].'</label></p>';
+ echo '<p><label onclick="grid_multiple_addnew(\''.$this->spremenljivka.'\', \'19\', \'1\');"><span class="sprites text"></span> '.$lang['srv_vprasanje_datum'].'</label></p>';
+
+ echo '<a onclick="$(\'#vrednost_edit\').html(\'\').hide(); return false;" href="#" style="position:absolute; right:10px; bottom:10px">'.$lang['srv_zapri'].'</a>';
+ }
+
+ function ajax_grid_multiple_addnew () {
+ global $lang;
+
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $tip = $_POST['tip'];
+ $podtip = $_POST['podtip'];
+
+ $b = new Branching($this->anketa);
+ $spr_id = $b->nova_spremenljivka(-2, 0, 0);
+
+ if ($tip == 19)
+ $vr = 1;
+ else
+ $vr = 3;
+
+ $s = sisplet_query("DELETE FROM srv_grid WHERE spr_id='$spr_id' AND vrstni_red > '$vr'");
+ $s = sisplet_query("UPDATE srv_spremenljivka SET grids='$vr' WHERE id='$spr_id'");
+
+ $sql = sisplet_query("SELECT MAX(vrstni_red) AS max FROM srv_grid_multiple WHERE ank_id='$this->anketa' AND parent='$this->spremenljivka'");
+ $row = mysqli_fetch_array($sql);
+ $vrstni_red = $row['max'] + 1;
+
+ $sql = sisplet_query("INSERT INTO srv_grid_multiple (ank_id, parent, spr_id, vrstni_red) VALUES ('$this->anketa', '$this->spremenljivka', '$spr_id', '$vrstni_red')");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+
+ Vprasanje::change_tip($spr_id, $tip);
+
+ if ($podtip > 0) {
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $spr_id;
+
+ if ($tip == 19) {
+ if ($podtip == 1) {
+ $v->set_datum(); // multigrid datum
+ }
+ }
+ }
+
+ $this->repare_grid_multiple($this->spremenljivka);
+ }
+
+ /**
+ * urejanje pod-spremenljivki v multiple gridu
+ *
+ */
+ function ajax_grid_multiple_edit () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ echo '<p><b>'.$lang['srv_analiza_opisne_subquestion'].'</b></p>';
+
+ echo '<p><span class="title">'.$lang['srv_odgovorov'].':</span> ';
+ echo '<span class="content"><select name="multi_grids_count" id="multi_grids_count" onChange="change_selectbox_size(\'' . $row['id'] . '\', $(this).val(), \'' . $lang['srv_select_box_vse'] . '\');">';
+ //echo '<span class="content"><select name="multi_grids_count" id="multi_grids_count" onchange="">';
+ // Vedno imamo najmanj 2 grida (drugace so stvari cudne v analizah) - namesto 1 se uporabi navaden radio tip vprasanja
+ // Pri number sliderju se rabi 1 (mogoče še kje - npr checkbox itd.... ) analize morajo delati tudi v tem primeru :P
+ for ($i=1; $i<=20; $i++)
+ echo '<option value="'.$i.'"'.($row['grids']==$i?' selected':'').'>'.$i.'</option>';
+
+ echo '</select></span>';
+ echo '</p>';
+
+ if ($row['tip'] == 6) {
+
+ echo '<p><span class="title">'.$lang['srv_orientacija'].': </span>';
+ //echo '<span class="content"><select id="spremenljivka_podtip" name="enota" onChange="show_selectbox_size(\'' . $row['id'] . '\', this.value);">';
+ echo '<span class="content"><select id="spremenljivka_podtip" name="enota" onChange="show_selectbox_size(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\');">';
+ //echo '<span class="content"><select id="spremenljivka_podtip" name="enota">';
+ echo '<option value="0" '.(($row['enota'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_classic'].'</option>';
+ echo '<option value="2" '.(($row['enota'] == 2) ? ' selected="true" ' : '').'>'.$lang['srv_dropdown'].'</option>';
+ echo '<option value="6" '.(($row['enota'] == 6) ? ' selected="true" ' : '').'>'.$lang['srv_select-box_radio'].'</option>';
+ echo '</select>';
+ echo '</span></p>';
+
+ $this->edit_selectbox_size ();
+ }
+
+ if ($row['tip'] == 16) {
+
+ echo '<p><span class="title">'.$lang['srv_orientacija'].': </span>';
+ //echo '<span class="content"><select id="spremenljivka_podtip" name="enota">';
+ //echo '<span class="content"><select id="spremenljivka_podtip" name="enota" onChange="show_selectbox_size(\'' . $row['id'] . '\', this.value);">';
+ echo '<span class="content"><select id="spremenljivka_podtip" name="enota" onChange="show_selectbox_size(\'' . $row['id'] . '\', this.value, \'' . $row['tip'] . '\');">';
+ echo '<option value="0" '.(($row['enota'] == 0) ? ' selected="true" ' : '').'>'.$lang['srv_classic'].'</option>';
+ echo '<option value="6" '.(($row['enota'] == 6) ? ' selected="true" ' : '').'>'.$lang['srv_select-box_check'].'</option>';
+ echo '</select>';
+ echo '</span></p>';
+
+ $this->edit_selectbox_size ();
+ }
+
+ if ($row['tip'] == 19) {
+
+ echo '<p>';
+
+ $taWidth = ($spremenljivkaParams->get('taWidth') ? $spremenljivkaParams->get('taWidth') : -1);
+ $taHeight = ($spremenljivkaParams->get('taHeight') ? $spremenljivkaParams->get('taHeight') : 1);
+
+
+ // Sirina polja
+ echo $lang['srv_textAreaWidth'].': ';
+
+ $size = $row['grids'];
+ $missing_count = 0;
+ # če imamo missinge size povečamo za 1 + številomissingov
+ $sql_grid_mv = sisplet_query("SELECT * FROM srv_grid WHERE spr_id='".$this->spremenljivka."' AND other != 0");
+ $missing_count = mysqli_num_rows($sql_grid_mv);
+ if ($missing_count > 0) {
+ $size += $missing_count + 1;
+ }
+
+ echo '<select name="taWidth" id="multi_taWidth">';
+ $maxWidth = round(50 / $size);
+ $maxWidth = 10;
+
+ echo '<option value="-1"' . ($taWidth == -1 ? ' selected="true"' : '') . '>'.$lang['default'].'</option>';
+ for($i=1; $i<$maxWidth; $i++){
+ echo '<option value="'.$i.'"' . ($taWidth == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select>';
+
+
+ // Visina polja
+ echo '<span class="spaceLeft">'.$lang['srv_textAreaHeight'].': <select name="taHeight" id="multi_taHeight">';
+ $maxHeight = 10;
+
+ for($i=1; $i<=$maxHeight; $i++){
+ echo '<option value="'.$i.'"' . ($taHeight == $i ? ' selected="true"' : '') . '>' . $i . '</option>';
+ }
+ echo '</select></span>';
+
+ echo '</p>';
+ }
+
+ if ($row['tip'] == 20) {
+
+ $this->edit_number();
+ }
+
+ // Prikaz podtabele glede na tip respondenta (admin, manager...)
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_visible_dostop'].': </span>';
+ echo '<span class="content"><select name="dostop" id="spremenljivka_dostop">';
+ echo '<option value="4"'.($row['dostop']==4?' selected':'').'>'.$lang['see_everybody'].'</option>';
+ echo '<option value="3"'.($row['dostop']==3?' selected':'').'>'.$lang['see_registered'].'</option>';
+ echo '<option value="2"'.($row['dostop']==2?' selected':'').'>'.$lang['see_member'].'</option>';
+ echo '<option value="1"'.($row['dostop']==1?' selected':'').'>'.$lang['see_manager'].'</option>';
+ echo '<option value="0"'.($row['dostop']==0?' selected':'').'>'.$lang['see_admin'].'</option>';
+ echo '</select></span>';
+ echo '</p>';
+
+ // Ce imamo datum
+ if ($row['tip'] == 19){
+ $is_datum = $spremenljivkaParams->get('multigrid-datum');
+
+ if ($is_datum == 1)
+ $this->edit_date_range();
+ }
+
+ // Sirina stolpca
+ $grid_width = $spremenljivkaParams->get('gridmultiple_width');
+ echo '<p>';
+ echo '<span class="title">'.$lang['srv_gridmultiple_width'].': </span>';
+ echo '<span class="content"><select name="gridmultiple_width" id="gridmultiple_width">';
+ echo '<option value="0"'.($grid_width==0?' selected':'').'>'.$lang['default'].'</option>';
+ echo '<option value="10"'.($grid_width==10?' selected':'').'>10%</option>';
+ echo '<option value="20"'.($grid_width==20?' selected':'').'>20%</option>';
+ echo '<option value="30"'.($grid_width==30?' selected':'').'>30%</option>';
+ echo '<option value="40"'.($grid_width==40?' selected':'').'>40%</option>';
+ echo '<option value="50"'.($grid_width==50?' selected':'').'>50%</option>';
+ echo '<option value="60"'.($grid_width==60?' selected':'').'>60%</option>';
+ echo '</select></span>';
+ echo '</p>';
+
+
+ echo '<br />';
+
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">
+ <a class="ovalbutton ovalbutton_orange" onclick="grid_multiple_save(\''.$this->spremenljivka.'\'); $(\'#vrednost_edit\').html(\'\').hide(); return false;" href="#">
+ <span>'.$lang['srv_potrdi'].'</span>
+ </a>
+ </span>';
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">
+ <a class="ovalbutton ovalbutton_gray" onclick="$(\'#fade\').fadeOut(\'slow\'); $(\'#vrednost_edit\').html(\'\').hide(); return false;" href="#">
+ <span>'.$lang['srv_zapri'].'</span>
+ </a>
+ </span>';
+
+ echo '<span class="buttonwrapper spaceLeft floatRight">
+ <a class="ovalbutton ovalbutton_gray" onclick="brisi_spremenljivko(\''.$this->spremenljivka.'\', undefined, \'0\'); $(\'#fade\').fadeOut(\'slow\'); $(\'#vrednost_edit\').html(\'\').hide(); return false;" href="#">
+ <span>'.$lang['srv_brisispremenljivko'].'</span>
+ </a>
+ </span>';
+
+ }
+
+ /**
+ * popravi srv_vrednost tabele za childe multiple grida (v urejanju se vedno ureja parenta)
+ *
+ * @param mixed $parent
+ */
+ function repare_grid_multiple($parent) {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $sql_parent = sisplet_query("SELECT naslov, naslov2, variable, variable_custom, other FROM srv_vrednost WHERE spr_id='$parent' ORDER BY vrstni_red");
+
+ $sql = sisplet_query("SELECT spr_id FROM srv_grid_multiple WHERE ank_id='$this->anketa' AND parent='$parent' ORDER BY vrstni_red");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ $sql_grid = sisplet_query("SELECT id, naslov, naslov2, variable, variable_custom FROM srv_vrednost WHERE spr_id = '$row[spr_id]' ORDER BY vrstni_red");
+
+ // dodamo manjkajoce vrstice
+ if (mysqli_num_rows($sql_grid) < mysqli_num_rows($sql_parent)) {
+
+ for ($i=mysqli_num_rows($sql_grid); $i<mysqli_num_rows($sql_parent); $i++) {
+ $this->vrednost_new('', 0, null, $row['spr_id']);
+ }
+
+ // pobrisemo odvecne vrstice
+ } elseif (mysqli_num_rows($sql_grid) > mysqli_num_rows($sql_parent)) {
+
+ $limit = mysqli_num_rows($sql_grid) - mysqli_num_rows($sql_parent);
+ $s = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$row[spr_id]' ORDER BY vrstni_red DESC LIMIT $limit");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ }
+
+ // popravimo napise
+ mysqli_data_seek($sql_parent, 0);
+ mysqli_data_seek($sql_grid, 0);
+
+ while ($row_grid = mysqli_fetch_array($sql_grid) ) {
+
+ $row_parent = mysqli_fetch_array($sql_parent);
+
+ if ($row_grid['naslov'] != $row_parent['naslov']
+ || $row_grid['naslov2'] != $row_parent['naslov2']
+ || $row_grid['variable'] != $row_parent['variable']
+ || $row_grid['variable_custom'] != $row_parent['variable_custom']
+ ) {
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($row_parent['naslov']);
+ $naslov2 = $purifier->purify_DB($row_parent['naslov2']);
+
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov='$naslov', naslov2='$naslov2', variable='$row_parent[variable]', variable_custom='$row_parent[variable_custom]', other='$row_parent[other]' WHERE id='$row_grid[id]'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+
+ // Nastavimo ustrezne variable
+ Common::prestevilci($row['spr_id']);
+ }
+ }
+
+ function ajax_hotspot_vrednost_new () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ global $lang;
+
+ $naslov = '';
+
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $this->spremenljivka;
+ $vrednost = $v->vrednost_new($naslov /*, $other, $mv*/);
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ if($row['tip'] != 27){ //ce ni heatmap, torej je image hotspot
+ Common::prestevilci($this->spremenljivka);
+ }
+
+ echo $vrednost;
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_get_hotspot_image() {
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $hotspot_image = ($spremenljivkaParams->get('hotspot_image') ? $spremenljivkaParams->get('hotspot_image') : "");
+
+ echo $hotspot_image;
+ }
+
+ function ajax_get_next_hotspot_vrednost() {
+
+ $spr_id = $_POST['spr_id'];
+
+ // Poberi podatke o na zadnje vnesenih obmocjih
+ $sqlR = sisplet_query("SELECT vre_id FROM srv_hotspot_regions WHERE spr_id = $spr_id ORDER BY region_index");
+
+ // ce je kaj v bazi
+ if(mysqli_num_rows($sqlR) != 0){
+ $sql_vre_id_middle = "";
+
+ while($rowR = mysqli_fetch_array($sqlR)){
+ $temp = $rowR['vre_id'];
+ $sql_vre_id_middle = $sql_vre_id_middle . "AND id != $temp "; //stavek z id-ji prisotnih obmocij
+ }
+
+ $sql_vre_id_begin = "SELECT id FROM srv_vrednost WHERE spr_id = $spr_id ";
+ $sql_vre_id_end = " ORDER BY vrstni_red LIMIT 1";
+ $sql_vre_id_whole = $sql_vre_id_begin.''.$sql_vre_id_middle.''.$sql_vre_id_end;
+ $sql_vre_id = sisplet_query($sql_vre_id_whole);
+ }
+ else{ //ce ni nicesar bazi
+ $sql_vre_id = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = $spr_id ORDER BY vrstni_red LIMIT 1");
+ }
+
+
+ $row_vre_id = mysqli_fetch_assoc($sql_vre_id);
+ if(mysqli_num_rows($sql_vre_id) != 0){ //ce je kaj v bazi
+ $next_vrednost = $row_vre_id['id'];
+ }
+
+ // prestej koliko je v bazi vrednosti in obmocij
+ $sqlc = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id=$spr_id");
+ $rowc = mysqli_fetch_assoc($sqlc);
+ $vre_num = $rowc['count']; //stevilo vrednosti
+ $sqlcr = sisplet_query("SELECT COUNT(*) AS count FROM srv_hotspot_regions WHERE spr_id=$spr_id");
+ $rowcr = mysqli_fetch_assoc($sqlcr);
+ $reg_num = $rowcr['count']; //stevilo obmocij
+
+ if ( mysqli_num_rows($sqlR) != 0 && ($reg_num == $vre_num) ){ //ce je stevilo vrednosti enako stevilu obmocij
+ $next_vrednost = ""; //vrednost naj bo prazna, tako, da bomo kasneje dodali novo vrednost v bazo
+ }
+
+ echo $next_vrednost; //vrni ustrezno vrednost
+ }
+
+ function ajax_hotspot_get_region_name() {
+ $spr_id = $_POST['spr_id'];
+ $vrednost = $_POST['vrednost'];
+
+ //poberi podatke o na trenutnem obmocju
+ $sqlR = sisplet_query("SELECT region_name FROM srv_hotspot_regions WHERE spr_id = $spr_id AND vre_id = $vrednost");
+ $rowR = mysqli_fetch_assoc($sqlR);
+
+ $region_name = $rowR['region_name'];
+
+ echo $region_name;
+ }
+
+
+ //primerjaj stevilo vnosov v srv_vrednost in srv_hotspot_regions za trenutno spremenljivko in preuredi srv_vrednost, ce je to potrebno
+ function ajax_get_hotspot_stevilo_vnosov(){
+ $spr_id = $_POST['spremenljivka'];
+
+ //preveri, ce je kaksno obmocje shranjeno v bazi
+ $sqlR = sisplet_query("SELECT vre_id, spr_id, region_name, variable, vrstni_red FROM srv_hotspot_regions WHERE spr_id = $spr_id");
+ $enako_stevilo_vnosov_za_hotspot = 1;
+
+ // ce se je uredilo obmocja, presaltalo na drugo postavitev in tam brisalo vrednosti (srv_vrednost), je potrebno restorat izbrisane odgovore iz srv_hotspot_regions v srv_vrednost
+ // prestej koliko je v bazi vrednosti in obmocij
+ $sqlc = sisplet_query("SELECT COUNT(*) AS count FROM srv_vrednost WHERE spr_id=$spr_id");
+ $rowc = mysqli_fetch_assoc($sqlc);
+ $vre_num = $rowc['count']; //stevilo vrednosti
+ $sqlcr = sisplet_query("SELECT COUNT(*) AS count FROM srv_hotspot_regions WHERE spr_id=$spr_id");
+ $rowcr = mysqli_fetch_assoc($sqlcr);
+ $reg_num = $rowcr['count']; //stevilo obmocij
+
+ if ( mysqli_num_rows($sqlR) != 0 && ($reg_num != $vre_num) ){ //ce imamo nekaj obmocij in ce je stevilo vrednosti razlicno od stevila obmocij
+ $enako_stevilo_vnosov_za_hotspot = 0;
+
+ //preglej obmocja in ustrezno uredi srv_vrednost
+ while($rowR = mysqli_fetch_array($sqlR)){
+ $vre_id = $rowR['vre_id'];
+ $spr_id = $rowR['spr_id'];
+ $naslov = $rowR['region_name'];
+ $variable = $rowR['variable'];
+ $vrstni_red = $rowR['vrstni_red'];
+ $sqlVrednost = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = $spr_id AND id = $vre_id");
+
+ //ce ni nicesar v srv_vrednost s tem id-jem, dodaj ustrezno vrednost
+ if(mysqli_num_rows($sqlVrednost) == 0){
+ $sql = sisplet_query("INSERT INTO srv_vrednost (id, spr_id, naslov, variable, vrstni_red) VALUES ($vre_id, '$spr_id', '$naslov', '$variable', '$vrstni_red')");
+ }else{ //drugace, posodobi informacije o ostalih obmocijh
+ $sql = sisplet_query("UPDATE srv_vrednost SET variable = '$variable', vrstni_red = '$vrstni_red' WHERE spr_id='$spr_id' AND id = $vre_id");
+ }
+ }
+
+ //preglej srv_vrednost in ustrezno izbrisi vrednosti brez obmocja, ker se jih je dodalo na roke, ko je bila druga postavitev (ce niso missingi)
+ $sqlV = sisplet_query("SELECT id FROM srv_vrednost WHERE spr_id = $spr_id AND other = 0");
+ while($rowV = mysqli_fetch_array($sqlV)){
+ $vre_id_V = $rowV['id'];
+ $sqlObmocje = sisplet_query("SELECT id FROM srv_hotspot_regions WHERE spr_id = $spr_id AND vre_id = $vre_id_V");
+
+ //ce ni obmocja s tem id-jem, izbrisi iz srv_vrednost vrednost s tem id-jem
+ if(mysqli_num_rows($sqlObmocje) == 0){
+ $sql = sisplet_query("DELETE FROM srv_vrednost WHERE id = '$vre_id_V' AND spr_id='$spr_id'");
+ }
+ }
+ }
+
+ echo $enako_stevilo_vnosov_za_hotspot;
+ }
+
+ function ajax_hotspot_region_cancel(){
+ $spr_id = $_POST['spr_id'];
+ $vre_id = $_POST['vre_id'];
+
+ $sqlR = sisplet_query("SELECT id FROM srv_hotspot_regions WHERE spr_id = $spr_id AND vre_id = '$vre_id'");
+
+ // Ce ni obmocja v bazi
+ if( mysqli_num_rows($sqlR) == 0){
+ $sql = sisplet_query("DELETE FROM srv_vrednost WHERE id = '$vre_id' AND spr_id='$spr_id'"); //brisi vrednost, ki se je skenslalo
+ }
+ }
+
+ function edit_trak_tabela(){
+ global $lang;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $diferencial_trak = ($spremenljivkaParams->get('diferencial_trak') ? $spremenljivkaParams->get('diferencial_trak') : 0); //za checkbox
+ $disable_diferencial_trak_hidden = ($diferencial_trak == 1) ? 'disabled' : '';
+ $diferencial_trak_starting_num = ($spremenljivkaParams->get('diferencial_trak_starting_num') ? $spremenljivkaParams->get('diferencial_trak_starting_num') : 0);
+ $trak_num_of_titles = ($spremenljivkaParams->get('trak_num_of_titles') ? $spremenljivkaParams->get('trak_num_of_titles') : 0);
+
+ //ce je diferencial ali klasicna tabela
+ if($row['enota'] == 1 || $row['enota'] == 0){
+ $display_trak = 'block';
+ if($diferencial_trak == 1){
+ $display_trak_starting_num = 'block';
+ }
+ else{
+ $display_trak_starting_num = 'none';
+ }
+ }
+ else{
+ $display_trak = 'none';
+ $display_trak_starting_num = 'none';
+ }
+
+ //koda za izris moznosti za vklop/izklop traku
+ echo '<div class="diferencial_trak_class" style="display: '.$display_trak.'">';
+ echo '<p><span class="title" ><label for="diferencial_trak_'.$this->spremenljivka.'">'.$lang['srv_diferencial_trak'].':</label></span>';
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="diferencial_trak" '.( $diferencial_trak == 1 ? ' checked="checked"' : '') .' onChange="diferencial_trak_checkbox_prop('.$this->spremenljivka.', '.$row['grids'].');" id="diferencial_trak_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_diferencial_trak_hidden.' type="hidden" value="0" name="diferencial_trak" id="diferencial_trak_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div>';
+ //koda za izris moznosti za vklop/izklop traku - konec
+
+ //koda za izris polja za vnos zacetne stevilke traku
+ echo '<div class="diferencial_trak_starting_num_class_'.$this->spremenljivka.'" style="display: '.$display_trak_starting_num.'"><p><span class="title">' . $lang['srv_diferencial_trak_starting_num'] . ':</span> <span class="content"><input type="text" name="diferencial_trak_starting_num" id="diferencial_trak_starting_num_'.$this->spremenljivka.'" value="' . $diferencial_trak_starting_num . '" size="8" onChange="diferencial_trak_change_values('.$this->spremenljivka.', '.$row['grids'].');"></input></span></p></div>';
+
+ echo '<div class="trak_num_of_titles_class" style="display: '.$display_trak_starting_num.'">';
+ echo '<p><span class="title" >'.$lang['srv_trak_num_of_titles'].':</span>';
+ echo '<span class="content"><select name="trak_num_of_titles" id="trak_num_of_titles">';
+
+ $deljivaStevila = [];
+ $indeksDeljivihStevil = 0;
+
+ for($i = 2; $i<=$row['grids']; $i++){
+ if(($row['grids']%$i == 0)&&$i!=2){
+ $deljivaStevila[$indeksDeljivihStevil] = $i;
+ $indeksDeljivihStevil++;
+ }
+ else if(($row['grids']%$i == 2)&&$i!=2){
+ $deljivaStevila[$indeksDeljivihStevil] = $i;
+ $indeksDeljivihStevil++;
+ }
+ elseif($i == 2){
+ $deljivaStevila[$indeksDeljivihStevil] = $i;
+ $indeksDeljivihStevil++;
+ }
+ }
+
+ for ($i=0; $i< sizeof($deljivaStevila); $i++){ //napolni dropdown z ustreznimi stevili vnosov
+ echo '<option value="'.$deljivaStevila[$i].'"'.($trak_num_of_titles == $deljivaStevila[$i] ? ' selected="true"' : '') . '>'.$deljivaStevila[$i].'</option>';
+ }
+ echo '</select></span>';
+ echo '</p>';
+ echo '</div>';
+ }
+
+ //posodobi skrite vrednosti odgovorov za diferencial trak
+ function ajax_diferencial_trak_skrite_vrednosti($spr_id, $num_grids, $diferencial_trak_starting_num){
+ if(isset ($_POST['spr_id'])){
+ $spr_id = $_POST['spr_id'];
+ }
+ if(isset ($_POST['num_grids'])){
+ $num_grids = $_POST['num_grids'];
+ }
+ if(isset ($_POST['diferencial_trak_starting_num'])){
+ $diferencial_trak_starting_num = $_POST['diferencial_trak_starting_num'];
+ }
+
+ $new_vrednosti_odgovorov = array();
+ $new_vrednosti_odgovorov[0] = $diferencial_trak_starting_num;
+
+ for($i = 0; $i < $num_grids; $i++){ //iz zacetne rocno vpisane vrednosti zgeneriraj se ostale glede na izbrano stevilo odgovorov
+ $id = $i + 1;
+ $sql = sisplet_query("UPDATE srv_grid SET variable = '$new_vrednosti_odgovorov[$i]' WHERE spr_id='$spr_id' AND id = $id");
+ $new_vrednosti_odgovorov[$i + 1] = $new_vrednosti_odgovorov[$i] + 1;
+ }
+ }
+
+ /**
+ * What is input type of this multilocation - 26 - 2 (marker, polyline, polygon)
+ * @return {string} type of input for multilocation
+ */
+ function ajax_get_input_type_map(){
+ $spr_id = $_POST['spr_id'];
+
+ $row = Cache::srv_spremenljivka($spr_id);
+ $newParams = new enkaParameters($row['params']);
+ $input = $newParams->get('multi_input_type') ? $newParams->get('multi_input_type') : 'marker';
+
+ echo $input;
+ }
+
+ function edit_drag_and_drop_new_look(){
+ global $lang;
+ global $admin_type;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $display_drag_and_drop_new_look = ($spremenljivkaParams->get('display_drag_and_drop_new_look') ? $spremenljivkaParams->get('display_drag_and_drop_new_look') : 0); //da bo po default-u izbrana moznost "okivirov"
+
+ if($row['enota'] == 9){ //ce je drag and drop
+ $display_new_look_option = 'block';
+ }
+ else{
+ $display_new_look_option = 'none';
+ }
+
+ // koda za dropdown za izbiro oblike okvirjev ali skatel
+ echo '<div class="drag_and_drop_new_look_class" style="display: '.$display_new_look_option.'">';
+ echo '<p><span class="title" >'.$lang['srv_drag_and_drop_new_look_option'].':</span>';
+ echo '<span class="content"><select name="display_drag_and_drop_new_look" id="drag_and_drop_new_look_'.$this->spremenljivka.'" onChange="drag_and_drop_new_look_checkbox_prop('.$this->spremenljivka.');">';
+ echo '<option value="0"'.($display_drag_and_drop_new_look=='0'?' selected':'').'>'.$lang['srv_drag_and_drop_new_look_option1'].'</option>';
+ echo '<option value="1"'.($display_drag_and_drop_new_look=='1'?' selected':'').'>'.$lang['srv_drag_and_drop_new_look_option2'].'</option>';
+ echo '</select></span></p>';
+ echo '</div>';
+ }
+
+ /**
+ * editiranje prilagajanja label stolpcev z radio buttoni
+ */
+ function edit_column_labels () {
+ global $lang;
+ global $default_grid_values;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $rowA = SurveyInfo::getInstance()->getSurveyRow();
+
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $diferencial_trak = ($spremenljivkaParams->get('diferencial_trak') ? $spremenljivkaParams->get('diferencial_trak') : 0); //za checkbox
+ $custom_column_label_option = ($spremenljivkaParams->get('custom_column_label_option') ? $spremenljivkaParams->get('custom_column_label_option') : 1);
+
+ $display = ( ( $row['tip'] == 6 && ($row['enota'] == 0 || $row['enota'] == 1) ) || ( $row['tip'] == 16 && ($row['enota'] == 0 || $row['enota'] == 1) ) ) && ($diferencial_trak == 0) ? '' : 'style="display:none;"';
+
+
+ echo '<div class="drop_custom_column_labels" '.$display.'>';
+
+ echo '<p><span class="title" >'.$lang['srv_custom_column_labels_presentation'].':</span>';
+
+ echo '<span class="content"><select name="custom_column_label_option" id="custom_column_label_option_'.$row['id'].'" >';
+ echo '<option value="1"'.($custom_column_label_option=='1'?' selected':'').'>'.$lang['srv_custom_column_labels_o1'].'</option>';
+ echo '<option value="2"'.($custom_column_label_option=='2'?' selected':'').'>'.$lang['srv_custom_column_labels_o2'].'</option>';
+ echo '<option value="3"'.($custom_column_label_option=='3'?' selected':'').'>'.$lang['srv_custom_column_labels_o3'].'</option>';
+ echo '</select></span>';
+
+ echo '</p>';
+
+ echo '</div>';
+ }
+
+ // Nastavitev za ponovitev header vrstice v gridu
+ function edit_grid_repeat_header () {
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $grid_repeat_header = ($spremenljivkaParams->get('grid_repeat_header') ? $spremenljivkaParams->get('grid_repeat_header') : 0);
+
+ echo '<div class="grid_repeat_header">';
+
+ echo '<p><span class="title" >'.$lang['srv_grid_repeat_header'].':</span>';
+
+ echo '<span class="content"><select name="grid_repeat_header" id="grid_repeat_header_'.$row['id'].'" >';
+ echo '<option value="0"'.($grid_repeat_header=='0'?' selected':'').'>'.$lang['srv_grid_repeat_header_0'].'</option>';
+ echo '<option value="5"'.($grid_repeat_header=='5'?' selected':'').'>'.$lang['srv_grid_repeat_header_5'].'</option>';
+ echo '<option value="10"'.($grid_repeat_header=='10'?' selected':'').'>'.$lang['srv_grid_repeat_header_10'].'</option>';
+ echo '<option value="15"'.($grid_repeat_header=='15'?' selected':'').'>'.$lang['srv_grid_repeat_header_15'].'</option>';
+ echo '<option value="20"'.($grid_repeat_header=='20'?' selected':'').'>'.$lang['srv_grid_repeat_header_20'].'</option>';
+ echo '</select></span>';
+
+ echo '</p>';
+
+ echo '</div>';
+ }
+
+
+ // nastavitve za heatmap
+ function edit_heatmap_settings(){
+ global $lang;
+ global $admin_type;
+ global $default_grid_values; //privzete default vmesne opisne labele
+
+ SurveySetting::getInstance()->Init($this->anketa);
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $hotspot_image = ($spremenljivkaParams->get('hotspot_image') ? $spremenljivkaParams->get('hotspot_image') : "");
+ $hotspot_region_visibility_option = ($spremenljivkaParams->get('hotspot_region_visibility_option') ? $spremenljivkaParams->get('hotspot_region_visibility_option') : 0);
+ $hotspot_tooltips_option = ($spremenljivkaParams->get('hotspot_tooltips_option') ? $spremenljivkaParams->get('hotspot_tooltips_option') : 0);
+ $hotspot_region_color = ($spremenljivkaParams->get('hotspot_region_color') ? $spremenljivkaParams->get('hotspot_region_color') : "");
+
+ $heatmap_num_clicks = ($spremenljivkaParams->get('heatmap_num_clicks') ? $spremenljivkaParams->get('heatmap_num_clicks') : 1);
+ $heatmap_show_clicks = ($spremenljivkaParams->get('heatmap_show_clicks') ? $spremenljivkaParams->get('heatmap_show_clicks') : 0); //za checkbox
+ $disable_heatmap_show_clicks_hidden = ($heatmap_show_clicks == 1) ? 'disabled' : '';
+ //$heatmap_region_settings = ($spremenljivkaParams->get('heatmap_region_settings') ? $spremenljivkaParams->get('heatmap_region_settings') : 0);
+ $heatmap_click_color = ($spremenljivkaParams->get('heatmap_click_color') ? $spremenljivkaParams->get('heatmap_click_color') : "");
+ $heatmap_click_size = ($spremenljivkaParams->get('heatmap_click_size') ? $spremenljivkaParams->get('heatmap_click_size') : 5);
+ $heatmap_click_shape = ($spremenljivkaParams->get('heatmap_click_shape') ? $spremenljivkaParams->get('heatmap_click_shape') : 1);
+
+ $heatmap_show_counter_clicks = ($spremenljivkaParams->get('heatmap_show_counter_clicks') ? $spremenljivkaParams->get('heatmap_show_counter_clicks') : 0); //za checkbox za stevec
+ $disable_heatmap_show_counter_clicks_hidden = ($heatmap_show_counter_clicks == 1) ? 'disabled' : '';
+
+ if($heatmap_num_clicks > 1){
+ $enableHeatMapClickCounter = "display: block";
+ }else{
+ $enableHeatMapClickCounter = "display: none";
+ }
+
+ if($heatmap_show_clicks == 1)
+ {
+ $heatmap_clicks_settings_display = 'style=""';
+ }else
+ {
+ $heatmap_clicks_settings_display = 'style="display:none"';
+ }
+
+
+ $spr_id = $row['id'];
+ //preveri, ce je kaksno obmocje shranjeno v bazi
+ //$sqlR = sisplet_query("SELECT * FROM srv_hotspot_regions WHERE spr_id = $spr_id");
+ $sqlR = sisplet_query("SELECT region_index, vre_id, region_name FROM srv_hotspot_regions WHERE spr_id = $spr_id");
+ //$rowR = mysqli_fetch_array($sql);
+
+ if($row['tip'] == 1 || $row['tip'] == 2){
+ $enota_orientation = $row['orientation'];
+ }else if($row['tip'] == 6){
+ $enota_orientation = $row['enota'];
+ }
+ ?>
+ <script>
+ $(document).ready(function(){
+ //show_hot_spot_settings_4Heatmap (<?=$row['id']?>, <?=$row['tip']?>, '<?=$hotspot_image?>', <?=$heatmap_region_settings?>);
+ show_hot_spot_settings_4Heatmap (<?=$row['id']?>, <?=$row['tip']?>, '<?=$hotspot_image?>');
+ init_colorPicker(<?=$row['id']?>);
+ });
+ </script>
+
+ <?
+
+ //roleta za izbiro najvecjega stevila klikov na sliko
+ echo '<p><span class="title">'.$lang['srv_vprasanje_heatmap_num_clicks'].':<span id="help_hotspot_visibility" class="spaceLeft">'.Help::display('srv_hotspot_visibility').' </span></span>';
+ echo '<span class="content"><select id="heatmap_num_clicks_' . $row['id'] . '" spr_id="'.$row['id'].'" name="heatmap_num_clicks" onChange="showHeatMapClickCounter($(this).val(), '.$row['id'].')">';
+ echo '<option value="1" '.(($heatmap_num_clicks == 1) ? ' selected="true" ' : '').'>1</option>';
+ echo '<option value="2" '.(($heatmap_num_clicks == 2) ? ' selected="true" ' : '').'>2</option>';
+ echo '<option value="3" '.(($heatmap_num_clicks == 3) ? ' selected="true" ' : '').'>3</option>';
+ echo '<option value="4" '.(($heatmap_num_clicks == 4) ? ' selected="true" ' : '').'>4</option>';
+ echo '<option value="5" '.(($heatmap_num_clicks == 5) ? ' selected="true" ' : '').'>5</option>';
+ echo '<option value="6" '.(($heatmap_num_clicks == 6) ? ' selected="true" ' : '').'>6</option>';
+ echo '<option value="7" '.(($heatmap_num_clicks == 7) ? ' selected="true" ' : '').'>7</option>';
+ echo '<option value="8" '.(($heatmap_num_clicks == 8) ? ' selected="true" ' : '').'>8</option>';
+ echo '<option value="9" '.(($heatmap_num_clicks == 9) ? ' selected="true" ' : '').'>9</option>';
+ echo '<option value="10" '.(($heatmap_num_clicks == 10) ? ' selected="true" ' : '').'>10</option>';
+ echo '</select>';
+ echo '</span></p>';
+ //roleta za izbiro najvecjega stevila klikov na sliko - konec
+
+ //checkbox za "Pokazi stevec klikov"
+ echo '<label for="heatmap_show_counter_clicks_'.$this->spremenljivka.'"><div style="'.$enableHeatMapClickCounter.'" class="heatmap_show_counter_clicks_class">';
+ echo '<p><span class="title" >'.$lang['srv_vprasanje_heatmap_show_counter_clicks'].':</span>';
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="heatmap_show_counter_clicks" '.( $heatmap_show_counter_clicks == 1 ? ' checked="checked"' : '') .' onChange="heatmap_show_counter_clicks_checkbox_prop('.$this->spremenljivka.');" id="heatmap_show_counter_clicks_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_heatmap_show_counter_clicks_hidden.' type="hidden" value="0" name="heatmap_show_counter_clicks" id="heatmap_show_counter_clicks_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div></label>';
+ //checkbox za "Pokazi stevec klikov" - konec
+
+ //checkbox za "Pokazi klike"
+ echo '<label for="heatmap_show_clicks_'.$this->spremenljivka.'"><div class="heatmap_show_clicks_class">';
+ echo '<p><span class="title" >'.$lang['srv_vprasanje_heatmap_show_clicks'].':</span>';
+ echo '<span class="content">';
+ echo '<input type="checkbox" value="1" name="heatmap_show_clicks" '.( $heatmap_show_clicks == 1 ? ' checked="checked"' : '') .' onChange="heatmap_show_clicks_checkbox_prop('.$this->spremenljivka.');" id="heatmap_show_clicks_'.$this->spremenljivka.'">';
+ echo '<input '.$disable_heatmap_show_clicks_hidden.' type="hidden" value="0" name="heatmap_show_clicks" id="heatmap_show_clicks_hidden_'.$this->spremenljivka.'">';
+ echo '</span></p>';
+ echo '</div></label>';
+ //checkbox za "Pokazi klike" - konec
+
+ //dodatne nastavitve, ce morajo biti kliki vidni
+
+ echo '<div id="heatmap_clicks_settings_'.$row['id'].'" '.$heatmap_clicks_settings_display.'>';
+
+ //Izbira barve klika
+ if ($heatmap_click_color == '') {
+ $value = '#000000';
+ echo '<div><p><span class="title">'.$lang['srv_vprasanje_heatmap_clicks_color'].': <a href="#" onclick="$(\'#color-click-'.$row['id'].'\').show(); $(this).parent().hide(); return false;" title="'.$lang['edit4'].'">'.$lang['srv_te_default'].' <span class="faicon edit"></span></a></span></p></div>';
+ }else{
+ $value = $heatmap_click_color;
+ }
+ echo '<div><p><span class="title" id="color-click-'.$row['id'].'" '.($heatmap_click_color==''?'style="display:none;"':'').'>'.$lang['srv_vprasanje_heatmap_clicks_color'].': ';
+ echo '<input type="text" id="color-click'.$row['id'].'" class="colorwell auto-save" name="heatmap_click_color" value="'.$value.'" data-id="'.$row['id'].'" data-type="'.$type.'" >';
+ echo '</span></p></div>';
+
+ echo '<div id="picker"></div>';
+ //Izbira barve klika - konec
+
+ //Izbira radija/velikosti klika
+ echo '<div><p><span>'.$lang['srv_vprasanje_heatmap_clicks_size'].': <input id="heatmapClickSize_'.$row['id'].'" name="heatmap_click_size" type="range" min="2" max="50" step="1" value="'.$heatmap_click_size.'" oninput="UpdateClickSizeSlider(value, '.$row['id'].')"/><output for="heatmapClickSize_'.$row['id'].'" id="heatmapClickSizeValue_'.$row['id'].'">'.$heatmap_click_size.'</output></span></p></div>';
+ //Izbira radija/velikosti klika - konec
+
+ //Izbira oblike klika $heatmap_click_shape
+ echo '<div><p><span class="title">'.$lang['srv_vprasanje_heatmap_clicks_shape'].': </span>';
+ echo '<span class="content"><select id="heatmapClickShape_' . $row['id'] . '" spr_id="'.$row['id'].'" name="heatmap_click_shape" onChange="">';
+ echo '<option value="1" '.(($heatmap_click_shape == 1) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_heatmap_clicks_shape_1'].'</option>';
+ echo '<option value="2" '.(($heatmap_click_shape == 2) ? ' selected="true" ' : '').'>'.$lang['srv_vprasanje_heatmap_clicks_shape_2'].'</option>';
+ echo '</select>';
+ echo '</span></p></div>';
+ //Izbira oblike klika - konec
+
+
+ echo '</div>';
+ //dodatne nastavitve, ce morajo biti kliki vidni - konec
+
+ //fieldset Obmocja - zacasno skrivanje
+ echo '<fieldset id="hot_spot_fieldset_'.$row['id'].'"><legend>'.$lang['srv_hot_spot_regions_menu'].'</legend>';
+ if (mysqli_num_rows($sqlR) != 0){
+ //pokazi shranjena obmocja
+ while ($rowR = mysqli_fetch_array($sqlR)) {
+ echo '<div id="hotspot_region_'.$rowR['region_index'].'" class="hotspot_region"><div id="hotspot_region_name_'.$rowR['region_index'].'" vre_id="'.$rowR['vre_id'].'" region_index = "'.$rowR['region_index'].'" class="hotspot_vrednost_inline" contenteditable="true">'.$rowR['region_name'].'</div><span class="faicon edit2 inline_hotspot_edit_region"></span><span class="faicon delete_circle icon-orange_link inline_hotspot_delete_region"></span><br /></div>';
+ }
+ }
+ //Sporocilo ob odsotnosti slike
+ echo '<p id="hotspot_message"><span class="title" >'.$lang['srv_hotspot_message'].'</span></p>';
+ //Sporocilo ob odsotnosti slike - konec
+
+ //Dodajanje območja - gumb
+ echo '<p><span class="title" ><button id="hot_spot_regions_add_button" type="button" onclick=" hotspot_edit_regions('.$row['id'].', 0)">'.$lang['srv_hot_spot_regions'].'</button></span></p>';
+
+ //*************************** SKRIVANJE NASTAVITEV OBMOCJA
+ $display_regions_menu = 'style="display:none;"'; //skrivanje nastavitev obmocja + v js datotekah
+ //***************************
+ //div za nastavitve obmocja
+ echo '<div id="heatmap_region_settings_'.$row['id'].'" '.$display_regions_menu.'>';
+ //Izbira barve obmocja
+ if ($hotspot_region_color == '') {
+ $value = '#000000';
+ echo '<span class="title">'.$lang['srv_hotspot_region_color_text'].': <a href="#" onclick="$(\'#color-'.$row['id'].'\').show(); $(this).parent().hide(); return false;" title="'.$lang['edit4'].'">'.$lang['srv_te_default'].' <span class="faicon edit"></span></a></span>';
+ }else{
+ $value = $hotspot_region_color;
+ }
+
+ echo '<span class="title" id="color-'.$row['id'].'" '.($hotspot_region_color==''?'style="display:none;"':'').'>'.$lang['srv_hotspot_region_color_text'].': ';
+ echo '<input type="text" id="color'.$row['id'].'" class="colorwell auto-save" name="hotspot_region_color" value="'.$value.'" data-id="'.$row['id'].'" data-type="'.$type.'" >';
+ echo '</span>';
+
+ echo '<div id="picker"></div>';
+ //Izbira barve obmocja - konec
+
+ //Regions visibility options
+ echo '<p><span class="title">'.$lang['srv_hotspot_visibility_options_title'].':<span id="help_hotspot_visibility" class="spaceLeft">'.Help::display('srv_hotspot_visibility').' </span></span>';
+ echo '<span class="title"><select id="hotspot_region_visibility_options_' . $row['id'] . '" spr_id="'.$row['id'].'" name="hotspot_region_visibility_option" onChange="">';
+ echo '<option value="0" '.(($hotspot_region_visibility_option == 0) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_visibility_options_0'].'</option>';
+ echo '<option value="1" '.(($hotspot_region_visibility_option == 1) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_visibility_options_1'].'</option>';
+ echo '<option value="2" '.(($hotspot_region_visibility_option == 2) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_visibility_options_2'].'</option>';
+ //echo '<option value="3" '.(($hotspot_region_visibility_option == 3) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_visibility_options_3'].'</option>';
+ echo '</select>';
+ echo '</span></p>';
+ //Regions visibility options - konec
+
+ //Tooltips options
+ if($row['tip'] == 1 || $row['tip'] == 2){ //ce je radio ali checkbox
+ $srv_hotspot_tooltip = 'srv_hotspot_tooltip';
+ }else if($row['tip'] == 6){
+ $srv_hotspot_tooltip = 'srv_hotspot_tooltip_grid';
+ }
+
+ echo '<p><span class="title">'.$lang['srv_hotspot_tooltips_options_title'].':<span id="help_hotspot_namig" class="spaceLeft">'.Help::display($srv_hotspot_tooltip).' </span></span>';
+ echo '<span class="title"><select id="hotspot_tooltips_options_' . $row['id'] . '" spr_id="'.$row['id'].'" name="hotspot_tooltips_option" onChange="">';
+ echo '<option value="0" '.(($hotspot_tooltips_option == 0) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_tooltips_options_0'].'</option>';
+ if($row['tip'] == 1 || $row['tip'] == 2){ //ce je radio ali checkbox
+ echo '<option value="1" '.(($hotspot_tooltips_option == 1) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_tooltips_options_1'].'</option>';
+ }
+ if($row['tip'] == 6){ //ce je radio grid
+ echo '<option value="2" '.(($hotspot_tooltips_option == 2) ? ' selected="true" ' : '').'>'.$lang['srv_hotspot_tooltips_options_2'].'</option>';
+ }
+
+ echo '</select>';
+ echo '</span></p>';
+ //Tooltips options - konec
+ echo '</div>';
+ //div za nastavitve obmocja - konec
+
+ echo '</fieldset>';
+ //fieldset Obmocja - konec
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.VprasanjeInline.php b/admin/survey/classes/class.VprasanjeInline.php
new file mode 100644
index 0000000..660a22f
--- /dev/null
+++ b/admin/survey/classes/class.VprasanjeInline.php
@@ -0,0 +1,688 @@
+<?php
+
+/**
+*
+* Inline nacin urejanja vprasanja
+*
+*/
+
+class VprasanjeInline {
+
+ var $anketa; // trenutna anketa
+ var $spremenljivka; // spremenljivka ki jo urejamo
+
+ var $db_table = '';
+ var $expanded = 0;
+
+ /**
+ * konstruktor
+ *
+ * @param mixed $anketa
+ * @return Vprasanje
+ */
+ function __construct ($anketa = 0) {
+
+ if (isset ($_GET['anketa']))
+ $this->anketa = $_GET['anketa'];
+ elseif (isset ($_POST['anketa']))
+ $this->anketa = $_POST['anketa'];
+ elseif ($anketa != 0)
+ $this->anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit($this->anketa);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('expanded') == 1)
+ $this->expanded = 1;
+ }
+
+
+ /**
+ * pohendla ajax klice za vprasanje
+ *
+ */
+ function ajax () {
+
+ if (isset($_POST['spremenljivka'])) $this->spremenljivka = $_POST['spremenljivka'];
+
+ // genericna resitev za vse nadaljne
+ $ajax = 'ajax_' . $_GET['a'];
+
+ if ( method_exists('VprasanjeInline', $ajax) )
+ $this->$ajax();
+ else
+ echo 'method '.$ajax.' does not exist';
+ }
+
+ function ajax_inline_vrednost_naslov_save () {
+ Common::updateEditStamp();
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+
+ $naslov = $_POST['naslov'];
+ $lang_id = $_POST['lang_id'];
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($naslov, -4) == '<br>') {
+ $naslov = substr($naslov, 0, -4);
+ }
+
+ $vrednost = $_POST['vrednost'];
+ $v = explode('_', $vrednost);
+ $vrednost = $v[0];
+ $vrednost2 = $v[1]; // naslov2 za diferencial
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if ( ! $vrednost > 0 ) return;
+
+ if ($vrednost2 == '2')
+ $_naslov = 'naslov2';
+ else
+ $_naslov = 'naslov';
+
+
+ // Navadno popravljanje (ne prevajanje)
+ if ($lang_id == 0) {
+ $s = sisplet_query("UPDATE srv_vrednost SET $_naslov='$naslov' WHERE id = '$vrednost'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ // Prevajamo za drug jezik
+ else {
+ // Semanticni diferencial posebej obravnavamo (naslov ali naslov2)
+ //if($row['tip'] == 6 && $row['enota'] == 1){
+ if($row['tip'] == 6 && ($row['enota'] == 1 || $row['enota'] == 4)){ //diferencial, one against another
+ // Ce popravljamo naslov2
+ if($vrednost2 == '2'){
+ $s = sisplet_query("INSERT INTO srv_language_vrednost
+ (ank_id, vre_id, lang_id, naslov2) VALUES ('$this->anketa', '$vrednost', '$lang_id', '$naslov')
+ ON DUPLICATE KEY UPDATE naslov2='$naslov'");
+ }
+ else{
+ $s = sisplet_query("INSERT INTO srv_language_vrednost
+ (ank_id, vre_id, lang_id, naslov) VALUES ('$this->anketa', '$vrednost', '$lang_id', '$naslov')
+ ON DUPLICATE KEY UPDATE naslov='$naslov'");
+ }
+ }
+ else{
+ if ($naslov != '')
+ $s = sisplet_query("REPLACE INTO srv_language_vrednost (ank_id, vre_id, lang_id, naslov) VALUES ('$this->anketa', '$vrednost', '$lang_id', '$naslov')");
+ else
+ $s = sisplet_query("DELETE FROM srv_language_vrednost WHERE ank_id='$this->anketa' AND vre_id='$vrednost' AND lang_id='$lang_id'");
+ }
+ }
+
+
+ if ($row['tip'] == 24) {
+ $v = new Vprasanje($this->anketa);
+ $v->repare_grid_multiple($this->spremenljivka);
+ }
+
+ echo mysql_real_unescape_string($naslov);
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_hotspot_vrednost_save () {
+ Common::updateEditStamp();
+
+ $naslov = $_POST['naslov'];
+ $lang_id = $_POST['lang_id'];
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($naslov, -4) == '<br>') {
+ $naslov = substr($naslov, 0, -4);
+ }
+
+ $vrednost = $_POST['vrednost'];
+ $v = explode('_', $vrednost);
+ $vrednost = $v[0];
+ $vrednost2 = $v[1]; // naslov2 za diferencial
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ if ( ! $vrednost > 0 ) return;
+
+ if ($vrednost2 == '2')
+ $_naslov = 'naslov2';
+ else
+ $_naslov = 'naslov';
+
+ if ($lang_id == 0) {
+ //$s = sisplet_query("UPDATE srv_vrednost SET $_naslov='$naslov' WHERE id = '$vrednost'");
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov='$naslov' WHERE id = '$vrednost'");
+ $sR = sisplet_query("UPDATE srv_hotspot_regions SET region_name='$naslov' WHERE vre_id = '$vrednost'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ } else {
+ if ($naslov != '')
+ $s = sisplet_query("REPLACE INTO srv_language_vrednost (ank_id, vre_id, lang_id, naslov) VALUES ('$this->anketa', '$vrednost', '$lang_id', '$naslov')");
+ else
+ $s = sisplet_query("DELETE FROM srv_language_vrednost WHERE ank_id='$this->anketa' AND vre_id='$vrednost' AND lang_id='$lang_id'");
+ }
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ if ($row['tip'] == 24) {
+ $v = new Vprasanje($this->anketa);
+ $v->repare_grid_multiple($this->spremenljivka);
+ }
+
+ echo mysql_real_unescape_string($naslov);
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_grid_naslov_save () {
+ Common::updateEditStamp();
+
+ $naslov = $_POST['naslov'];
+ $lang_id = $_POST['lang_id'];
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ $grid = $_POST['grid'];
+
+ if ($lang_id == 0) {
+ $s = sisplet_query("UPDATE srv_grid SET naslov='$naslov' WHERE id='$grid' AND spr_id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // dvojni gridi
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ if ($row['enota'] == 3) {
+ $sql = sisplet_query("SELECT id, spr_id FROM srv_grid WHERE spr_id='$this->spremenljivka' AND other!=0 AND part=1");
+ $s = sisplet_query("UPDATE srv_grid SET naslov='$naslov' WHERE id='".($grid + $row['grids'] + mysqli_num_rows($sql))."' AND spr_id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ else {
+
+ //if ($naslov != '')
+ $s = sisplet_query("INSERT INTO srv_language_grid
+ (ank_id, spr_id, grd_id, lang_id, naslov)
+ VALUES
+ ('$this->anketa', '$this->spremenljivka', '$grid', '$lang_id', '$naslov')
+ ON DUPLICATE KEY UPDATE naslov='$naslov'");
+ //else
+ // $s = sisplet_query("DELETE FROM srv_language_grid WHERE ank_id='$this->anketa' AND spr_id='$this->spremenljivka' AND grd_id='$grid' AND lang_id='$lang_id'");*/
+ }
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_grid_variable_save () {
+ Common::updateEditStamp();
+
+ $variable = $_POST['variable'];
+
+ $grid = $_POST['grid'];
+
+ $s = sisplet_query("UPDATE srv_grid SET variable='$variable' WHERE id='$grid' AND spr_id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ /*// dvojni gridi
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ if ($row['enota'] == 3) {
+ $s = sisplet_query("UPDATE srv_grid SET naslov='$naslov' WHERE id='".($grid + $row['grids'])."' AND spr_id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }*/
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_grid_subtitle_save () {
+ Common::updateEditStamp();
+
+ $subtitle = $_POST['subtitle'];
+ $value = $_POST['value'];
+ $lang_id = $_POST['lang_id'];
+ $grid_id = $_POST['grid_id'];
+
+ $purifier = New Purifier();
+ $subtitle = $purifier->purify_DB($subtitle);
+
+
+ // Navadno popravljanje (ne prevajanje)
+ if ($lang_id == 0) {
+ $s = sisplet_query("UPDATE srv_spremenljivka SET $subtitle='$value' WHERE id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+ // Prevajamo podnaslove za drug jezik
+ else{
+ //if ($value != '')
+ $s = sisplet_query("INSERT INTO srv_language_grid
+ (ank_id, spr_id, grd_id, lang_id, podnaslov)
+ VALUES
+ ('$this->anketa', '$this->spremenljivka', '$grid_id', '$lang_id', '$value')
+ ON DUPLICATE KEY UPDATE podnaslov='$value'");
+ /*else
+ $s = sisplet_query("DELETE FROM srv_language_grid WHERE ank_id='$this->anketa' AND spr_id='$this->spremenljivka' AND grd_id='$grid_id' AND lang_id='$lang_id'");*/
+ }
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_vrednost_new () {
+ Common::getInstance()->Init($this->anketa);
+ Common::getInstance()->updateEditStamp();
+
+ global $lang;
+
+ $naslov = '';
+ //$other = $_POST['other'];
+ //$mv = $_POST['mv'];
+
+ $v = new Vprasanje($this->anketa);
+ $v->spremenljivka = $this->spremenljivka;
+ $vrednost = $v->vrednost_new($naslov /*, $other, $mv*/);
+
+ Common::prestevilci($this->spremenljivka);
+
+ //$b = new Branching($this->anketa);
+ //$b->vprasanje($this->spremenljivka);
+
+ echo $vrednost;
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_vrednost_vrstni_red () {
+ Common::updateEditStamp();
+
+ $sortable = $_POST['sortable'];
+ print_r($sortable);
+ $exploded = explode('&', $sortable);
+
+ $i = 1;
+ foreach ($exploded AS $key) {
+ $key = str_replace('variabla_', '', $key);
+ $explode = explode('[]=', $key);
+ $sql = sisplet_query("UPDATE srv_vrednost SET vrstni_red = '$i' WHERE id = '$explode[1]'");
+ if (!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $i++;
+ }
+
+ Common::prestevilci($this->spremenljivka);
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_info_save() {
+ Common::updateEditStamp();
+
+ $info = $_POST['info'];
+ $lang_id = $_POST['lang_id'];
+
+ // Po�istimo opombo
+ $info = trim(strip_tags($info));
+
+ if ($lang_id == 0) {
+ sisplet_query("UPDATE srv_spremenljivka SET info='$info' WHERE id = '$this->spremenljivka'");
+ }
+ else {
+ //if ($info != '')
+ sisplet_query("INSERT INTO srv_language_spremenljivka (ank_id, spr_id, lang_id, info) VALUES ('$this->anketa', '$this->spremenljivka', '$lang_id', '$info') ON DUPLICATE KEY UPDATE info='$info'");
+ //else
+ // sisplet_query("DELETE FROM srv_language_spremenljivka WHERE ank_id='$this->anketa' AND spr_id='$this->spremenljivka' AND lang_id='$lang_id'");
+ }
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_variable_save() {
+ Common::updateEditStamp();
+
+ $variable = $_POST['variable'];
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ if ( in_array($row['variable'], array('email','telefon','ime','priimek','naziv','drugo')) && $row['sistem']==1 ) {
+
+ // tukaj ne pustimo spremeniti
+
+ } else {
+ if ($variable != $row['variable'])
+ sisplet_query("UPDATE srv_spremenljivka SET variable='$variable', variable_custom='1' WHERE id = '$this->spremenljivka'");
+ }
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_vrednost_variable_save () {
+ Common::updateEditStamp();
+
+ $variable = $_POST['variable'];
+ $vre_id = $_POST['vre_id'];
+
+ $sql = sisplet_query("SELECT variable FROM srv_vrednost WHERE id = '$vre_id'");
+ $row = mysqli_fetch_array($sql);
+
+ if ($row['variable'] != $variable) {
+ sisplet_query("UPDATE srv_vrednost SET variable='$variable', variable_custom='1' WHERE id = '$vre_id'");
+ }
+ }
+
+ function ajax_inline_label_save () {
+ Common::updateEditStamp();
+
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $purifier = New Purifier();
+ $Label = $purifier->purify_DB($_POST['label']);
+ //$Label = $_POST['label'];
+ $TipLabele = $_POST['tiplabele'];
+ //error_log("TipLabele: ".$TipLabele);
+ $lang_id = $_POST['lang_id'];
+
+ $TrenutnaLabela = ($spremenljivkaParams->get($TipLabele) ? $spremenljivkaParams->get($TipLabele) : '');
+ //error_log("TrenutnaLabela: ".$TrenutnaLabela);
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($Label, -4) == '<br>') {
+ $Label = substr($Label, 0, -4);
+ }
+
+ if ($lang_id == 0) {
+ $sql = sisplet_query("SELECT params FROM srv_spremenljivka WHERE id = '$this->spremenljivka'"); //poberi trenutne params iz baze
+ $row = mysqli_fetch_array($sql);
+
+ if($TrenutnaLabela != ''){
+ $TipLabelepart1 = strchr($row['params'], $TipLabele."="); //iz stringa, kjer so vsi params izlusci le string od TipLabele dalje
+ //print_r (explode("\n",$row['params'])); //explode(separator,string,limit)
+ $newTipLabele = $TipLabele.'='.$Label; //formiraj nov tip labele z labelo
+ $explodedparams = explode("\n",$row['params']); //spremeni string v array
+ for($i=0; $i<=sizeof($explodedparams); $i++){ //za vse elemente array-a
+ //echo 'Sem v for zanki';
+ if((strstr($explodedparams[$i], $TipLabele.'=') != '')){ //ce element array-a vsebuje besedilo z ustreznim tipom labele //strstr(string,search,before_search)
+ //echo 'Smo dobili string na indeksu: '.$i;
+ $indeks = $i; //zabele�i indeks
+ //echo 'Indeks1: '.$indeks;
+ //$explodedparams[$i] = $newTipLabele; //povozi ustrezen element array-a z novim tipom labele
+ //echo 'Exploded: '.$explodedparams[$i];
+ }
+ }
+
+ //echo 'Indeks2: '.$indeks;
+ $explodedparams[$indeks] = $newTipLabele; //povozi ustrezen element array-a z novim tipom labele
+ //print_r ($explodedparams);
+ $newparams = implode("\n",$explodedparams); //zdruzi array ponovno v string
+ //echo 'New params: '.$newparams;
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params = '$newparams' WHERE id='$this->spremenljivka'"); //posodobi params
+ }
+ elseif ($TrenutnaLabela == ''){
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params = CONCAT( srv_spremenljivka.params , '\n$TipLabele=$Label ') WHERE id='$this->spremenljivka'"); //k obstoje�im params dodaj �e naslednje
+ //echo $Label;
+ //print_r (explode("\n",$row['params'])); //explode(separator,string,limit)
+ }
+ }else{
+ if($TipLabele == 'MinLabel'){
+ $grid = 1;
+ }elseif($TipLabele =='MaxLabel'){
+ $grid = 2;
+ }else{
+ $grid = 0;
+ }
+
+ if ($TrenutnaLabela != ''){
+ $sString = "REPLACE INTO srv_language_slider (ank_id, spr_id, label_id, lang_id, label) VALUES ('$this->anketa', '$this->spremenljivka', '$grid', '$lang_id', '$Label')";
+ }else{
+ $sString = "DELETE FROM srv_language_slider WHERE ank_id='$this->anketa' AND spr_id='$this->spremenljivka' AND label_id='$grid' AND lang_id='$lang_id'";
+ }
+
+ if($grid == 0){ //ce je prevod custom opisnih label
+ $sString = "REPLACE INTO srv_language_slider (ank_id, spr_id, label_id, lang_id, label) VALUES ('$this->anketa', '$this->spremenljivka', '$grid', '$lang_id', '$Label')";
+ }
+ //error_log($sString);
+ $s = sisplet_query($sString);
+ }
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ Vprasanje::vprasanje_tracking();
+
+ }
+
+ function ajax_inline_nadnaslov_save () {
+ Common::updateEditStamp();
+
+ $anketa = $_POST['anketa'];
+ $naslov = $_POST['label'];
+ $lang_id = $_POST['lang_id'];
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ $grid = $_POST['grid'];
+
+ if ($lang_id != 0) {
+ if ($naslov != ''){
+ $s = sisplet_query("REPLACE INTO srv_language_grid (ank_id, spr_id, grd_id, lang_id, naslov) VALUES ('$anketa', '$this->spremenljivka', '$grid', '$lang_id', '$naslov')");
+ //$s = sisplet_query("INSERT INTO srv_language_grid (ank_id, spr_id, grd_id, lang_id, naslov) VALUES ('$anketa', '$this->spremenljivka', '$grid', '$lang_id', '$naslov')");
+ }
+ else{
+ $s = sisplet_query("DELETE FROM srv_language_grid WHERE ank_id='$anketa' AND spr_id='$this->spremenljivka' AND grd_id='$grid' AND lang_id='$lang_id'");
+ }
+
+ }elseif($lang_id == 0){
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $Label = $_POST['label'];
+ $TipLabele = $_POST['tiplabele'];
+
+ $TrenutnaLabela = ($spremenljivkaParams->get($TipLabele) ? $spremenljivkaParams->get($TipLabele) : '');
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($Label, -4) == '<br>') {
+ $Label = substr($Label, 0, -4);
+ }
+
+
+ $sql = sisplet_query("SELECT params FROM srv_spremenljivka WHERE id = '$this->spremenljivka'"); //poberi trenutne params iz baze
+ $row = mysqli_fetch_array($sql);
+
+
+ if($TrenutnaLabela != ''){
+ //echo "Update labele";
+ $TipLabelepart1 = strchr($row['params'], $TipLabele."="); //iz stringa, kjer so vsi params izlusci le string od TipLabele dalje
+ //print_r (explode("\n",$row['params'])); //explode(separator,string,limit)
+ $newTipLabele = $TipLabele.'='.$Label; //formiraj nov tip labele z labelo
+ $explodedparams = explode("\n",$row['params']); //spremeni string v array
+ for($i=0; $i<=sizeof($explodedparams); $i++){ //za vse elemente array-a
+ //echo 'Sem v for zanki';
+ if((strstr($explodedparams[$i], $TipLabele.'=') != '')){ //ce element array-a vsebuje besedilo z ustreznim tipom labele //strstr(string,search,before_search)
+ //echo 'Smo dobili string na indeksu: '.$i;
+ $indeks = $i; //zabele�i indeks
+ //echo 'Indeks1: '.$indeks;
+ //$explodedparams[$i] = $newTipLabele; //povozi ustrezen element array-a z novim tipom labele
+ //echo 'Exploded: '.$explodedparams[$i];
+ }
+ }
+
+ //echo 'Indeks2: '.$indeks;
+ $explodedparams[$indeks] = $newTipLabele; //povozi ustrezen element array-a z novim tipom labele
+ //print_r ($explodedparams);
+ $newparams = implode("\n",$explodedparams); //zdruzi array ponovno v string
+ //echo 'New params: '.$newparams;
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params = '$newparams' WHERE id='$this->spremenljivka'"); //posodobi params
+ }
+ elseif ($TrenutnaLabela == ''){
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params = CONCAT( srv_spremenljivka.params , '\n$TipLabele=$Label ') WHERE id='$this->spremenljivka'"); //k obstoje�im params dodaj �e naslednje
+ //echo $Label;
+ //print_r (explode("\n",$row['params'])); //explode(separator,string,limit)
+ //echo "Trenutna labela je prazna";
+ }
+ }
+
+/* error_log($anketa);
+ error_log($grid);
+ error_log($naslov); */
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+
+ function ajax_inline_labele_podrocij_save () {
+ Common::updateEditStamp();
+
+ #############################
+ $anketa = $_POST['anketa'];
+ $naslov = $_POST['naslov'];
+ $lang_id = $_POST['lang_id'];
+
+ $purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);
+
+ $grid = $_POST['grid'];
+
+ ############################
+
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $Label = $_POST['label'];
+ $TipLabele = $_POST['tiplabele'];
+
+ $TrenutnaLabela = ($spremenljivkaParams->get($TipLabele) ? $spremenljivkaParams->get($TipLabele) : '');
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($Label, -4) == '<br>') {
+ $Label = substr($Label, 0, -4);
+ }
+
+
+ $sql = sisplet_query("SELECT params FROM srv_spremenljivka WHERE id = '$this->spremenljivka'"); //poberi trenutne params iz baze
+ $row = mysqli_fetch_array($sql);
+
+
+ if($TrenutnaLabela != ''){
+ //echo "Update labele";
+ $TipLabelepart1 = strchr($row['params'], $TipLabele."="); //iz stringa, kjer so vsi params izlusci le string od TipLabele dalje
+ //print_r (explode("\n",$row['params'])); //explode(separator,string,limit)
+ $newTipLabele = $TipLabele.'='.$Label; //formiraj nov tip labele z labelo
+ $explodedparams = explode("\n",$row['params']); //spremeni string v array
+ for($i=0; $i<=sizeof($explodedparams); $i++){ //za vse elemente array-a
+ //echo 'Sem v for zanki';
+ if((strstr($explodedparams[$i], $TipLabele.'=') != '')){ //ce element array-a vsebuje besedilo z ustreznim tipom labele //strstr(string,search,before_search)
+ //echo 'Smo dobili string na indeksu: '.$i;
+ $indeks = $i; //zabele�i indeks
+ //echo 'Indeks1: '.$indeks;
+ //$explodedparams[$i] = $newTipLabele; //povozi ustrezen element array-a z novim tipom labele
+ //echo 'Exploded: '.$explodedparams[$i];
+ }
+ }
+
+ //echo 'Indeks2: '.$indeks;
+ $explodedparams[$indeks] = $newTipLabele; //povozi ustrezen element array-a z novim tipom labele
+ //print_r ($explodedparams);
+ $newparams = implode("\n",$explodedparams); //zdruzi array ponovno v string
+ //echo 'New params: '.$newparams;
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params = '$newparams' WHERE id='$this->spremenljivka'"); //posodobi params
+ }
+ elseif ($TrenutnaLabela == ''){
+ $s = sisplet_query("UPDATE srv_spremenljivka SET params = CONCAT( srv_spremenljivka.params , '\n$TipLabele=$Label ') WHERE id='$this->spremenljivka'"); //k obstoje�im params dodaj �e naslednje
+ //echo $Label;
+ //print_r (explode("\n",$row['params'])); //explode(separator,string,limit)
+ //echo "Trenutna labela je prazna";
+ }
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ Vprasanje::vprasanje_tracking();
+
+ }
+
+
+ function ajax_inline_opisne_labele_save () {
+ Common::updateEditStamp();
+
+ $row = Cache::srv_spremenljivka($this->spremenljivka);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+
+ $Label = $_POST['label'];
+ $TipLabele = $_POST['tiplabele'];
+
+ $TrenutnaLabela = ($spremenljivkaParams->get($TipLabele) ? $spremenljivkaParams->get($TipLabele) : '');
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($Label, -4) == '<br>') {
+ $Label = substr($Label, 0, -4);
+ }
+
+/* error_log("Label: ".$Label);
+ error_log("TipLabele: ".$TipLabele);
+ error_log("spr: ".$this->spremenljivka); */
+
+ $spremenljivkaParams->set($TipLabele, $Label);
+
+
+ $params = $spremenljivkaParams->getString();
+ $update .= " params = '$params' ";
+
+ $sqlString = "UPDATE srv_spremenljivka SET $update WHERE id = '$this->spremenljivka'";
+ //error_log($sqlString);
+ sisplet_query($sqlString);
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ Vprasanje::vprasanje_tracking();
+
+ }
+
+ function ajax_inline_variabla_vsota_save () {
+ Common::updateEditStamp();
+
+ $vsota = $_POST['inline_variabla_vsota'];
+
+ // firefox na koncu vsakega contenteditable doda <br>, ki ga tukaj odstranimo
+ if (substr($vsota, -4) == '<br>') {
+ $vsota = substr($vsota, 0, -4);
+ }
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET vsota='$vsota' WHERE id='$this->spremenljivka'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ Vprasanje::vprasanje_tracking();
+ }
+
+ function ajax_inline_hotspot_delete_region () {
+ Common::updateEditStamp();
+
+ $spr_id = $_POST['spr_id'];
+ $vre_id = $_POST['vre_id'];
+ $region_index = $_POST['region_index'];
+
+ //zbrisi podatke o obstojecem obmocju
+ $s = sisplet_query("DELETE FROM srv_hotspot_regions WHERE spr_id='$spr_id' AND region_index='$region_index'");
+ $v = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$spr_id' AND id='$vre_id'");
+ Common::repareVrednost($spr_id);
+ }
+
+ function ajax_inline_hotspot_update_region () {
+ Common::updateEditStamp();
+
+ $spr_id = $_POST['spr_id'];
+ //$vre_id = $_POST['vre_id'];
+
+ //posodobi podatke o obstojecih obmocjih po brisanju obmocja
+ $sqlv = sisplet_query("SELECT id, variable, vrstni_red FROM srv_vrednost WHERE spr_id = $spr_id");
+ while($rowv = mysqli_fetch_array($sqlv)){
+ $vre_id_V = $rowv['id'];
+ $variable = $rowv['variable'];
+ $vrstni_red = $rowv['vrstni_red'];
+ //echo $variable;
+ $sqlR = sisplet_query("UPDATE srv_hotspot_regions SET variable = '$variable', vrstni_red = '$vrstni_red' WHERE spr_id='$spr_id' AND vre_id = $vre_id_V");
+ }
+
+ //$s = sisplet_query("DELETE FROM srv_hotspot_regions WHERE spr_id='$spr_id' AND region_index='$region_index'");
+ //$v = sisplet_query("DELETE FROM srv_vrednost WHERE spr_id='$spr_id' AND id='$vre_id'");
+ }
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/class.params.php b/admin/survey/classes/class.params.php
new file mode 100644
index 0000000..49344aa
--- /dev/null
+++ b/admin/survey/classes/class.params.php
@@ -0,0 +1,268 @@
+<?php
+/**
+ * Created on 16.11.2008
+ *
+ * @author: Gorazd Veselic
+ */
+class enkaParameters
+{
+ /** @var object */
+ var $_params = null;
+ /**
+ * Constructor
+ * @param string The raw parms text
+ */
+ function __construct($text)
+ {
+ $this->_params = $this->parse($text);
+ }
+ /**
+ * Parsa tekstovni string
+ * @param mixed The ini string or array of lines
+ * @param boolean add an associative index for each section [in brackets]
+ * @return object
+ */
+ function parse($txt, $process_sections = false, $asArray = false)
+ {
+ if (is_string($txt))
+ {
+ $lines = explode("\n", $txt);
+ }
+ else
+ if (is_array($txt))
+ {
+ $lines = $txt;
+ }
+ else
+ {
+ $lines = array ();
+ }
+ $obj = $asArray ? array () : new stdClass();
+ $sec_name = '';
+ $unparsed = 0;
+ if (!$lines)
+ {
+ return $obj;
+ }
+ foreach ($lines as $line)
+ {
+ // ignore comments
+ if ($line && $line[0] == ';')
+ {
+ continue;
+ }
+ $line = trim($line);
+ if ($line == '')
+ {
+ continue;
+ }
+ if ($line && $line[0] == '[' && $line[strlen($line) - 1] == ']')
+ {
+ $sec_name = substr($line, 1, strlen($line) - 2);
+ if ($process_sections)
+ {
+ if ($asArray)
+ {
+ $obj[$sec_name] = array ();
+ }
+ else
+ {
+ $obj-> $sec_name = new stdClass();
+ }
+ }
+ }
+ else
+ {
+ if ($pos = strpos($line, '='))
+ {
+ $property = trim(substr($line, 0, $pos));
+ if (substr($property, 0, 1) == '"' && substr($property, -1) == '"')
+ {
+ $property = stripcslashes(substr($property, 1, count($property) - 2));
+ }
+ $value = trim(substr($line, $pos +1));
+ if ($value == 'false')
+ {
+ $value = false;
+ }
+ if ($value == 'true')
+ {
+ $value = true;
+ }
+ if (substr($value, 0, 1) == '"' && substr($value, -1) == '"')
+ {
+ $value = stripcslashes(substr($value, 1, count($value) - 2));
+ }
+ if ($process_sections)
+ {
+ $value = str_replace('\n', "\n", $value);
+ if ($sec_name != '')
+ {
+ if ($asArray)
+ {
+ $obj[$sec_name][$property] = $value;
+ }
+ else
+ {
+ $obj-> $sec_name-> $property = $value;
+ }
+ }
+ else
+ {
+ if ($asArray)
+ {
+ $obj[$property] = $value;
+ }
+ else
+ {
+ $obj-> $property = $value;
+ }
+ }
+ }
+ else
+ {
+ $value = str_replace('\n', "\n", $value);
+ if ($asArray)
+ {
+ $obj[$property] = $value;
+ }
+ else
+ {
+ $obj-> $property = $value;
+ }
+ }
+ }
+ else
+ {
+ if ($line && trim($line[0]) == ';')
+ {
+ continue;
+ }
+ if ($process_sections)
+ {
+ $property = '__invalid' . $unparsed++ . '__';
+ if ($process_sections)
+ {
+ if ($sec_name != '')
+ {
+ if ($asArray)
+ {
+ $obj[$sec_name][$property] = trim($line);
+ }
+ else
+ {
+ $obj-> $sec_name-> $property = trim($line);
+ }
+ }
+ else
+ {
+ if ($asArray)
+ {
+ $obj[$property] = trim($line);
+ }
+ else
+ {
+ $obj-> $property = trim($line);
+ }
+ }
+ }
+ else
+ {
+ if ($asArray)
+ {
+ $obj[$property] = trim($line);
+ }
+ else
+ {
+ $obj-> $property = trim($line);
+ }
+ }
+ }
+ }
+ }
+ }
+ return $obj;
+ }
+ /**
+ * Vrne params array
+ * @return object
+ */
+ function toObject()
+ {
+ return $this->_params;
+ }
+ /**
+ * Vrne array parametrov
+ * @return object
+ */
+ function toArray()
+ {
+ return enkaObjectToArray($this->_params);
+ }
+ /** Doda ali ponastavi posamezen parameter
+ * @param string The name of the param
+ * @param string The value of the parameter
+ * @return string The set value
+ */
+ function set($key, $value = '')
+ {
+ $this->_params-> $key = $value;
+ return $value;
+ }
+ /**
+ * Nastavi privzeto vrednost če le ta ni določena
+ * @param string The name of the param
+ * @param string The value of the parameter
+ * @return string The set value
+ */
+ function def($key, $value = '')
+ {
+ return $this->set($key, $this->get($key, $value));
+ }
+ /** Vrne vrednost posameznega parametra
+ * @param string The name of the param
+ * @param mixed The default value if not found
+ * @return string
+ */
+ function get($key, $default = '')
+ {
+ if (isset ($this->_params-> $key))
+ {
+ return $this->_params-> $key === '' ? $default : $this->_params-> $key;
+ }
+ else
+ {
+ return $default;
+ }
+ }
+ /** Vrne parametre v tekstovni obliki primeni za hrambo v sql tabeli
+ * @return string
+ */
+ function getString()
+ {
+ $txt = array ();
+ foreach (get_object_vars($this->_params) as $k => $v)
+ {
+ $txt[] = "$k=$v";
+ }
+ $saveparams = implode("\n", $txt);
+ return $saveparams;
+ }
+}
+function enkaObjectToArray($p_obj)
+{
+ $retarray = null;
+ if (is_object($p_obj))
+ {
+ $retarray = array ();
+ foreach (get_object_vars($p_obj) as $k => $v)
+ {
+ if (is_object($v))
+ $retarray[$k] = enkaObjectToArray($v);
+ else
+ $retarray[$k] = $v;
+ }
+ }
+ return $retarray;
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/Purifier.php b/admin/survey/classes/htmlpurifier-4.3.0/Purifier.php
new file mode 100644
index 0000000..b81137e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/Purifier.php
@@ -0,0 +1,94 @@
+<?php
+
+/**
+*
+* Pripravi default klice za HTML Purifier
+*
+*/
+class Purifier {
+
+ var $purifier = null;
+
+ /**
+ * v konstruktorju nastavimo lastno konfiguracijo
+ *
+ */
+ function __construct () {
+
+ $config = HTMLPurifier_Config::createDefault();
+ $config->set('HTML.DefinitionID', '1ka anketa');
+ $config->set('HTML.DefinitionRev', 6);
+ //$config->set('Cache.DefinitionImpl', null); // use when developing
+ if ($def = $config->maybeGetRawHTMLDefinition()) {
+ $def->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top,link');
+
+ $iframe = $def->addElement('iframe', 'Block', 'Flow', 'Common',
+ array(
+ 'src*' => 'URI',
+ 'height' => 'Length',
+ 'width' => 'Length',
+ 'frameborder' => 'Number'
+ )
+ );
+ $iframe->excludes = array('iframe' => true);
+
+ $object = $def->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', 'Common',
+ array(
+ 'archive' => 'URI',
+ 'classid' => 'URI',
+ 'codebase' => 'URI',
+ 'codetype' => 'Text',
+ 'data' => 'URI',
+ 'declare' => 'Bool#declare',
+ 'height' => 'Length',
+ 'name' => 'CDATA',
+ 'standby' => 'Text',
+ 'tabindex' => 'Number',
+ 'type' => 'ContentType',
+ 'width' => 'Length'
+ )
+ );
+
+ $param = $def->addElement('param', false, 'Empty', false,
+ array(
+ 'id' => 'ID',
+ 'name*' => 'Text',
+ 'type' => 'Text',
+ 'value' => 'Text',
+ 'valuetype' => 'Enum#data,ref,object'
+ )
+ );
+
+ }
+ $this->purifier = new HTMLPurifier($config);
+
+ }
+
+ /**
+ * Navaden purify, ce se bo kje rabil
+ *
+ */
+ function purify ( $string ) {
+
+ if ($this->purifier == null) return;
+
+ return $this->purifier->purify($string);
+
+ }
+
+ /**
+ * Ocistimo string in ga pripravimo za insert v bazo
+ *
+ */
+ function purify_DB ( $string ) {
+
+ if ($this->purifier == null) return;
+
+ // tukaj moramo najprej stripat slashe, drugace purify ne dela
+ return mysqli_real_escape_string($GLOBALS['connect_db'], $this->purifier->purify(mysql_real_unescape_string($string)) );
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.auto.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.auto.php
new file mode 100644
index 0000000..c810e87
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.auto.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * This is a stub include that automatically configures the include path.
+ */
+
+set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path() );
+require_once 'HTMLPurifier/Bootstrap.php';
+require_once 'HTMLPurifier.autoload.php';
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.autoload.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.autoload.php
new file mode 100644
index 0000000..0dca806
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.autoload.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * @file
+ * Convenience file that registers autoload handler for HTML Purifier.
+ * It also does some sanity checks.
+ */
+
+//if (function_exists('spl_autoload_register') && function_exists('spl_autoload_unregister')) {
+ // We need unregister for our pre-registering functionality
+ HTMLPurifier_Bootstrap::registerAutoload();
+ if (function_exists('__autoload')) {
+ // Be polite and ensure that userland autoload gets retained
+ spl_autoload_register('__autoload');
+ }
+/*} elseif (!function_exists('__autoload')) {
+ function __autoload($class) {
+ return HTMLPurifier_Bootstrap::autoload($class);
+ }
+}*/
+
+if (ini_get('zend.ze1_compatibility_mode')) {
+ trigger_error("HTML Purifier is not compatible with zend.ze1_compatibility_mode; please turn it off", E_USER_ERROR);
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.func.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.func.php
new file mode 100644
index 0000000..529a299
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.func.php
@@ -0,0 +1,23 @@
+<?php
+
+/**
+ * @file
+ * Defines a function wrapper for HTML Purifier for quick use.
+ * @note ''HTMLPurifier()'' is NOT the same as ''new HTMLPurifier()''
+ */
+
+/**
+ * Purify HTML.
+ * @param $html String HTML to purify
+ * @param $config Configuration to use, can be any value accepted by
+ * HTMLPurifier_Config::create()
+ */
+function HTMLPurifier($html, $config = null) {
+ static $purifier = false;
+ if (!$purifier) {
+ $purifier = new HTMLPurifier();
+ }
+ return $purifier->purify($html, $config);
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.includes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.includes.php
new file mode 100644
index 0000000..989c3fd
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.includes.php
@@ -0,0 +1,214 @@
+<?php
+
+/**
+ * @file
+ * This file was auto-generated by generate-includes.php and includes all of
+ * the core files required by HTML Purifier. Use this if performance is a
+ * primary concern and you are using an opcode cache. PLEASE DO NOT EDIT THIS
+ * FILE, changes will be overwritten the next time the script is run.
+ *
+ * @version 4.3.0
+ *
+ * @warning
+ * You must *not* include any other HTML Purifier files before this file,
+ * because 'require' not 'require_once' is used.
+ *
+ * @warning
+ * This file requires that the include path contains the HTML Purifier
+ * library directory; this is not auto-set.
+ */
+
+require 'HTMLPurifier.php';
+require 'HTMLPurifier/AttrCollections.php';
+require 'HTMLPurifier/AttrDef.php';
+require 'HTMLPurifier/AttrTransform.php';
+require 'HTMLPurifier/AttrTypes.php';
+require 'HTMLPurifier/AttrValidator.php';
+require 'HTMLPurifier/Bootstrap.php';
+require 'HTMLPurifier/Definition.php';
+require 'HTMLPurifier/CSSDefinition.php';
+require 'HTMLPurifier/ChildDef.php';
+require 'HTMLPurifier/Config.php';
+require 'HTMLPurifier/ConfigSchema.php';
+require 'HTMLPurifier/ContentSets.php';
+require 'HTMLPurifier/Context.php';
+require 'HTMLPurifier/DefinitionCache.php';
+require 'HTMLPurifier/DefinitionCacheFactory.php';
+require 'HTMLPurifier/Doctype.php';
+require 'HTMLPurifier/DoctypeRegistry.php';
+require 'HTMLPurifier/ElementDef.php';
+require 'HTMLPurifier/Encoder.php';
+require 'HTMLPurifier/EntityLookup.php';
+require 'HTMLPurifier/EntityParser.php';
+require 'HTMLPurifier/ErrorCollector.php';
+require 'HTMLPurifier/ErrorStruct.php';
+require 'HTMLPurifier/Exception.php';
+require 'HTMLPurifier/Filter.php';
+require 'HTMLPurifier/Generator.php';
+require 'HTMLPurifier/HTMLDefinition.php';
+require 'HTMLPurifier/HTMLModule.php';
+require 'HTMLPurifier/HTMLModuleManager.php';
+require 'HTMLPurifier/IDAccumulator.php';
+require 'HTMLPurifier/Injector.php';
+require 'HTMLPurifier/Language.php';
+require 'HTMLPurifier/LanguageFactory.php';
+require 'HTMLPurifier/Length.php';
+require 'HTMLPurifier/Lexer.php';
+require 'HTMLPurifier/PercentEncoder.php';
+require 'HTMLPurifier/PropertyList.php';
+require 'HTMLPurifier/PropertyListIterator.php';
+require 'HTMLPurifier/Strategy.php';
+require 'HTMLPurifier/StringHash.php';
+require 'HTMLPurifier/StringHashParser.php';
+require 'HTMLPurifier/TagTransform.php';
+require 'HTMLPurifier/Token.php';
+require 'HTMLPurifier/TokenFactory.php';
+require 'HTMLPurifier/URI.php';
+require 'HTMLPurifier/URIDefinition.php';
+require 'HTMLPurifier/URIFilter.php';
+require 'HTMLPurifier/URIParser.php';
+require 'HTMLPurifier/URIScheme.php';
+require 'HTMLPurifier/URISchemeRegistry.php';
+require 'HTMLPurifier/UnitConverter.php';
+require 'HTMLPurifier/VarParser.php';
+require 'HTMLPurifier/VarParserException.php';
+require 'HTMLPurifier/AttrDef/CSS.php';
+require 'HTMLPurifier/AttrDef/Enum.php';
+require 'HTMLPurifier/AttrDef/Integer.php';
+require 'HTMLPurifier/AttrDef/Lang.php';
+require 'HTMLPurifier/AttrDef/Switch.php';
+require 'HTMLPurifier/AttrDef/Text.php';
+require 'HTMLPurifier/AttrDef/URI.php';
+require 'HTMLPurifier/AttrDef/CSS/Number.php';
+require 'HTMLPurifier/AttrDef/CSS/AlphaValue.php';
+require 'HTMLPurifier/AttrDef/CSS/Background.php';
+require 'HTMLPurifier/AttrDef/CSS/BackgroundPosition.php';
+require 'HTMLPurifier/AttrDef/CSS/Border.php';
+require 'HTMLPurifier/AttrDef/CSS/Color.php';
+require 'HTMLPurifier/AttrDef/CSS/Composite.php';
+require 'HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php';
+require 'HTMLPurifier/AttrDef/CSS/Filter.php';
+require 'HTMLPurifier/AttrDef/CSS/Font.php';
+require 'HTMLPurifier/AttrDef/CSS/FontFamily.php';
+require 'HTMLPurifier/AttrDef/CSS/ImportantDecorator.php';
+require 'HTMLPurifier/AttrDef/CSS/Length.php';
+require 'HTMLPurifier/AttrDef/CSS/ListStyle.php';
+require 'HTMLPurifier/AttrDef/CSS/Multiple.php';
+require 'HTMLPurifier/AttrDef/CSS/Percentage.php';
+require 'HTMLPurifier/AttrDef/CSS/TextDecoration.php';
+require 'HTMLPurifier/AttrDef/CSS/URI.php';
+require 'HTMLPurifier/AttrDef/HTML/Bool.php';
+require 'HTMLPurifier/AttrDef/HTML/Nmtokens.php';
+require 'HTMLPurifier/AttrDef/HTML/Class.php';
+require 'HTMLPurifier/AttrDef/HTML/Color.php';
+require 'HTMLPurifier/AttrDef/HTML/FrameTarget.php';
+require 'HTMLPurifier/AttrDef/HTML/ID.php';
+require 'HTMLPurifier/AttrDef/HTML/Pixels.php';
+require 'HTMLPurifier/AttrDef/HTML/Length.php';
+require 'HTMLPurifier/AttrDef/HTML/LinkTypes.php';
+require 'HTMLPurifier/AttrDef/HTML/MultiLength.php';
+require 'HTMLPurifier/AttrDef/URI/Email.php';
+require 'HTMLPurifier/AttrDef/URI/Host.php';
+require 'HTMLPurifier/AttrDef/URI/IPv4.php';
+require 'HTMLPurifier/AttrDef/URI/IPv6.php';
+require 'HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';
+require 'HTMLPurifier/AttrTransform/Background.php';
+require 'HTMLPurifier/AttrTransform/BdoDir.php';
+require 'HTMLPurifier/AttrTransform/BgColor.php';
+require 'HTMLPurifier/AttrTransform/BoolToCSS.php';
+require 'HTMLPurifier/AttrTransform/Border.php';
+require 'HTMLPurifier/AttrTransform/EnumToCSS.php';
+require 'HTMLPurifier/AttrTransform/ImgRequired.php';
+require 'HTMLPurifier/AttrTransform/ImgSpace.php';
+require 'HTMLPurifier/AttrTransform/Input.php';
+require 'HTMLPurifier/AttrTransform/Lang.php';
+require 'HTMLPurifier/AttrTransform/Length.php';
+require 'HTMLPurifier/AttrTransform/Name.php';
+require 'HTMLPurifier/AttrTransform/NameSync.php';
+require 'HTMLPurifier/AttrTransform/Nofollow.php';
+require 'HTMLPurifier/AttrTransform/SafeEmbed.php';
+require 'HTMLPurifier/AttrTransform/SafeObject.php';
+require 'HTMLPurifier/AttrTransform/SafeParam.php';
+require 'HTMLPurifier/AttrTransform/ScriptRequired.php';
+require 'HTMLPurifier/AttrTransform/Textarea.php';
+require 'HTMLPurifier/ChildDef/Chameleon.php';
+require 'HTMLPurifier/ChildDef/Custom.php';
+require 'HTMLPurifier/ChildDef/Empty.php';
+require 'HTMLPurifier/ChildDef/Required.php';
+require 'HTMLPurifier/ChildDef/Optional.php';
+require 'HTMLPurifier/ChildDef/StrictBlockquote.php';
+require 'HTMLPurifier/ChildDef/Table.php';
+require 'HTMLPurifier/DefinitionCache/Decorator.php';
+require 'HTMLPurifier/DefinitionCache/Null.php';
+require 'HTMLPurifier/DefinitionCache/Serializer.php';
+require 'HTMLPurifier/DefinitionCache/Decorator/Cleanup.php';
+require 'HTMLPurifier/DefinitionCache/Decorator/Memory.php';
+require 'HTMLPurifier/HTMLModule/Bdo.php';
+require 'HTMLPurifier/HTMLModule/CommonAttributes.php';
+require 'HTMLPurifier/HTMLModule/Edit.php';
+require 'HTMLPurifier/HTMLModule/Forms.php';
+require 'HTMLPurifier/HTMLModule/Hypertext.php';
+require 'HTMLPurifier/HTMLModule/Image.php';
+require 'HTMLPurifier/HTMLModule/Legacy.php';
+require 'HTMLPurifier/HTMLModule/List.php';
+require 'HTMLPurifier/HTMLModule/Name.php';
+require 'HTMLPurifier/HTMLModule/Nofollow.php';
+require 'HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';
+require 'HTMLPurifier/HTMLModule/Object.php';
+require 'HTMLPurifier/HTMLModule/Presentation.php';
+require 'HTMLPurifier/HTMLModule/Proprietary.php';
+require 'HTMLPurifier/HTMLModule/Ruby.php';
+require 'HTMLPurifier/HTMLModule/SafeEmbed.php';
+require 'HTMLPurifier/HTMLModule/SafeObject.php';
+require 'HTMLPurifier/HTMLModule/Scripting.php';
+require 'HTMLPurifier/HTMLModule/StyleAttribute.php';
+require 'HTMLPurifier/HTMLModule/Tables.php';
+require 'HTMLPurifier/HTMLModule/Target.php';
+require 'HTMLPurifier/HTMLModule/Text.php';
+require 'HTMLPurifier/HTMLModule/Tidy.php';
+require 'HTMLPurifier/HTMLModule/XMLCommonAttributes.php';
+require 'HTMLPurifier/HTMLModule/Tidy/Name.php';
+require 'HTMLPurifier/HTMLModule/Tidy/Proprietary.php';
+require 'HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php';
+require 'HTMLPurifier/HTMLModule/Tidy/Strict.php';
+require 'HTMLPurifier/HTMLModule/Tidy/Transitional.php';
+require 'HTMLPurifier/HTMLModule/Tidy/XHTML.php';
+require 'HTMLPurifier/Injector/AutoParagraph.php';
+require 'HTMLPurifier/Injector/DisplayLinkURI.php';
+require 'HTMLPurifier/Injector/Linkify.php';
+require 'HTMLPurifier/Injector/PurifierLinkify.php';
+require 'HTMLPurifier/Injector/RemoveEmpty.php';
+require 'HTMLPurifier/Injector/RemoveSpansWithoutAttributes.php';
+require 'HTMLPurifier/Injector/SafeObject.php';
+require 'HTMLPurifier/Lexer/DOMLex.php';
+require 'HTMLPurifier/Lexer/DirectLex.php';
+require 'HTMLPurifier/Strategy/Composite.php';
+require 'HTMLPurifier/Strategy/Core.php';
+require 'HTMLPurifier/Strategy/FixNesting.php';
+require 'HTMLPurifier/Strategy/MakeWellFormed.php';
+require 'HTMLPurifier/Strategy/RemoveForeignElements.php';
+require 'HTMLPurifier/Strategy/ValidateAttributes.php';
+require 'HTMLPurifier/TagTransform/Font.php';
+require 'HTMLPurifier/TagTransform/Simple.php';
+require 'HTMLPurifier/Token/Comment.php';
+require 'HTMLPurifier/Token/Tag.php';
+require 'HTMLPurifier/Token/Empty.php';
+require 'HTMLPurifier/Token/End.php';
+require 'HTMLPurifier/Token/Start.php';
+require 'HTMLPurifier/Token/Text.php';
+require 'HTMLPurifier/URIFilter/DisableExternal.php';
+require 'HTMLPurifier/URIFilter/DisableExternalResources.php';
+require 'HTMLPurifier/URIFilter/DisableResources.php';
+require 'HTMLPurifier/URIFilter/HostBlacklist.php';
+require 'HTMLPurifier/URIFilter/MakeAbsolute.php';
+require 'HTMLPurifier/URIFilter/Munge.php';
+require 'HTMLPurifier/URIScheme/data.php';
+require 'HTMLPurifier/URIScheme/file.php';
+require 'HTMLPurifier/URIScheme/ftp.php';
+require 'HTMLPurifier/URIScheme/http.php';
+require 'HTMLPurifier/URIScheme/https.php';
+require 'HTMLPurifier/URIScheme/mailto.php';
+require 'HTMLPurifier/URIScheme/news.php';
+require 'HTMLPurifier/URIScheme/nntp.php';
+require 'HTMLPurifier/VarParser/Flexible.php';
+require 'HTMLPurifier/VarParser/Native.php';
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.kses.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.kses.php
new file mode 100644
index 0000000..307bd4b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.kses.php
@@ -0,0 +1,30 @@
+<?php
+
+/**
+ * @file
+ * Emulation layer for code that used kses(), substituting in HTML Purifier.
+ */
+
+require_once dirname(__FILE__) . '/HTMLPurifier.auto.php';
+
+function kses($string, $allowed_html, $allowed_protocols = null) {
+ $config = HTMLPurifier_Config::createDefault();
+ $allowed_elements = array();
+ $allowed_attributes = array();
+ foreach ($allowed_html as $element => $attributes) {
+ $allowed_elements[$element] = true;
+ foreach ($attributes as $attribute => $x) {
+ $allowed_attributes["$element.$attribute"] = true;
+ }
+ }
+ $config->set('HTML.AllowedElements', $allowed_elements);
+ $config->set('HTML.AllowedAttributes', $allowed_attributes);
+ $allowed_schemes = array();
+ if ($allowed_protocols !== null) {
+ $config->set('URI.AllowedSchemes', $allowed_protocols);
+ }
+ $purifier = new HTMLPurifier($config);
+ return $purifier->purify($string);
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.path.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.path.php
new file mode 100644
index 0000000..353492a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.path.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * @file
+ * Convenience stub file that adds HTML Purifier's library file to the path
+ * without any other side-effects.
+ */
+
+set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path() );
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.php
new file mode 100644
index 0000000..66d147c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.php
@@ -0,0 +1,237 @@
+<?php
+
+/*! @mainpage
+ *
+ * HTML Purifier is an HTML filter that will take an arbitrary snippet of
+ * HTML and rigorously test, validate and filter it into a version that
+ * is safe for output onto webpages. It achieves this by:
+ *
+ * -# Lexing (parsing into tokens) the document,
+ * -# Executing various strategies on the tokens:
+ * -# Removing all elements not in the whitelist,
+ * -# Making the tokens well-formed,
+ * -# Fixing the nesting of the nodes, and
+ * -# Validating attributes of the nodes; and
+ * -# Generating HTML from the purified tokens.
+ *
+ * However, most users will only need to interface with the HTMLPurifier
+ * and HTMLPurifier_Config.
+ */
+
+/*
+ HTML Purifier 4.3.0 - Standards Compliant HTML Filtering
+ Copyright (C) 2006-2008 Edward Z. Yang
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * Facade that coordinates HTML Purifier's subsystems in order to purify HTML.
+ *
+ * @note There are several points in which configuration can be specified
+ * for HTML Purifier. The precedence of these (from lowest to
+ * highest) is as follows:
+ * -# Instance: new HTMLPurifier($config)
+ * -# Invocation: purify($html, $config)
+ * These configurations are entirely independent of each other and
+ * are *not* merged (this behavior may change in the future).
+ *
+ * @todo We need an easier way to inject strategies using the configuration
+ * object.
+ */
+class HTMLPurifier
+{
+
+ /** Version of HTML Purifier */
+ public $version = '4.3.0';
+
+ /** Constant with version of HTML Purifier */
+ const VERSION = '4.3.0';
+
+ /** Global configuration object */
+ public $config;
+
+ /** Array of extra HTMLPurifier_Filter objects to run on HTML, for backwards compatibility */
+ private $filters = array();
+
+ /** Single instance of HTML Purifier */
+ private static $instance;
+
+ protected $strategy, $generator;
+
+ /**
+ * Resultant HTMLPurifier_Context of last run purification. Is an array
+ * of contexts if the last called method was purifyArray().
+ */
+ public $context;
+
+ /**
+ * Initializes the purifier.
+ * @param $config Optional HTMLPurifier_Config object for all instances of
+ * the purifier, if omitted, a default configuration is
+ * supplied (which can be overridden on a per-use basis).
+ * The parameter can also be any type that
+ * HTMLPurifier_Config::create() supports.
+ */
+ public function __construct($config = null) {
+
+ $this->config = HTMLPurifier_Config::create($config);
+
+ $this->strategy = new HTMLPurifier_Strategy_Core();
+
+ }
+
+ /**
+ * Adds a filter to process the output. First come first serve
+ * @param $filter HTMLPurifier_Filter object
+ */
+ public function addFilter($filter) {
+ trigger_error('HTMLPurifier->addFilter() is deprecated, use configuration directives in the Filter namespace or Filter.Custom', E_USER_WARNING);
+ $this->filters[] = $filter;
+ }
+
+ /**
+ * Filters an HTML snippet/document to be XSS-free and standards-compliant.
+ *
+ * @param $html String of HTML to purify
+ * @param $config HTMLPurifier_Config object for this operation, if omitted,
+ * defaults to the config object specified during this
+ * object's construction. The parameter can also be any type
+ * that HTMLPurifier_Config::create() supports.
+ * @return Purified HTML
+ */
+ public function purify($html, $config = null) {
+
+ // :TODO: make the config merge in, instead of replace
+ $config = $config ? HTMLPurifier_Config::create($config) : $this->config;
+
+ // implementation is partially environment dependant, partially
+ // configuration dependant
+ $lexer = HTMLPurifier_Lexer::create($config);
+
+ $context = new HTMLPurifier_Context();
+
+ // setup HTML generator
+ $this->generator = new HTMLPurifier_Generator($config, $context);
+ $context->register('Generator', $this->generator);
+
+ // set up global context variables
+ if ($config->get('Core.CollectErrors')) {
+ // may get moved out if other facilities use it
+ $language_factory = HTMLPurifier_LanguageFactory::instance();
+ $language = $language_factory->create($config, $context);
+ $context->register('Locale', $language);
+
+ $error_collector = new HTMLPurifier_ErrorCollector($context);
+ $context->register('ErrorCollector', $error_collector);
+ }
+
+ // setup id_accumulator context, necessary due to the fact that
+ // AttrValidator can be called from many places
+ $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
+ $context->register('IDAccumulator', $id_accumulator);
+
+ $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);
+
+ // setup filters
+ $filter_flags = $config->getBatch('Filter');
+ $custom_filters = $filter_flags['Custom'];
+ unset($filter_flags['Custom']);
+ $filters = array();
+ foreach ($filter_flags as $filter => $flag) {
+ if (!$flag) continue;
+ if (strpos($filter, '.') !== false) continue;
+ $class = "HTMLPurifier_Filter_$filter";
+ $filters[] = new $class;
+ }
+ foreach ($custom_filters as $filter) {
+ // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat
+ $filters[] = $filter;
+ }
+ $filters = array_merge($filters, $this->filters);
+ // maybe prepare(), but later
+
+ for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {
+ $html = $filters[$i]->preFilter($html, $config, $context);
+ }
+
+ // purified HTML
+ $html =
+ $this->generator->generateFromTokens(
+ // list of tokens
+ $this->strategy->execute(
+ // list of un-purified tokens
+ $lexer->tokenizeHTML(
+ // un-purified HTML
+ $html, $config, $context
+ ),
+ $config, $context
+ )
+ );
+
+ for ($i = $filter_size - 1; $i >= 0; $i--) {
+ $html = $filters[$i]->postFilter($html, $config, $context);
+ }
+
+ $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);
+ $this->context =& $context;
+ return $html;
+ }
+
+ /**
+ * Filters an array of HTML snippets
+ * @param $config Optional HTMLPurifier_Config object for this operation.
+ * See HTMLPurifier::purify() for more details.
+ * @return Array of purified HTML
+ */
+ public function purifyArray($array_of_html, $config = null) {
+ $context_array = array();
+ foreach ($array_of_html as $key => $html) {
+ $array_of_html[$key] = $this->purify($html, $config);
+ $context_array[$key] = $this->context;
+ }
+ $this->context = $context_array;
+ return $array_of_html;
+ }
+
+ /**
+ * Singleton for enforcing just one HTML Purifier in your system
+ * @param $prototype Optional prototype HTMLPurifier instance to
+ * overload singleton with, or HTMLPurifier_Config
+ * instance to configure the generated version with.
+ */
+ public static function instance($prototype = null) {
+ if (!self::$instance || $prototype) {
+ if ($prototype instanceof HTMLPurifier) {
+ self::$instance = $prototype;
+ } elseif ($prototype) {
+ self::$instance = new HTMLPurifier($prototype);
+ } else {
+ self::$instance = new HTMLPurifier();
+ }
+ }
+ return self::$instance;
+ }
+
+ /**
+ * @note Backwards compatibility, see instance()
+ */
+ public static function getInstance($prototype = null) {
+ return HTMLPurifier::instance($prototype);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.safe-includes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.safe-includes.php
new file mode 100644
index 0000000..d10cbf6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier.safe-includes.php
@@ -0,0 +1,208 @@
+<?php
+
+/**
+ * @file
+ * This file was auto-generated by generate-includes.php and includes all of
+ * the core files required by HTML Purifier. This is a convenience stub that
+ * includes all files using dirname(__FILE__) and require_once. PLEASE DO NOT
+ * EDIT THIS FILE, changes will be overwritten the next time the script is run.
+ *
+ * Changes to include_path are not necessary.
+ */
+
+$__dir = dirname(__FILE__);
+
+require_once $__dir . '/HTMLPurifier.php';
+require_once $__dir . '/HTMLPurifier/AttrCollections.php';
+require_once $__dir . '/HTMLPurifier/AttrDef.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform.php';
+require_once $__dir . '/HTMLPurifier/AttrTypes.php';
+require_once $__dir . '/HTMLPurifier/AttrValidator.php';
+require_once $__dir . '/HTMLPurifier/Bootstrap.php';
+require_once $__dir . '/HTMLPurifier/Definition.php';
+require_once $__dir . '/HTMLPurifier/CSSDefinition.php';
+require_once $__dir . '/HTMLPurifier/ChildDef.php';
+require_once $__dir . '/HTMLPurifier/Config.php';
+require_once $__dir . '/HTMLPurifier/ConfigSchema.php';
+require_once $__dir . '/HTMLPurifier/ContentSets.php';
+require_once $__dir . '/HTMLPurifier/Context.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCacheFactory.php';
+require_once $__dir . '/HTMLPurifier/Doctype.php';
+require_once $__dir . '/HTMLPurifier/DoctypeRegistry.php';
+require_once $__dir . '/HTMLPurifier/ElementDef.php';
+require_once $__dir . '/HTMLPurifier/Encoder.php';
+require_once $__dir . '/HTMLPurifier/EntityLookup.php';
+require_once $__dir . '/HTMLPurifier/EntityParser.php';
+require_once $__dir . '/HTMLPurifier/ErrorCollector.php';
+require_once $__dir . '/HTMLPurifier/ErrorStruct.php';
+require_once $__dir . '/HTMLPurifier/Exception.php';
+require_once $__dir . '/HTMLPurifier/Filter.php';
+require_once $__dir . '/HTMLPurifier/Generator.php';
+require_once $__dir . '/HTMLPurifier/HTMLDefinition.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule.php';
+require_once $__dir . '/HTMLPurifier/HTMLModuleManager.php';
+require_once $__dir . '/HTMLPurifier/IDAccumulator.php';
+require_once $__dir . '/HTMLPurifier/Injector.php';
+require_once $__dir . '/HTMLPurifier/Language.php';
+require_once $__dir . '/HTMLPurifier/LanguageFactory.php';
+require_once $__dir . '/HTMLPurifier/Length.php';
+require_once $__dir . '/HTMLPurifier/Lexer.php';
+require_once $__dir . '/HTMLPurifier/PercentEncoder.php';
+require_once $__dir . '/HTMLPurifier/PropertyList.php';
+require_once $__dir . '/HTMLPurifier/PropertyListIterator.php';
+require_once $__dir . '/HTMLPurifier/Strategy.php';
+require_once $__dir . '/HTMLPurifier/StringHash.php';
+require_once $__dir . '/HTMLPurifier/StringHashParser.php';
+require_once $__dir . '/HTMLPurifier/TagTransform.php';
+require_once $__dir . '/HTMLPurifier/Token.php';
+require_once $__dir . '/HTMLPurifier/TokenFactory.php';
+require_once $__dir . '/HTMLPurifier/URI.php';
+require_once $__dir . '/HTMLPurifier/URIDefinition.php';
+require_once $__dir . '/HTMLPurifier/URIFilter.php';
+require_once $__dir . '/HTMLPurifier/URIParser.php';
+require_once $__dir . '/HTMLPurifier/URIScheme.php';
+require_once $__dir . '/HTMLPurifier/URISchemeRegistry.php';
+require_once $__dir . '/HTMLPurifier/UnitConverter.php';
+require_once $__dir . '/HTMLPurifier/VarParser.php';
+require_once $__dir . '/HTMLPurifier/VarParserException.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Enum.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Integer.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Lang.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Switch.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Text.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Number.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/AlphaValue.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Background.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Border.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Color.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Composite.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Filter.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Font.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/FontFamily.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Length.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/ListStyle.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Multiple.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Percentage.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/TextDecoration.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/URI.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Bool.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Nmtokens.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Class.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Color.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/FrameTarget.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/ID.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Pixels.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Length.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/LinkTypes.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/MultiLength.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/Email.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/Host.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv4.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv6.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Background.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/BdoDir.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/BgColor.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/BoolToCSS.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Border.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/EnumToCSS.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/ImgRequired.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/ImgSpace.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Input.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Lang.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Length.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Name.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/NameSync.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Nofollow.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/SafeEmbed.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/SafeObject.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/SafeParam.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/ScriptRequired.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Textarea.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Chameleon.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Custom.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Empty.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Required.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Optional.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/StrictBlockquote.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Table.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Null.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Serializer.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Memory.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Bdo.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/CommonAttributes.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Edit.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Forms.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Hypertext.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Image.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Legacy.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/List.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Name.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Nofollow.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Object.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Presentation.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Proprietary.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Ruby.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/SafeEmbed.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/SafeObject.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Scripting.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/StyleAttribute.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tables.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Target.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Text.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/XMLCommonAttributes.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Name.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Proprietary.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Strict.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Transitional.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTML.php';
+require_once $__dir . '/HTMLPurifier/Injector/AutoParagraph.php';
+require_once $__dir . '/HTMLPurifier/Injector/DisplayLinkURI.php';
+require_once $__dir . '/HTMLPurifier/Injector/Linkify.php';
+require_once $__dir . '/HTMLPurifier/Injector/PurifierLinkify.php';
+require_once $__dir . '/HTMLPurifier/Injector/RemoveEmpty.php';
+require_once $__dir . '/HTMLPurifier/Injector/RemoveSpansWithoutAttributes.php';
+require_once $__dir . '/HTMLPurifier/Injector/SafeObject.php';
+require_once $__dir . '/HTMLPurifier/Lexer/DOMLex.php';
+require_once $__dir . '/HTMLPurifier/Lexer/DirectLex.php';
+require_once $__dir . '/HTMLPurifier/Strategy/Composite.php';
+require_once $__dir . '/HTMLPurifier/Strategy/Core.php';
+require_once $__dir . '/HTMLPurifier/Strategy/FixNesting.php';
+require_once $__dir . '/HTMLPurifier/Strategy/MakeWellFormed.php';
+require_once $__dir . '/HTMLPurifier/Strategy/RemoveForeignElements.php';
+require_once $__dir . '/HTMLPurifier/Strategy/ValidateAttributes.php';
+require_once $__dir . '/HTMLPurifier/TagTransform/Font.php';
+require_once $__dir . '/HTMLPurifier/TagTransform/Simple.php';
+require_once $__dir . '/HTMLPurifier/Token/Comment.php';
+require_once $__dir . '/HTMLPurifier/Token/Tag.php';
+require_once $__dir . '/HTMLPurifier/Token/Empty.php';
+require_once $__dir . '/HTMLPurifier/Token/End.php';
+require_once $__dir . '/HTMLPurifier/Token/Start.php';
+require_once $__dir . '/HTMLPurifier/Token/Text.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/DisableExternal.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/DisableExternalResources.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/DisableResources.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/HostBlacklist.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/MakeAbsolute.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/Munge.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/data.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/file.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/ftp.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/http.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/https.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/mailto.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/news.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/nntp.php';
+require_once $__dir . '/HTMLPurifier/VarParser/Flexible.php';
+require_once $__dir . '/HTMLPurifier/VarParser/Native.php';
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrCollections.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrCollections.php
new file mode 100644
index 0000000..2a8aaa3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrCollections.php
@@ -0,0 +1,128 @@
+<?php
+
+/**
+ * Defines common attribute collections that modules reference
+ */
+
+class HTMLPurifier_AttrCollections
+{
+
+ /**
+ * Associative array of attribute collections, indexed by name
+ */
+ public $info = array();
+
+ /**
+ * Performs all expansions on internal data for use by other inclusions
+ * It also collects all attribute collection extensions from
+ * modules
+ * @param $attr_types HTMLPurifier_AttrTypes instance
+ * @param $modules Hash array of HTMLPurifier_HTMLModule members
+ */
+ public function __construct($attr_types, $modules) {
+ // load extensions from the modules
+ foreach ($modules as $module) {
+ foreach ($module->attr_collections as $coll_i => $coll) {
+ if (!isset($this->info[$coll_i])) {
+ $this->info[$coll_i] = array();
+ }
+ foreach ($coll as $attr_i => $attr) {
+ if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) {
+ // merge in includes
+ $this->info[$coll_i][$attr_i] = array_merge(
+ $this->info[$coll_i][$attr_i], $attr);
+ continue;
+ }
+ $this->info[$coll_i][$attr_i] = $attr;
+ }
+ }
+ }
+ // perform internal expansions and inclusions
+ foreach ($this->info as $name => $attr) {
+ // merge attribute collections that include others
+ $this->performInclusions($this->info[$name]);
+ // replace string identifiers with actual attribute objects
+ $this->expandIdentifiers($this->info[$name], $attr_types);
+ }
+ }
+
+ /**
+ * Takes a reference to an attribute associative array and performs
+ * all inclusions specified by the zero index.
+ * @param &$attr Reference to attribute array
+ */
+ public function performInclusions(&$attr) {
+ if (!isset($attr[0])) return;
+ $merge = $attr[0];
+ $seen = array(); // recursion guard
+ // loop through all the inclusions
+ for ($i = 0; isset($merge[$i]); $i++) {
+ if (isset($seen[$merge[$i]])) continue;
+ $seen[$merge[$i]] = true;
+ // foreach attribute of the inclusion, copy it over
+ if (!isset($this->info[$merge[$i]])) continue;
+ foreach ($this->info[$merge[$i]] as $key => $value) {
+ if (isset($attr[$key])) continue; // also catches more inclusions
+ $attr[$key] = $value;
+ }
+ if (isset($this->info[$merge[$i]][0])) {
+ // recursion
+ $merge = array_merge($merge, $this->info[$merge[$i]][0]);
+ }
+ }
+ unset($attr[0]);
+ }
+
+ /**
+ * Expands all string identifiers in an attribute array by replacing
+ * them with the appropriate values inside HTMLPurifier_AttrTypes
+ * @param &$attr Reference to attribute array
+ * @param $attr_types HTMLPurifier_AttrTypes instance
+ */
+ public function expandIdentifiers(&$attr, $attr_types) {
+
+ // because foreach will process new elements we add, make sure we
+ // skip duplicates
+ $processed = array();
+
+ foreach ($attr as $def_i => $def) {
+ // skip inclusions
+ if ($def_i === 0) continue;
+
+ if (isset($processed[$def_i])) continue;
+
+ // determine whether or not attribute is required
+ if ($required = (strpos($def_i, '*') !== false)) {
+ // rename the definition
+ unset($attr[$def_i]);
+ $def_i = trim($def_i, '*');
+ $attr[$def_i] = $def;
+ }
+
+ $processed[$def_i] = true;
+
+ // if we've already got a literal object, move on
+ if (is_object($def)) {
+ // preserve previous required
+ $attr[$def_i]->required = ($required || $attr[$def_i]->required);
+ continue;
+ }
+
+ if ($def === false) {
+ unset($attr[$def_i]);
+ continue;
+ }
+
+ if ($t = $attr_types->get($def)) {
+ $attr[$def_i] = $t;
+ $attr[$def_i]->required = $required;
+ } else {
+ unset($attr[$def_i]);
+ }
+ }
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef.php
new file mode 100644
index 0000000..f001738
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef.php
@@ -0,0 +1,123 @@
+<?php
+
+/**
+ * Base class for all validating attribute definitions.
+ *
+ * This family of classes forms the core for not only HTML attribute validation,
+ * but also any sort of string that needs to be validated or cleaned (which
+ * means CSS properties and composite definitions are defined here too).
+ * Besides defining (through code) what precisely makes the string valid,
+ * subclasses are also responsible for cleaning the code if possible.
+ */
+
+abstract class HTMLPurifier_AttrDef
+{
+
+ /**
+ * Tells us whether or not an HTML attribute is minimized. Has no
+ * meaning in other contexts.
+ */
+ public $minimized = false;
+
+ /**
+ * Tells us whether or not an HTML attribute is required. Has no
+ * meaning in other contexts
+ */
+ public $required = false;
+
+ /**
+ * Validates and cleans passed string according to a definition.
+ *
+ * @param $string String to be validated and cleaned.
+ * @param $config Mandatory HTMLPurifier_Config object.
+ * @param $context Mandatory HTMLPurifier_AttrContext object.
+ */
+ abstract public function validate($string, $config, $context);
+
+ /**
+ * Convenience method that parses a string as if it were CDATA.
+ *
+ * This method process a string in the manner specified at
+ * <http://www.w3.org/TR/html4/types.html#h-6.2> by removing
+ * leading and trailing whitespace, ignoring line feeds, and replacing
+ * carriage returns and tabs with spaces. While most useful for HTML
+ * attributes specified as CDATA, it can also be applied to most CSS
+ * values.
+ *
+ * @note This method is not entirely standards compliant, as trim() removes
+ * more types of whitespace than specified in the spec. In practice,
+ * this is rarely a problem, as those extra characters usually have
+ * already been removed by HTMLPurifier_Encoder.
+ *
+ * @warning This processing is inconsistent with XML's whitespace handling
+ * as specified by section 3.3.3 and referenced XHTML 1.0 section
+ * 4.7. However, note that we are NOT necessarily
+ * parsing XML, thus, this behavior may still be correct. We
+ * assume that newlines have been normalized.
+ */
+ public function parseCDATA($string) {
+ $string = trim($string);
+ $string = str_replace(array("\n", "\t", "\r"), ' ', $string);
+ return $string;
+ }
+
+ /**
+ * Factory method for creating this class from a string.
+ * @param $string String construction info
+ * @return Created AttrDef object corresponding to $string
+ */
+ public function make($string) {
+ // default implementation, return a flyweight of this object.
+ // If $string has an effect on the returned object (i.e. you
+ // need to overload this method), it is best
+ // to clone or instantiate new copies. (Instantiation is safer.)
+ return $this;
+ }
+
+ /**
+ * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work
+ * properly. THIS IS A HACK!
+ */
+ protected function mungeRgb($string) {
+ return preg_replace('/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/', 'rgb(\1,\2,\3)', $string);
+ }
+
+ /**
+ * Parses a possibly escaped CSS string and returns the "pure"
+ * version of it.
+ */
+ protected function expandCSSEscape($string) {
+ // flexibly parse it
+ $ret = '';
+ for ($i = 0, $c = strlen($string); $i < $c; $i++) {
+ if ($string[$i] === '\\') {
+ $i++;
+ if ($i >= $c) {
+ $ret .= '\\';
+ break;
+ }
+ if (ctype_xdigit($string[$i])) {
+ $code = $string[$i];
+ for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {
+ if (!ctype_xdigit($string[$i])) break;
+ $code .= $string[$i];
+ }
+ // We have to be extremely careful when adding
+ // new characters, to make sure we're not breaking
+ // the encoding.
+ $char = HTMLPurifier_Encoder::unichr(hexdec($code));
+ if (HTMLPurifier_Encoder::cleanUTF8($char) === '') continue;
+ $ret .= $char;
+ if ($i < $c && trim($string[$i]) !== '') $i--;
+ continue;
+ }
+ if ($string[$i] === "\n") continue;
+ }
+ $ret .= $string[$i];
+ }
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS.php
new file mode 100644
index 0000000..1e7b886
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS.php
@@ -0,0 +1,87 @@
+<?php
+
+/**
+ * Validates the HTML attribute style, otherwise known as CSS.
+ * @note We don't implement the whole CSS specification, so it might be
+ * difficult to reuse this component in the context of validating
+ * actual stylesheet declarations.
+ * @note If we were really serious about validating the CSS, we would
+ * tokenize the styles and then parse the tokens. Obviously, we
+ * are not doing that. Doing that could seriously harm performance,
+ * but would make these components a lot more viable for a CSS
+ * filtering solution.
+ */
+class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef
+{
+
+ public function validate($css, $config, $context) {
+
+ $css = $this->parseCDATA($css);
+
+ $definition = $config->getCSSDefinition();
+
+ // we're going to break the spec and explode by semicolons.
+ // This is because semicolon rarely appears in escaped form
+ // Doing this is generally flaky but fast
+ // IT MIGHT APPEAR IN URIs, see HTMLPurifier_AttrDef_CSSURI
+ // for details
+
+ $declarations = explode(';', $css);
+ $propvalues = array();
+
+ /**
+ * Name of the current CSS property being validated.
+ */
+ $property = false;
+ $context->register('CurrentCSSProperty', $property);
+
+ foreach ($declarations as $declaration) {
+ if (!$declaration) continue;
+ if (!strpos($declaration, ':')) continue;
+ list($property, $value) = explode(':', $declaration, 2);
+ $property = trim($property);
+ $value = trim($value);
+ $ok = false;
+ do {
+ if (isset($definition->info[$property])) {
+ $ok = true;
+ break;
+ }
+ if (ctype_lower($property)) break;
+ $property = strtolower($property);
+ if (isset($definition->info[$property])) {
+ $ok = true;
+ break;
+ }
+ } while(0);
+ if (!$ok) continue;
+ // inefficient call, since the validator will do this again
+ if (strtolower(trim($value)) !== 'inherit') {
+ // inherit works for everything (but only on the base property)
+ $result = $definition->info[$property]->validate(
+ $value, $config, $context );
+ } else {
+ $result = 'inherit';
+ }
+ if ($result === false) continue;
+ $propvalues[$property] = $result;
+ }
+
+ $context->destroy('CurrentCSSProperty');
+
+ // procedure does not write the new CSS simultaneously, so it's
+ // slightly inefficient, but it's the only way of getting rid of
+ // duplicates. Perhaps config to optimize it, but not now.
+
+ $new_declarations = '';
+ foreach ($propvalues as $prop => $value) {
+ $new_declarations .= "$prop:$value;";
+ }
+
+ return $new_declarations ? $new_declarations : false;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php
new file mode 100644
index 0000000..93db63f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php
@@ -0,0 +1,21 @@
+<?php
+
+class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number
+{
+
+ public function __construct() {
+ parent::__construct(false); // opacity is non-negative, but we will clamp it
+ }
+
+ public function validate($number, $config, $context) {
+ $result = parent::validate($number, $config, $context);
+ if ($result === false) return $result;
+ $float = (float) $result;
+ if ($float < 0.0) $result = '0';
+ if ($float > 1.0) $result = '1';
+ return $result;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Background.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Background.php
new file mode 100644
index 0000000..34c8a6f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Background.php
@@ -0,0 +1,87 @@
+<?php
+
+/**
+ * Validates shorthand CSS property background.
+ * @warning Does not support url tokens that have internal spaces.
+ */
+class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Local copy of component validators.
+ * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl.
+ */
+ protected $info;
+
+ public function __construct($config) {
+ $def = $config->getCSSDefinition();
+ $this->info['background-color'] = $def->info['background-color'];
+ $this->info['background-image'] = $def->info['background-image'];
+ $this->info['background-repeat'] = $def->info['background-repeat'];
+ $this->info['background-attachment'] = $def->info['background-attachment'];
+ $this->info['background-position'] = $def->info['background-position'];
+ }
+
+ public function validate($string, $config, $context) {
+
+ // regular pre-processing
+ $string = $this->parseCDATA($string);
+ if ($string === '') return false;
+
+ // munge rgb() decl if necessary
+ $string = $this->mungeRgb($string);
+
+ // assumes URI doesn't have spaces in it
+ $bits = explode(' ', strtolower($string)); // bits to process
+
+ $caught = array();
+ $caught['color'] = false;
+ $caught['image'] = false;
+ $caught['repeat'] = false;
+ $caught['attachment'] = false;
+ $caught['position'] = false;
+
+ $i = 0; // number of catches
+ $none = false;
+
+ foreach ($bits as $bit) {
+ if ($bit === '') continue;
+ foreach ($caught as $key => $status) {
+ if ($key != 'position') {
+ if ($status !== false) continue;
+ $r = $this->info['background-' . $key]->validate($bit, $config, $context);
+ } else {
+ $r = $bit;
+ }
+ if ($r === false) continue;
+ if ($key == 'position') {
+ if ($caught[$key] === false) $caught[$key] = '';
+ $caught[$key] .= $r . ' ';
+ } else {
+ $caught[$key] = $r;
+ }
+ $i++;
+ break;
+ }
+ }
+
+ if (!$i) return false;
+ if ($caught['position'] !== false) {
+ $caught['position'] = $this->info['background-position']->
+ validate($caught['position'], $config, $context);
+ }
+
+ $ret = array();
+ foreach ($caught as $value) {
+ if ($value === false) continue;
+ $ret[] = $value;
+ }
+
+ if (empty($ret)) return false;
+ return implode(' ', $ret);
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php
new file mode 100644
index 0000000..6627218
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php
@@ -0,0 +1,133 @@
+<?php
+
+/* W3C says:
+ [ // adjective and number must be in correct order, even if
+ // you could switch them without introducing ambiguity.
+ // some browsers support that syntax
+ [
+ <percentage> | <length> | left | center | right
+ ]
+ [
+ <percentage> | <length> | top | center | bottom
+ ]?
+ ] |
+ [ // this signifies that the vertical and horizontal adjectives
+ // can be arbitrarily ordered, however, there can only be two,
+ // one of each, or none at all
+ [
+ left | center | right
+ ] ||
+ [
+ top | center | bottom
+ ]
+ ]
+ top, left = 0%
+ center, (none) = 50%
+ bottom, right = 100%
+*/
+
+/* QuirksMode says:
+ keyword + length/percentage must be ordered correctly, as per W3C
+
+ Internet Explorer and Opera, however, support arbitrary ordering. We
+ should fix it up.
+
+ Minor issue though, not strictly necessary.
+*/
+
+// control freaks may appreciate the ability to convert these to
+// percentages or something, but it's not necessary
+
+/**
+ * Validates the value of background-position.
+ */
+class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef
+{
+
+ protected $length;
+ protected $percentage;
+
+ public function __construct() {
+ $this->length = new HTMLPurifier_AttrDef_CSS_Length();
+ $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage();
+ }
+
+ public function validate($string, $config, $context) {
+ $string = $this->parseCDATA($string);
+ $bits = explode(' ', $string);
+
+ $keywords = array();
+ $keywords['h'] = false; // left, right
+ $keywords['v'] = false; // top, bottom
+ $keywords['ch'] = false; // center (first word)
+ $keywords['cv'] = false; // center (second word)
+ $measures = array();
+
+ $i = 0;
+
+ $lookup = array(
+ 'top' => 'v',
+ 'bottom' => 'v',
+ 'left' => 'h',
+ 'right' => 'h',
+ 'center' => 'c'
+ );
+
+ foreach ($bits as $bit) {
+ if ($bit === '') continue;
+
+ // test for keyword
+ $lbit = ctype_lower($bit) ? $bit : strtolower($bit);
+ if (isset($lookup[$lbit])) {
+ $status = $lookup[$lbit];
+ if ($status == 'c') {
+ if ($i == 0) {
+ $status = 'ch';
+ } else {
+ $status = 'cv';
+ }
+ }
+ $keywords[$status] = $lbit;
+ $i++;
+ }
+
+ // test for length
+ $r = $this->length->validate($bit, $config, $context);
+ if ($r !== false) {
+ $measures[] = $r;
+ $i++;
+ }
+
+ // test for percentage
+ $r = $this->percentage->validate($bit, $config, $context);
+ if ($r !== false) {
+ $measures[] = $r;
+ $i++;
+ }
+
+ }
+
+ if (!$i) return false; // no valid values were caught
+
+ $ret = array();
+
+ // first keyword
+ if ($keywords['h']) $ret[] = $keywords['h'];
+ elseif ($keywords['ch']) {
+ $ret[] = $keywords['ch'];
+ $keywords['cv'] = false; // prevent re-use: center = center center
+ }
+ elseif (count($measures)) $ret[] = array_shift($measures);
+
+ if ($keywords['v']) $ret[] = $keywords['v'];
+ elseif ($keywords['cv']) $ret[] = $keywords['cv'];
+ elseif (count($measures)) $ret[] = array_shift($measures);
+
+ if (empty($ret)) return false;
+ return implode(' ', $ret);
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Border.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Border.php
new file mode 100644
index 0000000..c3e279f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Border.php
@@ -0,0 +1,43 @@
+<?php
+
+/**
+ * Validates the border property as defined by CSS.
+ */
+class HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Local copy of properties this property is shorthand for.
+ */
+ protected $info = array();
+
+ public function __construct($config) {
+ $def = $config->getCSSDefinition();
+ $this->info['border-width'] = $def->info['border-width'];
+ $this->info['border-style'] = $def->info['border-style'];
+ $this->info['border-top-color'] = $def->info['border-top-color'];
+ }
+
+ public function validate($string, $config, $context) {
+ $string = $this->parseCDATA($string);
+ $string = $this->mungeRgb($string);
+ $bits = explode(' ', $string);
+ $done = array(); // segments we've finished
+ $ret = ''; // return value
+ foreach ($bits as $bit) {
+ foreach ($this->info as $propname => $validator) {
+ if (isset($done[$propname])) continue;
+ $r = $validator->validate($bit, $config, $context);
+ if ($r !== false) {
+ $ret .= $r . ' ';
+ $done[$propname] = true;
+ break;
+ }
+ }
+ }
+ return rtrim($ret);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Color.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Color.php
new file mode 100644
index 0000000..ec999d6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Color.php
@@ -0,0 +1,78 @@
+<?php
+
+/**
+ * Validates Color as defined by CSS.
+ */
+class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef
+{
+
+ public function validate($color, $config, $context) {
+
+ static $colors = null;
+ if ($colors === null) $colors = $config->get('Core.ColorKeywords');
+
+ $color = trim($color);
+ if ($color === '') return false;
+
+ $lower = strtolower($color);
+ if (isset($colors[$lower])) return $colors[$lower];
+
+ if (strpos($color, 'rgb(') !== false) {
+ // rgb literal handling
+ $length = strlen($color);
+ if (strpos($color, ')') !== $length - 1) return false;
+ $triad = substr($color, 4, $length - 4 - 1);
+ $parts = explode(',', $triad);
+ if (count($parts) !== 3) return false;
+ $type = false; // to ensure that they're all the same type
+ $new_parts = array();
+ foreach ($parts as $part) {
+ $part = trim($part);
+ if ($part === '') return false;
+ $length = strlen($part);
+ if ($part[$length - 1] === '%') {
+ // handle percents
+ if (!$type) {
+ $type = 'percentage';
+ } elseif ($type !== 'percentage') {
+ return false;
+ }
+ $num = (float) substr($part, 0, $length - 1);
+ if ($num < 0) $num = 0;
+ if ($num > 100) $num = 100;
+ $new_parts[] = "$num%";
+ } else {
+ // handle integers
+ if (!$type) {
+ $type = 'integer';
+ } elseif ($type !== 'integer') {
+ return false;
+ }
+ $num = (int) $part;
+ if ($num < 0) $num = 0;
+ if ($num > 255) $num = 255;
+ $new_parts[] = (string) $num;
+ }
+ }
+ $new_triad = implode(',', $new_parts);
+ $color = "rgb($new_triad)";
+ } else {
+ // hexadecimal handling
+ if ($color[0] === '#') {
+ $hex = substr($color, 1);
+ } else {
+ $hex = $color;
+ $color = '#' . $color;
+ }
+ $length = strlen($hex);
+ if ($length !== 3 && $length !== 6) return false;
+ if (!ctype_xdigit($hex)) return false;
+ }
+
+ return $color;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Composite.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Composite.php
new file mode 100644
index 0000000..9e9f071
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Composite.php
@@ -0,0 +1,38 @@
+<?php
+
+/**
+ * Allows multiple validators to attempt to validate attribute.
+ *
+ * Composite is just what it sounds like: a composite of many validators.
+ * This means that multiple HTMLPurifier_AttrDef objects will have a whack
+ * at the string. If one of them passes, that's what is returned. This is
+ * especially useful for CSS values, which often are a choice between
+ * an enumerated set of predefined values or a flexible data type.
+ */
+class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * List of HTMLPurifier_AttrDef objects that may process strings
+ * @todo Make protected
+ */
+ public $defs;
+
+ /**
+ * @param $defs List of HTMLPurifier_AttrDef objects
+ */
+ public function __construct($defs) {
+ $this->defs = $defs;
+ }
+
+ public function validate($string, $config, $context) {
+ foreach ($this->defs as $i => $def) {
+ $result = $this->defs[$i]->validate($string, $config, $context);
+ if ($result !== false) return $result;
+ }
+ return false;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php
new file mode 100644
index 0000000..52cac2a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php
@@ -0,0 +1,28 @@
+<?php
+
+/**
+ * Decorator which enables CSS properties to be disabled for specific elements.
+ */
+class HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef
+{
+ public $def, $element;
+
+ /**
+ * @param $def Definition to wrap
+ * @param $element Element to deny
+ */
+ public function __construct($def, $element) {
+ $this->def = $def;
+ $this->element = $element;
+ }
+ /**
+ * Checks if CurrentToken is set and equal to $this->element
+ */
+ public function validate($string, $config, $context) {
+ $token = $context->get('CurrentToken', true);
+ if ($token && $token->name == $this->element) return false;
+ return $this->def->validate($string, $config, $context);
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Filter.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Filter.php
new file mode 100644
index 0000000..4a0fb33
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Filter.php
@@ -0,0 +1,54 @@
+<?php
+
+/**
+ * Microsoft's proprietary filter: CSS property
+ * @note Currently supports the alpha filter. In the future, this will
+ * probably need an extensible framework
+ */
+class HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef
+{
+
+ protected $intValidator;
+
+ public function __construct() {
+ $this->intValidator = new HTMLPurifier_AttrDef_Integer();
+ }
+
+ public function validate($value, $config, $context) {
+ $value = $this->parseCDATA($value);
+ if ($value === 'none') return $value;
+ // if we looped this we could support multiple filters
+ $function_length = strcspn($value, '(');
+ $function = trim(substr($value, 0, $function_length));
+ if ($function !== 'alpha' &&
+ $function !== 'Alpha' &&
+ $function !== 'progid:DXImageTransform.Microsoft.Alpha'
+ ) return false;
+ $cursor = $function_length + 1;
+ $parameters_length = strcspn($value, ')', $cursor);
+ $parameters = substr($value, $cursor, $parameters_length);
+ $params = explode(',', $parameters);
+ $ret_params = array();
+ $lookup = array();
+ foreach ($params as $param) {
+ list($key, $value) = explode('=', $param);
+ $key = trim($key);
+ $value = trim($value);
+ if (isset($lookup[$key])) continue;
+ if ($key !== 'opacity') continue;
+ $value = $this->intValidator->validate($value, $config, $context);
+ if ($value === false) continue;
+ $int = (int) $value;
+ if ($int > 100) $value = '100';
+ if ($int < 0) $value = '0';
+ $ret_params[] = "$key=$value";
+ $lookup[$key] = true;
+ }
+ $ret_parameters = implode(',', $ret_params);
+ $ret_function = "$function($ret_parameters)";
+ return $ret_function;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Font.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Font.php
new file mode 100644
index 0000000..4e84fe8
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Font.php
@@ -0,0 +1,149 @@
+<?php
+
+/**
+ * Validates shorthand CSS property font.
+ */
+class HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Local copy of component validators.
+ *
+ * @note If we moved specific CSS property definitions to their own
+ * classes instead of having them be assembled at run time by
+ * CSSDefinition, this wouldn't be necessary. We'd instantiate
+ * our own copies.
+ */
+ protected $info = array();
+
+ public function __construct($config) {
+ $def = $config->getCSSDefinition();
+ $this->info['font-style'] = $def->info['font-style'];
+ $this->info['font-variant'] = $def->info['font-variant'];
+ $this->info['font-weight'] = $def->info['font-weight'];
+ $this->info['font-size'] = $def->info['font-size'];
+ $this->info['line-height'] = $def->info['line-height'];
+ $this->info['font-family'] = $def->info['font-family'];
+ }
+
+ public function validate($string, $config, $context) {
+
+ static $system_fonts = array(
+ 'caption' => true,
+ 'icon' => true,
+ 'menu' => true,
+ 'message-box' => true,
+ 'small-caption' => true,
+ 'status-bar' => true
+ );
+
+ // regular pre-processing
+ $string = $this->parseCDATA($string);
+ if ($string === '') return false;
+
+ // check if it's one of the keywords
+ $lowercase_string = strtolower($string);
+ if (isset($system_fonts[$lowercase_string])) {
+ return $lowercase_string;
+ }
+
+ $bits = explode(' ', $string); // bits to process
+ $stage = 0; // this indicates what we're looking for
+ $caught = array(); // which stage 0 properties have we caught?
+ $stage_1 = array('font-style', 'font-variant', 'font-weight');
+ $final = ''; // output
+
+ for ($i = 0, $size = count($bits); $i < $size; $i++) {
+ if ($bits[$i] === '') continue;
+ switch ($stage) {
+
+ // attempting to catch font-style, font-variant or font-weight
+ case 0:
+ foreach ($stage_1 as $validator_name) {
+ if (isset($caught[$validator_name])) continue;
+ $r = $this->info[$validator_name]->validate(
+ $bits[$i], $config, $context);
+ if ($r !== false) {
+ $final .= $r . ' ';
+ $caught[$validator_name] = true;
+ break;
+ }
+ }
+ // all three caught, continue on
+ if (count($caught) >= 3) $stage = 1;
+ if ($r !== false) break;
+
+ // attempting to catch font-size and perhaps line-height
+ case 1:
+ $found_slash = false;
+ if (strpos($bits[$i], '/') !== false) {
+ list($font_size, $line_height) =
+ explode('/', $bits[$i]);
+ if ($line_height === '') {
+ // ooh, there's a space after the slash!
+ $line_height = false;
+ $found_slash = true;
+ }
+ } else {
+ $font_size = $bits[$i];
+ $line_height = false;
+ }
+ $r = $this->info['font-size']->validate(
+ $font_size, $config, $context);
+ if ($r !== false) {
+ $final .= $r;
+ // attempt to catch line-height
+ if ($line_height === false) {
+ // we need to scroll forward
+ for ($j = $i + 1; $j < $size; $j++) {
+ if ($bits[$j] === '') continue;
+ if ($bits[$j] === '/') {
+ if ($found_slash) {
+ return false;
+ } else {
+ $found_slash = true;
+ continue;
+ }
+ }
+ $line_height = $bits[$j];
+ break;
+ }
+ } else {
+ // slash already found
+ $found_slash = true;
+ $j = $i;
+ }
+ if ($found_slash) {
+ $i = $j;
+ $r = $this->info['line-height']->validate(
+ $line_height, $config, $context);
+ if ($r !== false) {
+ $final .= '/' . $r;
+ }
+ }
+ $final .= ' ';
+ $stage = 2;
+ break;
+ }
+ return false;
+
+ // attempting to catch font-family
+ case 2:
+ $font_family =
+ implode(' ', array_slice($bits, $i, $size - $i));
+ $r = $this->info['font-family']->validate(
+ $font_family, $config, $context);
+ if ($r !== false) {
+ $final .= $r . ' ';
+ // processing completed successfully
+ return rtrim($final);
+ }
+ return false;
+ }
+ }
+ return false;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/FontFamily.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/FontFamily.php
new file mode 100644
index 0000000..e7fccaa
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/FontFamily.php
@@ -0,0 +1,197 @@
+<?php
+
+/**
+ * Validates a font family list according to CSS spec
+ */
+class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef
+{
+
+ protected $mask = null;
+
+ public function __construct() {
+ $this->mask = '- ';
+ for ($c = 'a'; $c <= 'z'; $c++) $this->mask .= $c;
+ for ($c = 'A'; $c <= 'Z'; $c++) $this->mask .= $c;
+ for ($c = '0'; $c <= '9'; $c++) $this->mask .= $c; // cast-y, but should be fine
+ // special bytes used by UTF-8
+ for ($i = 0x80; $i <= 0xFF; $i++) {
+ // We don't bother excluding invalid bytes in this range,
+ // because the our restriction of well-formed UTF-8 will
+ // prevent these from ever occurring.
+ $this->mask .= chr($i);
+ }
+
+ /*
+ PHP's internal strcspn implementation is
+ O(length of string * length of mask), making it inefficient
+ for large masks. However, it's still faster than
+ preg_match 8)
+ for (p = s1;;) {
+ spanp = s2;
+ do {
+ if (*spanp == c || p == s1_end) {
+ return p - s1;
+ }
+ } while (spanp++ < (s2_end - 1));
+ c = *++p;
+ }
+ */
+ // possible optimization: invert the mask.
+ }
+
+ public function validate($string, $config, $context) {
+ static $generic_names = array(
+ 'serif' => true,
+ 'sans-serif' => true,
+ 'monospace' => true,
+ 'fantasy' => true,
+ 'cursive' => true
+ );
+ $allowed_fonts = $config->get('CSS.AllowedFonts');
+
+ // assume that no font names contain commas in them
+ $fonts = explode(',', $string);
+ $final = '';
+ foreach($fonts as $font) {
+ $font = trim($font);
+ if ($font === '') continue;
+ // match a generic name
+ if (isset($generic_names[$font])) {
+ if ($allowed_fonts === null || isset($allowed_fonts[$font])) {
+ $final .= $font . ', ';
+ }
+ continue;
+ }
+ // match a quoted name
+ if ($font[0] === '"' || $font[0] === "'") {
+ $length = strlen($font);
+ if ($length <= 2) continue;
+ $quote = $font[0];
+ if ($font[$length - 1] !== $quote) continue;
+ $font = substr($font, 1, $length - 2);
+ }
+
+ $font = $this->expandCSSEscape($font);
+
+ // $font is a pure representation of the font name
+
+ if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) {
+ continue;
+ }
+
+ if (ctype_alnum($font) && $font !== '') {
+ // very simple font, allow it in unharmed
+ $final .= $font . ', ';
+ continue;
+ }
+
+ // bugger out on whitespace. form feed (0C) really
+ // shouldn't show up regardless
+ $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font);
+
+ // Here, there are various classes of characters which need
+ // to be treated differently:
+ // - Alphanumeric characters are essentially safe. We
+ // handled these above.
+ // - Spaces require quoting, though most parsers will do
+ // the right thing if there aren't any characters that
+ // can be misinterpreted
+ // - Dashes rarely occur, but they fairly unproblematic
+ // for parsing/rendering purposes.
+ // The above characters cover the majority of Western font
+ // names.
+ // - Arbitrary Unicode characters not in ASCII. Because
+ // most parsers give little thought to Unicode, treatment
+ // of these codepoints is basically uniform, even for
+ // punctuation-like codepoints. These characters can
+ // show up in non-Western pages and are supported by most
+ // major browsers, for example: "MS 明朝" is a
+ // legitimate font-name
+ // <http://ja.wikipedia.org/wiki/MS_明朝>. See
+ // the CSS3 spec for more examples:
+ // <http://www.w3.org/TR/2011/WD-css3-fonts-20110324/localizedfamilynames.png>
+ // You can see live samples of these on the Internet:
+ // <http://www.google.co.jp/search?q=font-family+MS+明朝|ゴシック>
+ // However, most of these fonts have ASCII equivalents:
+ // for example, 'MS Mincho', and it's considered
+ // professional to use ASCII font names instead of
+ // Unicode font names. Thanks Takeshi Terada for
+ // providing this information.
+ // The following characters, to my knowledge, have not been
+ // used to name font names.
+ // - Single quote. While theoretically you might find a
+ // font name that has a single quote in its name (serving
+ // as an apostrophe, e.g. Dave's Scribble), I haven't
+ // been able to find any actual examples of this.
+ // Internet Explorer's cssText translation (which I
+ // believe is invoked by innerHTML) normalizes any
+ // quoting to single quotes, and fails to escape single
+ // quotes. (Note that this is not IE's behavior for all
+ // CSS properties, just some sort of special casing for
+ // font-family). So a single quote *cannot* be used
+ // safely in the font-family context if there will be an
+ // innerHTML/cssText translation. Note that Firefox 3.x
+ // does this too.
+ // - Double quote. In IE, these get normalized to
+ // single-quotes, no matter what the encoding. (Fun
+ // fact, in IE8, the 'content' CSS property gained
+ // support, where they special cased to preserve encoded
+ // double quotes, but still translate unadorned double
+ // quotes into single quotes.) So, because their
+ // fixpoint behavior is identical to single quotes, they
+ // cannot be allowed either. Firefox 3.x displays
+ // single-quote style behavior.
+ // - Backslashes are reduced by one (so \\ -> \) every
+ // iteration, so they cannot be used safely. This shows
+ // up in IE7, IE8 and FF3
+ // - Semicolons, commas and backticks are handled properly.
+ // - The rest of the ASCII punctuation is handled properly.
+ // We haven't checked what browsers do to unadorned
+ // versions, but this is not important as long as the
+ // browser doesn't /remove/ surrounding quotes (as IE does
+ // for HTML).
+ //
+ // With these results in hand, we conclude that there are
+ // various levels of safety:
+ // - Paranoid: alphanumeric, spaces and dashes(?)
+ // - International: Paranoid + non-ASCII Unicode
+ // - Edgy: Everything except quotes, backslashes
+ // - NoJS: Standards compliance, e.g. sod IE. Note that
+ // with some judicious character escaping (since certain
+ // types of escaping doesn't work) this is theoretically
+ // OK as long as innerHTML/cssText is not called.
+ // We believe that international is a reasonable default
+ // (that we will implement now), and once we do more
+ // extensive research, we may feel comfortable with dropping
+ // it down to edgy.
+
+ // Edgy: alphanumeric, spaces, dashes and Unicode. Use of
+ // str(c)spn assumes that the string was already well formed
+ // Unicode (which of course it is).
+ if (strspn($font, $this->mask) !== strlen($font)) {
+ continue;
+ }
+
+ // Historical:
+ // In the absence of innerHTML/cssText, these ugly
+ // transforms don't pose a security risk (as \\ and \"
+ // might--these escapes are not supported by most browsers).
+ // We could try to be clever and use single-quote wrapping
+ // when there is a double quote present, but I have choosen
+ // not to implement that. (NOTE: you can reduce the amount
+ // of escapes by one depending on what quoting style you use)
+ // $font = str_replace('\\', '\\5C ', $font);
+ // $font = str_replace('"', '\\22 ', $font);
+ // $font = str_replace("'", '\\27 ', $font);
+
+ // font possibly with spaces, requires quoting
+ $final .= "'$font', ";
+ }
+ $final = rtrim($final, ', ');
+ if ($final === '') return false;
+ return $final;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php
new file mode 100644
index 0000000..35bc534
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * Decorator which enables !important to be used in CSS values.
+ */
+class HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef
+{
+ public $def, $allow;
+
+ /**
+ * @param $def Definition to wrap
+ * @param $allow Whether or not to allow !important
+ */
+ public function __construct($def, $allow = false) {
+ $this->def = $def;
+ $this->allow = $allow;
+ }
+ /**
+ * Intercepts and removes !important if necessary
+ */
+ public function validate($string, $config, $context) {
+ // test for ! and important tokens
+ $string = trim($string);
+ $is_important = false;
+ // :TODO: optimization: test directly for !important and ! important
+ if (strlen($string) >= 9 && substr($string, -9) === 'important') {
+ $temp = rtrim(substr($string, 0, -9));
+ // use a temp, because we might want to restore important
+ if (strlen($temp) >= 1 && substr($temp, -1) === '!') {
+ $string = rtrim(substr($temp, 0, -1));
+ $is_important = true;
+ }
+ }
+ $string = $this->def->validate($string, $config, $context);
+ if ($this->allow && $is_important) $string .= ' !important';
+ return $string;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Length.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Length.php
new file mode 100644
index 0000000..266010b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Length.php
@@ -0,0 +1,47 @@
+<?php
+
+/**
+ * Represents a Length as defined by CSS.
+ */
+class HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef
+{
+
+ protected $min, $max;
+
+ /**
+ * @param HTMLPurifier_Length $max Minimum length, or null for no bound. String is also acceptable.
+ * @param HTMLPurifier_Length $max Maximum length, or null for no bound. String is also acceptable.
+ */
+ public function __construct($min = null, $max = null) {
+ $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;
+ $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;
+ }
+
+ public function validate($string, $config, $context) {
+ $string = $this->parseCDATA($string);
+
+ // Optimizations
+ if ($string === '') return false;
+ if ($string === '0') return '0';
+ if (strlen($string) === 1) return false;
+
+ $length = HTMLPurifier_Length::make($string);
+ if (!$length->isValid()) return false;
+
+ if ($this->min) {
+ $c = $length->compareTo($this->min);
+ if ($c === false) return false;
+ if ($c < 0) return false;
+ }
+ if ($this->max) {
+ $c = $length->compareTo($this->max);
+ if ($c === false) return false;
+ if ($c > 0) return false;
+ }
+
+ return $length->toString();
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ListStyle.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ListStyle.php
new file mode 100644
index 0000000..350ef6c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/ListStyle.php
@@ -0,0 +1,78 @@
+<?php
+
+/**
+ * Validates shorthand CSS property list-style.
+ * @warning Does not support url tokens that have internal spaces.
+ */
+class HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Local copy of component validators.
+ * @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl.
+ */
+ protected $info;
+
+ public function __construct($config) {
+ $def = $config->getCSSDefinition();
+ $this->info['list-style-type'] = $def->info['list-style-type'];
+ $this->info['list-style-position'] = $def->info['list-style-position'];
+ $this->info['list-style-image'] = $def->info['list-style-image'];
+ }
+
+ public function validate($string, $config, $context) {
+
+ // regular pre-processing
+ $string = $this->parseCDATA($string);
+ if ($string === '') return false;
+
+ // assumes URI doesn't have spaces in it
+ $bits = explode(' ', strtolower($string)); // bits to process
+
+ $caught = array();
+ $caught['type'] = false;
+ $caught['position'] = false;
+ $caught['image'] = false;
+
+ $i = 0; // number of catches
+ $none = false;
+
+ foreach ($bits as $bit) {
+ if ($i >= 3) return; // optimization bit
+ if ($bit === '') continue;
+ foreach ($caught as $key => $status) {
+ if ($status !== false) continue;
+ $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);
+ if ($r === false) continue;
+ if ($r === 'none') {
+ if ($none) continue;
+ else $none = true;
+ if ($key == 'image') continue;
+ }
+ $caught[$key] = $r;
+ $i++;
+ break;
+ }
+ }
+
+ if (!$i) return false;
+
+ $ret = array();
+
+ // construct type
+ if ($caught['type']) $ret[] = $caught['type'];
+
+ // construct image
+ if ($caught['image']) $ret[] = $caught['image'];
+
+ // construct position
+ if ($caught['position']) $ret[] = $caught['position'];
+
+ if (empty($ret)) return false;
+ return implode(' ', $ret);
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Multiple.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Multiple.php
new file mode 100644
index 0000000..1298e8b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Multiple.php
@@ -0,0 +1,58 @@
+<?php
+
+/**
+ * Framework class for strings that involve multiple values.
+ *
+ * Certain CSS properties such as border-width and margin allow multiple
+ * lengths to be specified. This class can take a vanilla border-width
+ * definition and multiply it, usually into a max of four.
+ *
+ * @note Even though the CSS specification isn't clear about it, inherit
+ * can only be used alone: it will never manifest as part of a multi
+ * shorthand declaration. Thus, this class does not allow inherit.
+ */
+class HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Instance of component definition to defer validation to.
+ * @todo Make protected
+ */
+ public $single;
+
+ /**
+ * Max number of values allowed.
+ * @todo Make protected
+ */
+ public $max;
+
+ /**
+ * @param $single HTMLPurifier_AttrDef to multiply
+ * @param $max Max number of values allowed (usually four)
+ */
+ public function __construct($single, $max = 4) {
+ $this->single = $single;
+ $this->max = $max;
+ }
+
+ public function validate($string, $config, $context) {
+ $string = $this->parseCDATA($string);
+ if ($string === '') return false;
+ $parts = explode(' ', $string); // parseCDATA replaced \r, \t and \n
+ $length = count($parts);
+ $final = '';
+ for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) {
+ if (ctype_space($parts[$i])) continue;
+ $result = $this->single->validate($parts[$i], $config, $context);
+ if ($result !== false) {
+ $final .= $result . ' ';
+ $num++;
+ }
+ }
+ if ($final === '') return false;
+ return rtrim($final);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Number.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Number.php
new file mode 100644
index 0000000..7a74c10
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Number.php
@@ -0,0 +1,69 @@
+<?php
+
+/**
+ * Validates a number as defined by the CSS spec.
+ */
+class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Bool indicating whether or not only positive values allowed.
+ */
+ protected $non_negative = false;
+
+ /**
+ * @param $non_negative Bool indicating whether negatives are forbidden
+ */
+ public function __construct($non_negative = false) {
+ $this->non_negative = $non_negative;
+ }
+
+ /**
+ * @warning Some contexts do not pass $config, $context. These
+ * variables should not be used without checking HTMLPurifier_Length
+ */
+ public function validate($number, $config, $context) {
+
+ $number = $this->parseCDATA($number);
+
+ if ($number === '') return false;
+ if ($number === '0') return '0';
+
+ $sign = '';
+ switch ($number[0]) {
+ case '-':
+ if ($this->non_negative) return false;
+ $sign = '-';
+ case '+':
+ $number = substr($number, 1);
+ }
+
+ if (ctype_digit($number)) {
+ $number = ltrim($number, '0');
+ return $number ? $sign . $number : '0';
+ }
+
+ // Period is the only non-numeric character allowed
+ if (strpos($number, '.') === false) return false;
+
+ list($left, $right) = explode('.', $number, 2);
+
+ if ($left === '' && $right === '') return false;
+ if ($left !== '' && !ctype_digit($left)) return false;
+
+ $left = ltrim($left, '0');
+ $right = rtrim($right, '0');
+
+ if ($right === '') {
+ return $left ? $sign . $left : '0';
+ } elseif (!ctype_digit($right)) {
+ return false;
+ }
+
+ return $sign . $left . '.' . $right;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Percentage.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Percentage.php
new file mode 100644
index 0000000..b856af6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/Percentage.php
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * Validates a Percentage as defined by the CSS spec.
+ */
+class HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Instance of HTMLPurifier_AttrDef_CSS_Number to defer number validation
+ */
+ protected $number_def;
+
+ /**
+ * @param Bool indicating whether to forbid negative values
+ */
+ public function __construct($non_negative = false) {
+ $this->number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);
+ }
+
+ public function validate($string, $config, $context) {
+
+ $string = $this->parseCDATA($string);
+
+ if ($string === '') return false;
+ $length = strlen($string);
+ if ($length === 1) return false;
+ if ($string[$length - 1] !== '%') return false;
+
+ $number = substr($string, 0, $length - 1);
+ $number = $this->number_def->validate($number, $config, $context);
+
+ if ($number === false) return false;
+ return "$number%";
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php
new file mode 100644
index 0000000..52b9bf8
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php
@@ -0,0 +1,38 @@
+<?php
+
+/**
+ * Validates the value for the CSS property text-decoration
+ * @note This class could be generalized into a version that acts sort of
+ * like Enum except you can compound the allowed values.
+ */
+class HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef
+{
+
+ public function validate($string, $config, $context) {
+
+ static $allowed_values = array(
+ 'line-through' => true,
+ 'overline' => true,
+ 'underline' => true,
+ );
+
+ $string = strtolower($this->parseCDATA($string));
+
+ if ($string === 'none') return $string;
+
+ $parts = explode(' ', $string);
+ $final = '';
+ foreach ($parts as $part) {
+ if (isset($allowed_values[$part])) {
+ $final .= $part . ' ';
+ }
+ }
+ $final = rtrim($final);
+ if ($final === '') return false;
+ return $final;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/URI.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/URI.php
new file mode 100644
index 0000000..9bbe40b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/CSS/URI.php
@@ -0,0 +1,61 @@
+<?php
+
+/**
+ * Validates a URI in CSS syntax, which uses url('http://example.com')
+ * @note While theoretically speaking a URI in a CSS document could
+ * be non-embedded, as of CSS2 there is no such usage so we're
+ * generalizing it. This may need to be changed in the future.
+ * @warning Since HTMLPurifier_AttrDef_CSS blindly uses semicolons as
+ * the separator, you cannot put a literal semicolon in
+ * in the URI. Try percent encoding it, in that case.
+ */
+class HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI
+{
+
+ public function __construct() {
+ parent::__construct(true); // always embedded
+ }
+
+ public function validate($uri_string, $config, $context) {
+ // parse the URI out of the string and then pass it onto
+ // the parent object
+
+ $uri_string = $this->parseCDATA($uri_string);
+ if (strpos($uri_string, 'url(') !== 0) return false;
+ $uri_string = substr($uri_string, 4);
+ $new_length = strlen($uri_string) - 1;
+ if ($uri_string[$new_length] != ')') return false;
+ $uri = trim(substr($uri_string, 0, $new_length));
+
+ if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) {
+ $quote = $uri[0];
+ $new_length = strlen($uri) - 1;
+ if ($uri[$new_length] !== $quote) return false;
+ $uri = substr($uri, 1, $new_length - 1);
+ }
+
+ $uri = $this->expandCSSEscape($uri);
+
+ $result = parent::validate($uri, $config, $context);
+
+ if ($result === false) return false;
+
+ // extra sanity check; should have been done by URI
+ $result = str_replace(array('"', "\\", "\n", "\x0c", "\r"), "", $result);
+
+ // suspicious characters are ()'; we're going to percent encode
+ // them for safety.
+ $result = str_replace(array('(', ')', "'"), array('%28', '%29', '%27'), $result);
+
+ // there's an extra bug where ampersands lose their escaping on
+ // an innerHTML cycle, so a very unlucky query parameter could
+ // then change the meaning of the URL. Unfortunately, there's
+ // not much we can do about that...
+
+ return "url(\"$result\")";
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Enum.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Enum.php
new file mode 100644
index 0000000..88c6909
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Enum.php
@@ -0,0 +1,65 @@
+<?php
+
+// Enum = Enumerated
+/**
+ * Validates a keyword against a list of valid values.
+ * @warning The case-insensitive compare of this function uses PHP's
+ * built-in strtolower and ctype_lower functions, which may
+ * cause problems with international comparisons
+ */
+class HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Lookup table of valid values.
+ * @todo Make protected
+ */
+ public $valid_values = array();
+
+ /**
+ * Bool indicating whether or not enumeration is case sensitive.
+ * @note In general this is always case insensitive.
+ */
+ protected $case_sensitive = false; // values according to W3C spec
+
+ /**
+ * @param $valid_values List of valid values
+ * @param $case_sensitive Bool indicating whether or not case sensitive
+ */
+ public function __construct(
+ $valid_values = array(), $case_sensitive = false
+ ) {
+ $this->valid_values = array_flip($valid_values);
+ $this->case_sensitive = $case_sensitive;
+ }
+
+ public function validate($string, $config, $context) {
+ $string = trim($string);
+ if (!$this->case_sensitive) {
+ // we may want to do full case-insensitive libraries
+ $string = ctype_lower($string) ? $string : strtolower($string);
+ }
+ $result = isset($this->valid_values[$string]);
+
+ return $result ? $string : false;
+ }
+
+ /**
+ * @param $string In form of comma-delimited list of case-insensitive
+ * valid values. Example: "foo,bar,baz". Prepend "s:" to make
+ * case sensitive
+ */
+ public function make($string) {
+ if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') {
+ $string = substr($string, 2);
+ $sensitive = true;
+ } else {
+ $sensitive = false;
+ }
+ $values = explode(',', $string);
+ return new HTMLPurifier_AttrDef_Enum($values, $sensitive);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Bool.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Bool.php
new file mode 100644
index 0000000..93a43d0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Bool.php
@@ -0,0 +1,28 @@
+<?php
+
+/**
+ * Validates a boolean attribute
+ */
+class HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef
+{
+
+ protected $name;
+ public $minimized = true;
+
+ public function __construct($name = false) {$this->name = $name;}
+
+ public function validate($string, $config, $context) {
+ if (empty($string)) return false;
+ return $this->name;
+ }
+
+ /**
+ * @param $string Name of attribute
+ */
+ public function make($string) {
+ return new HTMLPurifier_AttrDef_HTML_Bool($string);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Class.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Class.php
new file mode 100644
index 0000000..ef0e21c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Class.php
@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * Implements special behavior for class attribute (normally NMTOKENS)
+ */
+class HTMLPurifier_AttrDef_HTML_Class extends HTMLPurifier_AttrDef_HTML_Nmtokens
+{
+ protected function split($string, $config, $context) {
+ // really, this twiddle should be lazy loaded
+ $name = $config->getDefinition('HTML')->doctype->name;
+ if ($name == "XHTML 1.1" || $name == "XHTML 2.0") {
+ return parent::split($string, $config, $context);
+ } else {
+ return preg_split('/\s+/', $string);
+ }
+ }
+ protected function filter($tokens, $config, $context) {
+ $allowed = $config->get('Attr.AllowedClasses');
+ $forbidden = $config->get('Attr.ForbiddenClasses');
+ $ret = array();
+ foreach ($tokens as $token) {
+ if (
+ ($allowed === null || isset($allowed[$token])) &&
+ !isset($forbidden[$token]) &&
+ // We need this O(n) check because of PHP's array
+ // implementation that casts -0 to 0.
+ !in_array($token, $ret, true)
+ ) {
+ $ret[] = $token;
+ }
+ }
+ return $ret;
+ }
+}
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Color.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Color.php
new file mode 100644
index 0000000..0575d8c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Color.php
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * Validates a color according to the HTML spec.
+ */
+class HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef
+{
+
+ public function validate($string, $config, $context) {
+
+ static $colors = null;
+ if ($colors === null) $colors = $config->get('Core.ColorKeywords');
+
+ $string = trim($string);
+
+ if (empty($string)) return false;
+ if (isset($colors[$string])) return $colors[$string];
+ if ($string[0] === '#') $hex = substr($string, 1);
+ else $hex = $string;
+
+ $length = strlen($hex);
+ if ($length !== 3 && $length !== 6) return false;
+ if (!ctype_xdigit($hex)) return false;
+ if ($length === 3) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
+
+ return "#$hex";
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php
new file mode 100644
index 0000000..8e4952e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php
@@ -0,0 +1,21 @@
+<?php
+
+/**
+ * Special-case enum attribute definition that lazy loads allowed frame targets
+ */
+class HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum
+{
+
+ public $valid_values = false; // uninitialized value
+ protected $case_sensitive = false;
+
+ public function __construct() {}
+
+ public function validate($string, $config, $context) {
+ if ($this->valid_values === false) $this->valid_values = $config->get('Attr.AllowedFrameTargets');
+ return parent::validate($string, $config, $context);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/ID.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/ID.php
new file mode 100644
index 0000000..373529f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/ID.php
@@ -0,0 +1,70 @@
+<?php
+
+/**
+ * Validates the HTML attribute ID.
+ * @warning Even though this is the id processor, it
+ * will ignore the directive Attr:IDBlacklist, since it will only
+ * go according to the ID accumulator. Since the accumulator is
+ * automatically generated, it will have already absorbed the
+ * blacklist. If you're hacking around, make sure you use load()!
+ */
+
+class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef
+{
+
+ // ref functionality disabled, since we also have to verify
+ // whether or not the ID it refers to exists
+
+ public function validate($id, $config, $context) {
+
+ if (!$config->get('Attr.EnableID')) return false;
+
+ $id = trim($id); // trim it first
+
+ if ($id === '') return false;
+
+ $prefix = $config->get('Attr.IDPrefix');
+ if ($prefix !== '') {
+ $prefix .= $config->get('Attr.IDPrefixLocal');
+ // prevent re-appending the prefix
+ if (strpos($id, $prefix) !== 0) $id = $prefix . $id;
+ } elseif ($config->get('Attr.IDPrefixLocal') !== '') {
+ trigger_error('%Attr.IDPrefixLocal cannot be used unless '.
+ '%Attr.IDPrefix is set', E_USER_WARNING);
+ }
+
+ //if (!$this->ref) {
+ $id_accumulator =& $context->get('IDAccumulator');
+ if (isset($id_accumulator->ids[$id])) return false;
+ //}
+
+ // we purposely avoid using regex, hopefully this is faster
+
+ if (ctype_alpha($id)) {
+ $result = true;
+ } else {
+ if (!ctype_alpha(@$id[0])) return false;
+ $trim = trim( // primitive style of regexps, I suppose
+ $id,
+ 'A..Za..z0..9:-._'
+ );
+ $result = ($trim === '');
+ }
+
+ $regexp = $config->get('Attr.IDBlacklistRegexp');
+ if ($regexp && preg_match($regexp, $id)) {
+ return false;
+ }
+
+ if (/*!$this->ref && */$result) $id_accumulator->add($id);
+
+ // if no change was made to the ID, return the result
+ // else, return the new id if stripping whitespace made it
+ // valid, or return false.
+ return $result ? $id : false;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Length.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Length.php
new file mode 100644
index 0000000..8521b2c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Length.php
@@ -0,0 +1,41 @@
+<?php
+
+/**
+ * Validates the HTML type length (not to be confused with CSS's length).
+ *
+ * This accepts integer pixels or percentages as lengths for certain
+ * HTML attributes.
+ */
+
+class HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels
+{
+
+ public function validate($string, $config, $context) {
+
+ $string = trim($string);
+ if ($string === '') return false;
+
+ $parent_result = parent::validate($string, $config, $context);
+ if ($parent_result !== false) return $parent_result;
+
+ $length = strlen($string);
+ $last_char = $string[$length - 1];
+
+ if ($last_char !== '%') return false;
+
+ $points = substr($string, 0, $length - 1);
+
+ if (!is_numeric($points)) return false;
+
+ $points = (int) $points;
+
+ if ($points < 0) return '0%';
+ if ($points > 100) return '100%';
+
+ return ((string) $points) . '%';
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php
new file mode 100644
index 0000000..dccdae1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php
@@ -0,0 +1,53 @@
+<?php
+
+/**
+ * Validates a rel/rev link attribute against a directive of allowed values
+ * @note We cannot use Enum because link types allow multiple
+ * values.
+ * @note Assumes link types are ASCII text
+ */
+class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef
+{
+
+ /** Name config attribute to pull. */
+ protected $name;
+
+ public function __construct($name) {
+ $configLookup = array(
+ 'rel' => 'AllowedRel',
+ 'rev' => 'AllowedRev'
+ );
+ if (!isset($configLookup[$name])) {
+ trigger_error('Unrecognized attribute name for link '.
+ 'relationship.', E_USER_ERROR);
+ return;
+ }
+ $this->name = $configLookup[$name];
+ }
+
+ public function validate($string, $config, $context) {
+
+ $allowed = $config->get('Attr.' . $this->name);
+ if (empty($allowed)) return false;
+
+ $string = $this->parseCDATA($string);
+ $parts = explode(' ', $string);
+
+ // lookup to prevent duplicates
+ $ret_lookup = array();
+ foreach ($parts as $part) {
+ $part = strtolower(trim($part));
+ if (!isset($allowed[$part])) continue;
+ $ret_lookup[$part] = true;
+ }
+
+ if (empty($ret_lookup)) return false;
+ $string = implode(' ', array_keys($ret_lookup));
+
+ return $string;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/MultiLength.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/MultiLength.php
new file mode 100644
index 0000000..4700c68
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/MultiLength.php
@@ -0,0 +1,41 @@
+<?php
+
+/**
+ * Validates a MultiLength as defined by the HTML spec.
+ *
+ * A multilength is either a integer (pixel count), a percentage, or
+ * a relative number.
+ */
+class HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length
+{
+
+ public function validate($string, $config, $context) {
+
+ $string = trim($string);
+ if ($string === '') return false;
+
+ $parent_result = parent::validate($string, $config, $context);
+ if ($parent_result !== false) return $parent_result;
+
+ $length = strlen($string);
+ $last_char = $string[$length - 1];
+
+ if ($last_char !== '*') return false;
+
+ $int = substr($string, 0, $length - 1);
+
+ if ($int == '') return '*';
+ if (!is_numeric($int)) return false;
+
+ $int = (int) $int;
+
+ if ($int < 0) return false;
+ if ($int == 0) return '0';
+ if ($int == 1) return '*';
+ return ((string) $int) . '*';
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Nmtokens.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Nmtokens.php
new file mode 100644
index 0000000..250267a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Nmtokens.php
@@ -0,0 +1,52 @@
+<?php
+
+/**
+ * Validates contents based on NMTOKENS attribute type.
+ */
+class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef
+{
+
+ public function validate($string, $config, $context) {
+
+ $string = trim($string);
+
+ // early abort: '' and '0' (strings that convert to false) are invalid
+ if (!$string) return false;
+
+ $tokens = $this->split($string, $config, $context);
+ $tokens = $this->filter($tokens, $config, $context);
+ if (empty($tokens)) return false;
+ return implode(' ', $tokens);
+
+ }
+
+ /**
+ * Splits a space separated list of tokens into its constituent parts.
+ */
+ protected function split($string, $config, $context) {
+ // OPTIMIZABLE!
+ // do the preg_match, capture all subpatterns for reformulation
+
+ // we don't support U+00A1 and up codepoints or
+ // escaping because I don't know how to do that with regexps
+ // and plus it would complicate optimization efforts (you never
+ // see that anyway).
+ $pattern = '/(?:(?<=\s)|\A)'. // look behind for space or string start
+ '((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)'.
+ '(?:(?=\s)|\z)/'; // look ahead for space or string end
+ preg_match_all($pattern, $string, $matches);
+ return $matches[1];
+ }
+
+ /**
+ * Template method for removing certain tokens based on arbitrary criteria.
+ * @note If we wanted to be really functional, we'd do an array_filter
+ * with a callback. But... we're not.
+ */
+ protected function filter($tokens, $config, $context) {
+ return $tokens;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Pixels.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Pixels.php
new file mode 100644
index 0000000..d765769
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/HTML/Pixels.php
@@ -0,0 +1,48 @@
+<?php
+
+/**
+ * Validates an integer representation of pixels according to the HTML spec.
+ */
+class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef
+{
+
+ protected $max;
+
+ public function __construct($max = null) {
+ $this->max = $max;
+ }
+
+ public function validate($string, $config, $context) {
+
+ $string = trim($string);
+ if ($string === '0') return $string;
+ if ($string === '') return false;
+ $length = strlen($string);
+ if (substr($string, $length - 2) == 'px') {
+ $string = substr($string, 0, $length - 2);
+ }
+ if (!is_numeric($string)) return false;
+ $int = (int) $string;
+
+ if ($int < 0) return '0';
+
+ // upper-bound value, extremely high values can
+ // crash operating systems, see <http://ha.ckers.org/imagecrash.html>
+ // WARNING, above link WILL crash you if you're using Windows
+
+ if ($this->max !== null && $int > $this->max) return (string) $this->max;
+
+ return (string) $int;
+
+ }
+
+ public function make($string) {
+ if ($string === '') $max = null;
+ else $max = (int) $string;
+ $class = get_class($this);
+ return new $class($max);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Integer.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Integer.php
new file mode 100644
index 0000000..6911478
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Integer.php
@@ -0,0 +1,73 @@
+<?php
+
+/**
+ * Validates an integer.
+ * @note While this class was modeled off the CSS definition, no currently
+ * allowed CSS uses this type. The properties that do are: widows,
+ * orphans, z-index, counter-increment, counter-reset. Some of the
+ * HTML attributes, however, find use for a non-negative version of this.
+ */
+class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Bool indicating whether or not negative values are allowed
+ */
+ protected $negative = true;
+
+ /**
+ * Bool indicating whether or not zero is allowed
+ */
+ protected $zero = true;
+
+ /**
+ * Bool indicating whether or not positive values are allowed
+ */
+ protected $positive = true;
+
+ /**
+ * @param $negative Bool indicating whether or not negative values are allowed
+ * @param $zero Bool indicating whether or not zero is allowed
+ * @param $positive Bool indicating whether or not positive values are allowed
+ */
+ public function __construct(
+ $negative = true, $zero = true, $positive = true
+ ) {
+ $this->negative = $negative;
+ $this->zero = $zero;
+ $this->positive = $positive;
+ }
+
+ public function validate($integer, $config, $context) {
+
+ $integer = $this->parseCDATA($integer);
+ if ($integer === '') return false;
+
+ // we could possibly simply typecast it to integer, but there are
+ // certain fringe cases that must not return an integer.
+
+ // clip leading sign
+ if ( $this->negative && $integer[0] === '-' ) {
+ $digits = substr($integer, 1);
+ if ($digits === '0') $integer = '0'; // rm minus sign for zero
+ } elseif( $this->positive && $integer[0] === '+' ) {
+ $digits = $integer = substr($integer, 1); // rm unnecessary plus
+ } else {
+ $digits = $integer;
+ }
+
+ // test if it's numeric
+ if (!ctype_digit($digits)) return false;
+
+ // perform scope tests
+ if (!$this->zero && $integer == 0) return false;
+ if (!$this->positive && $integer > 0) return false;
+ if (!$this->negative && $integer < 0) return false;
+
+ return $integer;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Lang.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Lang.php
new file mode 100644
index 0000000..844d467
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Lang.php
@@ -0,0 +1,73 @@
+<?php
+
+/**
+ * Validates the HTML attribute lang, effectively a language code.
+ * @note Built according to RFC 3066, which obsoleted RFC 1766
+ */
+class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef
+{
+
+ public function validate($string, $config, $context) {
+
+ $string = trim($string);
+ if (!$string) return false;
+
+ $subtags = explode('-', $string);
+ $num_subtags = count($subtags);
+
+ if ($num_subtags == 0) return false; // sanity check
+
+ // process primary subtag : $subtags[0]
+ $length = strlen($subtags[0]);
+ switch ($length) {
+ case 0:
+ return false;
+ case 1:
+ if (! ($subtags[0] == 'x' || $subtags[0] == 'i') ) {
+ return false;
+ }
+ break;
+ case 2:
+ case 3:
+ if (! ctype_alpha($subtags[0]) ) {
+ return false;
+ } elseif (! ctype_lower($subtags[0]) ) {
+ $subtags[0] = strtolower($subtags[0]);
+ }
+ break;
+ default:
+ return false;
+ }
+
+ $new_string = $subtags[0];
+ if ($num_subtags == 1) return $new_string;
+
+ // process second subtag : $subtags[1]
+ $length = strlen($subtags[1]);
+ if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) {
+ return $new_string;
+ }
+ if (!ctype_lower($subtags[1])) $subtags[1] = strtolower($subtags[1]);
+
+ $new_string .= '-' . $subtags[1];
+ if ($num_subtags == 2) return $new_string;
+
+ // process all other subtags, index 2 and up
+ for ($i = 2; $i < $num_subtags; $i++) {
+ $length = strlen($subtags[$i]);
+ if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) {
+ return $new_string;
+ }
+ if (!ctype_lower($subtags[$i])) {
+ $subtags[$i] = strtolower($subtags[$i]);
+ }
+ $new_string .= '-' . $subtags[$i];
+ }
+
+ return $new_string;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Switch.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Switch.php
new file mode 100644
index 0000000..ed45119
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Switch.php
@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * Decorator that, depending on a token, switches between two definitions.
+ */
+class HTMLPurifier_AttrDef_Switch
+{
+
+ protected $tag;
+ protected $withTag, $withoutTag;
+
+ /**
+ * @param string $tag Tag name to switch upon
+ * @param HTMLPurifier_AttrDef $with_tag Call if token matches tag
+ * @param HTMLPurifier_AttrDef $without_tag Call if token doesn't match, or there is no token
+ */
+ public function __construct($tag, $with_tag, $without_tag) {
+ $this->tag = $tag;
+ $this->withTag = $with_tag;
+ $this->withoutTag = $without_tag;
+ }
+
+ public function validate($string, $config, $context) {
+ $token = $context->get('CurrentToken', true);
+ if (!$token || $token->name !== $this->tag) {
+ return $this->withoutTag->validate($string, $config, $context);
+ } else {
+ return $this->withTag->validate($string, $config, $context);
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Text.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Text.php
new file mode 100644
index 0000000..4eb7772
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/Text.php
@@ -0,0 +1,15 @@
+<?php
+
+/**
+ * Validates arbitrary text according to the HTML spec.
+ */
+class HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef
+{
+
+ public function validate($string, $config, $context) {
+ return $this->parseCDATA($string);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI.php
new file mode 100644
index 0000000..0f861c0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI.php
@@ -0,0 +1,77 @@
+<?php
+
+/**
+ * Validates a URI as defined by RFC 3986.
+ * @note Scheme-specific mechanics deferred to HTMLPurifier_URIScheme
+ */
+class HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef
+{
+
+ protected $parser;
+ protected $embedsResource;
+
+ /**
+ * @param $embeds_resource_resource Does the URI here result in an extra HTTP request?
+ */
+ public function __construct($embeds_resource = false) {
+ $this->parser = new HTMLPurifier_URIParser();
+ $this->embedsResource = (bool) $embeds_resource;
+ }
+
+ public function make($string) {
+ $embeds = (bool) $string;
+ return new HTMLPurifier_AttrDef_URI($embeds);
+ }
+
+ public function validate($uri, $config, $context) {
+
+ if ($config->get('URI.Disable')) return false;
+
+ $uri = $this->parseCDATA($uri);
+
+ // parse the URI
+ $uri = $this->parser->parse($uri);
+ if ($uri === false) return false;
+
+ // add embedded flag to context for validators
+ $context->register('EmbeddedURI', $this->embedsResource);
+
+ $ok = false;
+ do {
+
+ // generic validation
+ $result = $uri->validate($config, $context);
+ if (!$result) break;
+
+ // chained filtering
+ $uri_def = $config->getDefinition('URI');
+ $result = $uri_def->filter($uri, $config, $context);
+ if (!$result) break;
+
+ // scheme-specific validation
+ $scheme_obj = $uri->getSchemeObj($config, $context);
+ if (!$scheme_obj) break;
+ if ($this->embedsResource && !$scheme_obj->browsable) break;
+ $result = $scheme_obj->validate($uri, $config, $context);
+ if (!$result) break;
+
+ // Post chained filtering
+ $result = $uri_def->postFilter($uri, $config, $context);
+ if (!$result) break;
+
+ // survived gauntlet
+ $ok = true;
+
+ } while (false);
+
+ $context->destroy('EmbeddedURI');
+ if (!$ok) return false;
+
+ // back to string
+ return $uri->toString();
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email.php
new file mode 100644
index 0000000..ff5cd31
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email.php
@@ -0,0 +1,17 @@
+<?php
+
+abstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Unpacks a mailbox into its display-name and address
+ */
+ function unpack($string) {
+ // needs to be implemented
+ }
+
+}
+
+// sub-implementations
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php
new file mode 100644
index 0000000..6dc98c6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php
@@ -0,0 +1,21 @@
+<?php
+
+/**
+ * Primitive email validation class based on the regexp found at
+ * http://www.regular-expressions.info/email.html
+ */
+class HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email
+{
+
+ public function validate($string, $config, $context) {
+ // no support for named mailboxes i.e. "Bob <bob@example.com>"
+ // that needs more percent encoding to be done
+ if ($string == '') return false;
+ $string = trim($string);
+ $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string);
+ return $result ? $string : false;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Host.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Host.php
new file mode 100644
index 0000000..4b4ad45
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/Host.php
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * Validates a host according to the IPv4, IPv6 and DNS (future) specifications.
+ */
+class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * Instance of HTMLPurifier_AttrDef_URI_IPv4 sub-validator
+ */
+ protected $ipv4;
+
+ /**
+ * Instance of HTMLPurifier_AttrDef_URI_IPv6 sub-validator
+ */
+ protected $ipv6;
+
+ public function __construct() {
+ $this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();
+ $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();
+ }
+
+ public function validate($string, $config, $context) {
+ $length = strlen($string);
+ // empty hostname is OK; it's usually semantically equivalent:
+ // the default host as defined by a URI scheme is used:
+ //
+ // If the URI scheme defines a default for host, then that
+ // default applies when the host subcomponent is undefined
+ // or when the registered name is empty (zero length).
+ if ($string === '') return '';
+ if ($length > 1 && $string[0] === '[' && $string[$length-1] === ']') {
+ //IPv6
+ $ip = substr($string, 1, $length - 2);
+ $valid = $this->ipv6->validate($ip, $config, $context);
+ if ($valid === false) return false;
+ return '['. $valid . ']';
+ }
+
+ // need to do checks on unusual encodings too
+ $ipv4 = $this->ipv4->validate($string, $config, $context);
+ if ($ipv4 !== false) return $ipv4;
+
+ // A regular domain name.
+
+ // This breaks I18N domain names, but we don't have proper IRI support,
+ // so force users to insert Punycode. If there's complaining we'll
+ // try to fix things into an international friendly form.
+
+ // The productions describing this are:
+ $a = '[a-z]'; // alpha
+ $an = '[a-z0-9]'; // alphanum
+ $and = '[a-z0-9-]'; // alphanum | "-"
+ // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
+ $domainlabel = "$an($and*$an)?";
+ // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
+ $toplabel = "$a($and*$an)?";
+ // hostname = *( domainlabel "." ) toplabel [ "." ]
+ $match = preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string);
+ if (!$match) return false;
+
+ return $string;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv4.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv4.php
new file mode 100644
index 0000000..a381809
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv4.php
@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * Validates an IPv4 address
+ * @author Feyd @ forums.devnetwork.net (public domain)
+ */
+class HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef
+{
+
+ /**
+ * IPv4 regex, protected so that IPv6 can reuse it
+ */
+ protected $ip4;
+
+ public function validate($aIP, $config, $context) {
+
+ if (!$this->ip4) $this->_loadRegex();
+
+ if (preg_match('#^' . $this->ip4 . '$#s', $aIP))
+ {
+ return $aIP;
+ }
+
+ return false;
+
+ }
+
+ /**
+ * Lazy load function to prevent regex from being stuffed in
+ * cache.
+ */
+ protected function _loadRegex() {
+ $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255
+ $this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})";
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv6.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv6.php
new file mode 100644
index 0000000..e49659e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrDef/URI/IPv6.php
@@ -0,0 +1,99 @@
+<?php
+
+/**
+ * Validates an IPv6 address.
+ * @author Feyd @ forums.devnetwork.net (public domain)
+ * @note This function requires brackets to have been removed from address
+ * in URI.
+ */
+class HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4
+{
+
+ public function validate($aIP, $config, $context) {
+
+ if (!$this->ip4) $this->_loadRegex();
+
+ $original = $aIP;
+
+ $hex = '[0-9a-fA-F]';
+ $blk = '(?:' . $hex . '{1,4})';
+ $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128
+
+ // prefix check
+ if (strpos($aIP, '/') !== false)
+ {
+ if (preg_match('#' . $pre . '$#s', $aIP, $find))
+ {
+ $aIP = substr($aIP, 0, 0-strlen($find[0]));
+ unset($find);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ // IPv4-compatiblity check
+ if (preg_match('#(?<=:'.')' . $this->ip4 . '$#s', $aIP, $find))
+ {
+ $aIP = substr($aIP, 0, 0-strlen($find[0]));
+ $ip = explode('.', $find[0]);
+ $ip = array_map('dechex', $ip);
+ $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];
+ unset($find, $ip);
+ }
+
+ // compression check
+ $aIP = explode('::', $aIP);
+ $c = count($aIP);
+ if ($c > 2)
+ {
+ return false;
+ }
+ elseif ($c == 2)
+ {
+ list($first, $second) = $aIP;
+ $first = explode(':', $first);
+ $second = explode(':', $second);
+
+ if (count($first) + count($second) > 8)
+ {
+ return false;
+ }
+
+ while(count($first) < 8)
+ {
+ array_push($first, '0');
+ }
+
+ array_splice($first, 8 - count($second), 8, $second);
+ $aIP = $first;
+ unset($first,$second);
+ }
+ else
+ {
+ $aIP = explode(':', $aIP[0]);
+ }
+ $c = count($aIP);
+
+ if ($c != 8)
+ {
+ return false;
+ }
+
+ // All the pieces should be 16-bit hex strings. Are they?
+ foreach ($aIP as $piece)
+ {
+ if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece)))
+ {
+ return false;
+ }
+ }
+
+ return $original;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform.php
new file mode 100644
index 0000000..e525c94
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform.php
@@ -0,0 +1,56 @@
+<?php
+
+/**
+ * Processes an entire attribute array for corrections needing multiple values.
+ *
+ * Occasionally, a certain attribute will need to be removed and popped onto
+ * another value. Instead of creating a complex return syntax for
+ * HTMLPurifier_AttrDef, we just pass the whole attribute array to a
+ * specialized object and have that do the special work. That is the
+ * family of HTMLPurifier_AttrTransform.
+ *
+ * An attribute transformation can be assigned to run before or after
+ * HTMLPurifier_AttrDef validation. See HTMLPurifier_HTMLDefinition for
+ * more details.
+ */
+
+abstract class HTMLPurifier_AttrTransform
+{
+
+ /**
+ * Abstract: makes changes to the attributes dependent on multiple values.
+ *
+ * @param $attr Assoc array of attributes, usually from
+ * HTMLPurifier_Token_Tag::$attr
+ * @param $config Mandatory HTMLPurifier_Config object.
+ * @param $context Mandatory HTMLPurifier_Context object
+ * @returns Processed attribute array.
+ */
+ abstract public function transform($attr, $config, $context);
+
+ /**
+ * Prepends CSS properties to the style attribute, creating the
+ * attribute if it doesn't exist.
+ * @param $attr Attribute array to process (passed by reference)
+ * @param $css CSS to prepend
+ */
+ public function prependCSS(&$attr, $css) {
+ $attr['style'] = isset($attr['style']) ? $attr['style'] : '';
+ $attr['style'] = $css . $attr['style'];
+ }
+
+ /**
+ * Retrieves and removes an attribute
+ * @param $attr Attribute array to process (passed by reference)
+ * @param $key Key of attribute to confiscate
+ */
+ public function confiscateAttr(&$attr, $key) {
+ if (!isset($attr[$key])) return null;
+ $value = $attr[$key];
+ unset($attr[$key]);
+ return $value;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Background.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Background.php
new file mode 100644
index 0000000..3dfcfd3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Background.php
@@ -0,0 +1,23 @@
+<?php
+
+/**
+ * Pre-transform that changes proprietary background attribute to CSS.
+ */
+class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform {
+
+ public function transform($attr, $config, $context) {
+
+ if (!isset($attr['background'])) return $attr;
+
+ $background = $this->confiscateAttr($attr, 'background');
+ // some validation should happen here
+
+ $this->prependCSS($attr, "background-image:url($background);");
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BdoDir.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BdoDir.php
new file mode 100644
index 0000000..e9800bb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BdoDir.php
@@ -0,0 +1,19 @@
+<?php
+
+// this MUST be placed in post, as it assumes that any value in dir is valid
+
+/**
+ * Post-trasnform that ensures that bdo tags have the dir attribute set.
+ */
+class HTMLPurifier_AttrTransform_BdoDir extends HTMLPurifier_AttrTransform
+{
+
+ public function transform($attr, $config, $context) {
+ if (isset($attr['dir'])) return $attr;
+ $attr['dir'] = $config->get('Attr.DefaultTextDir');
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BgColor.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BgColor.php
new file mode 100644
index 0000000..821ac57
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BgColor.php
@@ -0,0 +1,23 @@
+<?php
+
+/**
+ * Pre-transform that changes deprecated bgcolor attribute to CSS.
+ */
+class HTMLPurifier_AttrTransform_BgColor extends HTMLPurifier_AttrTransform {
+
+ public function transform($attr, $config, $context) {
+
+ if (!isset($attr['bgcolor'])) return $attr;
+
+ $bgcolor = $this->confiscateAttr($attr, 'bgcolor');
+ // some validation should happen here
+
+ $this->prependCSS($attr, "background-color:$bgcolor;");
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BoolToCSS.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BoolToCSS.php
new file mode 100644
index 0000000..d9bf3b5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/BoolToCSS.php
@@ -0,0 +1,36 @@
+<?php
+
+/**
+ * Pre-transform that changes converts a boolean attribute to fixed CSS
+ */
+class HTMLPurifier_AttrTransform_BoolToCSS extends HTMLPurifier_AttrTransform {
+
+ /**
+ * Name of boolean attribute that is trigger
+ */
+ protected $attr;
+
+ /**
+ * CSS declarations to add to style, needs trailing semicolon
+ */
+ protected $css;
+
+ /**
+ * @param $attr string attribute name to convert from
+ * @param $css string CSS declarations to add to style (needs semicolon)
+ */
+ public function __construct($attr, $css) {
+ $this->attr = $attr;
+ $this->css = $css;
+ }
+
+ public function transform($attr, $config, $context) {
+ if (!isset($attr[$this->attr])) return $attr;
+ unset($attr[$this->attr]);
+ $this->prependCSS($attr, $this->css);
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Border.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Border.php
new file mode 100644
index 0000000..b032ef2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Border.php
@@ -0,0 +1,18 @@
+<?php
+
+/**
+ * Pre-transform that changes deprecated border attribute to CSS.
+ */
+class HTMLPurifier_AttrTransform_Border extends HTMLPurifier_AttrTransform {
+
+ public function transform($attr, $config, $context) {
+ if (!isset($attr['border'])) return $attr;
+ $border_width = $this->confiscateAttr($attr, 'border');
+ // some validation should happen here
+ $this->prependCSS($attr, "border:{$border_width}px solid;");
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/EnumToCSS.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/EnumToCSS.php
new file mode 100644
index 0000000..39618eb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/EnumToCSS.php
@@ -0,0 +1,58 @@
+<?php
+
+/**
+ * Generic pre-transform that converts an attribute with a fixed number of
+ * values (enumerated) to CSS.
+ */
+class HTMLPurifier_AttrTransform_EnumToCSS extends HTMLPurifier_AttrTransform {
+
+ /**
+ * Name of attribute to transform from
+ */
+ protected $attr;
+
+ /**
+ * Lookup array of attribute values to CSS
+ */
+ protected $enumToCSS = array();
+
+ /**
+ * Case sensitivity of the matching
+ * @warning Currently can only be guaranteed to work with ASCII
+ * values.
+ */
+ protected $caseSensitive = false;
+
+ /**
+ * @param $attr String attribute name to transform from
+ * @param $enumToCSS Lookup array of attribute values to CSS
+ * @param $case_sensitive Boolean case sensitivity indicator, default false
+ */
+ public function __construct($attr, $enum_to_css, $case_sensitive = false) {
+ $this->attr = $attr;
+ $this->enumToCSS = $enum_to_css;
+ $this->caseSensitive = (bool) $case_sensitive;
+ }
+
+ public function transform($attr, $config, $context) {
+
+ if (!isset($attr[$this->attr])) return $attr;
+
+ $value = trim($attr[$this->attr]);
+ unset($attr[$this->attr]);
+
+ if (!$this->caseSensitive) $value = strtolower($value);
+
+ if (!isset($this->enumToCSS[$value])) {
+ return $attr;
+ }
+
+ $this->prependCSS($attr, $this->enumToCSS[$value]);
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgRequired.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgRequired.php
new file mode 100644
index 0000000..ca8b623
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgRequired.php
@@ -0,0 +1,43 @@
+<?php
+
+// must be called POST validation
+
+/**
+ * Transform that supplies default values for the src and alt attributes
+ * in img tags, as well as prevents the img tag from being removed
+ * because of a missing alt tag. This needs to be registered as both
+ * a pre and post attribute transform.
+ */
+class HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform
+{
+
+ public function transform($attr, $config, $context) {
+
+ $src = true;
+ if (!isset($attr['src'])) {
+ if ($config->get('Core.RemoveInvalidImg')) return $attr;
+ $attr['src'] = $config->get('Attr.DefaultInvalidImage');
+ $src = false;
+ }
+
+ if (!isset($attr['alt'])) {
+ if ($src) {
+ $alt = $config->get('Attr.DefaultImageAlt');
+ if ($alt === null) {
+ // truncate if the alt is too long
+ $attr['alt'] = substr(basename($attr['src']),0,40);
+ } else {
+ $attr['alt'] = $alt;
+ }
+ } else {
+ $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt');
+ }
+ }
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgSpace.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgSpace.php
new file mode 100644
index 0000000..25cb887
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ImgSpace.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * Pre-transform that changes deprecated hspace and vspace attributes to CSS
+ */
+class HTMLPurifier_AttrTransform_ImgSpace extends HTMLPurifier_AttrTransform {
+
+ protected $attr;
+ protected $css = array(
+ 'hspace' => array('left', 'right'),
+ 'vspace' => array('top', 'bottom')
+ );
+
+ public function __construct($attr) {
+ $this->attr = $attr;
+ if (!isset($this->css[$attr])) {
+ trigger_error(htmlspecialchars($attr) . ' is not valid space attribute');
+ }
+ }
+
+ public function transform($attr, $config, $context) {
+
+ if (!isset($attr[$this->attr])) return $attr;
+
+ $width = $this->confiscateAttr($attr, $this->attr);
+ // some validation could happen here
+
+ if (!isset($this->css[$this->attr])) return $attr;
+
+ $style = '';
+ foreach ($this->css[$this->attr] as $suffix) {
+ $property = "margin-$suffix";
+ $style .= "$property:{$width}px;";
+ }
+
+ $this->prependCSS($attr, $style);
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Input.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Input.php
new file mode 100644
index 0000000..2c3b4f8
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Input.php
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * Performs miscellaneous cross attribute validation and filtering for
+ * input elements. This is meant to be a post-transform.
+ */
+class HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform {
+
+ protected $pixels;
+
+ public function __construct() {
+ $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();
+ }
+
+ public function transform($attr, $config, $context) {
+ if (!isset($attr['type'])) $t = 'text';
+ else $t = strtolower($attr['type']);
+ if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') {
+ unset($attr['checked']);
+ }
+ if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') {
+ unset($attr['maxlength']);
+ }
+ if (isset($attr['size']) && $t !== 'text' && $t !== 'password') {
+ $result = $this->pixels->validate($attr['size'], $config, $context);
+ if ($result === false) unset($attr['size']);
+ else $attr['size'] = $result;
+ }
+ if (isset($attr['src']) && $t !== 'image') {
+ unset($attr['src']);
+ }
+ if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) {
+ $attr['value'] = '';
+ }
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Lang.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Lang.php
new file mode 100644
index 0000000..8d48393
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Lang.php
@@ -0,0 +1,28 @@
+<?php
+
+/**
+ * Post-transform that copies lang's value to xml:lang (and vice-versa)
+ * @note Theoretically speaking, this could be a pre-transform, but putting
+ * post is more efficient.
+ */
+class HTMLPurifier_AttrTransform_Lang extends HTMLPurifier_AttrTransform
+{
+
+ public function transform($attr, $config, $context) {
+
+ $lang = isset($attr['lang']) ? $attr['lang'] : false;
+ $xml_lang = isset($attr['xml:lang']) ? $attr['xml:lang'] : false;
+
+ if ($lang !== false && $xml_lang === false) {
+ $attr['xml:lang'] = $lang;
+ } elseif ($xml_lang !== false) {
+ $attr['lang'] = $xml_lang;
+ }
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Length.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Length.php
new file mode 100644
index 0000000..ed2643a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Length.php
@@ -0,0 +1,27 @@
+<?php
+
+/**
+ * Class for handling width/height length attribute transformations to CSS
+ */
+class HTMLPurifier_AttrTransform_Length extends HTMLPurifier_AttrTransform
+{
+
+ protected $name;
+ protected $cssName;
+
+ public function __construct($name, $css_name = null) {
+ $this->name = $name;
+ $this->cssName = $css_name ? $css_name : $name;
+ }
+
+ public function transform($attr, $config, $context) {
+ if (!isset($attr[$this->name])) return $attr;
+ $length = $this->confiscateAttr($attr, $this->name);
+ if(ctype_digit($length)) $length .= 'px';
+ $this->prependCSS($attr, $this->cssName . ":$length;");
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Name.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Name.php
new file mode 100644
index 0000000..dda70ea
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Name.php
@@ -0,0 +1,21 @@
+<?php
+
+/**
+ * Pre-transform that changes deprecated name attribute to ID if necessary
+ */
+class HTMLPurifier_AttrTransform_Name extends HTMLPurifier_AttrTransform
+{
+
+ public function transform($attr, $config, $context) {
+ // Abort early if we're using relaxed definition of name
+ if ($config->get('HTML.Attr.Name.UseCDATA')) return $attr;
+ if (!isset($attr['name'])) return $attr;
+ $id = $this->confiscateAttr($attr, 'name');
+ if ( isset($attr['id'])) return $attr;
+ $attr['id'] = $id;
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/NameSync.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/NameSync.php
new file mode 100644
index 0000000..68fae8c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/NameSync.php
@@ -0,0 +1,27 @@
+<?php
+
+/**
+ * Post-transform that performs validation to the name attribute; if
+ * it is present with an equivalent id attribute, it is passed through;
+ * otherwise validation is performed.
+ */
+class HTMLPurifier_AttrTransform_NameSync extends HTMLPurifier_AttrTransform
+{
+
+ public function __construct() {
+ $this->idDef = new HTMLPurifier_AttrDef_HTML_ID();
+ }
+
+ public function transform($attr, $config, $context) {
+ if (!isset($attr['name'])) return $attr;
+ $name = $attr['name'];
+ if (isset($attr['id']) && $attr['id'] === $name) return $attr;
+ $result = $this->idDef->validate($name, $config, $context);
+ if ($result === false) unset($attr['name']);
+ else $attr['name'] = $result;
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Nofollow.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Nofollow.php
new file mode 100644
index 0000000..1ae9edd
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Nofollow.php
@@ -0,0 +1,41 @@
+<?php
+
+// must be called POST validation
+
+/**
+ * Adds rel="nofollow" to all outbound links. This transform is
+ * only attached if Attr.Nofollow is TRUE.
+ */
+class HTMLPurifier_AttrTransform_Nofollow extends HTMLPurifier_AttrTransform
+{
+ private $parser;
+
+ public function __construct() {
+ $this->parser = new HTMLPurifier_URIParser();
+ }
+
+ public function transform($attr, $config, $context) {
+
+ if (!isset($attr['href'])) {
+ return $attr;
+ }
+
+ // XXX Kind of inefficient
+ $url = $this->parser->parse($attr['href']);
+ $scheme = $url->getSchemeObj($config, $context);
+
+ if (!is_null($url->host) && $scheme !== false && $scheme->browsable) {
+ if (isset($attr['rel'])) {
+ $attr['rel'] .= ' nofollow';
+ } else {
+ $attr['rel'] = 'nofollow';
+ }
+ }
+
+ return $attr;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeEmbed.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeEmbed.php
new file mode 100644
index 0000000..1017e6b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeEmbed.php
@@ -0,0 +1,15 @@
+<?php
+
+class HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform
+{
+ public $name = "SafeEmbed";
+
+ public function transform($attr, $config, $context) {
+ $attr['allowscriptaccess'] = 'never';
+ $attr['allownetworking'] = 'internal';
+ $attr['type'] = 'application/x-shockwave-flash';
+ return $attr;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeObject.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeObject.php
new file mode 100644
index 0000000..e909f16
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeObject.php
@@ -0,0 +1,16 @@
+<?php
+
+/**
+ * Writes default type for all objects. Currently only supports flash.
+ */
+class HTMLPurifier_AttrTransform_SafeObject extends HTMLPurifier_AttrTransform
+{
+ public $name = "SafeObject";
+
+ function transform($attr, $config, $context) {
+ if (!isset($attr['type'])) $attr['type'] = 'application/x-shockwave-flash';
+ return $attr;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeParam.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeParam.php
new file mode 100644
index 0000000..21ac90b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/SafeParam.php
@@ -0,0 +1,64 @@
+<?php
+
+/**
+ * Validates name/value pairs in param tags to be used in safe objects. This
+ * will only allow name values it recognizes, and pre-fill certain attributes
+ * with required values.
+ *
+ * @note
+ * This class only supports Flash. In the future, Quicktime support
+ * may be added.
+ *
+ * @warning
+ * This class expects an injector to add the necessary parameters tags.
+ */
+class HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform
+{
+ public $name = "SafeParam";
+ private $uri;
+
+ public function __construct() {
+ $this->uri = new HTMLPurifier_AttrDef_URI(true); // embedded
+ $this->wmode = new HTMLPurifier_AttrDef_Enum(array('window', 'opaque', 'transparent'));
+ }
+
+ public function transform($attr, $config, $context) {
+ // If we add support for other objects, we'll need to alter the
+ // transforms.
+ switch ($attr['name']) {
+ // application/x-shockwave-flash
+ // Keep this synchronized with Injector/SafeObject.php
+ case 'allowScriptAccess':
+ $attr['value'] = 'never';
+ break;
+ case 'allowNetworking':
+ $attr['value'] = 'internal';
+ break;
+ case 'allowFullScreen':
+ if ($config->get('HTML.FlashAllowFullScreen')) {
+ $attr['value'] = ($attr['value'] == 'true') ? 'true' : 'false';
+ } else {
+ $attr['value'] = 'false';
+ }
+ break;
+ case 'wmode':
+ $attr['value'] = $this->wmode->validate($attr['value'], $config, $context);
+ break;
+ case 'movie':
+ case 'src':
+ $attr['name'] = "movie";
+ $attr['value'] = $this->uri->validate($attr['value'], $config, $context);
+ break;
+ case 'flashvars':
+ // we're going to allow arbitrary inputs to the SWF, on
+ // the reasoning that it could only hack the SWF, not us.
+ break;
+ // add other cases to support other param name/value pairs
+ default:
+ $attr['name'] = $attr['value'] = null;
+ }
+ return $attr;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ScriptRequired.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ScriptRequired.php
new file mode 100644
index 0000000..7dfd2e8
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/ScriptRequired.php
@@ -0,0 +1,16 @@
+<?php
+
+/**
+ * Implements required attribute stipulation for <script>
+ */
+class HTMLPurifier_AttrTransform_ScriptRequired extends HTMLPurifier_AttrTransform
+{
+ public function transform($attr, $config, $context) {
+ if (!isset($attr['type'])) {
+ $attr['type'] = 'text/javascript';
+ }
+ return $attr;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Textarea.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Textarea.php
new file mode 100644
index 0000000..83749e9
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTransform/Textarea.php
@@ -0,0 +1,18 @@
+<?php
+
+/**
+ * Sets height/width defaults for <textarea>
+ */
+class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform
+{
+
+ public function transform($attr, $config, $context) {
+ // Calculated from Firefox
+ if (!isset($attr['cols'])) $attr['cols'] = '22';
+ if (!isset($attr['rows'])) $attr['rows'] = '3';
+ return $attr;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTypes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTypes.php
new file mode 100644
index 0000000..8202255
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrTypes.php
@@ -0,0 +1,77 @@
+<?php
+
+/**
+ * Provides lookup array of attribute types to HTMLPurifier_AttrDef objects
+ */
+class HTMLPurifier_AttrTypes
+{
+ /**
+ * Lookup array of attribute string identifiers to concrete implementations
+ */
+ protected $info = array();
+
+ /**
+ * Constructs the info array, supplying default implementations for attribute
+ * types.
+ */
+ public function __construct() {
+ // pseudo-types, must be instantiated via shorthand
+ $this->info['Enum'] = new HTMLPurifier_AttrDef_Enum();
+ $this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool();
+
+ $this->info['CDATA'] = new HTMLPurifier_AttrDef_Text();
+ $this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID();
+ $this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length();
+ $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength();
+ $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens();
+ $this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels();
+ $this->info['Text'] = new HTMLPurifier_AttrDef_Text();
+ $this->info['URI'] = new HTMLPurifier_AttrDef_URI();
+ $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();
+ $this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color();
+
+ // unimplemented aliases
+ $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();
+ $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();
+ $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();
+ $this->info['Character'] = new HTMLPurifier_AttrDef_Text();
+
+ // "proprietary" types
+ $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class();
+
+ // number is really a positive integer (one or more digits)
+ // FIXME: ^^ not always, see start and value of list items
+ $this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true);
+ }
+
+ /**
+ * Retrieves a type
+ * @param $type String type name
+ * @return Object AttrDef for type
+ */
+ public function get($type) {
+
+ // determine if there is any extra info tacked on
+ if (strpos($type, '#') !== false) list($type, $string) = explode('#', $type, 2);
+ else $string = '';
+
+ if (!isset($this->info[$type])) {
+ trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR);
+ return;
+ }
+
+ return $this->info[$type]->make($string);
+
+ }
+
+ /**
+ * Sets a new implementation for a type
+ * @param $type String type name
+ * @param $impl Object AttrDef for type
+ */
+ public function set($type, $impl) {
+ $this->info[$type] = $impl;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrValidator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrValidator.php
new file mode 100644
index 0000000..fb9d92e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/AttrValidator.php
@@ -0,0 +1,162 @@
+<?php
+
+/**
+ * Validates the attributes of a token. Doesn't manage required attributes
+ * very well. The only reason we factored this out was because RemoveForeignElements
+ * also needed it besides ValidateAttributes.
+ */
+class HTMLPurifier_AttrValidator
+{
+
+ /**
+ * Validates the attributes of a token, returning a modified token
+ * that has valid tokens
+ * @param $token Reference to token to validate. We require a reference
+ * because the operation this class performs on the token are
+ * not atomic, so the context CurrentToken to be updated
+ * throughout
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ */
+ public function validateToken(&$token, &$config, $context) {
+
+ $definition = $config->getHTMLDefinition();
+ $e =& $context->get('ErrorCollector', true);
+
+ // initialize IDAccumulator if necessary
+ $ok =& $context->get('IDAccumulator', true);
+ if (!$ok) {
+ $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
+ $context->register('IDAccumulator', $id_accumulator);
+ }
+
+ // initialize CurrentToken if necessary
+ $current_token =& $context->get('CurrentToken', true);
+ if (!$current_token) $context->register('CurrentToken', $token);
+
+ if (
+ !$token instanceof HTMLPurifier_Token_Start &&
+ !$token instanceof HTMLPurifier_Token_Empty
+ ) return $token;
+
+ // create alias to global definition array, see also $defs
+ // DEFINITION CALL
+ $d_defs = $definition->info_global_attr;
+
+ // don't update token until the very end, to ensure an atomic update
+ $attr = $token->attr;
+
+ // do global transformations (pre)
+ // nothing currently utilizes this
+ foreach ($definition->info_attr_transform_pre as $transform) {
+ $attr = $transform->transform($o = $attr, $config, $context);
+ if ($e) {
+ if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+ }
+ }
+
+ // do local transformations only applicable to this element (pre)
+ // ex. <p align="right"> to <p style="text-align:right;">
+ foreach ($definition->info[$token->name]->attr_transform_pre as $transform) {
+ $attr = $transform->transform($o = $attr, $config, $context);
+ if ($e) {
+ if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+ }
+ }
+
+ // create alias to this element's attribute definition array, see
+ // also $d_defs (global attribute definition array)
+ // DEFINITION CALL
+ $defs = $definition->info[$token->name]->attr;
+
+ $attr_key = false;
+ $context->register('CurrentAttr', $attr_key);
+
+ // iterate through all the attribute keypairs
+ // Watch out for name collisions: $key has previously been used
+ foreach ($attr as $attr_key => $value) {
+
+ // call the definition
+ if ( isset($defs[$attr_key]) ) {
+ // there is a local definition defined
+ if ($defs[$attr_key] === false) {
+ // We've explicitly been told not to allow this element.
+ // This is usually when there's a global definition
+ // that must be overridden.
+ // Theoretically speaking, we could have a
+ // AttrDef_DenyAll, but this is faster!
+ $result = false;
+ } else {
+ // validate according to the element's definition
+ $result = $defs[$attr_key]->validate(
+ $value, $config, $context
+ );
+ }
+ } elseif ( isset($d_defs[$attr_key]) ) {
+ // there is a global definition defined, validate according
+ // to the global definition
+ $result = $d_defs[$attr_key]->validate(
+ $value, $config, $context
+ );
+ } else {
+ // system never heard of the attribute? DELETE!
+ $result = false;
+ }
+
+ // put the results into effect
+ if ($result === false || $result === null) {
+ // this is a generic error message that should replaced
+ // with more specific ones when possible
+ if ($e) $e->send(E_ERROR, 'AttrValidator: Attribute removed');
+
+ // remove the attribute
+ unset($attr[$attr_key]);
+ } elseif (is_string($result)) {
+ // generally, if a substitution is happening, there
+ // was some sort of implicit correction going on. We'll
+ // delegate it to the attribute classes to say exactly what.
+
+ // simple substitution
+ $attr[$attr_key] = $result;
+ } else {
+ // nothing happens
+ }
+
+ // we'd also want slightly more complicated substitution
+ // involving an array as the return value,
+ // although we're not sure how colliding attributes would
+ // resolve (certain ones would be completely overriden,
+ // others would prepend themselves).
+ }
+
+ $context->destroy('CurrentAttr');
+
+ // post transforms
+
+ // global (error reporting untested)
+ foreach ($definition->info_attr_transform_post as $transform) {
+ $attr = $transform->transform($o = $attr, $config, $context);
+ if ($e) {
+ if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+ }
+ }
+
+ // local (error reporting untested)
+ foreach ($definition->info[$token->name]->attr_transform_post as $transform) {
+ $attr = $transform->transform($o = $attr, $config, $context);
+ if ($e) {
+ if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+ }
+ }
+
+ $token->attr = $attr;
+
+ // destroy CurrentToken if we made it ourselves
+ if (!$current_token) $context->destroy('CurrentToken');
+
+ }
+
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Bootstrap.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Bootstrap.php
new file mode 100644
index 0000000..7c3e230
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Bootstrap.php
@@ -0,0 +1,104 @@
+<?php
+
+// constants are slow, so we use as few as possible
+if (!defined('HTMLPURIFIER_PREFIX')) {
+ define('HTMLPURIFIER_PREFIX', realpath(dirname(__FILE__) . '/..'));
+}
+
+// accomodations for versions earlier than 5.0.2
+// borrowed from PHP_Compat, LGPL licensed, by Aidan Lister <aidan@php.net>
+if (!defined('PHP_EOL')) {
+ switch (strtoupper(substr(PHP_OS, 0, 3))) {
+ case 'WIN':
+ define('PHP_EOL', "\r\n");
+ break;
+ case 'DAR':
+ define('PHP_EOL', "\r");
+ break;
+ default:
+ define('PHP_EOL', "\n");
+ }
+}
+
+/**
+ * Bootstrap class that contains meta-functionality for HTML Purifier such as
+ * the autoload function.
+ *
+ * @note
+ * This class may be used without any other files from HTML Purifier.
+ */
+class HTMLPurifier_Bootstrap
+{
+
+ /**
+ * Autoload function for HTML Purifier
+ * @param $class Class to load
+ */
+ public static function autoload($class) {
+ $file = HTMLPurifier_Bootstrap::getPath($class);
+ if (!$file) return false;
+ // Technically speaking, it should be ok and more efficient to
+ // just do 'require', but Antonio Parraga reports that with
+ // Zend extensions such as Zend debugger and APC, this invariant
+ // may be broken. Since we have efficient alternatives, pay
+ // the cost here and avoid the bug.
+ require_once HTMLPURIFIER_PREFIX . '/' . $file;
+ return true;
+ }
+
+ /**
+ * Returns the path for a specific class.
+ */
+ public static function getPath($class) {
+ if (strncmp('HTMLPurifier', $class, 12) !== 0) return false;
+ // Custom implementations
+ if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) {
+ $code = str_replace('_', '-', substr($class, 22));
+ $file = 'HTMLPurifier/Language/classes/' . $code . '.php';
+ } else {
+ $file = str_replace('_', '/', $class) . '.php';
+ }
+ if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) return false;
+ return $file;
+ }
+
+ /**
+ * "Pre-registers" our autoloader on the SPL stack.
+ */
+ public static function registerAutoload() {
+ $autoload = array('HTMLPurifier_Bootstrap', 'autoload');
+ if ( ($funcs = spl_autoload_functions()) === false ) {
+ spl_autoload_register($autoload);
+ } elseif (function_exists('spl_autoload_unregister')) {
+ $buggy = version_compare(PHP_VERSION, '5.2.11', '<');
+ $compat = version_compare(PHP_VERSION, '5.1.2', '<=') &&
+ version_compare(PHP_VERSION, '5.1.0', '>=');
+ foreach ($funcs as $func) {
+ if ($buggy && is_array($func)) {
+ // :TRICKY: There are some compatibility issues and some
+ // places where we need to error out
+ $reflector = new ReflectionMethod($func[0], $func[1]);
+ if (!$reflector->isStatic()) {
+ throw new Exception('
+ HTML Purifier autoloader registrar is not compatible
+ with non-static object methods due to PHP Bug #44144;
+ Please do not use HTMLPurifier.autoload.php (or any
+ file that includes this file); instead, place the code:
+ spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\'))
+ after your own autoloaders.
+ ');
+ }
+ // Suprisingly, spl_autoload_register supports the
+ // Class::staticMethod callback format, although call_user_func doesn't
+ if ($compat) $func = implode('::', $func);
+ }
+ spl_autoload_unregister($func);
+ }
+ spl_autoload_register($autoload);
+ foreach ($funcs as $func) spl_autoload_register($func);
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/CSSDefinition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/CSSDefinition.php
new file mode 100644
index 0000000..9d0460c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/CSSDefinition.php
@@ -0,0 +1,322 @@
+<?php
+
+/**
+ * Defines allowed CSS attributes and what their values are.
+ * @see HTMLPurifier_HTMLDefinition
+ */
+class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition
+{
+
+ public $type = 'CSS';
+
+ /**
+ * Assoc array of attribute name to definition object.
+ */
+ public $info = array();
+
+ /**
+ * Constructs the info array. The meat of this class.
+ */
+ protected function doSetup($config) {
+
+ $this->info['text-align'] = new HTMLPurifier_AttrDef_Enum(
+ array('left', 'right', 'center', 'justify'), false);
+
+ $border_style =
+ $this->info['border-bottom-style'] =
+ $this->info['border-right-style'] =
+ $this->info['border-left-style'] =
+ $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum(
+ array('none', 'hidden', 'dotted', 'dashed', 'solid', 'double',
+ 'groove', 'ridge', 'inset', 'outset'), false);
+
+ $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style);
+
+ $this->info['clear'] = new HTMLPurifier_AttrDef_Enum(
+ array('none', 'left', 'right', 'both'), false);
+ $this->info['float'] = new HTMLPurifier_AttrDef_Enum(
+ array('none', 'left', 'right'), false);
+ $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum(
+ array('normal', 'italic', 'oblique'), false);
+ $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum(
+ array('normal', 'small-caps'), false);
+
+ $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite(
+ array(
+ new HTMLPurifier_AttrDef_Enum(array('none')),
+ new HTMLPurifier_AttrDef_CSS_URI()
+ )
+ );
+
+ $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum(
+ array('inside', 'outside'), false);
+ $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum(
+ array('disc', 'circle', 'square', 'decimal', 'lower-roman',
+ 'upper-roman', 'lower-alpha', 'upper-alpha', 'none'), false);
+ $this->info['list-style-image'] = $uri_or_none;
+
+ $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config);
+
+ $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum(
+ array('capitalize', 'uppercase', 'lowercase', 'none'), false);
+ $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color();
+
+ $this->info['background-image'] = $uri_or_none;
+ $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum(
+ array('repeat', 'repeat-x', 'repeat-y', 'no-repeat')
+ );
+ $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum(
+ array('scroll', 'fixed')
+ );
+ $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition();
+
+ $border_color =
+ $this->info['border-top-color'] =
+ $this->info['border-bottom-color'] =
+ $this->info['border-left-color'] =
+ $this->info['border-right-color'] =
+ $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('transparent')),
+ new HTMLPurifier_AttrDef_CSS_Color()
+ ));
+
+ $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config);
+
+ $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color);
+
+ $border_width =
+ $this->info['border-top-width'] =
+ $this->info['border-bottom-width'] =
+ $this->info['border-left-width'] =
+ $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')),
+ new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative
+ ));
+
+ $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width);
+
+ $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('normal')),
+ new HTMLPurifier_AttrDef_CSS_Length()
+ ));
+
+ $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('normal')),
+ new HTMLPurifier_AttrDef_CSS_Length()
+ ));
+
+ $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('xx-small', 'x-small',
+ 'small', 'medium', 'large', 'x-large', 'xx-large',
+ 'larger', 'smaller')),
+ new HTMLPurifier_AttrDef_CSS_Percentage(),
+ new HTMLPurifier_AttrDef_CSS_Length()
+ ));
+
+ $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('normal')),
+ new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives
+ new HTMLPurifier_AttrDef_CSS_Length('0'),
+ new HTMLPurifier_AttrDef_CSS_Percentage(true)
+ ));
+
+ $margin =
+ $this->info['margin-top'] =
+ $this->info['margin-bottom'] =
+ $this->info['margin-left'] =
+ $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_CSS_Length(),
+ new HTMLPurifier_AttrDef_CSS_Percentage(),
+ new HTMLPurifier_AttrDef_Enum(array('auto'))
+ ));
+
+ $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin);
+
+ // non-negative
+ $padding =
+ $this->info['padding-top'] =
+ $this->info['padding-bottom'] =
+ $this->info['padding-left'] =
+ $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_CSS_Length('0'),
+ new HTMLPurifier_AttrDef_CSS_Percentage(true)
+ ));
+
+ $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding);
+
+ $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_CSS_Length(),
+ new HTMLPurifier_AttrDef_CSS_Percentage()
+ ));
+
+ $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_CSS_Length('0'),
+ new HTMLPurifier_AttrDef_CSS_Percentage(true),
+ new HTMLPurifier_AttrDef_Enum(array('auto'))
+ ));
+ $max = $config->get('CSS.MaxImgLength');
+
+ $this->info['width'] =
+ $this->info['height'] =
+ $max === null ?
+ $trusted_wh :
+ new HTMLPurifier_AttrDef_Switch('img',
+ // For img tags:
+ new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_CSS_Length('0', $max),
+ new HTMLPurifier_AttrDef_Enum(array('auto'))
+ )),
+ // For everyone else:
+ $trusted_wh
+ );
+
+ $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration();
+
+ $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily();
+
+ // this could use specialized code
+ $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum(
+ array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300',
+ '400', '500', '600', '700', '800', '900'), false);
+
+ // MUST be called after other font properties, as it references
+ // a CSSDefinition object
+ $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config);
+
+ // same here
+ $this->info['border'] =
+ $this->info['border-bottom'] =
+ $this->info['border-top'] =
+ $this->info['border-left'] =
+ $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);
+
+ $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(array(
+ 'collapse', 'separate'));
+
+ $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(array(
+ 'top', 'bottom'));
+
+ $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum(array(
+ 'auto', 'fixed'));
+
+ $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Enum(array('baseline', 'sub', 'super',
+ 'top', 'text-top', 'middle', 'bottom', 'text-bottom')),
+ new HTMLPurifier_AttrDef_CSS_Length(),
+ new HTMLPurifier_AttrDef_CSS_Percentage()
+ ));
+
+ $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);
+
+ // partial support
+ $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(array('nowrap'));
+
+ if ($config->get('CSS.Proprietary')) {
+ $this->doSetupProprietary($config);
+ }
+
+ if ($config->get('CSS.AllowTricky')) {
+ $this->doSetupTricky($config);
+ }
+
+ if ($config->get('CSS.Trusted')) {
+ $this->doSetupTrusted($config);
+ }
+
+ $allow_important = $config->get('CSS.AllowImportant');
+ // wrap all attr-defs with decorator that handles !important
+ foreach ($this->info as $k => $v) {
+ $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);
+ }
+
+ $this->setupConfigStuff($config);
+ }
+
+ protected function doSetupProprietary($config) {
+ // Internet Explorer only scrollbar colors
+ $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
+ $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color();
+ $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
+ $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color();
+ $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color();
+ $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
+
+ // technically not proprietary, but CSS3, and no one supports it
+ $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
+ $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
+ $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
+
+ // only opacity, for now
+ $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter();
+
+ }
+
+ protected function doSetupTricky($config) {
+ $this->info['display'] = new HTMLPurifier_AttrDef_Enum(array(
+ 'inline', 'block', 'list-item', 'run-in', 'compact',
+ 'marker', 'table', 'inline-table', 'table-row-group',
+ 'table-header-group', 'table-footer-group', 'table-row',
+ 'table-column-group', 'table-column', 'table-cell', 'table-caption', 'none'
+ ));
+ $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(array(
+ 'visible', 'hidden', 'collapse'
+ ));
+ $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));
+ }
+
+ protected function doSetupTrusted($config) {
+ $this->info['position'] = new HTMLPurifier_AttrDef_Enum(array(
+ 'static', 'relative', 'absolute', 'fixed'
+ ));
+ $this->info['top'] =
+ $this->info['left'] =
+ $this->info['right'] =
+ $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_CSS_Length(),
+ new HTMLPurifier_AttrDef_CSS_Percentage(),
+ new HTMLPurifier_AttrDef_Enum(array('auto')),
+ ));
+ $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
+ new HTMLPurifier_AttrDef_Integer(),
+ new HTMLPurifier_AttrDef_Enum(array('auto')),
+ ));
+ }
+
+ /**
+ * Performs extra config-based processing. Based off of
+ * HTMLPurifier_HTMLDefinition.
+ * @todo Refactor duplicate elements into common class (probably using
+ * composition, not inheritance).
+ */
+ protected function setupConfigStuff($config) {
+
+ // setup allowed elements
+ $support = "(for information on implementing this, see the ".
+ "support forums) ";
+ $allowed_properties = $config->get('CSS.AllowedProperties');
+ if ($allowed_properties !== null) {
+ foreach ($this->info as $name => $d) {
+ if(!isset($allowed_properties[$name])) unset($this->info[$name]);
+ unset($allowed_properties[$name]);
+ }
+ // emit errors
+ foreach ($allowed_properties as $name => $d) {
+ // :TODO: Is this htmlspecialchars() call really necessary?
+ $name = htmlspecialchars($name);
+ trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING);
+ }
+ }
+
+ $forbidden_properties = $config->get('CSS.ForbiddenProperties');
+ if ($forbidden_properties !== null) {
+ foreach ($this->info as $name => $d) {
+ if (isset($forbidden_properties[$name])) {
+ unset($this->info[$name]);
+ }
+ }
+ }
+
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef.php
new file mode 100644
index 0000000..2b3456c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef.php
@@ -0,0 +1,48 @@
+<?php
+
+/**
+ * Defines allowed child nodes and validates tokens against it.
+ */
+abstract class HTMLPurifier_ChildDef
+{
+ /**
+ * Type of child definition, usually right-most part of class name lowercase.
+ * Used occasionally in terms of context.
+ */
+ public $type;
+
+ /**
+ * Bool that indicates whether or not an empty array of children is okay
+ *
+ * This is necessary for redundant checking when changes affecting
+ * a child node may cause a parent node to now be disallowed.
+ */
+ public $allow_empty;
+
+ /**
+ * Lookup array of all elements that this definition could possibly allow
+ */
+ public $elements = array();
+
+ /**
+ * Get lookup of tag names that should not close this element automatically.
+ * All other elements will do so.
+ */
+ public function getAllowedElements($config) {
+ return $this->elements;
+ }
+
+ /**
+ * Validates nodes according to definition and returns modification.
+ *
+ * @param $tokens_of_children Array of HTMLPurifier_Token
+ * @param $config HTMLPurifier_Config object
+ * @param $context HTMLPurifier_Context object
+ * @return bool true to leave nodes as is
+ * @return bool false to remove parent node
+ * @return array of replacement child tokens
+ */
+ abstract public function validateChildren($tokens_of_children, $config, $context);
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Chameleon.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Chameleon.php
new file mode 100644
index 0000000..4b1956f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Chameleon.php
@@ -0,0 +1,48 @@
+<?php
+
+/**
+ * Definition that uses different definitions depending on context.
+ *
+ * The del and ins tags are notable because they allow different types of
+ * elements depending on whether or not they're in a block or inline context.
+ * Chameleon allows this behavior to happen by using two different
+ * definitions depending on context. While this somewhat generalized,
+ * it is specifically intended for those two tags.
+ */
+class HTMLPurifier_ChildDef_Chameleon extends HTMLPurifier_ChildDef
+{
+
+ /**
+ * Instance of the definition object to use when inline. Usually stricter.
+ */
+ public $inline;
+
+ /**
+ * Instance of the definition object to use when block.
+ */
+ public $block;
+
+ public $type = 'chameleon';
+
+ /**
+ * @param $inline List of elements to allow when inline.
+ * @param $block List of elements to allow when block.
+ */
+ public function __construct($inline, $block) {
+ $this->inline = new HTMLPurifier_ChildDef_Optional($inline);
+ $this->block = new HTMLPurifier_ChildDef_Optional($block);
+ $this->elements = $this->block->elements;
+ }
+
+ public function validateChildren($tokens_of_children, $config, $context) {
+ if ($context->get('IsInline') === false) {
+ return $this->block->validateChildren(
+ $tokens_of_children, $config, $context);
+ } else {
+ return $this->inline->validateChildren(
+ $tokens_of_children, $config, $context);
+ }
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Custom.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Custom.php
new file mode 100644
index 0000000..b7816c5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Custom.php
@@ -0,0 +1,90 @@
+<?php
+
+/**
+ * Custom validation class, accepts DTD child definitions
+ *
+ * @warning Currently this class is an all or nothing proposition, that is,
+ * it will only give a bool return value.
+ */
+class HTMLPurifier_ChildDef_Custom extends HTMLPurifier_ChildDef
+{
+ public $type = 'custom';
+ public $allow_empty = false;
+ /**
+ * Allowed child pattern as defined by the DTD
+ */
+ public $dtd_regex;
+ /**
+ * PCRE regex derived from $dtd_regex
+ * @private
+ */
+ private $_pcre_regex;
+ /**
+ * @param $dtd_regex Allowed child pattern from the DTD
+ */
+ public function __construct($dtd_regex) {
+ $this->dtd_regex = $dtd_regex;
+ $this->_compileRegex();
+ }
+ /**
+ * Compiles the PCRE regex from a DTD regex ($dtd_regex to $_pcre_regex)
+ */
+ protected function _compileRegex() {
+ $raw = str_replace(' ', '', $this->dtd_regex);
+ if ($raw{0} != '(') {
+ $raw = "($raw)";
+ }
+ $el = '[#a-zA-Z0-9_.-]+';
+ $reg = $raw;
+
+ // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M
+ // DOING! Seriously: if there's problems, please report them.
+
+ // collect all elements into the $elements array
+ preg_match_all("/$el/", $reg, $matches);
+ foreach ($matches[0] as $match) {
+ $this->elements[$match] = true;
+ }
+
+ // setup all elements as parentheticals with leading commas
+ $reg = preg_replace("/$el/", '(,\\0)', $reg);
+
+ // remove commas when they were not solicited
+ $reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg);
+
+ // remove all non-paranthetical commas: they are handled by first regex
+ $reg = preg_replace("/,\(/", '(', $reg);
+
+ $this->_pcre_regex = $reg;
+ }
+ public function validateChildren($tokens_of_children, $config, $context) {
+ $list_of_children = '';
+ $nesting = 0; // depth into the nest
+ foreach ($tokens_of_children as $token) {
+ if (!empty($token->is_whitespace)) continue;
+
+ $is_child = ($nesting == 0); // direct
+
+ if ($token instanceof HTMLPurifier_Token_Start) {
+ $nesting++;
+ } elseif ($token instanceof HTMLPurifier_Token_End) {
+ $nesting--;
+ }
+
+ if ($is_child) {
+ $list_of_children .= $token->name . ',';
+ }
+ }
+ // add leading comma to deal with stray comma declarations
+ $list_of_children = ',' . rtrim($list_of_children, ',');
+ $okay =
+ preg_match(
+ '/^,?'.$this->_pcre_regex.'$/',
+ $list_of_children
+ );
+
+ return (bool) $okay;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Empty.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Empty.php
new file mode 100644
index 0000000..3ab3ba2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Empty.php
@@ -0,0 +1,20 @@
+<?php
+
+/**
+ * Definition that disallows all elements.
+ * @warning validateChildren() in this class is actually never called, because
+ * empty elements are corrected in HTMLPurifier_Strategy_MakeWellFormed
+ * before child definitions are parsed in earnest by
+ * HTMLPurifier_Strategy_FixNesting.
+ */
+class HTMLPurifier_ChildDef_Empty extends HTMLPurifier_ChildDef
+{
+ public $allow_empty = true;
+ public $type = 'empty';
+ public function __construct() {}
+ public function validateChildren($tokens_of_children, $config, $context) {
+ return array();
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Optional.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Optional.php
new file mode 100644
index 0000000..02efaeb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Optional.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * Definition that allows a set of elements, and allows no children.
+ * @note This is a hack to reuse code from HTMLPurifier_ChildDef_Required,
+ * really, one shouldn't inherit from the other. Only altered behavior
+ * is to overload a returned false with an array. Thus, it will never
+ * return false.
+ */
+class HTMLPurifier_ChildDef_Optional extends HTMLPurifier_ChildDef_Required
+{
+ public $allow_empty = true;
+ public $type = 'optional';
+ public function validateChildren($tokens_of_children, $config, $context) {
+ $result = parent::validateChildren($tokens_of_children, $config, $context);
+ // we assume that $tokens_of_children is not modified
+ if ($result === false) {
+ if (empty($tokens_of_children)) return true;
+ elseif ($this->whitespace) return $tokens_of_children;
+ else return array();
+ }
+ return $result;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Required.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Required.php
new file mode 100644
index 0000000..7751c12
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Required.php
@@ -0,0 +1,117 @@
+<?php
+
+/**
+ * Definition that allows a set of elements, but disallows empty children.
+ */
+class HTMLPurifier_ChildDef_Required extends HTMLPurifier_ChildDef
+{
+ /**
+ * Lookup table of allowed elements.
+ * @public
+ */
+ public $elements = array();
+ /**
+ * Whether or not the last passed node was all whitespace.
+ */
+ protected $whitespace = false;
+ /**
+ * @param $elements List of allowed element names (lowercase).
+ */
+ public function __construct($elements) {
+ if (is_string($elements)) {
+ $elements = str_replace(' ', '', $elements);
+ $elements = explode('|', $elements);
+ }
+ $keys = array_keys($elements);
+ if ($keys == array_keys($keys)) {
+ $elements = array_flip($elements);
+ foreach ($elements as $i => $x) {
+ $elements[$i] = true;
+ if (empty($i)) unset($elements[$i]); // remove blank
+ }
+ }
+ $this->elements = $elements;
+ }
+ public $allow_empty = false;
+ public $type = 'required';
+ public function validateChildren($tokens_of_children, $config, $context) {
+ // Flag for subclasses
+ $this->whitespace = false;
+
+ // if there are no tokens, delete parent node
+ if (empty($tokens_of_children)) return false;
+
+ // the new set of children
+ $result = array();
+
+ // current depth into the nest
+ $nesting = 0;
+
+ // whether or not we're deleting a node
+ $is_deleting = false;
+
+ // whether or not parsed character data is allowed
+ // this controls whether or not we silently drop a tag
+ // or generate escaped HTML from it
+ $pcdata_allowed = isset($this->elements['#PCDATA']);
+
+ // a little sanity check to make sure it's not ALL whitespace
+ $all_whitespace = true;
+
+ // some configuration
+ $escape_invalid_children = $config->get('Core.EscapeInvalidChildren');
+
+ // generator
+ $gen = new HTMLPurifier_Generator($config, $context);
+
+ foreach ($tokens_of_children as $token) {
+ if (!empty($token->is_whitespace)) {
+ $result[] = $token;
+ continue;
+ }
+ $all_whitespace = false; // phew, we're not talking about whitespace
+
+ $is_child = ($nesting == 0);
+
+ if ($token instanceof HTMLPurifier_Token_Start) {
+ $nesting++;
+ } elseif ($token instanceof HTMLPurifier_Token_End) {
+ $nesting--;
+ }
+
+ if ($is_child) {
+ $is_deleting = false;
+ if (!isset($this->elements[$token->name])) {
+ $is_deleting = true;
+ if ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text) {
+ $result[] = $token;
+ } elseif ($pcdata_allowed && $escape_invalid_children) {
+ $result[] = new HTMLPurifier_Token_Text(
+ $gen->generateFromToken($token)
+ );
+ }
+ continue;
+ }
+ }
+ if (!$is_deleting || ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text)) {
+ $result[] = $token;
+ } elseif ($pcdata_allowed && $escape_invalid_children) {
+ $result[] =
+ new HTMLPurifier_Token_Text(
+ $gen->generateFromToken($token)
+ );
+ } else {
+ // drop silently
+ }
+ }
+ if (empty($result)) return false;
+ if ($all_whitespace) {
+ $this->whitespace = true;
+ return false;
+ }
+ if ($tokens_of_children == $result) return true;
+ return $result;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/StrictBlockquote.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/StrictBlockquote.php
new file mode 100644
index 0000000..3a8cfbc
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/StrictBlockquote.php
@@ -0,0 +1,88 @@
+<?php
+
+/**
+ * Takes the contents of blockquote when in strict and reformats for validation.
+ */
+class HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Required
+{
+ protected $real_elements;
+ protected $fake_elements;
+ public $allow_empty = true;
+ public $type = 'strictblockquote';
+ protected $init = false;
+
+ /**
+ * @note We don't want MakeWellFormed to auto-close inline elements since
+ * they might be allowed.
+ */
+ public function getAllowedElements($config) {
+ $this->init($config);
+ return $this->fake_elements;
+ }
+
+ public function validateChildren($tokens_of_children, $config, $context) {
+
+ $this->init($config);
+
+ // trick the parent class into thinking it allows more
+ $this->elements = $this->fake_elements;
+ $result = parent::validateChildren($tokens_of_children, $config, $context);
+ $this->elements = $this->real_elements;
+
+ if ($result === false) return array();
+ if ($result === true) $result = $tokens_of_children;
+
+ $def = $config->getHTMLDefinition();
+ $block_wrap_start = new HTMLPurifier_Token_Start($def->info_block_wrapper);
+ $block_wrap_end = new HTMLPurifier_Token_End( $def->info_block_wrapper);
+ $is_inline = false;
+ $depth = 0;
+ $ret = array();
+
+ // assuming that there are no comment tokens
+ foreach ($result as $i => $token) {
+ $token = $result[$i];
+ // ifs are nested for readability
+ if (!$is_inline) {
+ if (!$depth) {
+ if (
+ ($token instanceof HTMLPurifier_Token_Text && !$token->is_whitespace) ||
+ (!$token instanceof HTMLPurifier_Token_Text && !isset($this->elements[$token->name]))
+ ) {
+ $is_inline = true;
+ $ret[] = $block_wrap_start;
+ }
+ }
+ } else {
+ if (!$depth) {
+ // starting tokens have been inline text / empty
+ if ($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) {
+ if (isset($this->elements[$token->name])) {
+ // ended
+ $ret[] = $block_wrap_end;
+ $is_inline = false;
+ }
+ }
+ }
+ }
+ $ret[] = $token;
+ if ($token instanceof HTMLPurifier_Token_Start) $depth++;
+ if ($token instanceof HTMLPurifier_Token_End) $depth--;
+ }
+ if ($is_inline) $ret[] = $block_wrap_end;
+ return $ret;
+ }
+
+ private function init($config) {
+ if (!$this->init) {
+ $def = $config->getHTMLDefinition();
+ // allow all inline elements
+ $this->real_elements = $this->elements;
+ $this->fake_elements = $def->info_content_sets['Flow'];
+ $this->fake_elements['#PCDATA'] = true;
+ $this->init = true;
+ }
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Table.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Table.php
new file mode 100644
index 0000000..7e6e435
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ChildDef/Table.php
@@ -0,0 +1,142 @@
+<?php
+
+/**
+ * Definition for tables
+ */
+class HTMLPurifier_ChildDef_Table extends HTMLPurifier_ChildDef
+{
+ public $allow_empty = false;
+ public $type = 'table';
+ public $elements = array('tr' => true, 'tbody' => true, 'thead' => true,
+ 'tfoot' => true, 'caption' => true, 'colgroup' => true, 'col' => true);
+ public function __construct() {}
+ public function validateChildren($tokens_of_children, $config, $context) {
+ if (empty($tokens_of_children)) return false;
+
+ // this ensures that the loop gets run one last time before closing
+ // up. It's a little bit of a hack, but it works! Just make sure you
+ // get rid of the token later.
+ $tokens_of_children[] = false;
+
+ // only one of these elements is allowed in a table
+ $caption = false;
+ $thead = false;
+ $tfoot = false;
+
+ // as many of these as you want
+ $cols = array();
+ $content = array();
+
+ $nesting = 0; // current depth so we can determine nodes
+ $is_collecting = false; // are we globbing together tokens to package
+ // into one of the collectors?
+ $collection = array(); // collected nodes
+ $tag_index = 0; // the first node might be whitespace,
+ // so this tells us where the start tag is
+
+ foreach ($tokens_of_children as $token) {
+ $is_child = ($nesting == 0);
+
+ if ($token === false) {
+ // terminating sequence started
+ } elseif ($token instanceof HTMLPurifier_Token_Start) {
+ $nesting++;
+ } elseif ($token instanceof HTMLPurifier_Token_End) {
+ $nesting--;
+ }
+
+ // handle node collection
+ if ($is_collecting) {
+ if ($is_child) {
+ // okay, let's stash the tokens away
+ // first token tells us the type of the collection
+ switch ($collection[$tag_index]->name) {
+ case 'tr':
+ case 'tbody':
+ $content[] = $collection;
+ break;
+ case 'caption':
+ if ($caption !== false) break;
+ $caption = $collection;
+ break;
+ case 'thead':
+ case 'tfoot':
+ // access the appropriate variable, $thead or $tfoot
+ $var = $collection[$tag_index]->name;
+ if ($$var === false) {
+ $$var = $collection;
+ } else {
+ // transmutate the first and less entries into
+ // tbody tags, and then put into content
+ $collection[$tag_index]->name = 'tbody';
+ $collection[count($collection)-1]->name = 'tbody';
+ $content[] = $collection;
+ }
+ break;
+ case 'colgroup':
+ $cols[] = $collection;
+ break;
+ }
+ $collection = array();
+ $is_collecting = false;
+ $tag_index = 0;
+ } else {
+ // add the node to the collection
+ $collection[] = $token;
+ }
+ }
+
+ // terminate
+ if ($token === false) break;
+
+ if ($is_child) {
+ // determine what we're dealing with
+ if ($token->name == 'col') {
+ // the only empty tag in the possie, we can handle it
+ // immediately
+ $cols[] = array_merge($collection, array($token));
+ $collection = array();
+ $tag_index = 0;
+ continue;
+ }
+ switch($token->name) {
+ case 'caption':
+ case 'colgroup':
+ case 'thead':
+ case 'tfoot':
+ case 'tbody':
+ case 'tr':
+ $is_collecting = true;
+ $collection[] = $token;
+ continue;
+ default:
+ if (!empty($token->is_whitespace)) {
+ $collection[] = $token;
+ $tag_index++;
+ }
+ continue;
+ }
+ }
+ }
+
+ if (empty($content)) return false;
+
+ $ret = array();
+ if ($caption !== false) $ret = array_merge($ret, $caption);
+ if ($cols !== false) foreach ($cols as $token_array) $ret = array_merge($ret, $token_array);
+ if ($thead !== false) $ret = array_merge($ret, $thead);
+ if ($tfoot !== false) $ret = array_merge($ret, $tfoot);
+ foreach ($content as $token_array) $ret = array_merge($ret, $token_array);
+ if (!empty($collection) && $is_collecting == false){
+ // grab the trailing space
+ $ret = array_merge($ret, $collection);
+ }
+
+ array_pop($tokens_of_children); // remove phantom token
+
+ return ($ret === $tokens_of_children) ? true : $ret;
+
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Config.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Config.php
new file mode 100644
index 0000000..49ffab7
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Config.php
@@ -0,0 +1,709 @@
+<?php
+
+/**
+ * Configuration object that triggers customizable behavior.
+ *
+ * @warning This class is strongly defined: that means that the class
+ * will fail if an undefined directive is retrieved or set.
+ *
+ * @note Many classes that could (although many times don't) use the
+ * configuration object make it a mandatory parameter. This is
+ * because a configuration object should always be forwarded,
+ * otherwise, you run the risk of missing a parameter and then
+ * being stumped when a configuration directive doesn't work.
+ *
+ * @todo Reconsider some of the public member variables
+ */
+class HTMLPurifier_Config
+{
+
+ /**
+ * HTML Purifier's version
+ */
+ public $version = '4.3.0';
+
+ /**
+ * Bool indicator whether or not to automatically finalize
+ * the object if a read operation is done
+ */
+ public $autoFinalize = true;
+
+ // protected member variables
+
+ /**
+ * Namespace indexed array of serials for specific namespaces (see
+ * getSerial() for more info).
+ */
+ protected $serials = array();
+
+ /**
+ * Serial for entire configuration object
+ */
+ protected $serial;
+
+ /**
+ * Parser for variables
+ */
+ protected $parser;
+
+ /**
+ * Reference HTMLPurifier_ConfigSchema for value checking
+ * @note This is public for introspective purposes. Please don't
+ * abuse!
+ */
+ public $def;
+
+ /**
+ * Indexed array of definitions
+ */
+ protected $definitions;
+
+ /**
+ * Bool indicator whether or not config is finalized
+ */
+ protected $finalized = false;
+
+ /**
+ * Property list containing configuration directives.
+ */
+ protected $plist;
+
+ /**
+ * Whether or not a set is taking place due to an
+ * alias lookup.
+ */
+ private $aliasMode;
+
+ /**
+ * Set to false if you do not want line and file numbers in errors
+ * (useful when unit testing). This will also compress some errors
+ * and exceptions.
+ */
+ public $chatty = true;
+
+ /**
+ * Current lock; only gets to this namespace are allowed.
+ */
+ private $lock;
+
+ /**
+ * @param $definition HTMLPurifier_ConfigSchema that defines what directives
+ * are allowed.
+ */
+ public function __construct($definition, $parent = null) {
+ $parent = $parent ? $parent : $definition->defaultPlist;
+ $this->plist = new HTMLPurifier_PropertyList($parent);
+ $this->def = $definition; // keep a copy around for checking
+ $this->parser = new HTMLPurifier_VarParser_Flexible();
+ }
+
+ /**
+ * Convenience constructor that creates a config object based on a mixed var
+ * @param mixed $config Variable that defines the state of the config
+ * object. Can be: a HTMLPurifier_Config() object,
+ * an array of directives based on loadArray(),
+ * or a string filename of an ini file.
+ * @param HTMLPurifier_ConfigSchema Schema object
+ * @return Configured HTMLPurifier_Config object
+ */
+ public static function create($config, $schema = null) {
+ if ($config instanceof HTMLPurifier_Config) {
+ // pass-through
+ return $config;
+ }
+ if (!$schema) {
+ $ret = HTMLPurifier_Config::createDefault();
+ } else {
+ $ret = new HTMLPurifier_Config($schema);
+ }
+ if (is_string($config)) $ret->loadIni($config);
+ elseif (is_array($config)) $ret->loadArray($config);
+ return $ret;
+ }
+
+ /**
+ * Creates a new config object that inherits from a previous one.
+ * @param HTMLPurifier_Config $config Configuration object to inherit
+ * from.
+ * @return HTMLPurifier_Config object with $config as its parent.
+ */
+ public static function inherit(HTMLPurifier_Config $config) {
+ return new HTMLPurifier_Config($config->def, $config->plist);
+ }
+
+ /**
+ * Convenience constructor that creates a default configuration object.
+ * @return Default HTMLPurifier_Config object.
+ */
+ public static function createDefault() {
+ $definition = HTMLPurifier_ConfigSchema::instance();
+ $config = new HTMLPurifier_Config($definition);
+ return $config;
+ }
+
+ /**
+ * Retreives a value from the configuration.
+ * @param $key String key
+ */
+ public function get($key, $a = null) {
+ if ($a !== null) {
+ $this->triggerError("Using deprecated API: use \$config->get('$key.$a') instead", E_USER_WARNING);
+ $key = "$key.$a";
+ }
+ if (!$this->finalized) $this->autoFinalize();
+ if (!isset($this->def->info[$key])) {
+ // can't add % due to SimpleTest bug
+ $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
+ E_USER_WARNING);
+ return;
+ }
+ if (isset($this->def->info[$key]->isAlias)) {
+ $d = $this->def->info[$key];
+ $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,
+ E_USER_ERROR);
+ return;
+ }
+ if ($this->lock) {
+ list($ns) = explode('.', $key);
+ if ($ns !== $this->lock) {
+ $this->triggerError('Cannot get value of namespace ' . $ns . ' when lock for ' . $this->lock . ' is active, this probably indicates a Definition setup method is accessing directives that are not within its namespace', E_USER_ERROR);
+ return;
+ }
+ }
+ return $this->plist->get($key);
+ }
+
+ /**
+ * Retreives an array of directives to values from a given namespace
+ * @param $namespace String namespace
+ */
+ public function getBatch($namespace) {
+ if (!$this->finalized) $this->autoFinalize();
+ $full = $this->getAll();
+ if (!isset($full[$namespace])) {
+ $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
+ E_USER_WARNING);
+ return;
+ }
+ return $full[$namespace];
+ }
+
+ /**
+ * Returns a md5 signature of a segment of the configuration object
+ * that uniquely identifies that particular configuration
+ * @note Revision is handled specially and is removed from the batch
+ * before processing!
+ * @param $namespace Namespace to get serial for
+ */
+ public function getBatchSerial($namespace) {
+ if (empty($this->serials[$namespace])) {
+ $batch = $this->getBatch($namespace);
+ unset($batch['DefinitionRev']);
+ $this->serials[$namespace] = md5(serialize($batch));
+ }
+ return $this->serials[$namespace];
+ }
+
+ /**
+ * Returns a md5 signature for the entire configuration object
+ * that uniquely identifies that particular configuration
+ */
+ public function getSerial() {
+ if (empty($this->serial)) {
+ $this->serial = md5(serialize($this->getAll()));
+ }
+ return $this->serial;
+ }
+
+ /**
+ * Retrieves all directives, organized by namespace
+ * @warning This is a pretty inefficient function, avoid if you can
+ */
+ public function getAll() {
+ if (!$this->finalized) $this->autoFinalize();
+ $ret = array();
+ foreach ($this->plist->squash() as $name => $value) {
+ list($ns, $key) = explode('.', $name, 2);
+ $ret[$ns][$key] = $value;
+ }
+ return $ret;
+ }
+
+ /**
+ * Sets a value to configuration.
+ * @param $key String key
+ * @param $value Mixed value
+ */
+ public function set($key, $value, $a = null) {
+ if (strpos($key, '.') === false) {
+ $namespace = $key;
+ $directive = $value;
+ $value = $a;
+ $key = "$key.$directive";
+ $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
+ } else {
+ list($namespace) = explode('.', $key);
+ }
+ if ($this->isFinalized('Cannot set directive after finalization')) return;
+ if (!isset($this->def->info[$key])) {
+ $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
+ E_USER_WARNING);
+ return;
+ }
+ $def = $this->def->info[$key];
+
+ if (isset($def->isAlias)) {
+ if ($this->aliasMode) {
+ $this->triggerError('Double-aliases not allowed, please fix '.
+ 'ConfigSchema bug with' . $key, E_USER_ERROR);
+ return;
+ }
+ $this->aliasMode = true;
+ $this->set($def->key, $value);
+ $this->aliasMode = false;
+ $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
+ return;
+ }
+
+ // Raw type might be negative when using the fully optimized form
+ // of stdclass, which indicates allow_null == true
+ $rtype = is_int($def) ? $def : $def->type;
+ if ($rtype < 0) {
+ $type = -$rtype;
+ $allow_null = true;
+ } else {
+ $type = $rtype;
+ $allow_null = isset($def->allow_null);
+ }
+
+ try {
+ $value = $this->parser->parse($value, $type, $allow_null);
+ } catch (HTMLPurifier_VarParserException $e) {
+ $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
+ return;
+ }
+ if (is_string($value) && is_object($def)) {
+ // resolve value alias if defined
+ if (isset($def->aliases[$value])) {
+ $value = $def->aliases[$value];
+ }
+ // check to see if the value is allowed
+ if (isset($def->allowed) && !isset($def->allowed[$value])) {
+ $this->triggerError('Value not supported, valid values are: ' .
+ $this->_listify($def->allowed), E_USER_WARNING);
+ return;
+ }
+ }
+ $this->plist->set($key, $value);
+
+ // reset definitions if the directives they depend on changed
+ // this is a very costly process, so it's discouraged
+ // with finalization
+ if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {
+ $this->definitions[$namespace] = null;
+ }
+
+ $this->serials[$namespace] = false;
+ }
+
+ /**
+ * Convenience function for error reporting
+ */
+ private function _listify($lookup) {
+ $list = array();
+ foreach ($lookup as $name => $b) $list[] = $name;
+ return implode(', ', $list);
+ }
+
+ /**
+ * Retrieves object reference to the HTML definition.
+ * @param $raw Return a copy that has not been setup yet. Must be
+ * called before it's been setup, otherwise won't work.
+ * @param $optimized If true, this method may return null, to
+ * indicate that a cached version of the modified
+ * definition object is available and no further edits
+ * are necessary. Consider using
+ * maybeGetRawHTMLDefinition, which is more explicitly
+ * named, instead.
+ */
+ public function getHTMLDefinition($raw = false, $optimized = false) {
+ return $this->getDefinition('HTML', $raw, $optimized);
+ }
+
+ /**
+ * Retrieves object reference to the CSS definition
+ * @param $raw Return a copy that has not been setup yet. Must be
+ * called before it's been setup, otherwise won't work.
+ * @param $optimized If true, this method may return null, to
+ * indicate that a cached version of the modified
+ * definition object is available and no further edits
+ * are necessary. Consider using
+ * maybeGetRawCSSDefinition, which is more explicitly
+ * named, instead.
+ */
+ public function getCSSDefinition($raw = false, $optimized = false) {
+ return $this->getDefinition('CSS', $raw, $optimized);
+ }
+
+ /**
+ * Retrieves object reference to the URI definition
+ * @param $raw Return a copy that has not been setup yet. Must be
+ * called before it's been setup, otherwise won't work.
+ * @param $optimized If true, this method may return null, to
+ * indicate that a cached version of the modified
+ * definition object is available and no further edits
+ * are necessary. Consider using
+ * maybeGetRawURIDefinition, which is more explicitly
+ * named, instead.
+ */
+ public function getURIDefinition($raw = false, $optimized = false) {
+ return $this->getDefinition('URI', $raw, $optimized);
+ }
+
+ /**
+ * Retrieves a definition
+ * @param $type Type of definition: HTML, CSS, etc
+ * @param $raw Whether or not definition should be returned raw
+ * @param $optimized Only has an effect when $raw is true. Whether
+ * or not to return null if the result is already present in
+ * the cache. This is off by default for backwards
+ * compatibility reasons, but you need to do things this
+ * way in order to ensure that caching is done properly.
+ * Check out enduser-customize.html for more details.
+ * We probably won't ever change this default, as much as the
+ * maybe semantics is the "right thing to do."
+ */
+ public function getDefinition($type, $raw = false, $optimized = false) {
+ if ($optimized && !$raw) {
+ throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false");
+ }
+ if (!$this->finalized) $this->autoFinalize();
+ // temporarily suspend locks, so we can handle recursive definition calls
+ $lock = $this->lock;
+ $this->lock = null;
+ $factory = HTMLPurifier_DefinitionCacheFactory::instance();
+ $cache = $factory->create($type, $this);
+ $this->lock = $lock;
+ if (!$raw) {
+ // full definition
+ // ---------------
+ // check if definition is in memory
+ if (!empty($this->definitions[$type])) {
+ $def = $this->definitions[$type];
+ // check if the definition is setup
+ if ($def->setup) {
+ return $def;
+ } else {
+ $def->setup($this);
+ if ($def->optimized) $cache->add($def, $this);
+ return $def;
+ }
+ }
+ // check if definition is in cache
+ $def = $cache->get($this);
+ if ($def) {
+ // definition in cache, save to memory and return it
+ $this->definitions[$type] = $def;
+ return $def;
+ }
+ // initialize it
+ $def = $this->initDefinition($type);
+ // set it up
+ $this->lock = $type;
+ $def->setup($this);
+ $this->lock = null;
+ // save in cache
+ $cache->add($def, $this);
+ // return it
+ return $def;
+ } else {
+ // raw definition
+ // --------------
+ // check preconditions
+ $def = null;
+ if ($optimized) {
+ if (is_null($this->get($type . '.DefinitionID'))) {
+ // fatally error out if definition ID not set
+ throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
+ }
+ }
+ if (!empty($this->definitions[$type])) {
+ $def = $this->definitions[$type];
+ if ($def->setup && !$optimized) {
+ $extra = $this->chatty ? " (try moving this code block earlier in your initialization)" : "";
+ throw new HTMLPurifier_Exception("Cannot retrieve raw definition after it has already been setup" . $extra);
+ }
+ if ($def->optimized === null) {
+ $extra = $this->chatty ? " (try flushing your cache)" : "";
+ throw new HTMLPurifier_Exception("Optimization status of definition is unknown" . $extra);
+ }
+ if ($def->optimized !== $optimized) {
+ $msg = $optimized ? "optimized" : "unoptimized";
+ $extra = $this->chatty ? " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)" : "";
+ throw new HTMLPurifier_Exception("Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra);
+ }
+ }
+ // check if definition was in memory
+ if ($def) {
+ if ($def->setup) {
+ // invariant: $optimized === true (checked above)
+ return null;
+ } else {
+ return $def;
+ }
+ }
+ // if optimized, check if definition was in cache
+ // (because we do the memory check first, this formulation
+ // is prone to cache slamming, but I think
+ // guaranteeing that either /all/ of the raw
+ // setup code or /none/ of it is run is more important.)
+ if ($optimized) {
+ // This code path only gets run once; once we put
+ // something in $definitions (which is guaranteed by the
+ // trailing code), we always short-circuit above.
+ $def = $cache->get($this);
+ if ($def) {
+ // save the full definition for later, but don't
+ // return it yet
+ $this->definitions[$type] = $def;
+ return null;
+ }
+ }
+ // check invariants for creation
+ if (!$optimized) {
+ if (!is_null($this->get($type . '.DefinitionID'))) {
+ if ($this->chatty) {
+ $this->triggerError("Due to a documentation error in previous version of HTML Purifier, your definitions are not being cached. If this is OK, you can remove the %$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, modify your code to use maybeGetRawDefinition, and test if the returned value is null before making any edits (if it is null, that means that a cached version is available, and no raw operations are necessary). See <a href='http://htmlpurifier.org/docs/enduser-customize.html#optimized'>Customize</a> for more details", E_USER_WARNING);
+ } else {
+ $this->triggerError("Useless DefinitionID declaration", E_USER_WARNING);
+ }
+ }
+ }
+ // initialize it
+ $def = $this->initDefinition($type);
+ $def->optimized = $optimized;
+ return $def;
+ }
+ throw new HTMLPurifier_Exception("The impossible happened!");
+ }
+
+ private function initDefinition($type) {
+ // quick checks failed, let's create the object
+ if ($type == 'HTML') {
+ $def = new HTMLPurifier_HTMLDefinition();
+ } elseif ($type == 'CSS') {
+ $def = new HTMLPurifier_CSSDefinition();
+ } elseif ($type == 'URI') {
+ $def = new HTMLPurifier_URIDefinition();
+ } else {
+ throw new HTMLPurifier_Exception("Definition of $type type not supported");
+ }
+ $this->definitions[$type] = $def;
+ return $def;
+ }
+
+ public function maybeGetRawDefinition($name) {
+ return $this->getDefinition($name, true, true);
+ }
+
+ public function maybeGetRawHTMLDefinition() {
+ return $this->getDefinition('HTML', true, true);
+ }
+
+ public function maybeGetRawCSSDefinition() {
+ return $this->getDefinition('CSS', true, true);
+ }
+
+ public function maybeGetRawURIDefinition() {
+ return $this->getDefinition('URI', true, true);
+ }
+
+ /**
+ * Loads configuration values from an array with the following structure:
+ * Namespace.Directive => Value
+ * @param $config_array Configuration associative array
+ */
+ public function loadArray($config_array) {
+ if ($this->isFinalized('Cannot load directives after finalization')) return;
+ foreach ($config_array as $key => $value) {
+ $key = str_replace('_', '.', $key);
+ if (strpos($key, '.') !== false) {
+ $this->set($key, $value);
+ } else {
+ $namespace = $key;
+ $namespace_values = $value;
+ foreach ($namespace_values as $directive => $value) {
+ $this->set($namespace .'.'. $directive, $value);
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns a list of array(namespace, directive) for all directives
+ * that are allowed in a web-form context as per an allowed
+ * namespaces/directives list.
+ * @param $allowed List of allowed namespaces/directives
+ */
+ public static function getAllowedDirectivesForForm($allowed, $schema = null) {
+ if (!$schema) {
+ $schema = HTMLPurifier_ConfigSchema::instance();
+ }
+ if ($allowed !== true) {
+ if (is_string($allowed)) $allowed = array($allowed);
+ $allowed_ns = array();
+ $allowed_directives = array();
+ $blacklisted_directives = array();
+ foreach ($allowed as $ns_or_directive) {
+ if (strpos($ns_or_directive, '.') !== false) {
+ // directive
+ if ($ns_or_directive[0] == '-') {
+ $blacklisted_directives[substr($ns_or_directive, 1)] = true;
+ } else {
+ $allowed_directives[$ns_or_directive] = true;
+ }
+ } else {
+ // namespace
+ $allowed_ns[$ns_or_directive] = true;
+ }
+ }
+ }
+ $ret = array();
+ foreach ($schema->info as $key => $def) {
+ list($ns, $directive) = explode('.', $key, 2);
+ if ($allowed !== true) {
+ if (isset($blacklisted_directives["$ns.$directive"])) continue;
+ if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
+ }
+ if (isset($def->isAlias)) continue;
+ if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
+ $ret[] = array($ns, $directive);
+ }
+ return $ret;
+ }
+
+ /**
+ * Loads configuration values from $_GET/$_POST that were posted
+ * via ConfigForm
+ * @param $array $_GET or $_POST array to import
+ * @param $index Index/name that the config variables are in
+ * @param $allowed List of allowed namespaces/directives
+ * @param $mq_fix Boolean whether or not to enable magic quotes fix
+ * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
+ */
+ public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
+ $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
+ $config = HTMLPurifier_Config::create($ret, $schema);
+ return $config;
+ }
+
+ /**
+ * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
+ * @note Same parameters as loadArrayFromForm
+ */
+ public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
+ $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
+ $this->loadArray($ret);
+ }
+
+ /**
+ * Prepares an array from a form into something usable for the more
+ * strict parts of HTMLPurifier_Config
+ */
+ public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
+ if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
+ $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
+
+ $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
+ $ret = array();
+ foreach ($allowed as $key) {
+ list($ns, $directive) = $key;
+ $skey = "$ns.$directive";
+ if (!empty($array["Null_$skey"])) {
+ $ret[$ns][$directive] = null;
+ continue;
+ }
+ if (!isset($array[$skey])) continue;
+ $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
+ $ret[$ns][$directive] = $value;
+ }
+ return $ret;
+ }
+
+ /**
+ * Loads configuration values from an ini file
+ * @param $filename Name of ini file
+ */
+ public function loadIni($filename) {
+ if ($this->isFinalized('Cannot load directives after finalization')) return;
+ $array = parse_ini_file($filename, true);
+ $this->loadArray($array);
+ }
+
+ /**
+ * Checks whether or not the configuration object is finalized.
+ * @param $error String error message, or false for no error
+ */
+ public function isFinalized($error = false) {
+ if ($this->finalized && $error) {
+ $this->triggerError($error, E_USER_ERROR);
+ }
+ return $this->finalized;
+ }
+
+ /**
+ * Finalizes configuration only if auto finalize is on and not
+ * already finalized
+ */
+ public function autoFinalize() {
+ if ($this->autoFinalize) {
+ $this->finalize();
+ } else {
+ $this->plist->squash(true);
+ }
+ }
+
+ /**
+ * Finalizes a configuration object, prohibiting further change
+ */
+ public function finalize() {
+ $this->finalized = true;
+ unset($this->parser);
+ }
+
+ /**
+ * Produces a nicely formatted error message by supplying the
+ * stack frame information OUTSIDE of HTMLPurifier_Config.
+ */
+ protected function triggerError($msg, $no) {
+ // determine previous stack frame
+ $extra = '';
+ if ($this->chatty) {
+ $trace = debug_backtrace();
+ // zip(tail(trace), trace) -- but PHP is not Haskell har har
+ for ($i = 0, $c = count($trace); $i < $c - 1; $i++) {
+ if ($trace[$i + 1]['class'] === 'HTMLPurifier_Config') {
+ continue;
+ }
+ $frame = $trace[$i];
+ $extra = " invoked on line {$frame['line']} in file {$frame['file']}";
+ break;
+ }
+ }
+ trigger_error($msg . $extra, $no);
+ }
+
+ /**
+ * Returns a serialized form of the configuration object that can
+ * be reconstituted.
+ */
+ public function serialize() {
+ $this->getDefinition('HTML');
+ $this->getDefinition('CSS');
+ $this->getDefinition('URI');
+ return serialize($this);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema.php
new file mode 100644
index 0000000..9551ba1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema.php
@@ -0,0 +1,164 @@
+<?php
+
+/**
+ * Configuration definition, defines directives and their defaults.
+ */
+class HTMLPurifier_ConfigSchema {
+
+ /**
+ * Defaults of the directives and namespaces.
+ * @note This shares the exact same structure as HTMLPurifier_Config::$conf
+ */
+ public $defaults = array();
+
+ /**
+ * The default property list. Do not edit this property list.
+ */
+ public $defaultPlist;
+
+ /**
+ * Definition of the directives. The structure of this is:
+ *
+ * array(
+ * 'Namespace' => array(
+ * 'Directive' => new stdclass(),
+ * )
+ * )
+ *
+ * The stdclass may have the following properties:
+ *
+ * - If isAlias isn't set:
+ * - type: Integer type of directive, see HTMLPurifier_VarParser for definitions
+ * - allow_null: If set, this directive allows null values
+ * - aliases: If set, an associative array of value aliases to real values
+ * - allowed: If set, a lookup array of allowed (string) values
+ * - If isAlias is set:
+ * - namespace: Namespace this directive aliases to
+ * - name: Directive name this directive aliases to
+ *
+ * In certain degenerate cases, stdclass will actually be an integer. In
+ * that case, the value is equivalent to an stdclass with the type
+ * property set to the integer. If the integer is negative, type is
+ * equal to the absolute value of integer, and allow_null is true.
+ *
+ * This class is friendly with HTMLPurifier_Config. If you need introspection
+ * about the schema, you're better of using the ConfigSchema_Interchange,
+ * which uses more memory but has much richer information.
+ */
+ public $info = array();
+
+ /**
+ * Application-wide singleton
+ */
+ static protected $singleton;
+
+ public function __construct() {
+ $this->defaultPlist = new HTMLPurifier_PropertyList();
+ }
+
+ /**
+ * Unserializes the default ConfigSchema.
+ */
+ public static function makeFromSerial() {
+ $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser');
+ $r = unserialize($contents);
+ if (!$r) {
+ $hash = sha1($contents);
+ trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR);
+ }
+ return $r;
+ }
+
+ /**
+ * Retrieves an instance of the application-wide configuration definition.
+ */
+ public static function instance($prototype = null) {
+ if ($prototype !== null) {
+ HTMLPurifier_ConfigSchema::$singleton = $prototype;
+ } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) {
+ HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial();
+ }
+ return HTMLPurifier_ConfigSchema::$singleton;
+ }
+
+ /**
+ * Defines a directive for configuration
+ * @warning Will fail of directive's namespace is defined.
+ * @warning This method's signature is slightly different from the legacy
+ * define() static method! Beware!
+ * @param $namespace Namespace the directive is in
+ * @param $name Key of directive
+ * @param $default Default value of directive
+ * @param $type Allowed type of the directive. See
+ * HTMLPurifier_DirectiveDef::$type for allowed values
+ * @param $allow_null Whether or not to allow null values
+ */
+ public function add($key, $default, $type, $allow_null) {
+ $obj = new stdclass();
+ $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type];
+ if ($allow_null) $obj->allow_null = true;
+ $this->info[$key] = $obj;
+ $this->defaults[$key] = $default;
+ $this->defaultPlist->set($key, $default);
+ }
+
+ /**
+ * Defines a directive value alias.
+ *
+ * Directive value aliases are convenient for developers because it lets
+ * them set a directive to several values and get the same result.
+ * @param $namespace Directive's namespace
+ * @param $name Name of Directive
+ * @param $aliases Hash of aliased values to the real alias
+ */
+ public function addValueAliases($key, $aliases) {
+ if (!isset($this->info[$key]->aliases)) {
+ $this->info[$key]->aliases = array();
+ }
+ foreach ($aliases as $alias => $real) {
+ $this->info[$key]->aliases[$alias] = $real;
+ }
+ }
+
+ /**
+ * Defines a set of allowed values for a directive.
+ * @warning This is slightly different from the corresponding static
+ * method definition.
+ * @param $namespace Namespace of directive
+ * @param $name Name of directive
+ * @param $allowed Lookup array of allowed values
+ */
+ public function addAllowedValues($key, $allowed) {
+ $this->info[$key]->allowed = $allowed;
+ }
+
+ /**
+ * Defines a directive alias for backwards compatibility
+ * @param $namespace
+ * @param $name Directive that will be aliased
+ * @param $new_namespace
+ * @param $new_name Directive that the alias will be to
+ */
+ public function addAlias($key, $new_key) {
+ $obj = new stdclass;
+ $obj->key = $new_key;
+ $obj->isAlias = true;
+ $this->info[$key] = $obj;
+ }
+
+ /**
+ * Replaces any stdclass that only has the type property with type integer.
+ */
+ public function postProcess() {
+ foreach ($this->info as $key => $v) {
+ if (count((array) $v) == 1) {
+ $this->info[$key] = $v->type;
+ } elseif (count((array) $v) == 2 && isset($v->allow_null)) {
+ $this->info[$key] = -$v->type;
+ }
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php
new file mode 100644
index 0000000..92bd630
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * Converts HTMLPurifier_ConfigSchema_Interchange to our runtime
+ * representation used to perform checks on user configuration.
+ */
+class HTMLPurifier_ConfigSchema_Builder_ConfigSchema
+{
+
+ public function build($interchange) {
+ $schema = new HTMLPurifier_ConfigSchema();
+ foreach ($interchange->directives as $d) {
+ $schema->add(
+ $d->id->key,
+ $d->default,
+ $d->type,
+ $d->typeAllowsNull
+ );
+ if ($d->allowed !== null) {
+ $schema->addAllowedValues(
+ $d->id->key,
+ $d->allowed
+ );
+ }
+ foreach ($d->aliases as $alias) {
+ $schema->addAlias(
+ $alias->key,
+ $d->id->key
+ );
+ }
+ if ($d->valueAliases !== null) {
+ $schema->addValueAliases(
+ $d->id->key,
+ $d->valueAliases
+ );
+ }
+ }
+ $schema->postProcess();
+ return $schema;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/Xml.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/Xml.php
new file mode 100644
index 0000000..7924b6a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Builder/Xml.php
@@ -0,0 +1,106 @@
+<?php
+
+/**
+ * Converts HTMLPurifier_ConfigSchema_Interchange to an XML format,
+ * which can be further processed to generate documentation.
+ */
+class HTMLPurifier_ConfigSchema_Builder_Xml extends XMLWriter
+{
+
+ protected $interchange;
+ private $namespace;
+
+ protected function writeHTMLDiv($html) {
+ $this->startElement('div');
+
+ $purifier = HTMLPurifier::getInstance();
+ $html = $purifier->purify($html);
+ $this->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
+ $this->writeRaw($html);
+
+ $this->endElement(); // div
+ }
+
+ protected function export($var) {
+ if ($var === array()) return 'array()';
+ return var_export($var, true);
+ }
+
+ public function build($interchange) {
+ // global access, only use as last resort
+ $this->interchange = $interchange;
+
+ $this->setIndent(true);
+ $this->startDocument('1.0', 'UTF-8');
+ $this->startElement('configdoc');
+ $this->writeElement('title', $interchange->name);
+
+ foreach ($interchange->directives as $directive) {
+ $this->buildDirective($directive);
+ }
+
+ if ($this->namespace) $this->endElement(); // namespace
+
+ $this->endElement(); // configdoc
+ $this->flush();
+ }
+
+ public function buildDirective($directive) {
+
+ // Kludge, although I suppose having a notion of a "root namespace"
+ // certainly makes things look nicer when documentation is built.
+ // Depends on things being sorted.
+ if (!$this->namespace || $this->namespace !== $directive->id->getRootNamespace()) {
+ if ($this->namespace) $this->endElement(); // namespace
+ $this->namespace = $directive->id->getRootNamespace();
+ $this->startElement('namespace');
+ $this->writeAttribute('id', $this->namespace);
+ $this->writeElement('name', $this->namespace);
+ }
+
+ $this->startElement('directive');
+ $this->writeAttribute('id', $directive->id->toString());
+
+ $this->writeElement('name', $directive->id->getDirective());
+
+ $this->startElement('aliases');
+ foreach ($directive->aliases as $alias) $this->writeElement('alias', $alias->toString());
+ $this->endElement(); // aliases
+
+ $this->startElement('constraints');
+ if ($directive->version) $this->writeElement('version', $directive->version);
+ $this->startElement('type');
+ if ($directive->typeAllowsNull) $this->writeAttribute('allow-null', 'yes');
+ $this->text($directive->type);
+ $this->endElement(); // type
+ if ($directive->allowed) {
+ $this->startElement('allowed');
+ foreach ($directive->allowed as $value => $x) $this->writeElement('value', $value);
+ $this->endElement(); // allowed
+ }
+ $this->writeElement('default', $this->export($directive->default));
+ $this->writeAttribute('xml:space', 'preserve');
+ if ($directive->external) {
+ $this->startElement('external');
+ foreach ($directive->external as $project) $this->writeElement('project', $project);
+ $this->endElement();
+ }
+ $this->endElement(); // constraints
+
+ if ($directive->deprecatedVersion) {
+ $this->startElement('deprecated');
+ $this->writeElement('version', $directive->deprecatedVersion);
+ $this->writeElement('use', $directive->deprecatedUse->toString());
+ $this->endElement(); // deprecated
+ }
+
+ $this->startElement('description');
+ $this->writeHTMLDiv($directive->description);
+ $this->endElement(); // description
+
+ $this->endElement(); // directive
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Exception.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Exception.php
new file mode 100644
index 0000000..1abdcfc
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Exception.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * Exceptions related to configuration schema
+ */
+class HTMLPurifier_ConfigSchema_Exception extends HTMLPurifier_Exception
+{
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange.php
new file mode 100644
index 0000000..ca4e4b6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange.php
@@ -0,0 +1,42 @@
+<?php
+
+/**
+ * Generic schema interchange format that can be converted to a runtime
+ * representation (HTMLPurifier_ConfigSchema) or HTML documentation. Members
+ * are completely validated.
+ */
+class HTMLPurifier_ConfigSchema_Interchange
+{
+
+ /**
+ * Name of the application this schema is describing.
+ */
+ public $name;
+
+ /**
+ * Array of Directive ID => array(directive info)
+ */
+ public $directives = array();
+
+ /**
+ * Adds a directive array to $directives
+ */
+ public function addDirective($directive) {
+ if (isset($this->directives[$i = $directive->id->toString()])) {
+ throw new HTMLPurifier_ConfigSchema_Exception("Cannot redefine directive '$i'");
+ }
+ $this->directives[$i] = $directive;
+ }
+
+ /**
+ * Convenience function to perform standard validation. Throws exception
+ * on failed validation.
+ */
+ public function validate() {
+ $validator = new HTMLPurifier_ConfigSchema_Validator();
+ return $validator->validate($this);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php
new file mode 100644
index 0000000..2dced1f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php
@@ -0,0 +1,77 @@
+<?php
+
+/**
+ * Interchange component class describing configuration directives.
+ */
+class HTMLPurifier_ConfigSchema_Interchange_Directive
+{
+
+ /**
+ * ID of directive, instance of HTMLPurifier_ConfigSchema_Interchange_Id.
+ */
+ public $id;
+
+ /**
+ * String type, e.g. 'integer' or 'istring'.
+ */
+ public $type;
+
+ /**
+ * Default value, e.g. 3 or 'DefaultVal'.
+ */
+ public $default;
+
+ /**
+ * HTML description.
+ */
+ public $description;
+
+ /**
+ * Boolean whether or not null is allowed as a value.
+ */
+ public $typeAllowsNull = false;
+
+ /**
+ * Lookup table of allowed scalar values, e.g. array('allowed' => true).
+ * Null if all values are allowed.
+ */
+ public $allowed;
+
+ /**
+ * List of aliases for the directive,
+ * e.g. array(new HTMLPurifier_ConfigSchema_Interchange_Id('Ns', 'Dir'))).
+ */
+ public $aliases = array();
+
+ /**
+ * Hash of value aliases, e.g. array('alt' => 'real'). Null if value
+ * aliasing is disabled (necessary for non-scalar types).
+ */
+ public $valueAliases;
+
+ /**
+ * Version of HTML Purifier the directive was introduced, e.g. '1.3.1'.
+ * Null if the directive has always existed.
+ */
+ public $version;
+
+ /**
+ * ID of directive that supercedes this old directive, is an instance
+ * of HTMLPurifier_ConfigSchema_Interchange_Id. Null if not deprecated.
+ */
+ public $deprecatedUse;
+
+ /**
+ * Version of HTML Purifier this directive was deprecated. Null if not
+ * deprecated.
+ */
+ public $deprecatedVersion;
+
+ /**
+ * List of external projects this directive depends on, e.g. array('CSSTidy').
+ */
+ public $external = array();
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Id.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Id.php
new file mode 100644
index 0000000..404c404
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Interchange/Id.php
@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * Represents a directive ID in the interchange format.
+ */
+class HTMLPurifier_ConfigSchema_Interchange_Id
+{
+
+ public $key;
+
+ public function __construct($key) {
+ $this->key = $key;
+ }
+
+ /**
+ * @warning This is NOT magic, to ensure that people don't abuse SPL and
+ * cause problems for PHP 5.0 support.
+ */
+ public function toString() {
+ return $this->key;
+ }
+
+ public function getRootNamespace() {
+ return substr($this->key, 0, strpos($this->key, "."));
+ }
+
+ public function getDirective() {
+ return substr($this->key, strpos($this->key, ".") + 1);
+ }
+
+ public static function make($id) {
+ return new HTMLPurifier_ConfigSchema_Interchange_Id($id);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php
new file mode 100644
index 0000000..3d499e5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php
@@ -0,0 +1,180 @@
+<?php
+
+class HTMLPurifier_ConfigSchema_InterchangeBuilder
+{
+
+ /**
+ * Used for processing DEFAULT, nothing else.
+ */
+ protected $varParser;
+
+ public function __construct($varParser = null) {
+ $this->varParser = $varParser ? $varParser : new HTMLPurifier_VarParser_Native();
+ }
+
+ public static function buildFromDirectory($dir = null) {
+ $builder = new HTMLPurifier_ConfigSchema_InterchangeBuilder();
+ $interchange = new HTMLPurifier_ConfigSchema_Interchange();
+ return $builder->buildDir($interchange, $dir);
+ }
+
+ public function buildDir($interchange, $dir = null) {
+ if (!$dir) $dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema';
+ if (file_exists($dir . '/info.ini')) {
+ $info = parse_ini_file($dir . '/info.ini');
+ $interchange->name = $info['name'];
+ }
+
+ $files = array();
+ $dh = opendir($dir);
+ while (false !== ($file = readdir($dh))) {
+ if (!$file || $file[0] == '.' || strrchr($file, '.') !== '.txt') {
+ continue;
+ }
+ $files[] = $file;
+ }
+ closedir($dh);
+
+ sort($files);
+ foreach ($files as $file) {
+ $this->buildFile($interchange, $dir . '/' . $file);
+ }
+
+ return $interchange;
+ }
+
+ public function buildFile($interchange, $file) {
+ $parser = new HTMLPurifier_StringHashParser();
+ $this->build(
+ $interchange,
+ new HTMLPurifier_StringHash( $parser->parseFile($file) )
+ );
+ }
+
+ /**
+ * Builds an interchange object based on a hash.
+ * @param $interchange HTMLPurifier_ConfigSchema_Interchange object to build
+ * @param $hash HTMLPurifier_ConfigSchema_StringHash source data
+ */
+ public function build($interchange, $hash) {
+ if (!$hash instanceof HTMLPurifier_StringHash) {
+ $hash = new HTMLPurifier_StringHash($hash);
+ }
+ if (!isset($hash['ID'])) {
+ throw new HTMLPurifier_ConfigSchema_Exception('Hash does not have any ID');
+ }
+ if (strpos($hash['ID'], '.') === false) {
+ if (count($hash) == 2 && isset($hash['DESCRIPTION'])) {
+ $hash->offsetGet('DESCRIPTION'); // prevent complaining
+ } else {
+ throw new HTMLPurifier_ConfigSchema_Exception('All directives must have a namespace');
+ }
+ } else {
+ $this->buildDirective($interchange, $hash);
+ }
+ $this->_findUnused($hash);
+ }
+
+ public function buildDirective($interchange, $hash) {
+ $directive = new HTMLPurifier_ConfigSchema_Interchange_Directive();
+
+ // These are required elements:
+ $directive->id = $this->id($hash->offsetGet('ID'));
+ $id = $directive->id->toString(); // convenience
+
+ if (isset($hash['TYPE'])) {
+ $type = explode('/', $hash->offsetGet('TYPE'));
+ if (isset($type[1])) $directive->typeAllowsNull = true;
+ $directive->type = $type[0];
+ } else {
+ throw new HTMLPurifier_ConfigSchema_Exception("TYPE in directive hash '$id' not defined");
+ }
+
+ if (isset($hash['DEFAULT'])) {
+ try {
+ $directive->default = $this->varParser->parse($hash->offsetGet('DEFAULT'), $directive->type, $directive->typeAllowsNull);
+ } catch (HTMLPurifier_VarParserException $e) {
+ throw new HTMLPurifier_ConfigSchema_Exception($e->getMessage() . " in DEFAULT in directive hash '$id'");
+ }
+ }
+
+ if (isset($hash['DESCRIPTION'])) {
+ $directive->description = $hash->offsetGet('DESCRIPTION');
+ }
+
+ if (isset($hash['ALLOWED'])) {
+ $directive->allowed = $this->lookup($this->evalArray($hash->offsetGet('ALLOWED')));
+ }
+
+ if (isset($hash['VALUE-ALIASES'])) {
+ $directive->valueAliases = $this->evalArray($hash->offsetGet('VALUE-ALIASES'));
+ }
+
+ if (isset($hash['ALIASES'])) {
+ $raw_aliases = trim($hash->offsetGet('ALIASES'));
+ $aliases = preg_split('/\s*,\s*/', $raw_aliases);
+ foreach ($aliases as $alias) {
+ $directive->aliases[] = $this->id($alias);
+ }
+ }
+
+ if (isset($hash['VERSION'])) {
+ $directive->version = $hash->offsetGet('VERSION');
+ }
+
+ if (isset($hash['DEPRECATED-USE'])) {
+ $directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE'));
+ }
+
+ if (isset($hash['DEPRECATED-VERSION'])) {
+ $directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION');
+ }
+
+ if (isset($hash['EXTERNAL'])) {
+ $directive->external = preg_split('/\s*,\s*/', trim($hash->offsetGet('EXTERNAL')));
+ }
+
+ $interchange->addDirective($directive);
+ }
+
+ /**
+ * Evaluates an array PHP code string without array() wrapper
+ */
+ protected function evalArray($contents) {
+ return eval('return array('. $contents .');');
+ }
+
+ /**
+ * Converts an array list into a lookup array.
+ */
+ protected function lookup($array) {
+ $ret = array();
+ foreach ($array as $val) $ret[$val] = true;
+ return $ret;
+ }
+
+ /**
+ * Convenience function that creates an HTMLPurifier_ConfigSchema_Interchange_Id
+ * object based on a string Id.
+ */
+ protected function id($id) {
+ return HTMLPurifier_ConfigSchema_Interchange_Id::make($id);
+ }
+
+ /**
+ * Triggers errors for any unused keys passed in the hash; such keys
+ * may indicate typos, missing values, etc.
+ * @param $hash Instance of ConfigSchema_StringHash to check.
+ */
+ protected function _findUnused($hash) {
+ $accessed = $hash->getAccessed();
+ foreach ($hash as $k => $v) {
+ if (!isset($accessed[$k])) {
+ trigger_error("String hash key '$k' not used by builder", E_USER_NOTICE);
+ }
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Validator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Validator.php
new file mode 100644
index 0000000..5772493
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/Validator.php
@@ -0,0 +1,206 @@
+<?php
+
+/**
+ * Performs validations on HTMLPurifier_ConfigSchema_Interchange
+ *
+ * @note If you see '// handled by InterchangeBuilder', that means a
+ * design decision in that class would prevent this validation from
+ * ever being necessary. We have them anyway, however, for
+ * redundancy.
+ */
+class HTMLPurifier_ConfigSchema_Validator
+{
+
+ /**
+ * Easy to access global objects.
+ */
+ protected $interchange, $aliases;
+
+ /**
+ * Context-stack to provide easy to read error messages.
+ */
+ protected $context = array();
+
+ /**
+ * HTMLPurifier_VarParser to test default's type.
+ */
+ protected $parser;
+
+ public function __construct() {
+ $this->parser = new HTMLPurifier_VarParser();
+ }
+
+ /**
+ * Validates a fully-formed interchange object. Throws an
+ * HTMLPurifier_ConfigSchema_Exception if there's a problem.
+ */
+ public function validate($interchange) {
+ $this->interchange = $interchange;
+ $this->aliases = array();
+ // PHP is a bit lax with integer <=> string conversions in
+ // arrays, so we don't use the identical !== comparison
+ foreach ($interchange->directives as $i => $directive) {
+ $id = $directive->id->toString();
+ if ($i != $id) $this->error(false, "Integrity violation: key '$i' does not match internal id '$id'");
+ $this->validateDirective($directive);
+ }
+ return true;
+ }
+
+ /**
+ * Validates a HTMLPurifier_ConfigSchema_Interchange_Id object.
+ */
+ public function validateId($id) {
+ $id_string = $id->toString();
+ $this->context[] = "id '$id_string'";
+ if (!$id instanceof HTMLPurifier_ConfigSchema_Interchange_Id) {
+ // handled by InterchangeBuilder
+ $this->error(false, 'is not an instance of HTMLPurifier_ConfigSchema_Interchange_Id');
+ }
+ // keys are now unconstrained (we might want to narrow down to A-Za-z0-9.)
+ // we probably should check that it has at least one namespace
+ $this->with($id, 'key')
+ ->assertNotEmpty()
+ ->assertIsString(); // implicit assertIsString handled by InterchangeBuilder
+ array_pop($this->context);
+ }
+
+ /**
+ * Validates a HTMLPurifier_ConfigSchema_Interchange_Directive object.
+ */
+ public function validateDirective($d) {
+ $id = $d->id->toString();
+ $this->context[] = "directive '$id'";
+ $this->validateId($d->id);
+
+ $this->with($d, 'description')
+ ->assertNotEmpty();
+
+ // BEGIN - handled by InterchangeBuilder
+ $this->with($d, 'type')
+ ->assertNotEmpty();
+ $this->with($d, 'typeAllowsNull')
+ ->assertIsBool();
+ try {
+ // This also tests validity of $d->type
+ $this->parser->parse($d->default, $d->type, $d->typeAllowsNull);
+ } catch (HTMLPurifier_VarParserException $e) {
+ $this->error('default', 'had error: ' . $e->getMessage());
+ }
+ // END - handled by InterchangeBuilder
+
+ if (!is_null($d->allowed) || !empty($d->valueAliases)) {
+ // allowed and valueAliases require that we be dealing with
+ // strings, so check for that early.
+ $d_int = HTMLPurifier_VarParser::$types[$d->type];
+ if (!isset(HTMLPurifier_VarParser::$stringTypes[$d_int])) {
+ $this->error('type', 'must be a string type when used with allowed or value aliases');
+ }
+ }
+
+ $this->validateDirectiveAllowed($d);
+ $this->validateDirectiveValueAliases($d);
+ $this->validateDirectiveAliases($d);
+
+ array_pop($this->context);
+ }
+
+ /**
+ * Extra validation if $allowed member variable of
+ * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.
+ */
+ public function validateDirectiveAllowed($d) {
+ if (is_null($d->allowed)) return;
+ $this->with($d, 'allowed')
+ ->assertNotEmpty()
+ ->assertIsLookup(); // handled by InterchangeBuilder
+ if (is_string($d->default) && !isset($d->allowed[$d->default])) {
+ $this->error('default', 'must be an allowed value');
+ }
+ $this->context[] = 'allowed';
+ foreach ($d->allowed as $val => $x) {
+ if (!is_string($val)) $this->error("value $val", 'must be a string');
+ }
+ array_pop($this->context);
+ }
+
+ /**
+ * Extra validation if $valueAliases member variable of
+ * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.
+ */
+ public function validateDirectiveValueAliases($d) {
+ if (is_null($d->valueAliases)) return;
+ $this->with($d, 'valueAliases')
+ ->assertIsArray(); // handled by InterchangeBuilder
+ $this->context[] = 'valueAliases';
+ foreach ($d->valueAliases as $alias => $real) {
+ if (!is_string($alias)) $this->error("alias $alias", 'must be a string');
+ if (!is_string($real)) $this->error("alias target $real from alias '$alias'", 'must be a string');
+ if ($alias === $real) {
+ $this->error("alias '$alias'", "must not be an alias to itself");
+ }
+ }
+ if (!is_null($d->allowed)) {
+ foreach ($d->valueAliases as $alias => $real) {
+ if (isset($d->allowed[$alias])) {
+ $this->error("alias '$alias'", 'must not be an allowed value');
+ } elseif (!isset($d->allowed[$real])) {
+ $this->error("alias '$alias'", 'must be an alias to an allowed value');
+ }
+ }
+ }
+ array_pop($this->context);
+ }
+
+ /**
+ * Extra validation if $aliases member variable of
+ * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.
+ */
+ public function validateDirectiveAliases($d) {
+ $this->with($d, 'aliases')
+ ->assertIsArray(); // handled by InterchangeBuilder
+ $this->context[] = 'aliases';
+ foreach ($d->aliases as $alias) {
+ $this->validateId($alias);
+ $s = $alias->toString();
+ if (isset($this->interchange->directives[$s])) {
+ $this->error("alias '$s'", 'collides with another directive');
+ }
+ if (isset($this->aliases[$s])) {
+ $other_directive = $this->aliases[$s];
+ $this->error("alias '$s'", "collides with alias for directive '$other_directive'");
+ }
+ $this->aliases[$s] = $d->id->toString();
+ }
+ array_pop($this->context);
+ }
+
+ // protected helper functions
+
+ /**
+ * Convenience function for generating HTMLPurifier_ConfigSchema_ValidatorAtom
+ * for validating simple member variables of objects.
+ */
+ protected function with($obj, $member) {
+ return new HTMLPurifier_ConfigSchema_ValidatorAtom($this->getFormattedContext(), $obj, $member);
+ }
+
+ /**
+ * Emits an error, providing helpful context.
+ */
+ protected function error($target, $msg) {
+ if ($target !== false) $prefix = ucfirst($target) . ' in ' . $this->getFormattedContext();
+ else $prefix = ucfirst($this->getFormattedContext());
+ throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg));
+ }
+
+ /**
+ * Returns a formatted context string.
+ */
+ protected function getFormattedContext() {
+ return implode(' in ', array_reverse($this->context));
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php
new file mode 100644
index 0000000..7bb887b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php
@@ -0,0 +1,66 @@
+<?php
+
+/**
+ * Fluent interface for validating the contents of member variables.
+ * This should be immutable. See HTMLPurifier_ConfigSchema_Validator for
+ * use-cases. We name this an 'atom' because it's ONLY for validations that
+ * are independent and usually scalar.
+ */
+class HTMLPurifier_ConfigSchema_ValidatorAtom
+{
+
+ protected $context, $obj, $member, $contents;
+
+ public function __construct($context, $obj, $member) {
+ $this->context = $context;
+ $this->obj = $obj;
+ $this->member = $member;
+ $this->contents =& $obj->$member;
+ }
+
+ public function assertIsString() {
+ if (!is_string($this->contents)) $this->error('must be a string');
+ return $this;
+ }
+
+ public function assertIsBool() {
+ if (!is_bool($this->contents)) $this->error('must be a boolean');
+ return $this;
+ }
+
+ public function assertIsArray() {
+ if (!is_array($this->contents)) $this->error('must be an array');
+ return $this;
+ }
+
+ public function assertNotNull() {
+ if ($this->contents === null) $this->error('must not be null');
+ return $this;
+ }
+
+ public function assertAlnum() {
+ $this->assertIsString();
+ if (!ctype_alnum($this->contents)) $this->error('must be alphanumeric');
+ return $this;
+ }
+
+ public function assertNotEmpty() {
+ if (empty($this->contents)) $this->error('must not be empty');
+ return $this;
+ }
+
+ public function assertIsLookup() {
+ $this->assertIsArray();
+ foreach ($this->contents as $v) {
+ if ($v !== true) $this->error('must be a lookup array');
+ }
+ return $this;
+ }
+
+ protected function error($msg) {
+ throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema.ser b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema.ser
new file mode 100644
index 0000000..245ba5d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema.ser
Binary files differ
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt
new file mode 100644
index 0000000..4a42382
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt
@@ -0,0 +1,8 @@
+Attr.AllowedClasses
+TYPE: lookup/null
+VERSION: 4.0.0
+DEFAULT: null
+--DESCRIPTION--
+List of allowed class values in the class attribute. By default, this is null,
+which means all classes are allowed.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt
new file mode 100644
index 0000000..b033eb5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt
@@ -0,0 +1,12 @@
+Attr.AllowedFrameTargets
+TYPE: lookup
+DEFAULT: array()
+--DESCRIPTION--
+Lookup table of all allowed link frame targets. Some commonly used link
+targets include _blank, _self, _parent and _top. Values should be
+lowercase, as validation will be done in a case-sensitive manner despite
+W3C's recommendation. XHTML 1.0 Strict does not permit the target attribute
+so this directive will have no effect in that doctype. XHTML 1.1 does not
+enable the Target module by default, you will have to manually enable it
+(see the module documentation for more details.)
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt
new file mode 100644
index 0000000..ed72a9d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt
@@ -0,0 +1,9 @@
+Attr.AllowedRel
+TYPE: lookup
+VERSION: 1.6.0
+DEFAULT: array()
+--DESCRIPTION--
+List of allowed forward document relationships in the rel attribute. Common
+values may be nofollow or print. By default, this is empty, meaning that no
+document relationships are allowed.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt
new file mode 100644
index 0000000..1ae672d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt
@@ -0,0 +1,9 @@
+Attr.AllowedRev
+TYPE: lookup
+VERSION: 1.6.0
+DEFAULT: array()
+--DESCRIPTION--
+List of allowed reverse document relationships in the rev attribute. This
+attribute is a bit of an edge-case; if you don't know what it is for, stay
+away.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt
new file mode 100644
index 0000000..119a9d2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt
@@ -0,0 +1,19 @@
+Attr.ClassUseCDATA
+TYPE: bool/null
+DEFAULT: null
+VERSION: 4.0.0
+--DESCRIPTION--
+If null, class will auto-detect the doctype and, if matching XHTML 1.1 or
+XHTML 2.0, will use the restrictive NMTOKENS specification of class. Otherwise,
+it will use a relaxed CDATA definition. If true, the relaxed CDATA definition
+is forced; if false, the NMTOKENS definition is forced. To get behavior
+of HTML Purifier prior to 4.0.0, set this directive to false.
+
+Some rational behind the auto-detection:
+in previous versions of HTML Purifier, it was assumed that the form of
+class was NMTOKENS, as specified by the XHTML Modularization (representing
+XHTML 1.1 and XHTML 2.0). The DTDs for HTML 4.01 and XHTML 1.0, however
+specify class as CDATA. HTML 5 effectively defines it as CDATA, but
+with the additional constraint that each name should be unique (this is not
+explicitly outlined in previous specifications).
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt
new file mode 100644
index 0000000..80b1431
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt
@@ -0,0 +1,11 @@
+Attr.DefaultImageAlt
+TYPE: string/null
+DEFAULT: null
+VERSION: 3.2.0
+--DESCRIPTION--
+This is the content of the alt tag of an image if the user had not
+previously specified an alt attribute. This applies to all images without
+a valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which
+only applies to invalid images, and overrides in the case of an invalid image.
+Default behavior with null is to use the basename of the src tag for the alt.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt
new file mode 100644
index 0000000..c51000d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt
@@ -0,0 +1,9 @@
+Attr.DefaultInvalidImage
+TYPE: string
+DEFAULT: ''
+--DESCRIPTION--
+This is the default image an img tag will be pointed to if it does not have
+a valid src attribute. In future versions, we may allow the image tag to
+be removed completely, but due to design issues, this is not possible right
+now.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt
new file mode 100644
index 0000000..c1ec4b0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt
@@ -0,0 +1,8 @@
+Attr.DefaultInvalidImageAlt
+TYPE: string
+DEFAULT: 'Invalid image'
+--DESCRIPTION--
+This is the content of the alt tag of an invalid image if the user had not
+previously specified an alt attribute. It has no effect when the image is
+valid but there was no alt attribute present.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt
new file mode 100644
index 0000000..f57dcc4
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt
@@ -0,0 +1,10 @@
+Attr.DefaultTextDir
+TYPE: string
+DEFAULT: 'ltr'
+--DESCRIPTION--
+Defines the default text direction (ltr or rtl) of the document being
+parsed. This generally is the same as the value of the dir attribute in
+HTML, or ltr if that is not specified.
+--ALLOWED--
+'ltr', 'rtl'
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt
new file mode 100644
index 0000000..9b93a55
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt
@@ -0,0 +1,16 @@
+Attr.EnableID
+TYPE: bool
+DEFAULT: false
+VERSION: 1.2.0
+--DESCRIPTION--
+Allows the ID attribute in HTML. This is disabled by default due to the
+fact that without proper configuration user input can easily break the
+validation of a webpage by specifying an ID that is already on the
+surrounding HTML. If you don't mind throwing caution to the wind, enable
+this directive, but I strongly recommend you also consider blacklisting IDs
+you use (%Attr.IDBlacklist) or prefixing all user supplied IDs
+(%Attr.IDPrefix). When set to true HTML Purifier reverts to the behavior of
+pre-1.2.0 versions.
+--ALIASES--
+HTML.EnableAttrID
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt
new file mode 100644
index 0000000..fed8954
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt
@@ -0,0 +1,8 @@
+Attr.ForbiddenClasses
+TYPE: lookup
+VERSION: 4.0.0
+DEFAULT: array()
+--DESCRIPTION--
+List of forbidden class values in the class attribute. By default, this is
+empty, which means that no classes are forbidden. See also %Attr.AllowedClasses.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt
new file mode 100644
index 0000000..52168bb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt
@@ -0,0 +1,5 @@
+Attr.IDBlacklist
+TYPE: list
+DEFAULT: array()
+DESCRIPTION: Array of IDs not allowed in the document.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt
new file mode 100644
index 0000000..7b85043
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt
@@ -0,0 +1,9 @@
+Attr.IDBlacklistRegexp
+TYPE: string/null
+VERSION: 1.6.0
+DEFAULT: NULL
+--DESCRIPTION--
+PCRE regular expression to be matched against all IDs. If the expression is
+matches, the ID is rejected. Use this with care: may cause significant
+degradation. ID matching is done after all other validation.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt
new file mode 100644
index 0000000..5781382
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt
@@ -0,0 +1,12 @@
+Attr.IDPrefix
+TYPE: string
+VERSION: 1.2.0
+DEFAULT: ''
+--DESCRIPTION--
+String to prefix to IDs. If you have no idea what IDs your pages may use,
+you may opt to simply add a prefix to all user-submitted ID attributes so
+that they are still usable, but will not conflict with core page IDs.
+Example: setting the directive to 'user_' will result in a user submitted
+'foo' to become 'user_foo' Be sure to set %HTML.EnableAttrID to true
+before using this.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt
new file mode 100644
index 0000000..f91fcd6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt
@@ -0,0 +1,14 @@
+Attr.IDPrefixLocal
+TYPE: string
+VERSION: 1.2.0
+DEFAULT: ''
+--DESCRIPTION--
+Temporary prefix for IDs used in conjunction with %Attr.IDPrefix. If you
+need to allow multiple sets of user content on web page, you may need to
+have a seperate prefix that changes with each iteration. This way,
+seperately submitted user content displayed on the same page doesn't
+clobber each other. Ideal values are unique identifiers for the content it
+represents (i.e. the id of the row in the database). Be sure to add a
+seperator (like an underscore) at the end. Warning: this directive will
+not work unless %Attr.IDPrefix is set to a non-empty value!
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt
new file mode 100644
index 0000000..2d7f94e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt
@@ -0,0 +1,31 @@
+AutoFormat.AutoParagraph
+TYPE: bool
+VERSION: 2.0.1
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+ This directive turns on auto-paragraphing, where double newlines are
+ converted in to paragraphs whenever possible. Auto-paragraphing:
+</p>
+<ul>
+ <li>Always applies to inline elements or text in the root node,</li>
+ <li>Applies to inline elements or text with double newlines in nodes
+ that allow paragraph tags,</li>
+ <li>Applies to double newlines in paragraph tags</li>
+</ul>
+<p>
+ <code>p</code> tags must be allowed for this directive to take effect.
+ We do not use <code>br</code> tags for paragraphing, as that is
+ semantically incorrect.
+</p>
+<p>
+ To prevent auto-paragraphing as a content-producer, refrain from using
+ double-newlines except to specify a new paragraph or in contexts where
+ it has special meaning (whitespace usually has no meaning except in
+ tags like <code>pre</code>, so this should not be difficult.) To prevent
+ the paragraphing of inline text adjacent to block elements, wrap them
+ in <code>div</code> tags (the behavior is slightly different outside of
+ the root node.)
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt
new file mode 100644
index 0000000..2eb1974
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt
@@ -0,0 +1,12 @@
+AutoFormat.Custom
+TYPE: list
+VERSION: 2.0.1
+DEFAULT: array()
+--DESCRIPTION--
+
+<p>
+ This directive can be used to add custom auto-format injectors.
+ Specify an array of injector names (class name minus the prefix)
+ or concrete implementations. Injector class must exist.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt
new file mode 100644
index 0000000..c955de7
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt
@@ -0,0 +1,11 @@
+AutoFormat.DisplayLinkURI
+TYPE: bool
+VERSION: 3.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ This directive turns on the in-text display of URIs in &lt;a&gt; tags, and disables
+ those links. For example, <a href="http://example.com">example</a> becomes
+ example (<a>http://example.com</a>).
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt
new file mode 100644
index 0000000..328b2b2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt
@@ -0,0 +1,12 @@
+AutoFormat.Linkify
+TYPE: bool
+VERSION: 2.0.1
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+ This directive turns on linkification, auto-linking http, ftp and
+ https URLs. <code>a</code> tags with the <code>href</code> attribute
+ must be allowed.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt
new file mode 100644
index 0000000..d0532b6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt
@@ -0,0 +1,12 @@
+AutoFormat.PurifierLinkify.DocURL
+TYPE: string
+VERSION: 2.0.1
+DEFAULT: '#%s'
+ALIASES: AutoFormatParam.PurifierLinkifyDocURL
+--DESCRIPTION--
+<p>
+ Location of configuration documentation to link to, let %s substitute
+ into the configuration's namespace and directive names sans the percent
+ sign.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt
new file mode 100644
index 0000000..f3ab259
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt
@@ -0,0 +1,12 @@
+AutoFormat.PurifierLinkify
+TYPE: bool
+VERSION: 2.0.1
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+ Internal auto-formatter that converts configuration directives in
+ syntax <a>%Namespace.Directive</a> to links. <code>a</code> tags
+ with the <code>href</code> attribute must be allowed.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt
new file mode 100644
index 0000000..219d04a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt
@@ -0,0 +1,11 @@
+AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions
+TYPE: lookup
+VERSION: 4.0.0
+DEFAULT: array('td' => true, 'th' => true)
+--DESCRIPTION--
+<p>
+ When %AutoFormat.RemoveEmpty and %AutoFormat.RemoveEmpty.RemoveNbsp
+ are enabled, this directive defines what HTML elements should not be
+ removede if they have only a non-breaking space in them.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt
new file mode 100644
index 0000000..5f355d6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt
@@ -0,0 +1,15 @@
+AutoFormat.RemoveEmpty.RemoveNbsp
+TYPE: bool
+VERSION: 4.0.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ When enabled, HTML Purifier will treat any elements that contain only
+ non-breaking spaces as well as regular whitespace as empty, and remove
+ them when %AutoForamt.RemoveEmpty is enabled.
+</p>
+<p>
+ See %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions for a list of elements
+ that don't have this behavior applied to them.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt
new file mode 100644
index 0000000..6b5a7a5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt
@@ -0,0 +1,46 @@
+AutoFormat.RemoveEmpty
+TYPE: bool
+VERSION: 3.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ When enabled, HTML Purifier will attempt to remove empty elements that
+ contribute no semantic information to the document. The following types
+ of nodes will be removed:
+</p>
+<ul><li>
+ Tags with no attributes and no content, and that are not empty
+ elements (remove <code>&lt;a&gt;&lt;/a&gt;</code> but not
+ <code>&lt;br /&gt;</code>), and
+ </li>
+ <li>
+ Tags with no content, except for:<ul>
+ <li>The <code>colgroup</code> element, or</li>
+ <li>
+ Elements with the <code>id</code> or <code>name</code> attribute,
+ when those attributes are permitted on those elements.
+ </li>
+ </ul></li>
+</ul>
+<p>
+ Please be very careful when using this functionality; while it may not
+ seem that empty elements contain useful information, they can alter the
+ layout of a document given appropriate styling. This directive is most
+ useful when you are processing machine-generated HTML, please avoid using
+ it on regular user HTML.
+</p>
+<p>
+ Elements that contain only whitespace will be treated as empty. Non-breaking
+ spaces, however, do not count as whitespace. See
+ %AutoFormat.RemoveEmpty.RemoveNbsp for alternate behavior.
+</p>
+<p>
+ This algorithm is not perfect; you may still notice some empty tags,
+ particularly if a node had elements, but those elements were later removed
+ because they were not permitted in that context, or tags that, after
+ being auto-closed by another tag, where empty. This is for safety reasons
+ to prevent clever code from breaking validation. The general rule of thumb:
+ if a tag looked empty on the way in, it will get removed; if HTML Purifier
+ made it empty, it will stay.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt
new file mode 100644
index 0000000..a448770
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt
@@ -0,0 +1,11 @@
+AutoFormat.RemoveSpansWithoutAttributes
+TYPE: bool
+VERSION: 4.0.1
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ This directive causes <code>span</code> tags without any attributes
+ to be removed. It will also remove spans that had all attributes
+ removed during processing.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt
new file mode 100644
index 0000000..8096eb0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt
@@ -0,0 +1,8 @@
+CSS.AllowImportant
+TYPE: bool
+DEFAULT: false
+VERSION: 3.1.0
+--DESCRIPTION--
+This parameter determines whether or not !important cascade modifiers should
+be allowed in user CSS. If false, !important will stripped.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt
new file mode 100644
index 0000000..9d34deb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt
@@ -0,0 +1,11 @@
+CSS.AllowTricky
+TYPE: bool
+DEFAULT: false
+VERSION: 3.1.0
+--DESCRIPTION--
+This parameter determines whether or not to allow "tricky" CSS properties and
+values. Tricky CSS properties/values can drastically modify page layout or
+be used for deceptive practices but do not directly constitute a security risk.
+For example, <code>display:none;</code> is considered a tricky property that
+will only be allowed if this directive is set to true.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt
new file mode 100644
index 0000000..7c2b547
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt
@@ -0,0 +1,12 @@
+CSS.AllowedFonts
+TYPE: lookup/null
+VERSION: 4.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+<p>
+ Allows you to manually specify a set of allowed fonts. If
+ <code>NULL</code>, all fonts are allowed. This directive
+ affects generic names (serif, sans-serif, monospace, cursive,
+ fantasy) as well as specific font families.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt
new file mode 100644
index 0000000..f1ba513
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt
@@ -0,0 +1,18 @@
+CSS.AllowedProperties
+TYPE: lookup/null
+VERSION: 3.1.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ If HTML Purifier's style attributes set is unsatisfactory for your needs,
+ you can overload it with your own list of tags to allow. Note that this
+ method is subtractive: it does its job by taking away from HTML Purifier
+ usual feature set, so you cannot add an attribute that HTML Purifier never
+ supported in the first place.
+</p>
+<p>
+ <strong>Warning:</strong> If another directive conflicts with the
+ elements here, <em>that</em> directive will win and override.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt
new file mode 100644
index 0000000..96b4108
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt
@@ -0,0 +1,11 @@
+CSS.DefinitionRev
+TYPE: int
+VERSION: 2.0.0
+DEFAULT: 1
+--DESCRIPTION--
+
+<p>
+ Revision identifier for your custom definition. See
+ %HTML.DefinitionRev for details.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt
new file mode 100644
index 0000000..923e8e9
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt
@@ -0,0 +1,13 @@
+CSS.ForbiddenProperties
+TYPE: lookup
+VERSION: 4.2.0
+DEFAULT: array()
+--DESCRIPTION--
+<p>
+ This is the logical inverse of %CSS.AllowedProperties, and it will
+ override that directive or any other directive. If possible,
+ %CSS.AllowedProperties is recommended over this directive,
+ because it can sometimes be difficult to tell whether or not you've
+ forbidden all of the CSS properties you truly would like to disallow.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt
new file mode 100644
index 0000000..3808581
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt
@@ -0,0 +1,16 @@
+CSS.MaxImgLength
+TYPE: string/null
+DEFAULT: '1200px'
+VERSION: 3.1.1
+--DESCRIPTION--
+<p>
+ This parameter sets the maximum allowed length on <code>img</code> tags,
+ effectively the <code>width</code> and <code>height</code> properties.
+ Only absolute units of measurement (in, pt, pc, mm, cm) and pixels (px) are allowed. This is
+ in place to prevent imagecrash attacks, disable with null at your own risk.
+ This directive is similar to %HTML.MaxImgLength, and both should be
+ concurrently edited, although there are
+ subtle differences in the input format (the CSS max is a number with
+ a unit).
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt
new file mode 100644
index 0000000..8a26f22
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt
@@ -0,0 +1,10 @@
+CSS.Proprietary
+TYPE: bool
+VERSION: 3.0.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+ Whether or not to allow safe, proprietary CSS values.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt
new file mode 100644
index 0000000..917ec42
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt
@@ -0,0 +1,9 @@
+CSS.Trusted
+TYPE: bool
+VERSION: 4.2.1
+DEFAULT: false
+--DESCRIPTION--
+Indicates whether or not the user's CSS input is trusted or not. If the
+input is trusted, a more expansive set of allowed properties. See
+also %HTML.Trusted.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt
new file mode 100644
index 0000000..afc6a87
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt
@@ -0,0 +1,14 @@
+Cache.DefinitionImpl
+TYPE: string/null
+VERSION: 2.0.0
+DEFAULT: 'Serializer'
+--DESCRIPTION--
+
+This directive defines which method to use when caching definitions,
+the complex data-type that makes HTML Purifier tick. Set to null
+to disable caching (not recommended, as you will see a definite
+performance degradation).
+
+--ALIASES--
+Core.DefinitionCache
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt
new file mode 100644
index 0000000..668f248
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt
@@ -0,0 +1,13 @@
+Cache.SerializerPath
+TYPE: string/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ Absolute path with no trailing slash to store serialized definitions in.
+ Default is within the
+ HTML Purifier library inside DefinitionCache/Serializer. This
+ path must be writable by the webserver.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt
new file mode 100644
index 0000000..9c27b0a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt
@@ -0,0 +1,11 @@
+Cache.SerializerPermissions
+TYPE: int
+VERSION: 4.3.0
+DEFAULT: 0755
+--DESCRIPTION--
+
+<p>
+ Directory permissions of the files and directories created inside
+ the DefinitionCache/Serializer or other custom serializer path.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt
new file mode 100644
index 0000000..e0fa378
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt
@@ -0,0 +1,18 @@
+Core.AggressivelyFixLt
+TYPE: bool
+VERSION: 2.1.0
+DEFAULT: true
+--DESCRIPTION--
+<p>
+ This directive enables aggressive pre-filter fixes HTML Purifier can
+ perform in order to ensure that open angled-brackets do not get killed
+ during parsing stage. Enabling this will result in two preg_replace_callback
+ calls and at least two preg_replace calls for every HTML document parsed;
+ if your users make very well-formed HTML, you can set this directive false.
+ This has no effect when DirectLex is used.
+</p>
+<p>
+ <strong>Notice:</strong> This directive's default turned from false to true
+ in HTML Purifier 3.2.0.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt
new file mode 100644
index 0000000..c6ea069
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt
@@ -0,0 +1,12 @@
+Core.CollectErrors
+TYPE: bool
+VERSION: 2.0.0
+DEFAULT: false
+--DESCRIPTION--
+
+Whether or not to collect errors found while filtering the document. This
+is a useful way to give feedback to your users. <strong>Warning:</strong>
+Currently this feature is very patchy and experimental, with lots of
+possible error messages not yet implemented. It will not cause any
+problems, but it may not help your users either.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt
new file mode 100644
index 0000000..b8c259d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt
@@ -0,0 +1,28 @@
+Core.ColorKeywords
+TYPE: hash
+VERSION: 2.0.0
+--DEFAULT--
+array (
+ 'maroon' => '#800000',
+ 'red' => '#FF0000',
+ 'orange' => '#FFA500',
+ 'yellow' => '#FFFF00',
+ 'olive' => '#808000',
+ 'purple' => '#800080',
+ 'fuchsia' => '#FF00FF',
+ 'white' => '#FFFFFF',
+ 'lime' => '#00FF00',
+ 'green' => '#008000',
+ 'navy' => '#000080',
+ 'blue' => '#0000FF',
+ 'aqua' => '#00FFFF',
+ 'teal' => '#008080',
+ 'black' => '#000000',
+ 'silver' => '#C0C0C0',
+ 'gray' => '#808080',
+)
+--DESCRIPTION--
+
+Lookup array of color names to six digit hexadecimal number corresponding
+to color, with preceding hash mark. Used when parsing colors.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt
new file mode 100644
index 0000000..656d378
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt
@@ -0,0 +1,14 @@
+Core.ConvertDocumentToFragment
+TYPE: bool
+DEFAULT: true
+--DESCRIPTION--
+
+This parameter determines whether or not the filter should convert
+input that is a full document with html and body tags to a fragment
+of just the contents of a body tag. This parameter is simply something
+HTML Purifier can do during an edge-case: for most inputs, this
+processing is not necessary.
+
+--ALIASES--
+Core.AcceptFullDocuments
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt
new file mode 100644
index 0000000..2f54e46
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt
@@ -0,0 +1,17 @@
+Core.DirectLexLineNumberSyncInterval
+TYPE: int
+VERSION: 2.0.0
+DEFAULT: 0
+--DESCRIPTION--
+
+<p>
+ Specifies the number of tokens the DirectLex line number tracking
+ implementations should process before attempting to resyncronize the
+ current line count by manually counting all previous new-lines. When
+ at 0, this functionality is disabled. Lower values will decrease
+ performance, and this is only strictly necessary if the counting
+ algorithm is buggy (in which case you should report it as a bug).
+ This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is
+ not being used.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt
new file mode 100644
index 0000000..89e2ae3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt
@@ -0,0 +1,15 @@
+Core.Encoding
+TYPE: istring
+DEFAULT: 'utf-8'
+--DESCRIPTION--
+If for some reason you are unable to convert all webpages to UTF-8, you can
+use this directive as a stop-gap compatibility change to let HTML Purifier
+deal with non UTF-8 input. This technique has notable deficiencies:
+absolutely no characters outside of the selected character encoding will be
+preserved, not even the ones that have been ampersand escaped (this is due
+to a UTF-8 specific <em>feature</em> that automatically resolves all
+entities), making it pretty useless for anything except the most I18N-blind
+applications, although %Core.EscapeNonASCIICharacters offers fixes this
+trouble with another tradeoff. This directive only accepts ISO-8859-1 if
+iconv is not enabled.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt
new file mode 100644
index 0000000..be932b1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt
@@ -0,0 +1,10 @@
+Core.EscapeInvalidChildren
+TYPE: bool
+DEFAULT: false
+--DESCRIPTION--
+When true, a child is found that is not allowed in the context of the
+parent element will be transformed into text as if it were ASCII. When
+false, that element and all internal tags will be dropped, though text will
+be preserved. There is no option for dropping the element but preserving
+child nodes.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt
new file mode 100644
index 0000000..299775f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt
@@ -0,0 +1,7 @@
+Core.EscapeInvalidTags
+TYPE: bool
+DEFAULT: false
+--DESCRIPTION--
+When true, invalid tags will be written back to the document as plain text.
+Otherwise, they are silently dropped.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt
new file mode 100644
index 0000000..f50db2f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt
@@ -0,0 +1,13 @@
+Core.EscapeNonASCIICharacters
+TYPE: bool
+VERSION: 1.4.0
+DEFAULT: false
+--DESCRIPTION--
+This directive overcomes a deficiency in %Core.Encoding by blindly
+converting all non-ASCII characters into decimal numeric entities before
+converting it to its native encoding. This means that even characters that
+can be expressed in the non-UTF-8 encoding will be entity-ized, which can
+be a real downer for encodings like Big5. It also assumes that the ASCII
+repetoire is available, although this is the case for almost all encodings.
+Anyway, use UTF-8!
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt
new file mode 100644
index 0000000..c337e47
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt
@@ -0,0 +1,19 @@
+Core.HiddenElements
+TYPE: lookup
+--DEFAULT--
+array (
+ 'script' => true,
+ 'style' => true,
+)
+--DESCRIPTION--
+
+<p>
+ This directive is a lookup array of elements which should have their
+ contents removed when they are not allowed by the HTML definition.
+ For example, the contents of a <code>script</code> tag are not
+ normally shown in a document, so if script tags are to be removed,
+ their contents should be removed to. This is opposed to a <code>b</code>
+ tag, which defines some presentational changes but does not hide its
+ contents.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt
new file mode 100644
index 0000000..ed1f39b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt
@@ -0,0 +1,10 @@
+Core.Language
+TYPE: string
+VERSION: 2.0.0
+DEFAULT: 'en'
+--DESCRIPTION--
+
+ISO 639 language code for localizable things in HTML Purifier to use,
+which is mainly error reporting. There is currently only an English (en)
+translation, so this directive is currently useless.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt
new file mode 100644
index 0000000..e11c015
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt
@@ -0,0 +1,34 @@
+Core.LexerImpl
+TYPE: mixed/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ This parameter determines what lexer implementation can be used. The
+ valid values are:
+</p>
+<dl>
+ <dt><em>null</em></dt>
+ <dd>
+ Recommended, the lexer implementation will be auto-detected based on
+ your PHP-version and configuration.
+ </dd>
+ <dt><em>string</em> lexer identifier</dt>
+ <dd>
+ This is a slim way of manually overridding the implementation.
+ Currently recognized values are: DOMLex (the default PHP5
+implementation)
+ and DirectLex (the default PHP4 implementation). Only use this if
+ you know what you are doing: usually, the auto-detection will
+ manage things for cases you aren't even aware of.
+ </dd>
+ <dt><em>object</em> lexer instance</dt>
+ <dd>
+ Super-advanced: you can specify your own, custom, implementation that
+ implements the interface defined by <code>HTMLPurifier_Lexer</code>.
+ I may remove this option simply because I don't expect anyone
+ to use it.
+ </dd>
+</dl>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt
new file mode 100644
index 0000000..838f10f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt
@@ -0,0 +1,16 @@
+Core.MaintainLineNumbers
+TYPE: bool/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ If true, HTML Purifier will add line number information to all tokens.
+ This is useful when error reporting is turned on, but can result in
+ significant performance degradation and should not be used when
+ unnecessary. This directive must be used with the DirectLex lexer,
+ as the DOMLex lexer does not (yet) support this functionality.
+ If the value is null, an appropriate value will be selected based
+ on other configuration.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt
new file mode 100644
index 0000000..94a8860
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt
@@ -0,0 +1,11 @@
+Core.NormalizeNewlines
+TYPE: bool
+VERSION: 4.2.0
+DEFAULT: true
+--DESCRIPTION--
+<p>
+ Whether or not to normalize newlines to the operating
+ system default. When <code>false</code>, HTML Purifier
+ will attempt to preserve mixed newline files.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt
new file mode 100644
index 0000000..704ac56
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt
@@ -0,0 +1,12 @@
+Core.RemoveInvalidImg
+TYPE: bool
+DEFAULT: true
+VERSION: 1.3.0
+--DESCRIPTION--
+
+<p>
+ This directive enables pre-emptive URI checking in <code>img</code>
+ tags, as the attribute validation strategy is not authorized to
+ remove elements from the document. Revert to pre-1.3.0 behavior by setting to false.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt
new file mode 100644
index 0000000..ed6f134
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt
@@ -0,0 +1,11 @@
+Core.RemoveProcessingInstructions
+TYPE: bool
+VERSION: 4.2.0
+DEFAULT: false
+--DESCRIPTION--
+Instead of escaping processing instructions in the form <code>&lt;? ...
+?&gt;</code>, remove it out-right. This may be useful if the HTML
+you are validating contains XML processing instruction gunk, however,
+it can also be user-unfriendly for people attempting to post PHP
+snippets.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt
new file mode 100644
index 0000000..efbe994
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt
@@ -0,0 +1,12 @@
+Core.RemoveScriptContents
+TYPE: bool/null
+DEFAULT: NULL
+VERSION: 2.0.0
+DEPRECATED-VERSION: 2.1.0
+DEPRECATED-USE: Core.HiddenElements
+--DESCRIPTION--
+<p>
+ This directive enables HTML Purifier to remove not only script tags
+ but all of their contents.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt
new file mode 100644
index 0000000..861ae66
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt
@@ -0,0 +1,11 @@
+Filter.Custom
+TYPE: list
+VERSION: 3.1.0
+DEFAULT: array()
+--DESCRIPTION--
+<p>
+ This directive can be used to add custom filters; it is nearly the
+ equivalent of the now deprecated <code>HTMLPurifier-&gt;addFilter()</code>
+ method. Specify an array of concrete implementations.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt
new file mode 100644
index 0000000..6960263
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt
@@ -0,0 +1,14 @@
+Filter.ExtractStyleBlocks.Escaping
+TYPE: bool
+VERSION: 3.0.0
+DEFAULT: true
+ALIASES: Filter.ExtractStyleBlocksEscaping, FilterParam.ExtractStyleBlocksEscaping
+--DESCRIPTION--
+
+<p>
+ Whether or not to escape the dangerous characters &lt;, &gt; and &amp;
+ as \3C, \3E and \26, respectively. This is can be safely set to false
+ if the contents of StyleBlocks will be placed in an external stylesheet,
+ where there is no risk of it being interpreted as HTML.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt
new file mode 100644
index 0000000..baa81ae
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt
@@ -0,0 +1,29 @@
+Filter.ExtractStyleBlocks.Scope
+TYPE: string/null
+VERSION: 3.0.0
+DEFAULT: NULL
+ALIASES: Filter.ExtractStyleBlocksScope, FilterParam.ExtractStyleBlocksScope
+--DESCRIPTION--
+
+<p>
+ If you would like users to be able to define external stylesheets, but
+ only allow them to specify CSS declarations for a specific node and
+ prevent them from fiddling with other elements, use this directive.
+ It accepts any valid CSS selector, and will prepend this to any
+ CSS declaration extracted from the document. For example, if this
+ directive is set to <code>#user-content</code> and a user uses the
+ selector <code>a:hover</code>, the final selector will be
+ <code>#user-content a:hover</code>.
+</p>
+<p>
+ The comma shorthand may be used; consider the above example, with
+ <code>#user-content, #user-content2</code>, the final selector will
+ be <code>#user-content a:hover, #user-content2 a:hover</code>.
+</p>
+<p>
+ <strong>Warning:</strong> It is possible for users to bypass this measure
+ using a naughty + selector. This is a bug in CSS Tidy 1.3, not HTML
+ Purifier, and I am working to get it fixed. Until then, HTML Purifier
+ performs a basic check to prevent this.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt
new file mode 100644
index 0000000..3b70189
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt
@@ -0,0 +1,16 @@
+Filter.ExtractStyleBlocks.TidyImpl
+TYPE: mixed/null
+VERSION: 3.1.0
+DEFAULT: NULL
+ALIASES: FilterParam.ExtractStyleBlocksTidyImpl
+--DESCRIPTION--
+<p>
+ If left NULL, HTML Purifier will attempt to instantiate a <code>csstidy</code>
+ class to use for internal cleaning. This will usually be good enough.
+</p>
+<p>
+ However, for trusted user input, you can set this to <code>false</code> to
+ disable cleaning. In addition, you can supply your own concrete implementation
+ of Tidy's interface to use, although I don't know why you'd want to do that.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt
new file mode 100644
index 0000000..be0177d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt
@@ -0,0 +1,74 @@
+Filter.ExtractStyleBlocks
+TYPE: bool
+VERSION: 3.1.0
+DEFAULT: false
+EXTERNAL: CSSTidy
+--DESCRIPTION--
+<p>
+ This directive turns on the style block extraction filter, which removes
+ <code>style</code> blocks from input HTML, cleans them up with CSSTidy,
+ and places them in the <code>StyleBlocks</code> context variable, for further
+ use by you, usually to be placed in an external stylesheet, or a
+ <code>style</code> block in the <code>head</code> of your document.
+</p>
+<p>
+ Sample usage:
+</p>
+<pre><![CDATA[
+<?php
+ header('Content-type: text/html; charset=utf-8');
+ echo '<?xml version="1.0" encoding="UTF-8"?>';
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+ <title>Filter.ExtractStyleBlocks</title>
+<?php
+ require_once '/path/to/library/HTMLPurifier.auto.php';
+ require_once '/path/to/csstidy.class.php';
+
+ $dirty = '<style>body {color:#F00;}</style> Some text';
+
+ $config = HTMLPurifier_Config::createDefault();
+ $config->set('Filter', 'ExtractStyleBlocks', true);
+ $purifier = new HTMLPurifier($config);
+
+ $html = $purifier->purify($dirty);
+
+ // This implementation writes the stylesheets to the styles/ directory.
+ // You can also echo the styles inside the document, but it's a bit
+ // more difficult to make sure they get interpreted properly by
+ // browsers; try the usual CSS armoring techniques.
+ $styles = $purifier->context->get('StyleBlocks');
+ $dir = 'styles/';
+ if (!is_dir($dir)) mkdir($dir);
+ $hash = sha1($_GET['html']);
+ foreach ($styles as $i => $style) {
+ file_put_contents($name = $dir . $hash . "_$i");
+ echo '<link rel="stylesheet" type="text/css" href="'.$name.'" />';
+ }
+?>
+</head>
+<body>
+ <div>
+ <?php echo $html; ?>
+ </div>
+</b]]><![CDATA[ody>
+</html>
+]]></pre>
+<p>
+ <strong>Warning:</strong> It is possible for a user to mount an
+ imagecrash attack using this CSS. Counter-measures are difficult;
+ it is not simply enough to limit the range of CSS lengths (using
+ relative lengths with many nesting levels allows for large values
+ to be attained without actually specifying them in the stylesheet),
+ and the flexible nature of selectors makes it difficult to selectively
+ disable lengths on image tags (HTML Purifier, however, does disable
+ CSS width and height in inline styling). There are probably two effective
+ counter measures: an explicit width and height set to auto in all
+ images in your document (unlikely) or the disabling of width and
+ height (somewhat reasonable). Whether or not these measures should be
+ used is left to the reader.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt
new file mode 100644
index 0000000..8822186
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt
@@ -0,0 +1,16 @@
+Filter.YouTube
+TYPE: bool
+VERSION: 3.1.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ <strong>Warning:</strong> Deprecated in favor of %HTML.SafeObject and
+ %Output.FlashCompat (turn both on to allow YouTube videos and other
+ Flash content).
+</p>
+<p>
+ This directive enables YouTube video embedding in HTML Purifier. Check
+ <a href="http://htmlpurifier.org/docs/enduser-youtube.html">this document
+ on embedding videos</a> for more information on what this filter does.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt
new file mode 100644
index 0000000..afd48a0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt
@@ -0,0 +1,25 @@
+HTML.Allowed
+TYPE: itext/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ This is a preferred convenience directive that combines
+ %HTML.AllowedElements and %HTML.AllowedAttributes.
+ Specify elements and attributes that are allowed using:
+ <code>element1[attr1|attr2],element2...</code>. For example,
+ if you would like to only allow paragraphs and links, specify
+ <code>a[href],p</code>. You can specify attributes that apply
+ to all elements using an asterisk, e.g. <code>*[lang]</code>.
+ You can also use newlines instead of commas to separate elements.
+</p>
+<p>
+ <strong>Warning</strong>:
+ All of the constraints on the component directives are still enforced.
+ The syntax is a <em>subset</em> of TinyMCE's <code>valid_elements</code>
+ whitelist: directly copy-pasting it here will probably result in
+ broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes
+ are set, this directive has no effect.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt
new file mode 100644
index 0000000..0e6ec54
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt
@@ -0,0 +1,19 @@
+HTML.AllowedAttributes
+TYPE: lookup/null
+VERSION: 1.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ If HTML Purifier's attribute set is unsatisfactory, overload it!
+ The syntax is "tag.attr" or "*.attr" for the global attributes
+ (style, id, class, dir, lang, xml:lang).
+</p>
+<p>
+ <strong>Warning:</strong> If another directive conflicts with the
+ elements here, <em>that</em> directive will win and override. For
+ example, %HTML.EnableAttrID will take precedence over *.id in this
+ directive. You must set that directive to true before you can use
+ IDs at all.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt
new file mode 100644
index 0000000..ca3c13d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt
@@ -0,0 +1,23 @@
+HTML.AllowedElements
+TYPE: lookup/null
+VERSION: 1.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+<p>
+ If HTML Purifier's tag set is unsatisfactory for your needs, you can
+ overload it with your own list of tags to allow. If you change
+ this, you probably also want to change %HTML.AllowedAttributes; see
+ also %HTML.Allowed which lets you set allowed elements and
+ attributes at the same time.
+</p>
+<p>
+ If you attempt to allow an element that HTML Purifier does not know
+ about, HTML Purifier will raise an error. You will need to manually
+ tell HTML Purifier about this element by using the
+ <a href="http://htmlpurifier.org/docs/enduser-customize.html">advanced customization features.</a>
+</p>
+<p>
+ <strong>Warning:</strong> If another directive conflicts with the
+ elements here, <em>that</em> directive will win and override.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt
new file mode 100644
index 0000000..e373791
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt
@@ -0,0 +1,20 @@
+HTML.AllowedModules
+TYPE: lookup/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ A doctype comes with a set of usual modules to use. Without having
+ to mucking about with the doctypes, you can quickly activate or
+ disable these modules by specifying which modules you wish to allow
+ with this directive. This is most useful for unit testing specific
+ modules, although end users may find it useful for their own ends.
+</p>
+<p>
+ If you specify a module that does not exist, the manager will silently
+ fail to use it, so be careful! User-defined modules are not affected
+ by this directive. Modules defined in %HTML.CoreModules are not
+ affected by this directive.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt
new file mode 100644
index 0000000..75d680e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt
@@ -0,0 +1,11 @@
+HTML.Attr.Name.UseCDATA
+TYPE: bool
+DEFAULT: false
+VERSION: 4.0.0
+--DESCRIPTION--
+The W3C specification DTD defines the name attribute to be CDATA, not ID, due
+to limitations of DTD. In certain documents, this relaxed behavior is desired,
+whether it is to specify duplicate names, or to specify names that would be
+illegal IDs (for example, names that begin with a digit.) Set this configuration
+directive to true to use the relaxed parsing rules.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt
new file mode 100644
index 0000000..f32b802
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt
@@ -0,0 +1,18 @@
+HTML.BlockWrapper
+TYPE: string
+VERSION: 1.3.0
+DEFAULT: 'p'
+--DESCRIPTION--
+
+<p>
+ String name of element to wrap inline elements that are inside a block
+ context. This only occurs in the children of blockquote in strict mode.
+</p>
+<p>
+ Example: by default value,
+ <code>&lt;blockquote&gt;Foo&lt;/blockquote&gt;</code> would become
+ <code>&lt;blockquote&gt;&lt;p&gt;Foo&lt;/p&gt;&lt;/blockquote&gt;</code>.
+ The <code>&lt;p&gt;</code> tags can be replaced with whatever you desire,
+ as long as it is a block level element.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt
new file mode 100644
index 0000000..fc8e402
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt
@@ -0,0 +1,23 @@
+HTML.CoreModules
+TYPE: lookup
+VERSION: 2.0.0
+--DEFAULT--
+array (
+ 'Structure' => true,
+ 'Text' => true,
+ 'Hypertext' => true,
+ 'List' => true,
+ 'NonXMLCommonAttributes' => true,
+ 'XMLCommonAttributes' => true,
+ 'CommonAttributes' => true,
+)
+--DESCRIPTION--
+
+<p>
+ Certain modularized doctypes (XHTML, namely), have certain modules
+ that must be included for the doctype to be an conforming document
+ type: put those modules here. By default, XHTML's core modules
+ are used. You can set this to a blank array to disable core module
+ protection, but this is not recommended.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt
new file mode 100644
index 0000000..a2bde5d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt
@@ -0,0 +1,9 @@
+HTML.CustomDoctype
+TYPE: string/null
+VERSION: 2.0.1
+DEFAULT: NULL
+--DESCRIPTION--
+
+A custom doctype for power-users who defined there own document
+type. This directive only applies when %HTML.Doctype is blank.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt
new file mode 100644
index 0000000..f5433e3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt
@@ -0,0 +1,33 @@
+HTML.DefinitionID
+TYPE: string/null
+DEFAULT: NULL
+VERSION: 2.0.0
+--DESCRIPTION--
+
+<p>
+ Unique identifier for a custom-built HTML definition. If you edit
+ the raw version of the HTMLDefinition, introducing changes that the
+ configuration object does not reflect, you must specify this variable.
+ If you change your custom edits, you should change this directive, or
+ clear your cache. Example:
+</p>
+<pre>
+$config = HTMLPurifier_Config::createDefault();
+$config->set('HTML', 'DefinitionID', '1');
+$def = $config->getHTMLDefinition();
+$def->addAttribute('a', 'tabindex', 'Number');
+</pre>
+<p>
+ In the above example, the configuration is still at the defaults, but
+ using the advanced API, an extra attribute has been added. The
+ configuration object normally has no way of knowing that this change
+ has taken place, so it needs an extra directive: %HTML.DefinitionID.
+ If someone else attempts to use the default configuration, these two
+ pieces of code will not clobber each other in the cache, since one has
+ an extra directive attached to it.
+</p>
+<p>
+ You <em>must</em> specify a value to this directive to use the
+ advanced API features.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt
new file mode 100644
index 0000000..0bb5a71
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt
@@ -0,0 +1,16 @@
+HTML.DefinitionRev
+TYPE: int
+VERSION: 2.0.0
+DEFAULT: 1
+--DESCRIPTION--
+
+<p>
+ Revision identifier for your custom definition specified in
+ %HTML.DefinitionID. This serves the same purpose: uniquely identifying
+ your custom definition, but this one does so in a chronological
+ context: revision 3 is more up-to-date then revision 2. Thus, when
+ this gets incremented, the cache handling is smart enough to clean
+ up any older revisions of your definition as well as flush the
+ cache.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt
new file mode 100644
index 0000000..a6969b9
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt
@@ -0,0 +1,11 @@
+HTML.Doctype
+TYPE: string/null
+DEFAULT: NULL
+--DESCRIPTION--
+Doctype to use during filtering. Technically speaking this is not actually
+a doctype (as it does not identify a corresponding DTD), but we are using
+this name for sake of simplicity. When non-blank, this will override any
+older directives like %HTML.XHTML or %HTML.Strict.
+--ALLOWED--
+'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1'
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt
new file mode 100644
index 0000000..08d641f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt
@@ -0,0 +1,11 @@
+HTML.FlashAllowFullScreen
+TYPE: bool
+VERSION: 4.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ Whether or not to permit embedded Flash content from
+ %HTML.SafeObject to expand to the full screen. Corresponds to
+ the <code>allowFullScreen</code> parameter.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt
new file mode 100644
index 0000000..2b8df97
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt
@@ -0,0 +1,21 @@
+HTML.ForbiddenAttributes
+TYPE: lookup
+VERSION: 3.1.0
+DEFAULT: array()
+--DESCRIPTION--
+<p>
+ While this directive is similar to %HTML.AllowedAttributes, for
+ forwards-compatibility with XML, this attribute has a different syntax. Instead of
+ <code>tag.attr</code>, use <code>tag@attr</code>. To disallow <code>href</code>
+ attributes in <code>a</code> tags, set this directive to
+ <code>a@href</code>. You can also disallow an attribute globally with
+ <code>attr</code> or <code>*@attr</code> (either syntax is fine; the latter
+ is provided for consistency with %HTML.AllowedAttributes).
+</p>
+<p>
+ <strong>Warning:</strong> This directive complements %HTML.ForbiddenElements,
+ accordingly, check
+ out that directive for a discussion of why you
+ should think twice before using this directive.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt
new file mode 100644
index 0000000..40466c4
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt
@@ -0,0 +1,20 @@
+HTML.ForbiddenElements
+TYPE: lookup
+VERSION: 3.1.0
+DEFAULT: array()
+--DESCRIPTION--
+<p>
+ This was, perhaps, the most requested feature ever in HTML
+ Purifier. Please don't abuse it! This is the logical inverse of
+ %HTML.AllowedElements, and it will override that directive, or any
+ other directive.
+</p>
+<p>
+ If possible, %HTML.Allowed is recommended over this directive, because it
+ can sometimes be difficult to tell whether or not you've forbidden all of
+ the behavior you would like to disallow. If you forbid <code>img</code>
+ with the expectation of preventing images on your site, you'll be in for
+ a nasty surprise when people start using the <code>background-image</code>
+ CSS property.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt
new file mode 100644
index 0000000..3197479
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt
@@ -0,0 +1,14 @@
+HTML.MaxImgLength
+TYPE: int/null
+DEFAULT: 1200
+VERSION: 3.1.1
+--DESCRIPTION--
+<p>
+ This directive controls the maximum number of pixels in the width and
+ height attributes in <code>img</code> tags. This is
+ in place to prevent imagecrash attacks, disable with null at your own risk.
+ This directive is similar to %CSS.MaxImgLength, and both should be
+ concurrently edited, although there are
+ subtle differences in the input format (the HTML max is an integer).
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt
new file mode 100644
index 0000000..7aa3563
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt
@@ -0,0 +1,7 @@
+HTML.Nofollow
+TYPE: bool
+VERSION: 4.3.0
+DEFAULT: FALSE
+--DESCRIPTION--
+If enabled, nofollow rel attributes are added to all outgoing links.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt
new file mode 100644
index 0000000..2d2fbd1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt
@@ -0,0 +1,12 @@
+HTML.Parent
+TYPE: string
+VERSION: 1.3.0
+DEFAULT: 'div'
+--DESCRIPTION--
+
+<p>
+ String name of element that HTML fragment passed to library will be
+ inserted in. An interesting variation would be using span as the
+ parent element, meaning that only inline tags would be allowed.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt
new file mode 100644
index 0000000..b3c45e1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt
@@ -0,0 +1,12 @@
+HTML.Proprietary
+TYPE: bool
+VERSION: 3.1.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ Whether or not to allow proprietary elements and attributes in your
+ documents, as per <code>HTMLPurifier_HTMLModule_Proprietary</code>.
+ <strong>Warning:</strong> This can cause your documents to stop
+ validating!
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt
new file mode 100644
index 0000000..556fa67
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt
@@ -0,0 +1,13 @@
+HTML.SafeEmbed
+TYPE: bool
+VERSION: 3.1.1
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ Whether or not to permit embed tags in documents, with a number of extra
+ security features added to prevent script execution. This is similar to
+ what websites like MySpace do to embed tags. Embed is a proprietary
+ element and will cause your website to stop validating; you should
+ see if you can use %Output.FlashCompat with %HTML.SafeObject instead
+ first.</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt
new file mode 100644
index 0000000..07f6e53
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt
@@ -0,0 +1,13 @@
+HTML.SafeObject
+TYPE: bool
+VERSION: 3.1.1
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ Whether or not to permit object tags in documents, with a number of extra
+ security features added to prevent script execution. This is similar to
+ what websites like MySpace do to object tags. You should also enable
+ %Output.FlashCompat in order to generate Internet Explorer
+ compatibility code for your object tags.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt
new file mode 100644
index 0000000..d99663a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt
@@ -0,0 +1,9 @@
+HTML.Strict
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+DEPRECATED-VERSION: 1.7.0
+DEPRECATED-USE: HTML.Doctype
+--DESCRIPTION--
+Determines whether or not to use Transitional (loose) or Strict rulesets.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt
new file mode 100644
index 0000000..602453f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt
@@ -0,0 +1,8 @@
+HTML.TidyAdd
+TYPE: lookup
+VERSION: 2.0.0
+DEFAULT: array()
+--DESCRIPTION--
+
+Fixes to add to the default set of Tidy fixes as per your level.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt
new file mode 100644
index 0000000..bf943e8
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt
@@ -0,0 +1,24 @@
+HTML.TidyLevel
+TYPE: string
+VERSION: 2.0.0
+DEFAULT: 'medium'
+--DESCRIPTION--
+
+<p>General level of cleanliness the Tidy module should enforce.
+There are four allowed values:</p>
+<dl>
+ <dt>none</dt>
+ <dd>No extra tidying should be done</dd>
+ <dt>light</dt>
+ <dd>Only fix elements that would be discarded otherwise due to
+ lack of support in doctype</dd>
+ <dt>medium</dt>
+ <dd>Enforce best practices</dd>
+ <dt>heavy</dt>
+ <dd>Transform all deprecated elements and attributes to standards
+ compliant equivalents</dd>
+</dl>
+
+--ALLOWED--
+'none', 'light', 'medium', 'heavy'
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt
new file mode 100644
index 0000000..92cca2a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt
@@ -0,0 +1,8 @@
+HTML.TidyRemove
+TYPE: lookup
+VERSION: 2.0.0
+DEFAULT: array()
+--DESCRIPTION--
+
+Fixes to remove from the default set of Tidy fixes as per your level.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt
new file mode 100644
index 0000000..bc8e654
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt
@@ -0,0 +1,9 @@
+HTML.Trusted
+TYPE: bool
+VERSION: 2.0.0
+DEFAULT: false
+--DESCRIPTION--
+Indicates whether or not the user input is trusted or not. If the input is
+trusted, a more expansive set of allowed tags and attributes will be used.
+See also %CSS.Trusted.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt
new file mode 100644
index 0000000..a3c2f42
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt
@@ -0,0 +1,11 @@
+HTML.XHTML
+TYPE: bool
+DEFAULT: true
+VERSION: 1.1.0
+DEPRECATED-VERSION: 1.7.0
+DEPRECATED-USE: HTML.Doctype
+--DESCRIPTION--
+Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor.
+--ALIASES--
+Core.XHTML
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt
new file mode 100644
index 0000000..2a13704
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt
@@ -0,0 +1,10 @@
+Output.CommentScriptContents
+TYPE: bool
+VERSION: 2.0.0
+DEFAULT: true
+--DESCRIPTION--
+Determines whether or not HTML Purifier should attempt to fix up the
+contents of script tags for legacy browsers with comments.
+--ALIASES--
+Core.CommentScriptContents
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt
new file mode 100644
index 0000000..d215ba2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt
@@ -0,0 +1,15 @@
+Output.FixInnerHTML
+TYPE: bool
+VERSION: 4.3.0
+DEFAULT: true
+--DESCRIPTION--
+<p>
+ If true, HTML Purifier will protect against Internet Explorer's
+ mishandling of the <code>innerHTML</code> attribute by appending
+ a space to any attribute that does not contain angled brackets, spaces
+ or quotes, but contains a backtick. This slightly changes the
+ semantics of any given attribute, so if this is unacceptable and
+ you do not use <code>innerHTML</code> on any of your pages, you can
+ turn this directive off.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt
new file mode 100644
index 0000000..e58f91a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt
@@ -0,0 +1,11 @@
+Output.FlashCompat
+TYPE: bool
+VERSION: 4.1.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ If true, HTML Purifier will generate Internet Explorer compatibility
+ code for all object code. This is highly recommended if you enable
+ %HTML.SafeObject.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt
new file mode 100644
index 0000000..4bb9025
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt
@@ -0,0 +1,13 @@
+Output.Newline
+TYPE: string/null
+VERSION: 2.0.1
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ Newline string to format final output with. If left null, HTML Purifier
+ will auto-detect the default newline type of the system and use that;
+ you can manually override it here. Remember, \r\n is Windows, \r
+ is Mac, and \n is Unix.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt
new file mode 100644
index 0000000..3223106
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt
@@ -0,0 +1,14 @@
+Output.SortAttr
+TYPE: bool
+VERSION: 3.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ If true, HTML Purifier will sort attributes by name before writing them back
+ to the document, converting a tag like: <code>&lt;el b="" a="" c="" /&gt;</code>
+ to <code>&lt;el a="" b="" c="" /&gt;</code>. This is a workaround for
+ a bug in FCKeditor which causes it to swap attributes order, adding noise
+ to text diffs. If you're not seeing this bug, chances are, you don't need
+ this directive.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt
new file mode 100644
index 0000000..23dd4d3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt
@@ -0,0 +1,25 @@
+Output.TidyFormat
+TYPE: bool
+VERSION: 1.1.1
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ Determines whether or not to run Tidy on the final output for pretty
+ formatting reasons, such as indentation and wrap.
+</p>
+<p>
+ This can greatly improve readability for editors who are hand-editing
+ the HTML, but is by no means necessary as HTML Purifier has already
+ fixed all major errors the HTML may have had. Tidy is a non-default
+ extension, and this directive will silently fail if Tidy is not
+ available.
+</p>
+<p>
+ If you are looking to make the overall look of your page's source
+ better, I recommend running Tidy on the entire page rather than just
+ user-content (after all, the indentation relative to the containing
+ blocks will be incorrect).
+</p>
+--ALIASES--
+Core.TidyFormat
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt
new file mode 100644
index 0000000..d1820cd
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt
@@ -0,0 +1,7 @@
+Test.ForceNoIconv
+TYPE: bool
+DEFAULT: false
+--DESCRIPTION--
+When set to true, HTMLPurifier_Encoder will act as if iconv does not exist
+and use only pure PHP implementations.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt
new file mode 100644
index 0000000..47714f5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt
@@ -0,0 +1,17 @@
+URI.AllowedSchemes
+TYPE: lookup
+--DEFAULT--
+array (
+ 'http' => true,
+ 'https' => true,
+ 'mailto' => true,
+ 'ftp' => true,
+ 'nntp' => true,
+ 'news' => true,
+)
+--DESCRIPTION--
+Whitelist that defines the schemes that a URI is allowed to have. This
+prevents XSS attacks from using pseudo-schemes like javascript or mocha.
+There is also support for the <code>data</code> and <code>file</code>
+URI schemes, but they are not enabled by default.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt
new file mode 100644
index 0000000..ba47308
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt
@@ -0,0 +1,17 @@
+URI.Base
+TYPE: string/null
+VERSION: 2.1.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ The base URI is the URI of the document this purified HTML will be
+ inserted into. This information is important if HTML Purifier needs
+ to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute
+ is on. You may use a non-absolute URI for this value, but behavior
+ may vary (%URI.MakeAbsolute deals nicely with both absolute and
+ relative paths, but forwards-compatibility is not guaranteed).
+ <strong>Warning:</strong> If set, the scheme on this URI
+ overrides the one specified by %URI.DefaultScheme.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt
new file mode 100644
index 0000000..0700e0b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt
@@ -0,0 +1,10 @@
+URI.DefaultScheme
+TYPE: string
+DEFAULT: 'http'
+--DESCRIPTION--
+
+<p>
+ Defines through what scheme the output will be served, in order to
+ select the proper object validator when no scheme information is present.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt
new file mode 100644
index 0000000..523204c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt
@@ -0,0 +1,11 @@
+URI.DefinitionID
+TYPE: string/null
+VERSION: 2.1.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ Unique identifier for a custom-built URI definition. If you want
+ to add custom URIFilters, you must specify this value.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt
new file mode 100644
index 0000000..a9c07b1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt
@@ -0,0 +1,11 @@
+URI.DefinitionRev
+TYPE: int
+VERSION: 2.1.0
+DEFAULT: 1
+--DESCRIPTION--
+
+<p>
+ Revision identifier for your custom definition. See
+ %HTML.DefinitionRev for details.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt
new file mode 100644
index 0000000..b19ca1d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt
@@ -0,0 +1,14 @@
+URI.Disable
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+ Disables all URIs in all forms. Not sure why you'd want to do that
+ (after all, the Internet's founded on the notion of a hyperlink).
+</p>
+
+--ALIASES--
+Attr.DisableURI
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt
new file mode 100644
index 0000000..9132ea4
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt
@@ -0,0 +1,11 @@
+URI.DisableExternal
+TYPE: bool
+VERSION: 1.2.0
+DEFAULT: false
+--DESCRIPTION--
+Disables links to external websites. This is a highly effective anti-spam
+and anti-pagerank-leech measure, but comes at a hefty price: nolinks or
+images outside of your domain will be allowed. Non-linkified URIs will
+still be preserved. If you want to be able to link to subdomains or use
+absolute URIs, specify %URI.Host for your website.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt
new file mode 100644
index 0000000..d74bc1e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt
@@ -0,0 +1,13 @@
+URI.DisableExternalResources
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+--DESCRIPTION--
+Disables the embedding of external resources, preventing users from
+embedding things like images from other hosts. This prevents access
+tracking (good for email viewers), bandwidth leeching, cross-site request
+forging, goatse.cx posting, and other nasties, but also results in a loss
+of end-user functionality (they can't directly post a pic they posted from
+Flickr anymore). Use it if you don't have a robust user-content moderation
+team.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt
new file mode 100644
index 0000000..6c10614
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt
@@ -0,0 +1,15 @@
+URI.DisableResources
+TYPE: bool
+VERSION: 4.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ Disables embedding resources, essentially meaning no pictures. You can
+ still link to them though. See %URI.DisableExternalResources for why
+ this might be a good idea.
+</p>
+<p>
+ <em>Note:</em> While this directive has been available since 1.3.0,
+ it didn't actually start doing anything until 4.2.0.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt
new file mode 100644
index 0000000..ba0e6bc
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt
@@ -0,0 +1,19 @@
+URI.Host
+TYPE: string/null
+VERSION: 1.2.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ Defines the domain name of the server, so we can determine whether or
+ an absolute URI is from your website or not. Not strictly necessary,
+ as users should be using relative URIs to reference resources on your
+ website. It will, however, let you use absolute URIs to link to
+ subdomains of the domain you post here: i.e. example.com will allow
+ sub.example.com. However, higher up domains will still be excluded:
+ if you set %URI.Host to sub.example.com, example.com will be blocked.
+ <strong>Note:</strong> This directive overrides %URI.Base because
+ a given page may be on a sub-domain, but you wish HTML Purifier to be
+ more relaxed and allow some of the parent domains too.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt
new file mode 100644
index 0000000..825fef2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt
@@ -0,0 +1,9 @@
+URI.HostBlacklist
+TYPE: list
+VERSION: 1.3.0
+DEFAULT: array()
+--DESCRIPTION--
+List of strings that are forbidden in the host of any URI. Use it to kill
+domain names of spam, etc. Note that it will catch anything in the domain,
+so <tt>moo.com</tt> will catch <tt>moo.com.example.com</tt>.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt
new file mode 100644
index 0000000..eb58c7f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt
@@ -0,0 +1,13 @@
+URI.MakeAbsolute
+TYPE: bool
+VERSION: 2.1.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+ Converts all URIs into absolute forms. This is useful when the HTML
+ being filtered assumes a specific base path, but will actually be
+ viewed in a different context (and setting an alternate base URI is
+ not possible). %URI.Base must be set for this directive to work.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt
new file mode 100644
index 0000000..bedd610
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt
@@ -0,0 +1,83 @@
+URI.Munge
+TYPE: string/null
+VERSION: 1.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+ Munges all browsable (usually http, https and ftp)
+ absolute URIs into another URI, usually a URI redirection service.
+ This directive accepts a URI, formatted with a <code>%s</code> where
+ the url-encoded original URI should be inserted (sample:
+ <code>http://www.google.com/url?q=%s</code>).
+</p>
+<p>
+ Uses for this directive:
+</p>
+<ul>
+ <li>
+ Prevent PageRank leaks, while being fairly transparent
+ to users (you may also want to add some client side JavaScript to
+ override the text in the statusbar). <strong>Notice</strong>:
+ Many security experts believe that this form of protection does not deter spam-bots.
+ </li>
+ <li>
+ Redirect users to a splash page telling them they are leaving your
+ website. While this is poor usability practice, it is often mandated
+ in corporate environments.
+ </li>
+</ul>
+<p>
+ Prior to HTML Purifier 3.1.1, this directive also enabled the munging
+ of browsable external resources, which could break things if your redirection
+ script was a splash page or used <code>meta</code> tags. To revert to
+ previous behavior, please use %URI.MungeResources.
+</p>
+<p>
+ You may want to also use %URI.MungeSecretKey along with this directive
+ in order to enforce what URIs your redirector script allows. Open
+ redirector scripts can be a security risk and negatively affect the
+ reputation of your domain name.
+</p>
+<p>
+ Starting with HTML Purifier 3.1.1, there is also these substitutions:
+</p>
+<table>
+ <thead>
+ <tr>
+ <th>Key</th>
+ <th>Description</th>
+ <th>Example <code>&lt;a href=""&gt;</code></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>%r</td>
+ <td>1 - The URI embeds a resource<br />(blank) - The URI is merely a link</td>
+ <td></td>
+ </tr>
+ <tr>
+ <td>%n</td>
+ <td>The name of the tag this URI came from</td>
+ <td>a</td>
+ </tr>
+ <tr>
+ <td>%m</td>
+ <td>The name of the attribute this URI came from</td>
+ <td>href</td>
+ </tr>
+ <tr>
+ <td>%p</td>
+ <td>The name of the CSS property this URI came from, or blank if irrelevant</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+<p>
+ Admittedly, these letters are somewhat arbitrary; the only stipulation
+ was that they couldn't be a through f. r is for resource (I would have preferred
+ e, but you take what you can get), n is for name, m
+ was picked because it came after n (and I couldn't use a), p is for
+ property.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt
new file mode 100644
index 0000000..ed4b5b0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt
@@ -0,0 +1,17 @@
+URI.MungeResources
+TYPE: bool
+VERSION: 3.1.1
+DEFAULT: false
+--DESCRIPTION--
+<p>
+ If true, any URI munging directives like %URI.Munge
+ will also apply to embedded resources, such as <code>&lt;img src=""&gt;</code>.
+ Be careful enabling this directive if you have a redirector script
+ that does not use the <code>Location</code> HTTP header; all of your images
+ and other embedded resources will break.
+</p>
+<p>
+ <strong>Warning:</strong> It is strongly advised you use this in conjunction
+ %URI.MungeSecretKey to mitigate the security risk of an open redirector.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt
new file mode 100644
index 0000000..3b50c8c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt
@@ -0,0 +1,30 @@
+URI.MungeSecretKey
+TYPE: string/null
+VERSION: 3.1.1
+DEFAULT: NULL
+--DESCRIPTION--
+<p>
+ This directive enables secure checksum generation along with %URI.Munge.
+ It should be set to a secure key that is not shared with anyone else.
+ The checksum can be placed in the URI using %t. Use of this checksum
+ affords an additional level of protection by allowing a redirector
+ to check if a URI has passed through HTML Purifier with this line:
+</p>
+
+<pre>$checksum === sha1($secret_key . ':' . $url)</pre>
+
+<p>
+ If the output is TRUE, the redirector script should accept the URI.
+</p>
+
+<p>
+ Please note that it would still be possible for an attacker to procure
+ secure hashes en-mass by abusing your website's Preview feature or the
+ like, but this service affords an additional level of protection
+ that should be combined with website blacklisting.
+</p>
+
+<p>
+ Remember this has no effect if %URI.Munge is not on.
+</p>
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt
new file mode 100644
index 0000000..8b387de
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt
@@ -0,0 +1,9 @@
+URI.OverrideAllowedSchemes
+TYPE: bool
+DEFAULT: true
+--DESCRIPTION--
+If this is set to true (which it is by default), you can override
+%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the
+registry. If false, you will also have to update that directive in order
+to add more schemes.
+--# vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/info.ini b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/info.ini
new file mode 100644
index 0000000..58e0ce4
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ConfigSchema/schema/info.ini
@@ -0,0 +1,3 @@
+name = "HTML Purifier"
+
+; vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ContentSets.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ContentSets.php
new file mode 100644
index 0000000..7aafd88
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ContentSets.php
@@ -0,0 +1,155 @@
+<?php
+
+/**
+ * @todo Unit test
+ */
+class HTMLPurifier_ContentSets
+{
+
+ /**
+ * List of content set strings (pipe seperators) indexed by name.
+ */
+ public $info = array();
+
+ /**
+ * List of content set lookups (element => true) indexed by name.
+ * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets
+ */
+ public $lookup = array();
+
+ /**
+ * Synchronized list of defined content sets (keys of info)
+ */
+ protected $keys = array();
+ /**
+ * Synchronized list of defined content values (values of info)
+ */
+ protected $values = array();
+
+ /**
+ * Merges in module's content sets, expands identifiers in the content
+ * sets and populates the keys, values and lookup member variables.
+ * @param $modules List of HTMLPurifier_HTMLModule
+ */
+ public function __construct($modules) {
+ if (!is_array($modules)) $modules = array($modules);
+ // populate content_sets based on module hints
+ // sorry, no way of overloading
+ foreach ($modules as $module_i => $module) {
+ foreach ($module->content_sets as $key => $value) {
+ $temp = $this->convertToLookup($value);
+ if (isset($this->lookup[$key])) {
+ // add it into the existing content set
+ $this->lookup[$key] = array_merge($this->lookup[$key], $temp);
+ } else {
+ $this->lookup[$key] = $temp;
+ }
+ }
+ }
+ $old_lookup = false;
+ while ($old_lookup !== $this->lookup) {
+ $old_lookup = $this->lookup;
+ foreach ($this->lookup as $i => $set) {
+ $add = array();
+ foreach ($set as $element => $x) {
+ if (isset($this->lookup[$element])) {
+ $add += $this->lookup[$element];
+ unset($this->lookup[$i][$element]);
+ }
+ }
+ $this->lookup[$i] += $add;
+ }
+ }
+
+ foreach ($this->lookup as $key => $lookup) {
+ $this->info[$key] = implode(' | ', array_keys($lookup));
+ }
+ $this->keys = array_keys($this->info);
+ $this->values = array_values($this->info);
+ }
+
+ /**
+ * Accepts a definition; generates and assigns a ChildDef for it
+ * @param $def HTMLPurifier_ElementDef reference
+ * @param $module Module that defined the ElementDef
+ */
+ public function generateChildDef(&$def, $module) {
+ if (!empty($def->child)) return; // already done!
+ $content_model = $def->content_model;
+ if (is_string($content_model)) {
+ // Assume that $this->keys is alphanumeric
+ $def->content_model = preg_replace_callback(
+ '/\b(' . implode('|', $this->keys) . ')\b/',
+ array($this, 'generateChildDefCallback'),
+ $content_model
+ );
+ //$def->content_model = str_replace(
+ // $this->keys, $this->values, $content_model);
+ }
+ $def->child = $this->getChildDef($def, $module);
+ }
+
+ public function generateChildDefCallback($matches) {
+ return $this->info[$matches[0]];
+ }
+
+ /**
+ * Instantiates a ChildDef based on content_model and content_model_type
+ * member variables in HTMLPurifier_ElementDef
+ * @note This will also defer to modules for custom HTMLPurifier_ChildDef
+ * subclasses that need content set expansion
+ * @param $def HTMLPurifier_ElementDef to have ChildDef extracted
+ * @return HTMLPurifier_ChildDef corresponding to ElementDef
+ */
+ public function getChildDef($def, $module) {
+ $value = $def->content_model;
+ if (is_object($value)) {
+ trigger_error(
+ 'Literal object child definitions should be stored in '.
+ 'ElementDef->child not ElementDef->content_model',
+ E_USER_NOTICE
+ );
+ return $value;
+ }
+ switch ($def->content_model_type) {
+ case 'required':
+ return new HTMLPurifier_ChildDef_Required($value);
+ case 'optional':
+ return new HTMLPurifier_ChildDef_Optional($value);
+ case 'empty':
+ return new HTMLPurifier_ChildDef_Empty();
+ case 'custom':
+ return new HTMLPurifier_ChildDef_Custom($value);
+ }
+ // defer to its module
+ $return = false;
+ if ($module->defines_child_def) { // save a func call
+ $return = $module->getChildDef($def);
+ }
+ if ($return !== false) return $return;
+ // error-out
+ trigger_error(
+ 'Could not determine which ChildDef class to instantiate',
+ E_USER_ERROR
+ );
+ return false;
+ }
+
+ /**
+ * Converts a string list of elements separated by pipes into
+ * a lookup array.
+ * @param $string List of elements
+ * @return Lookup array of elements
+ */
+ protected function convertToLookup($string) {
+ $array = explode('|', str_replace(' ', '', $string));
+ $ret = array();
+ foreach ($array as $i => $k) {
+ $ret[$k] = true;
+ }
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Context.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Context.php
new file mode 100644
index 0000000..9351f89
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Context.php
@@ -0,0 +1,82 @@
+<?php
+
+/**
+ * Registry object that contains information about the current context.
+ * @warning Is a bit buggy when variables are set to null: it thinks
+ * they don't exist! So use false instead, please.
+ * @note Since the variables Context deals with may not be objects,
+ * references are very important here! Do not remove!
+ */
+class HTMLPurifier_Context
+{
+
+ /**
+ * Private array that stores the references.
+ */
+ private $_storage = array();
+
+ /**
+ * Registers a variable into the context.
+ * @param $name String name
+ * @param $ref Reference to variable to be registered
+ */
+ public function register($name, &$ref) {
+ if (isset($this->_storage[$name])) {
+ trigger_error("Name $name produces collision, cannot re-register",
+ E_USER_ERROR);
+ return;
+ }
+ $this->_storage[$name] =& $ref;
+ }
+
+ /**
+ * Retrieves a variable reference from the context.
+ * @param $name String name
+ * @param $ignore_error Boolean whether or not to ignore error
+ */
+ public function &get($name, $ignore_error = false) {
+ if (!isset($this->_storage[$name])) {
+ if (!$ignore_error) {
+ trigger_error("Attempted to retrieve non-existent variable $name",
+ E_USER_ERROR);
+ }
+ $var = null; // so we can return by reference
+ return $var;
+ }
+ return $this->_storage[$name];
+ }
+
+ /**
+ * Destorys a variable in the context.
+ * @param $name String name
+ */
+ public function destroy($name) {
+ if (!isset($this->_storage[$name])) {
+ trigger_error("Attempted to destroy non-existent variable $name",
+ E_USER_ERROR);
+ return;
+ }
+ unset($this->_storage[$name]);
+ }
+
+ /**
+ * Checks whether or not the variable exists.
+ * @param $name String name
+ */
+ public function exists($name) {
+ return isset($this->_storage[$name]);
+ }
+
+ /**
+ * Loads a series of variables from an associative array
+ * @param $context_array Assoc array of variables to load
+ */
+ public function loadArray($context_array) {
+ foreach ($context_array as $key => $discard) {
+ $this->register($key, $context_array[$key]);
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Definition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Definition.php
new file mode 100644
index 0000000..8a54054
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Definition.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Super-class for definition datatype objects, implements serialization
+ * functions for the class.
+ */
+abstract class HTMLPurifier_Definition
+{
+
+ /**
+ * Has setup() been called yet?
+ */
+ public $setup = false;
+
+ /**
+ * If true, write out the final definition object to the cache after
+ * setup. This will be true only if all invocations to get a raw
+ * definition object are also optimized. This does not cause file
+ * system thrashing because on subsequent calls the cached object
+ * is used and any writes to the raw definition object are short
+ * circuited. See enduser-customize.html for the high-level
+ * picture.
+ */
+ public $optimized = null;
+
+ /**
+ * What type of definition is it?
+ */
+ public $type;
+
+ /**
+ * Sets up the definition object into the final form, something
+ * not done by the constructor
+ * @param $config HTMLPurifier_Config instance
+ */
+ abstract protected function doSetup($config);
+
+ /**
+ * Setup function that aborts if already setup
+ * @param $config HTMLPurifier_Config instance
+ */
+ public function setup($config) {
+ if ($this->setup) return;
+ $this->setup = true;
+ $this->doSetup($config);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache.php
new file mode 100644
index 0000000..7520fa1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache.php
@@ -0,0 +1,108 @@
+<?php
+
+/**
+ * Abstract class representing Definition cache managers that implements
+ * useful common methods and is a factory.
+ * @todo Create a separate maintenance file advanced users can use to
+ * cache their custom HTMLDefinition, which can be loaded
+ * via a configuration directive
+ * @todo Implement memcached
+ */
+abstract class HTMLPurifier_DefinitionCache
+{
+
+ public $type;
+
+ /**
+ * @param $name Type of definition objects this instance of the
+ * cache will handle.
+ */
+ public function __construct($type) {
+ $this->type = $type;
+ }
+
+ /**
+ * Generates a unique identifier for a particular configuration
+ * @param Instance of HTMLPurifier_Config
+ */
+ public function generateKey($config) {
+ return $config->version . ',' . // possibly replace with function calls
+ $config->getBatchSerial($this->type) . ',' .
+ $config->get($this->type . '.DefinitionRev');
+ }
+
+ /**
+ * Tests whether or not a key is old with respect to the configuration's
+ * version and revision number.
+ * @param $key Key to test
+ * @param $config Instance of HTMLPurifier_Config to test against
+ */
+ public function isOld($key, $config) {
+ if (substr_count($key, ',') < 2) return true;
+ list($version, $hash, $revision) = explode(',', $key, 3);
+ $compare = version_compare($version, $config->version);
+ // version mismatch, is always old
+ if ($compare != 0) return true;
+ // versions match, ids match, check revision number
+ if (
+ $hash == $config->getBatchSerial($this->type) &&
+ $revision < $config->get($this->type . '.DefinitionRev')
+ ) return true;
+ return false;
+ }
+
+ /**
+ * Checks if a definition's type jives with the cache's type
+ * @note Throws an error on failure
+ * @param $def Definition object to check
+ * @return Boolean true if good, false if not
+ */
+ public function checkDefType($def) {
+ if ($def->type !== $this->type) {
+ trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}");
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Adds a definition object to the cache
+ */
+ abstract public function add($def, $config);
+
+ /**
+ * Unconditionally saves a definition object to the cache
+ */
+ abstract public function set($def, $config);
+
+ /**
+ * Replace an object in the cache
+ */
+ abstract public function replace($def, $config);
+
+ /**
+ * Retrieves a definition object from the cache
+ */
+ abstract public function get($config);
+
+ /**
+ * Removes a definition object to the cache
+ */
+ abstract public function remove($config);
+
+ /**
+ * Clears all objects from cache
+ */
+ abstract public function flush($config);
+
+ /**
+ * Clears all expired (older version or revision) objects from cache
+ * @note Be carefuly implementing this method as flush. Flush must
+ * not interfere with other Definition types, and cleanup()
+ * should not be repeatedly called by userland code.
+ */
+ abstract public function cleanup($config);
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator.php
new file mode 100644
index 0000000..5d45da3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator.php
@@ -0,0 +1,62 @@
+<?php
+
+class HTMLPurifier_DefinitionCache_Decorator extends HTMLPurifier_DefinitionCache
+{
+
+ /**
+ * Cache object we are decorating
+ */
+ public $cache;
+
+ public function __construct() {}
+
+ /**
+ * Lazy decorator function
+ * @param $cache Reference to cache object to decorate
+ */
+ public function decorate(&$cache) {
+ $decorator = $this->copy();
+ // reference is necessary for mocks in PHP 4
+ $decorator->cache =& $cache;
+ $decorator->type = $cache->type;
+ return $decorator;
+ }
+
+ /**
+ * Cross-compatible clone substitute
+ */
+ public function copy() {
+ return new HTMLPurifier_DefinitionCache_Decorator();
+ }
+
+ public function add($def, $config) {
+ return $this->cache->add($def, $config);
+ }
+
+ public function set($def, $config) {
+ return $this->cache->set($def, $config);
+ }
+
+ public function replace($def, $config) {
+ return $this->cache->replace($def, $config);
+ }
+
+ public function get($config) {
+ return $this->cache->get($config);
+ }
+
+ public function remove($config) {
+ return $this->cache->remove($config);
+ }
+
+ public function flush($config) {
+ return $this->cache->flush($config);
+ }
+
+ public function cleanup($config) {
+ return $this->cache->cleanup($config);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php
new file mode 100644
index 0000000..c357949
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php
@@ -0,0 +1,43 @@
+<?php
+
+/**
+ * Definition cache decorator class that cleans up the cache
+ * whenever there is a cache miss.
+ */
+class HTMLPurifier_DefinitionCache_Decorator_Cleanup extends
+ HTMLPurifier_DefinitionCache_Decorator
+{
+
+ public $name = 'Cleanup';
+
+ public function copy() {
+ return new HTMLPurifier_DefinitionCache_Decorator_Cleanup();
+ }
+
+ public function add($def, $config) {
+ $status = parent::add($def, $config);
+ if (!$status) parent::cleanup($config);
+ return $status;
+ }
+
+ public function set($def, $config) {
+ $status = parent::set($def, $config);
+ if (!$status) parent::cleanup($config);
+ return $status;
+ }
+
+ public function replace($def, $config) {
+ $status = parent::replace($def, $config);
+ if (!$status) parent::cleanup($config);
+ return $status;
+ }
+
+ public function get($config) {
+ $ret = parent::get($config);
+ if (!$ret) parent::cleanup($config);
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Memory.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Memory.php
new file mode 100644
index 0000000..f35217e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Memory.php
@@ -0,0 +1,46 @@
+<?php
+
+/**
+ * Definition cache decorator class that saves all cache retrievals
+ * to PHP's memory; good for unit tests or circumstances where
+ * there are lots of configuration objects floating around.
+ */
+class HTMLPurifier_DefinitionCache_Decorator_Memory extends
+ HTMLPurifier_DefinitionCache_Decorator
+{
+
+ protected $definitions;
+ public $name = 'Memory';
+
+ public function copy() {
+ return new HTMLPurifier_DefinitionCache_Decorator_Memory();
+ }
+
+ public function add($def, $config) {
+ $status = parent::add($def, $config);
+ if ($status) $this->definitions[$this->generateKey($config)] = $def;
+ return $status;
+ }
+
+ public function set($def, $config) {
+ $status = parent::set($def, $config);
+ if ($status) $this->definitions[$this->generateKey($config)] = $def;
+ return $status;
+ }
+
+ public function replace($def, $config) {
+ $status = parent::replace($def, $config);
+ if ($status) $this->definitions[$this->generateKey($config)] = $def;
+ return $status;
+ }
+
+ public function get($config) {
+ $key = $this->generateKey($config);
+ if (isset($this->definitions[$key])) return $this->definitions[$key];
+ $this->definitions[$key] = parent::get($config);
+ return $this->definitions[$key];
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in
new file mode 100644
index 0000000..f33fe37
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in
@@ -0,0 +1,47 @@
+<?php
+
+require_once 'HTMLPurifier/DefinitionCache/Decorator.php';
+
+/**
+ * Definition cache decorator template.
+ */
+class HTMLPurifier_DefinitionCache_Decorator_Template extends
+ HTMLPurifier_DefinitionCache_Decorator
+{
+
+ var $name = 'Template'; // replace this
+
+ function copy() {
+ // replace class name with yours
+ return new HTMLPurifier_DefinitionCache_Decorator_Template();
+ }
+
+ // remove methods you don't need
+
+ function add($def, $config) {
+ return parent::add($def, $config);
+ }
+
+ function set($def, $config) {
+ return parent::set($def, $config);
+ }
+
+ function replace($def, $config) {
+ return parent::replace($def, $config);
+ }
+
+ function get($config) {
+ return parent::get($config);
+ }
+
+ function flush() {
+ return parent::flush();
+ }
+
+ function cleanup($config) {
+ return parent::cleanup($config);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Null.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Null.php
new file mode 100644
index 0000000..7e697f7
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Null.php
@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * Null cache object to use when no caching is on.
+ */
+class HTMLPurifier_DefinitionCache_Null extends HTMLPurifier_DefinitionCache
+{
+
+ public function add($def, $config) {
+ return false;
+ }
+
+ public function set($def, $config) {
+ return false;
+ }
+
+ public function replace($def, $config) {
+ return false;
+ }
+
+ public function remove($config) {
+ return false;
+ }
+
+ public function get($config) {
+ return false;
+ }
+
+ public function flush($config) {
+ return false;
+ }
+
+ public function cleanup($config) {
+ return false;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer.php
new file mode 100644
index 0000000..1627f3b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer.php
@@ -0,0 +1,191 @@
+<?php
+
+class HTMLPurifier_DefinitionCache_Serializer extends
+ HTMLPurifier_DefinitionCache
+{
+
+ public function add($def, $config) {
+ if (!$this->checkDefType($def)) return;
+ $file = $this->generateFilePath($config);
+ if (file_exists($file)) return false;
+ if (!$this->_prepareDir($config)) return false;
+ return $this->_write($file, serialize($def), $config);
+ }
+
+ public function set($def, $config) {
+ if (!$this->checkDefType($def)) return;
+ $file = $this->generateFilePath($config);
+ if (!$this->_prepareDir($config)) return false;
+ return $this->_write($file, serialize($def), $config);
+ }
+
+ public function replace($def, $config) {
+ if (!$this->checkDefType($def)) return;
+ $file = $this->generateFilePath($config);
+ if (!file_exists($file)) return false;
+ if (!$this->_prepareDir($config)) return false;
+ return $this->_write($file, serialize($def), $config);
+ }
+
+ public function get($config) {
+ $file = $this->generateFilePath($config);
+ if (!file_exists($file)) return false;
+ return unserialize(file_get_contents($file));
+ }
+
+ public function remove($config) {
+ $file = $this->generateFilePath($config);
+ if (!file_exists($file)) return false;
+ return unlink($file);
+ }
+
+ public function flush($config) {
+ if (!$this->_prepareDir($config)) return false;
+ $dir = $this->generateDirectoryPath($config);
+ $dh = opendir($dir);
+ while (false !== ($filename = readdir($dh))) {
+ if (empty($filename)) continue;
+ if ($filename[0] === '.') continue;
+ unlink($dir . '/' . $filename);
+ }
+ }
+
+ public function cleanup($config) {
+ if (!$this->_prepareDir($config)) return false;
+ $dir = $this->generateDirectoryPath($config);
+ $dh = opendir($dir);
+ while (false !== ($filename = readdir($dh))) {
+ if (empty($filename)) continue;
+ if ($filename[0] === '.') continue;
+ $key = substr($filename, 0, strlen($filename) - 4);
+ if ($this->isOld($key, $config)) unlink($dir . '/' . $filename);
+ }
+ }
+
+ /**
+ * Generates the file path to the serial file corresponding to
+ * the configuration and definition name
+ * @todo Make protected
+ */
+ public function generateFilePath($config) {
+ $key = $this->generateKey($config);
+ return $this->generateDirectoryPath($config) . '/' . $key . '.ser';
+ }
+
+ /**
+ * Generates the path to the directory contain this cache's serial files
+ * @note No trailing slash
+ * @todo Make protected
+ */
+ public function generateDirectoryPath($config) {
+ $base = $this->generateBaseDirectoryPath($config);
+ return $base . '/' . $this->type;
+ }
+
+ /**
+ * Generates path to base directory that contains all definition type
+ * serials
+ * @todo Make protected
+ */
+ public function generateBaseDirectoryPath($config) {
+ $base = $config->get('Cache.SerializerPath');
+ $base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base;
+ return $base;
+ }
+
+ /**
+ * Convenience wrapper function for file_put_contents
+ * @param $file File name to write to
+ * @param $data Data to write into file
+ * @param $config Config object
+ * @return Number of bytes written if success, or false if failure.
+ */
+ private function _write($file, $data, $config) {
+ $result = file_put_contents($file, $data);
+ if ($result !== false) {
+ // set permissions of the new file (no execute)
+ $chmod = $config->get('Cache.SerializerPermissions');
+ if (!$chmod) {
+ $chmod = 0644; // invalid config or simpletest
+ }
+ $chmod = $chmod & 0666;
+ chmod($file, $chmod);
+ }
+ return $result;
+ }
+
+ /**
+ * Prepares the directory that this type stores the serials in
+ * @param $config Config object
+ * @return True if successful
+ */
+ private function _prepareDir($config) {
+ $directory = $this->generateDirectoryPath($config);
+ $chmod = $config->get('Cache.SerializerPermissions');
+ if (!$chmod) {
+ $chmod = 0755; // invalid config or simpletest
+ }
+ if (!is_dir($directory)) {
+ $base = $this->generateBaseDirectoryPath($config);
+ if (!is_dir($base)) {
+ trigger_error('Base directory '.$base.' does not exist,
+ please create or change using %Cache.SerializerPath',
+ E_USER_WARNING);
+ return false;
+ } elseif (!$this->_testPermissions($base, $chmod)) {
+ return false;
+ }
+ $old = umask(0000);
+ mkdir($directory, $chmod);
+ umask($old);
+ } elseif (!$this->_testPermissions($directory, $chmod)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Tests permissions on a directory and throws out friendly
+ * error messages and attempts to chmod it itself if possible
+ * @param $dir Directory path
+ * @param $chmod Permissions
+ * @return True if directory writable
+ */
+ private function _testPermissions($dir, $chmod) {
+ // early abort, if it is writable, everything is hunky-dory
+ if (is_writable($dir)) return true;
+ if (!is_dir($dir)) {
+ // generally, you'll want to handle this beforehand
+ // so a more specific error message can be given
+ trigger_error('Directory '.$dir.' does not exist',
+ E_USER_WARNING);
+ return false;
+ }
+ if (function_exists('posix_getuid')) {
+ // POSIX system, we can give more specific advice
+ if (fileowner($dir) === posix_getuid()) {
+ // we can chmod it ourselves
+ $chmod = $chmod | 0700;
+ if (chmod($dir, $chmod)) return true;
+ } elseif (filegroup($dir) === posix_getgid()) {
+ $chmod = $chmod | 0070;
+ } else {
+ // PHP's probably running as nobody, so we'll
+ // need to give global permissions
+ $chmod = $chmod | 0777;
+ }
+ trigger_error('Directory '.$dir.' not writable, '.
+ 'please chmod to ' . decoct($chmod),
+ E_USER_WARNING);
+ } else {
+ // generic error message
+ trigger_error('Directory '.$dir.' not writable, '.
+ 'please alter file permissions',
+ E_USER_WARNING);
+ }
+ return false;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/CSS/4.3.0,4af9cb41e1f64636f725057634b6a44b,1.ser b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/CSS/4.3.0,4af9cb41e1f64636f725057634b6a44b,1.ser
new file mode 100644
index 0000000..f2dcb33
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/CSS/4.3.0,4af9cb41e1f64636f725057634b6a44b,1.ser
Binary files differ
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,3a30aa3a44d5568ce8742bef8d8eb769,1.ser b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,3a30aa3a44d5568ce8742bef8d8eb769,1.ser
new file mode 100644
index 0000000..088b96f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,3a30aa3a44d5568ce8742bef8d8eb769,1.ser
Binary files differ
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,6e3fa754534c1e442cac3cc9c6e91513,6.ser b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,6e3fa754534c1e442cac3cc9c6e91513,6.ser
new file mode 100644
index 0000000..dc8447b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/HTML/4.3.0,6e3fa754534c1e442cac3cc9c6e91513,6.ser
Binary files differ
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/README b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/README
new file mode 100644
index 0000000..ba005de
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/README
@@ -0,0 +1,3 @@
+This is a dummy file to prevent Git from ignoring this empty directory.
+
+ vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/URI/4.3.0,05c766101e813c246917b022f97b5e6e,1.ser b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/URI/4.3.0,05c766101e813c246917b022f97b5e6e,1.ser
new file mode 100644
index 0000000..3f14aa3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCache/Serializer/URI/4.3.0,05c766101e813c246917b022f97b5e6e,1.ser
Binary files differ
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCacheFactory.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCacheFactory.php
new file mode 100644
index 0000000..4230c2c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DefinitionCacheFactory.php
@@ -0,0 +1,91 @@
+<?php
+
+/**
+ * Responsible for creating definition caches.
+ */
+class HTMLPurifier_DefinitionCacheFactory
+{
+
+ protected $caches = array('Serializer' => array());
+ protected $implementations = array();
+ protected $decorators = array();
+
+ /**
+ * Initialize default decorators
+ */
+ public function setup() {
+ $this->addDecorator('Cleanup');
+ }
+
+ /**
+ * Retrieves an instance of global definition cache factory.
+ */
+ public static function instance($prototype = null) {
+ static $instance;
+ if ($prototype !== null) {
+ $instance = $prototype;
+ } elseif ($instance === null || $prototype === true) {
+ $instance = new HTMLPurifier_DefinitionCacheFactory();
+ $instance->setup();
+ }
+ return $instance;
+ }
+
+ /**
+ * Registers a new definition cache object
+ * @param $short Short name of cache object, for reference
+ * @param $long Full class name of cache object, for construction
+ */
+ public function register($short, $long) {
+ $this->implementations[$short] = $long;
+ }
+
+ /**
+ * Factory method that creates a cache object based on configuration
+ * @param $name Name of definitions handled by cache
+ * @param $config Instance of HTMLPurifier_Config
+ */
+ public function create($type, $config) {
+ $method = $config->get('Cache.DefinitionImpl');
+ if ($method === null) {
+ return new HTMLPurifier_DefinitionCache_Null($type);
+ }
+ if (!empty($this->caches[$method][$type])) {
+ return $this->caches[$method][$type];
+ }
+ if (
+ isset($this->implementations[$method]) &&
+ class_exists($class = $this->implementations[$method], false)
+ ) {
+ $cache = new $class($type);
+ } else {
+ if ($method != 'Serializer') {
+ trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING);
+ }
+ $cache = new HTMLPurifier_DefinitionCache_Serializer($type);
+ }
+ foreach ($this->decorators as $decorator) {
+ $new_cache = $decorator->decorate($cache);
+ // prevent infinite recursion in PHP 4
+ unset($cache);
+ $cache = $new_cache;
+ }
+ $this->caches[$method][$type] = $cache;
+ return $this->caches[$method][$type];
+ }
+
+ /**
+ * Registers a decorator to add to all new cache objects
+ * @param
+ */
+ public function addDecorator($decorator) {
+ if (is_string($decorator)) {
+ $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator";
+ $decorator = new $class;
+ }
+ $this->decorators[$decorator->name] = $decorator;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Doctype.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Doctype.php
new file mode 100644
index 0000000..de87c56
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Doctype.php
@@ -0,0 +1,60 @@
+<?php
+
+/**
+ * Represents a document type, contains information on which modules
+ * need to be loaded.
+ * @note This class is inspected by Printer_HTMLDefinition->renderDoctype.
+ * If structure changes, please update that function.
+ */
+class HTMLPurifier_Doctype
+{
+ /**
+ * Full name of doctype
+ */
+ public $name;
+
+ /**
+ * List of standard modules (string identifiers or literal objects)
+ * that this doctype uses
+ */
+ public $modules = array();
+
+ /**
+ * List of modules to use for tidying up code
+ */
+ public $tidyModules = array();
+
+ /**
+ * Is the language derived from XML (i.e. XHTML)?
+ */
+ public $xml = true;
+
+ /**
+ * List of aliases for this doctype
+ */
+ public $aliases = array();
+
+ /**
+ * Public DTD identifier
+ */
+ public $dtdPublic;
+
+ /**
+ * System DTD identifier
+ */
+ public $dtdSystem;
+
+ public function __construct($name = null, $xml = true, $modules = array(),
+ $tidyModules = array(), $aliases = array(), $dtd_public = null, $dtd_system = null
+ ) {
+ $this->name = $name;
+ $this->xml = $xml;
+ $this->modules = $modules;
+ $this->tidyModules = $tidyModules;
+ $this->aliases = $aliases;
+ $this->dtdPublic = $dtd_public;
+ $this->dtdSystem = $dtd_system;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DoctypeRegistry.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DoctypeRegistry.php
new file mode 100644
index 0000000..9aa3f25
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/DoctypeRegistry.php
@@ -0,0 +1,103 @@
+<?php
+
+class HTMLPurifier_DoctypeRegistry
+{
+
+ /**
+ * Hash of doctype names to doctype objects
+ */
+ protected $doctypes;
+
+ /**
+ * Lookup table of aliases to real doctype names
+ */
+ protected $aliases;
+
+ /**
+ * Registers a doctype to the registry
+ * @note Accepts a fully-formed doctype object, or the
+ * parameters for constructing a doctype object
+ * @param $doctype Name of doctype or literal doctype object
+ * @param $modules Modules doctype will load
+ * @param $modules_for_modes Modules doctype will load for certain modes
+ * @param $aliases Alias names for doctype
+ * @return Editable registered doctype
+ */
+ public function register($doctype, $xml = true, $modules = array(),
+ $tidy_modules = array(), $aliases = array(), $dtd_public = null, $dtd_system = null
+ ) {
+ if (!is_array($modules)) $modules = array($modules);
+ if (!is_array($tidy_modules)) $tidy_modules = array($tidy_modules);
+ if (!is_array($aliases)) $aliases = array($aliases);
+ if (!is_object($doctype)) {
+ $doctype = new HTMLPurifier_Doctype(
+ $doctype, $xml, $modules, $tidy_modules, $aliases, $dtd_public, $dtd_system
+ );
+ }
+ $this->doctypes[$doctype->name] = $doctype;
+ $name = $doctype->name;
+ // hookup aliases
+ foreach ($doctype->aliases as $alias) {
+ if (isset($this->doctypes[$alias])) continue;
+ $this->aliases[$alias] = $name;
+ }
+ // remove old aliases
+ if (isset($this->aliases[$name])) unset($this->aliases[$name]);
+ return $doctype;
+ }
+
+ /**
+ * Retrieves reference to a doctype of a certain name
+ * @note This function resolves aliases
+ * @note When possible, use the more fully-featured make()
+ * @param $doctype Name of doctype
+ * @return Editable doctype object
+ */
+ public function get($doctype) {
+ if (isset($this->aliases[$doctype])) $doctype = $this->aliases[$doctype];
+ if (!isset($this->doctypes[$doctype])) {
+ trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR);
+ $anon = new HTMLPurifier_Doctype($doctype);
+ return $anon;
+ }
+ return $this->doctypes[$doctype];
+ }
+
+ /**
+ * Creates a doctype based on a configuration object,
+ * will perform initialization on the doctype
+ * @note Use this function to get a copy of doctype that config
+ * can hold on to (this is necessary in order to tell
+ * Generator whether or not the current document is XML
+ * based or not).
+ */
+ public function make($config) {
+ return clone $this->get($this->getDoctypeFromConfig($config));
+ }
+
+ /**
+ * Retrieves the doctype from the configuration object
+ */
+ public function getDoctypeFromConfig($config) {
+ // recommended test
+ $doctype = $config->get('HTML.Doctype');
+ if (!empty($doctype)) return $doctype;
+ $doctype = $config->get('HTML.CustomDoctype');
+ if (!empty($doctype)) return $doctype;
+ // backwards-compatibility
+ if ($config->get('HTML.XHTML')) {
+ $doctype = 'XHTML 1.0';
+ } else {
+ $doctype = 'HTML 4.01';
+ }
+ if ($config->get('HTML.Strict')) {
+ $doctype .= ' Strict';
+ } else {
+ $doctype .= ' Transitional';
+ }
+ return $doctype;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ElementDef.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ElementDef.php
new file mode 100644
index 0000000..bb16054
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ElementDef.php
@@ -0,0 +1,183 @@
+<?php
+
+/**
+ * Structure that stores an HTML element definition. Used by
+ * HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule.
+ * @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition.
+ * Please update that class too.
+ * @warning If you add new properties to this class, you MUST update
+ * the mergeIn() method.
+ */
+class HTMLPurifier_ElementDef
+{
+
+ /**
+ * Does the definition work by itself, or is it created solely
+ * for the purpose of merging into another definition?
+ */
+ public $standalone = true;
+
+ /**
+ * Associative array of attribute name to HTMLPurifier_AttrDef
+ * @note Before being processed by HTMLPurifier_AttrCollections
+ * when modules are finalized during
+ * HTMLPurifier_HTMLDefinition->setup(), this array may also
+ * contain an array at index 0 that indicates which attribute
+ * collections to load into the full array. It may also
+ * contain string indentifiers in lieu of HTMLPurifier_AttrDef,
+ * see HTMLPurifier_AttrTypes on how they are expanded during
+ * HTMLPurifier_HTMLDefinition->setup() processing.
+ */
+ public $attr = array();
+
+ /**
+ * Indexed list of tag's HTMLPurifier_AttrTransform to be done before validation
+ */
+ public $attr_transform_pre = array();
+
+ /**
+ * Indexed list of tag's HTMLPurifier_AttrTransform to be done after validation
+ */
+ public $attr_transform_post = array();
+
+ /**
+ * HTMLPurifier_ChildDef of this tag.
+ */
+ public $child;
+
+ /**
+ * Abstract string representation of internal ChildDef rules. See
+ * HTMLPurifier_ContentSets for how this is parsed and then transformed
+ * into an HTMLPurifier_ChildDef.
+ * @warning This is a temporary variable that is not available after
+ * being processed by HTMLDefinition
+ */
+ public $content_model;
+
+ /**
+ * Value of $child->type, used to determine which ChildDef to use,
+ * used in combination with $content_model.
+ * @warning This must be lowercase
+ * @warning This is a temporary variable that is not available after
+ * being processed by HTMLDefinition
+ */
+ public $content_model_type;
+
+
+
+ /**
+ * Does the element have a content model (#PCDATA | Inline)*? This
+ * is important for chameleon ins and del processing in
+ * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't
+ * have to worry about this one.
+ */
+ public $descendants_are_inline = false;
+
+ /**
+ * List of the names of required attributes this element has. Dynamically
+ * populated by HTMLPurifier_HTMLDefinition::getElement
+ */
+ public $required_attr = array();
+
+ /**
+ * Lookup table of tags excluded from all descendants of this tag.
+ * @note SGML permits exclusions for all descendants, but this is
+ * not possible with DTDs or XML Schemas. W3C has elected to
+ * use complicated compositions of content_models to simulate
+ * exclusion for children, but we go the simpler, SGML-style
+ * route of flat-out exclusions, which correctly apply to
+ * all descendants and not just children. Note that the XHTML
+ * Modularization Abstract Modules are blithely unaware of such
+ * distinctions.
+ */
+ public $excludes = array();
+
+ /**
+ * This tag is explicitly auto-closed by the following tags.
+ */
+ public $autoclose = array();
+
+ /**
+ * If a foreign element is found in this element, test if it is
+ * allowed by this sub-element; if it is, instead of closing the
+ * current element, place it inside this element.
+ */
+ public $wrap;
+
+ /**
+ * Whether or not this is a formatting element affected by the
+ * "Active Formatting Elements" algorithm.
+ */
+ public $formatting;
+
+ /**
+ * Low-level factory constructor for creating new standalone element defs
+ */
+ public static function create($content_model, $content_model_type, $attr) {
+ $def = new HTMLPurifier_ElementDef();
+ $def->content_model = $content_model;
+ $def->content_model_type = $content_model_type;
+ $def->attr = $attr;
+ return $def;
+ }
+
+ /**
+ * Merges the values of another element definition into this one.
+ * Values from the new element def take precedence if a value is
+ * not mergeable.
+ */
+ public function mergeIn($def) {
+
+ // later keys takes precedence
+ foreach($def->attr as $k => $v) {
+ if ($k === 0) {
+ // merge in the includes
+ // sorry, no way to override an include
+ foreach ($v as $v2) {
+ $this->attr[0][] = $v2;
+ }
+ continue;
+ }
+ if ($v === false) {
+ if (isset($this->attr[$k])) unset($this->attr[$k]);
+ continue;
+ }
+ $this->attr[$k] = $v;
+ }
+ $this->_mergeAssocArray($this->attr_transform_pre, $def->attr_transform_pre);
+ $this->_mergeAssocArray($this->attr_transform_post, $def->attr_transform_post);
+ $this->_mergeAssocArray($this->excludes, $def->excludes);
+
+ if(!empty($def->content_model)) {
+ $this->content_model =
+ str_replace("#SUPER", $this->content_model, $def->content_model);
+ $this->child = false;
+ }
+ if(!empty($def->content_model_type)) {
+ $this->content_model_type = $def->content_model_type;
+ $this->child = false;
+ }
+ if(!is_null($def->child)) $this->child = $def->child;
+ if(!is_null($def->formatting)) $this->formatting = $def->formatting;
+ if($def->descendants_are_inline) $this->descendants_are_inline = $def->descendants_are_inline;
+
+ }
+
+ /**
+ * Merges one array into another, removes values which equal false
+ * @param $a1 Array by reference that is merged into
+ * @param $a2 Array that merges into $a1
+ */
+ private function _mergeAssocArray(&$a1, $a2) {
+ foreach ($a2 as $k => $v) {
+ if ($v === false) {
+ if (isset($a1[$k])) unset($a1[$k]);
+ continue;
+ }
+ $a1[$k] = $v;
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Encoder.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Encoder.php
new file mode 100644
index 0000000..2dbb023
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Encoder.php
@@ -0,0 +1,426 @@
+<?php
+
+/**
+ * A UTF-8 specific character encoder that handles cleaning and transforming.
+ * @note All functions in this class should be static.
+ */
+class HTMLPurifier_Encoder
+{
+
+ /**
+ * Constructor throws fatal error if you attempt to instantiate class
+ */
+ private function __construct() {
+ trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);
+ }
+
+ /**
+ * Error-handler that mutes errors, alternative to shut-up operator.
+ */
+ public static function muteErrorHandler() {}
+
+ /**
+ * Cleans a UTF-8 string for well-formedness and SGML validity
+ *
+ * It will parse according to UTF-8 and return a valid UTF8 string, with
+ * non-SGML codepoints excluded.
+ *
+ * @note Just for reference, the non-SGML code points are 0 to 31 and
+ * 127 to 159, inclusive. However, we allow code points 9, 10
+ * and 13, which are the tab, line feed and carriage return
+ * respectively. 128 and above the code points map to multibyte
+ * UTF-8 representations.
+ *
+ * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and
+ * hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the
+ * LGPL license. Notes on what changed are inside, but in general,
+ * the original code transformed UTF-8 text into an array of integer
+ * Unicode codepoints. Understandably, transforming that back to
+ * a string would be somewhat expensive, so the function was modded to
+ * directly operate on the string. However, this discourages code
+ * reuse, and the logic enumerated here would be useful for any
+ * function that needs to be able to understand UTF-8 characters.
+ * As of right now, only smart lossless character encoding converters
+ * would need that, and I'm probably not going to implement them.
+ * Once again, PHP 6 should solve all our problems.
+ */
+ public static function cleanUTF8($str, $force_php = false) {
+
+ // UTF-8 validity is checked since PHP 4.3.5
+ // This is an optimization: if the string is already valid UTF-8, no
+ // need to do PHP stuff. 99% of the time, this will be the case.
+ // The regexp matches the XML char production, as well as well as excluding
+ // non-SGML codepoints U+007F to U+009F
+ if (preg_match('/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', $str)) {
+ return $str;
+ }
+
+ $mState = 0; // cached expected number of octets after the current octet
+ // until the beginning of the next UTF8 character sequence
+ $mUcs4 = 0; // cached Unicode character
+ $mBytes = 1; // cached expected number of octets in the current sequence
+
+ // original code involved an $out that was an array of Unicode
+ // codepoints. Instead of having to convert back into UTF-8, we've
+ // decided to directly append valid UTF-8 characters onto a string
+ // $out once they're done. $char accumulates raw bytes, while $mUcs4
+ // turns into the Unicode code point, so there's some redundancy.
+
+ $out = '';
+ $char = '';
+
+ $len = strlen($str);
+ for($i = 0; $i < $len; $i++) {
+ $in = ord($str{$i});
+ $char .= $str[$i]; // append byte to char
+ if (0 == $mState) {
+ // When mState is zero we expect either a US-ASCII character
+ // or a multi-octet sequence.
+ if (0 == (0x80 & ($in))) {
+ // US-ASCII, pass straight through.
+ if (($in <= 31 || $in == 127) &&
+ !($in == 9 || $in == 13 || $in == 10) // save \r\t\n
+ ) {
+ // control characters, remove
+ } else {
+ $out .= $char;
+ }
+ // reset
+ $char = '';
+ $mBytes = 1;
+ } elseif (0xC0 == (0xE0 & ($in))) {
+ // First octet of 2 octet sequence
+ $mUcs4 = ($in);
+ $mUcs4 = ($mUcs4 & 0x1F) << 6;
+ $mState = 1;
+ $mBytes = 2;
+ } elseif (0xE0 == (0xF0 & ($in))) {
+ // First octet of 3 octet sequence
+ $mUcs4 = ($in);
+ $mUcs4 = ($mUcs4 & 0x0F) << 12;
+ $mState = 2;
+ $mBytes = 3;
+ } elseif (0xF0 == (0xF8 & ($in))) {
+ // First octet of 4 octet sequence
+ $mUcs4 = ($in);
+ $mUcs4 = ($mUcs4 & 0x07) << 18;
+ $mState = 3;
+ $mBytes = 4;
+ } elseif (0xF8 == (0xFC & ($in))) {
+ // First octet of 5 octet sequence.
+ //
+ // This is illegal because the encoded codepoint must be
+ // either:
+ // (a) not the shortest form or
+ // (b) outside the Unicode range of 0-0x10FFFF.
+ // Rather than trying to resynchronize, we will carry on
+ // until the end of the sequence and let the later error
+ // handling code catch it.
+ $mUcs4 = ($in);
+ $mUcs4 = ($mUcs4 & 0x03) << 24;
+ $mState = 4;
+ $mBytes = 5;
+ } elseif (0xFC == (0xFE & ($in))) {
+ // First octet of 6 octet sequence, see comments for 5
+ // octet sequence.
+ $mUcs4 = ($in);
+ $mUcs4 = ($mUcs4 & 1) << 30;
+ $mState = 5;
+ $mBytes = 6;
+ } else {
+ // Current octet is neither in the US-ASCII range nor a
+ // legal first octet of a multi-octet sequence.
+ $mState = 0;
+ $mUcs4 = 0;
+ $mBytes = 1;
+ $char = '';
+ }
+ } else {
+ // When mState is non-zero, we expect a continuation of the
+ // multi-octet sequence
+ if (0x80 == (0xC0 & ($in))) {
+ // Legal continuation.
+ $shift = ($mState - 1) * 6;
+ $tmp = $in;
+ $tmp = ($tmp & 0x0000003F) << $shift;
+ $mUcs4 |= $tmp;
+
+ if (0 == --$mState) {
+ // End of the multi-octet sequence. mUcs4 now contains
+ // the final Unicode codepoint to be output
+
+ // Check for illegal sequences and codepoints.
+
+ // From Unicode 3.1, non-shortest form is illegal
+ if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
+ ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
+ ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
+ (4 < $mBytes) ||
+ // From Unicode 3.2, surrogate characters = illegal
+ (($mUcs4 & 0xFFFFF800) == 0xD800) ||
+ // Codepoints outside the Unicode range are illegal
+ ($mUcs4 > 0x10FFFF)
+ ) {
+
+ } elseif (0xFEFF != $mUcs4 && // omit BOM
+ // check for valid Char unicode codepoints
+ (
+ 0x9 == $mUcs4 ||
+ 0xA == $mUcs4 ||
+ 0xD == $mUcs4 ||
+ (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||
+ // 7F-9F is not strictly prohibited by XML,
+ // but it is non-SGML, and thus we don't allow it
+ (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||
+ (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)
+ )
+ ) {
+ $out .= $char;
+ }
+ // initialize UTF8 cache (reset)
+ $mState = 0;
+ $mUcs4 = 0;
+ $mBytes = 1;
+ $char = '';
+ }
+ } else {
+ // ((0xC0 & (*in) != 0x80) && (mState != 0))
+ // Incomplete multi-octet sequence.
+ // used to result in complete fail, but we'll reset
+ $mState = 0;
+ $mUcs4 = 0;
+ $mBytes = 1;
+ $char ='';
+ }
+ }
+ }
+ return $out;
+ }
+
+ /**
+ * Translates a Unicode codepoint into its corresponding UTF-8 character.
+ * @note Based on Feyd's function at
+ * <http://forums.devnetwork.net/viewtopic.php?p=191404#191404>,
+ * which is in public domain.
+ * @note While we're going to do code point parsing anyway, a good
+ * optimization would be to refuse to translate code points that
+ * are non-SGML characters. However, this could lead to duplication.
+ * @note This is very similar to the unichr function in
+ * maintenance/generate-entity-file.php (although this is superior,
+ * due to its sanity checks).
+ */
+
+ // +----------+----------+----------+----------+
+ // | 33222222 | 22221111 | 111111 | |
+ // | 10987654 | 32109876 | 54321098 | 76543210 | bit
+ // +----------+----------+----------+----------+
+ // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F
+ // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF
+ // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF
+ // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF
+ // +----------+----------+----------+----------+
+ // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
+ // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
+ // +----------+----------+----------+----------+
+
+ public static function unichr($code) {
+ if($code > 1114111 or $code < 0 or
+ ($code >= 55296 and $code <= 57343) ) {
+ // bits are set outside the "valid" range as defined
+ // by UNICODE 4.1.0
+ return '';
+ }
+
+ $x = $y = $z = $w = 0;
+ if ($code < 128) {
+ // regular ASCII character
+ $x = $code;
+ } else {
+ // set up bits for UTF-8
+ $x = ($code & 63) | 128;
+ if ($code < 2048) {
+ $y = (($code & 2047) >> 6) | 192;
+ } else {
+ $y = (($code & 4032) >> 6) | 128;
+ if($code < 65536) {
+ $z = (($code >> 12) & 15) | 224;
+ } else {
+ $z = (($code >> 12) & 63) | 128;
+ $w = (($code >> 18) & 7) | 240;
+ }
+ }
+ }
+ // set up the actual character
+ $ret = '';
+ if($w) $ret .= chr($w);
+ if($z) $ret .= chr($z);
+ if($y) $ret .= chr($y);
+ $ret .= chr($x);
+
+ return $ret;
+ }
+
+ /**
+ * Converts a string to UTF-8 based on configuration.
+ */
+ public static function convertToUTF8($str, $config, $context) {
+ $encoding = $config->get('Core.Encoding');
+ if ($encoding === 'utf-8') return $str;
+ static $iconv = null;
+ if ($iconv === null) $iconv = function_exists('iconv');
+ set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
+ if ($iconv && !$config->get('Test.ForceNoIconv')) {
+ $str = iconv($encoding, 'utf-8//IGNORE', $str);
+ if ($str === false) {
+ // $encoding is not a valid encoding
+ restore_error_handler();
+ trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
+ return '';
+ }
+ // If the string is bjorked by Shift_JIS or a similar encoding
+ // that doesn't support all of ASCII, convert the naughty
+ // characters to their true byte-wise ASCII/UTF-8 equivalents.
+ $str = strtr($str, HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding));
+ restore_error_handler();
+ return $str;
+ } elseif ($encoding === 'iso-8859-1') {
+ $str = utf8_encode($str);
+ restore_error_handler();
+ return $str;
+ }
+ trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
+ }
+
+ /**
+ * Converts a string from UTF-8 based on configuration.
+ * @note Currently, this is a lossy conversion, with unexpressable
+ * characters being omitted.
+ */
+ public static function convertFromUTF8($str, $config, $context) {
+ $encoding = $config->get('Core.Encoding');
+ if ($encoding === 'utf-8') return $str;
+ static $iconv = null;
+ if ($iconv === null) $iconv = function_exists('iconv');
+ if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
+ $str = HTMLPurifier_Encoder::convertToASCIIDumbLossless($str);
+ }
+ set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
+ if ($iconv && !$config->get('Test.ForceNoIconv')) {
+ // Undo our previous fix in convertToUTF8, otherwise iconv will barf
+ $ascii_fix = HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding);
+ if (!$escape && !empty($ascii_fix)) {
+ $clear_fix = array();
+ foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';
+ $str = strtr($str, $clear_fix);
+ }
+ $str = strtr($str, array_flip($ascii_fix));
+ // Normal stuff
+ $str = iconv('utf-8', $encoding . '//IGNORE', $str);
+ restore_error_handler();
+ return $str;
+ } elseif ($encoding === 'iso-8859-1') {
+ $str = utf8_decode($str);
+ restore_error_handler();
+ return $str;
+ }
+ trigger_error('Encoding not supported', E_USER_ERROR);
+ }
+
+ /**
+ * Lossless (character-wise) conversion of HTML to ASCII
+ * @param $str UTF-8 string to be converted to ASCII
+ * @returns ASCII encoded string with non-ASCII character entity-ized
+ * @warning Adapted from MediaWiki, claiming fair use: this is a common
+ * algorithm. If you disagree with this license fudgery,
+ * implement it yourself.
+ * @note Uses decimal numeric entities since they are best supported.
+ * @note This is a DUMB function: it has no concept of keeping
+ * character entities that the projected character encoding
+ * can allow. We could possibly implement a smart version
+ * but that would require it to also know which Unicode
+ * codepoints the charset supported (not an easy task).
+ * @note Sort of with cleanUTF8() but it assumes that $str is
+ * well-formed UTF-8
+ */
+ public static function convertToASCIIDumbLossless($str) {
+ $bytesleft = 0;
+ $result = '';
+ $working = 0;
+ $len = strlen($str);
+ for( $i = 0; $i < $len; $i++ ) {
+ $bytevalue = ord( $str[$i] );
+ if( $bytevalue <= 0x7F ) { //0xxx xxxx
+ $result .= chr( $bytevalue );
+ $bytesleft = 0;
+ } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
+ $working = $working << 6;
+ $working += ($bytevalue & 0x3F);
+ $bytesleft--;
+ if( $bytesleft <= 0 ) {
+ $result .= "&#" . $working . ";";
+ }
+ } elseif( $bytevalue <= 0xDF ) { //110x xxxx
+ $working = $bytevalue & 0x1F;
+ $bytesleft = 1;
+ } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
+ $working = $bytevalue & 0x0F;
+ $bytesleft = 2;
+ } else { //1111 0xxx
+ $working = $bytevalue & 0x07;
+ $bytesleft = 3;
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * This expensive function tests whether or not a given character
+ * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will
+ * fail this test, and require special processing. Variable width
+ * encodings shouldn't ever fail.
+ *
+ * @param string $encoding Encoding name to test, as per iconv format
+ * @param bool $bypass Whether or not to bypass the precompiled arrays.
+ * @return Array of UTF-8 characters to their corresponding ASCII,
+ * which can be used to "undo" any overzealous iconv action.
+ */
+ public static function testEncodingSupportsASCII($encoding, $bypass = false) {
+ static $encodings = array();
+ if (!$bypass) {
+ if (isset($encodings[$encoding])) return $encodings[$encoding];
+ $lenc = strtolower($encoding);
+ switch ($lenc) {
+ case 'shift_jis':
+ return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
+ case 'johab':
+ return array("\xE2\x82\xA9" => '\\');
+ }
+ if (strpos($lenc, 'iso-8859-') === 0) return array();
+ }
+ $ret = array();
+ set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
+ if (iconv('UTF-8', $encoding, 'a') === false) return false;
+ for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
+ $c = chr($i); // UTF-8 char
+ $r = iconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
+ if (
+ $r === '' ||
+ // This line is needed for iconv implementations that do not
+ // omit characters that do not exist in the target character set
+ ($r === $c && iconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
+ ) {
+ // Reverse engineer: what's the UTF-8 equiv of this byte
+ // sequence? This assumes that there's no variable width
+ // encoding that doesn't support ASCII.
+ $ret[iconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
+ }
+ }
+ restore_error_handler();
+ $encodings[$encoding] = $ret;
+ return $ret;
+ }
+
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup.php
new file mode 100644
index 0000000..61c3d56
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * Object that provides entity lookup table from entity name to character
+ */
+class HTMLPurifier_EntityLookup {
+
+ /**
+ * Assoc array of entity name to character represented.
+ */
+ public $table;
+
+ /**
+ * Sets up the entity lookup table from the serialized file contents.
+ * @note The serialized contents are versioned, but were generated
+ * using the maintenance script generate_entity_file.php
+ * @warning This is not in constructor to help enforce the Singleton
+ */
+ public function setup($file = false) {
+ if (!$file) {
+ $file = HTMLPURIFIER_PREFIX . '/HTMLPurifier/EntityLookup/entities.ser';
+ }
+ $this->table = unserialize(file_get_contents($file));
+ }
+
+ /**
+ * Retrieves sole instance of the object.
+ * @param Optional prototype of custom lookup table to overload with.
+ */
+ public static function instance($prototype = false) {
+ // no references, since PHP doesn't copy unless modified
+ static $instance = null;
+ if ($prototype) {
+ $instance = $prototype;
+ } elseif (!$instance) {
+ $instance = new HTMLPurifier_EntityLookup();
+ $instance->setup();
+ }
+ return $instance;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup/entities.ser b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup/entities.ser
new file mode 100644
index 0000000..e8b0812
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityLookup/entities.ser
@@ -0,0 +1 @@
+a:253:{s:4:"fnof";s:2:"ƒ";s:5:"Alpha";s:2:"Α";s:4:"Beta";s:2:"Β";s:5:"Gamma";s:2:"Γ";s:5:"Delta";s:2:"Δ";s:7:"Epsilon";s:2:"Ε";s:4:"Zeta";s:2:"Ζ";s:3:"Eta";s:2:"Η";s:5:"Theta";s:2:"Θ";s:4:"Iota";s:2:"Ι";s:5:"Kappa";s:2:"Κ";s:6:"Lambda";s:2:"Λ";s:2:"Mu";s:2:"Μ";s:2:"Nu";s:2:"Ν";s:2:"Xi";s:2:"Ξ";s:7:"Omicron";s:2:"Ο";s:2:"Pi";s:2:"Π";s:3:"Rho";s:2:"Ρ";s:5:"Sigma";s:2:"Σ";s:3:"Tau";s:2:"Τ";s:7:"Upsilon";s:2:"Υ";s:3:"Phi";s:2:"Φ";s:3:"Chi";s:2:"Χ";s:3:"Psi";s:2:"Ψ";s:5:"Omega";s:2:"Ω";s:5:"alpha";s:2:"α";s:4:"beta";s:2:"β";s:5:"gamma";s:2:"γ";s:5:"delta";s:2:"δ";s:7:"epsilon";s:2:"ε";s:4:"zeta";s:2:"ζ";s:3:"eta";s:2:"η";s:5:"theta";s:2:"θ";s:4:"iota";s:2:"ι";s:5:"kappa";s:2:"κ";s:6:"lambda";s:2:"λ";s:2:"mu";s:2:"μ";s:2:"nu";s:2:"ν";s:2:"xi";s:2:"ξ";s:7:"omicron";s:2:"ο";s:2:"pi";s:2:"π";s:3:"rho";s:2:"ρ";s:6:"sigmaf";s:2:"ς";s:5:"sigma";s:2:"σ";s:3:"tau";s:2:"τ";s:7:"upsilon";s:2:"υ";s:3:"phi";s:2:"φ";s:3:"chi";s:2:"χ";s:3:"psi";s:2:"ψ";s:5:"omega";s:2:"ω";s:8:"thetasym";s:2:"ϑ";s:5:"upsih";s:2:"ϒ";s:3:"piv";s:2:"ϖ";s:4:"bull";s:3:"•";s:6:"hellip";s:3:"…";s:5:"prime";s:3:"′";s:5:"Prime";s:3:"″";s:5:"oline";s:3:"‾";s:5:"frasl";s:3:"⁄";s:6:"weierp";s:3:"℘";s:5:"image";s:3:"ℑ";s:4:"real";s:3:"ℜ";s:5:"trade";s:3:"™";s:7:"alefsym";s:3:"ℵ";s:4:"larr";s:3:"←";s:4:"uarr";s:3:"↑";s:4:"rarr";s:3:"→";s:4:"darr";s:3:"↓";s:4:"harr";s:3:"↔";s:5:"crarr";s:3:"↵";s:4:"lArr";s:3:"⇐";s:4:"uArr";s:3:"⇑";s:4:"rArr";s:3:"⇒";s:4:"dArr";s:3:"⇓";s:4:"hArr";s:3:"⇔";s:6:"forall";s:3:"∀";s:4:"part";s:3:"∂";s:5:"exist";s:3:"∃";s:5:"empty";s:3:"∅";s:5:"nabla";s:3:"∇";s:4:"isin";s:3:"∈";s:5:"notin";s:3:"∉";s:2:"ni";s:3:"∋";s:4:"prod";s:3:"∏";s:3:"sum";s:3:"∑";s:5:"minus";s:3:"−";s:6:"lowast";s:3:"∗";s:5:"radic";s:3:"√";s:4:"prop";s:3:"∝";s:5:"infin";s:3:"∞";s:3:"ang";s:3:"∠";s:3:"and";s:3:"∧";s:2:"or";s:3:"∨";s:3:"cap";s:3:"∩";s:3:"cup";s:3:"∪";s:3:"int";s:3:"∫";s:6:"there4";s:3:"∴";s:3:"sim";s:3:"∼";s:4:"cong";s:3:"≅";s:5:"asymp";s:3:"≈";s:2:"ne";s:3:"≠";s:5:"equiv";s:3:"≡";s:2:"le";s:3:"≤";s:2:"ge";s:3:"≥";s:3:"sub";s:3:"⊂";s:3:"sup";s:3:"⊃";s:4:"nsub";s:3:"⊄";s:4:"sube";s:3:"⊆";s:4:"supe";s:3:"⊇";s:5:"oplus";s:3:"⊕";s:6:"otimes";s:3:"⊗";s:4:"perp";s:3:"⊥";s:4:"sdot";s:3:"⋅";s:5:"lceil";s:3:"⌈";s:5:"rceil";s:3:"⌉";s:6:"lfloor";s:3:"⌊";s:6:"rfloor";s:3:"⌋";s:4:"lang";s:3:"〈";s:4:"rang";s:3:"〉";s:3:"loz";s:3:"◊";s:6:"spades";s:3:"♠";s:5:"clubs";s:3:"♣";s:6:"hearts";s:3:"♥";s:5:"diams";s:3:"♦";s:4:"quot";s:1:""";s:3:"amp";s:1:"&";s:2:"lt";s:1:"<";s:2:"gt";s:1:">";s:4:"apos";s:1:"'";s:5:"OElig";s:2:"Œ";s:5:"oelig";s:2:"œ";s:6:"Scaron";s:2:"Š";s:6:"scaron";s:2:"š";s:4:"Yuml";s:2:"Ÿ";s:4:"circ";s:2:"ˆ";s:5:"tilde";s:2:"˜";s:4:"ensp";s:3:" ";s:4:"emsp";s:3:" ";s:6:"thinsp";s:3:" ";s:4:"zwnj";s:3:"‌";s:3:"zwj";s:3:"‍";s:3:"lrm";s:3:"‎";s:3:"rlm";s:3:"‏";s:5:"ndash";s:3:"–";s:5:"mdash";s:3:"—";s:5:"lsquo";s:3:"‘";s:5:"rsquo";s:3:"’";s:5:"sbquo";s:3:"‚";s:5:"ldquo";s:3:"“";s:5:"rdquo";s:3:"”";s:5:"bdquo";s:3:"„";s:6:"dagger";s:3:"†";s:6:"Dagger";s:3:"‡";s:6:"permil";s:3:"‰";s:6:"lsaquo";s:3:"‹";s:6:"rsaquo";s:3:"›";s:4:"euro";s:3:"€";s:4:"nbsp";s:2:" ";s:5:"iexcl";s:2:"¡";s:4:"cent";s:2:"¢";s:5:"pound";s:2:"£";s:6:"curren";s:2:"¤";s:3:"yen";s:2:"¥";s:6:"brvbar";s:2:"¦";s:4:"sect";s:2:"§";s:3:"uml";s:2:"¨";s:4:"copy";s:2:"©";s:4:"ordf";s:2:"ª";s:5:"laquo";s:2:"«";s:3:"not";s:2:"¬";s:3:"shy";s:2:"­";s:3:"reg";s:2:"®";s:4:"macr";s:2:"¯";s:3:"deg";s:2:"°";s:6:"plusmn";s:2:"±";s:4:"sup2";s:2:"²";s:4:"sup3";s:2:"³";s:5:"acute";s:2:"´";s:5:"micro";s:2:"µ";s:4:"para";s:2:"¶";s:6:"middot";s:2:"·";s:5:"cedil";s:2:"¸";s:4:"sup1";s:2:"¹";s:4:"ordm";s:2:"º";s:5:"raquo";s:2:"»";s:6:"frac14";s:2:"¼";s:6:"frac12";s:2:"½";s:6:"frac34";s:2:"¾";s:6:"iquest";s:2:"¿";s:6:"Agrave";s:2:"À";s:6:"Aacute";s:2:"Á";s:5:"Acirc";s:2:"Â";s:6:"Atilde";s:2:"Ã";s:4:"Auml";s:2:"Ä";s:5:"Aring";s:2:"Å";s:5:"AElig";s:2:"Æ";s:6:"Ccedil";s:2:"Ç";s:6:"Egrave";s:2:"È";s:6:"Eacute";s:2:"É";s:5:"Ecirc";s:2:"Ê";s:4:"Euml";s:2:"Ë";s:6:"Igrave";s:2:"Ì";s:6:"Iacute";s:2:"Í";s:5:"Icirc";s:2:"Î";s:4:"Iuml";s:2:"Ï";s:3:"ETH";s:2:"Ð";s:6:"Ntilde";s:2:"Ñ";s:6:"Ograve";s:2:"Ò";s:6:"Oacute";s:2:"Ó";s:5:"Ocirc";s:2:"Ô";s:6:"Otilde";s:2:"Õ";s:4:"Ouml";s:2:"Ö";s:5:"times";s:2:"×";s:6:"Oslash";s:2:"Ø";s:6:"Ugrave";s:2:"Ù";s:6:"Uacute";s:2:"Ú";s:5:"Ucirc";s:2:"Û";s:4:"Uuml";s:2:"Ü";s:6:"Yacute";s:2:"Ý";s:5:"THORN";s:2:"Þ";s:5:"szlig";s:2:"ß";s:6:"agrave";s:2:"à";s:6:"aacute";s:2:"á";s:5:"acirc";s:2:"â";s:6:"atilde";s:2:"ã";s:4:"auml";s:2:"ä";s:5:"aring";s:2:"å";s:5:"aelig";s:2:"æ";s:6:"ccedil";s:2:"ç";s:6:"egrave";s:2:"è";s:6:"eacute";s:2:"é";s:5:"ecirc";s:2:"ê";s:4:"euml";s:2:"ë";s:6:"igrave";s:2:"ì";s:6:"iacute";s:2:"í";s:5:"icirc";s:2:"î";s:4:"iuml";s:2:"ï";s:3:"eth";s:2:"ð";s:6:"ntilde";s:2:"ñ";s:6:"ograve";s:2:"ò";s:6:"oacute";s:2:"ó";s:5:"ocirc";s:2:"ô";s:6:"otilde";s:2:"õ";s:4:"ouml";s:2:"ö";s:6:"divide";s:2:"÷";s:6:"oslash";s:2:"ø";s:6:"ugrave";s:2:"ù";s:6:"uacute";s:2:"ú";s:5:"ucirc";s:2:"û";s:4:"uuml";s:2:"ü";s:6:"yacute";s:2:"ý";s:5:"thorn";s:2:"þ";s:4:"yuml";s:2:"ÿ";} \ No newline at end of file
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityParser.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityParser.php
new file mode 100644
index 0000000..8369e5b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/EntityParser.php
@@ -0,0 +1,144 @@
+<?php
+
+// if want to implement error collecting here, we'll need to use some sort
+// of global data (probably trigger_error) because it's impossible to pass
+// $config or $context to the callback functions.
+
+/**
+ * Handles referencing and derefencing character entities
+ */
+class HTMLPurifier_EntityParser
+{
+
+ /**
+ * Reference to entity lookup table.
+ */
+ protected $_entity_lookup;
+
+ /**
+ * Callback regex string for parsing entities.
+ */
+ protected $_substituteEntitiesRegex =
+'/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/';
+// 1. hex 2. dec 3. string (XML style)
+
+
+ /**
+ * Decimal to parsed string conversion table for special entities.
+ */
+ protected $_special_dec2str =
+ array(
+ 34 => '"',
+ 38 => '&',
+ 39 => "'",
+ 60 => '<',
+ 62 => '>'
+ );
+
+ /**
+ * Stripped entity names to decimal conversion table for special entities.
+ */
+ protected $_special_ent2dec =
+ array(
+ 'quot' => 34,
+ 'amp' => 38,
+ 'lt' => 60,
+ 'gt' => 62
+ );
+
+ /**
+ * Substitutes non-special entities with their parsed equivalents. Since
+ * running this whenever you have parsed character is t3h 5uck, we run
+ * it before everything else.
+ *
+ * @param $string String to have non-special entities parsed.
+ * @returns Parsed string.
+ */
+ public function substituteNonSpecialEntities($string) {
+ // it will try to detect missing semicolons, but don't rely on it
+ return preg_replace_callback(
+ $this->_substituteEntitiesRegex,
+ array($this, 'nonSpecialEntityCallback'),
+ $string
+ );
+ }
+
+ /**
+ * Callback function for substituteNonSpecialEntities() that does the work.
+ *
+ * @param $matches PCRE matches array, with 0 the entire match, and
+ * either index 1, 2 or 3 set with a hex value, dec value,
+ * or string (respectively).
+ * @returns Replacement string.
+ */
+
+ protected function nonSpecialEntityCallback($matches) {
+ // replaces all but big five
+ $entity = $matches[0];
+ $is_num = (@$matches[0][1] === '#');
+ if ($is_num) {
+ $is_hex = (@$entity[2] === 'x');
+ $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2];
+
+ // abort for special characters
+ if (isset($this->_special_dec2str[$code])) return $entity;
+
+ return HTMLPurifier_Encoder::unichr($code);
+ } else {
+ if (isset($this->_special_ent2dec[$matches[3]])) return $entity;
+ if (!$this->_entity_lookup) {
+ $this->_entity_lookup = HTMLPurifier_EntityLookup::instance();
+ }
+ if (isset($this->_entity_lookup->table[$matches[3]])) {
+ return $this->_entity_lookup->table[$matches[3]];
+ } else {
+ return $entity;
+ }
+ }
+ }
+
+ /**
+ * Substitutes only special entities with their parsed equivalents.
+ *
+ * @notice We try to avoid calling this function because otherwise, it
+ * would have to be called a lot (for every parsed section).
+ *
+ * @param $string String to have non-special entities parsed.
+ * @returns Parsed string.
+ */
+ public function substituteSpecialEntities($string) {
+ return preg_replace_callback(
+ $this->_substituteEntitiesRegex,
+ array($this, 'specialEntityCallback'),
+ $string);
+ }
+
+ /**
+ * Callback function for substituteSpecialEntities() that does the work.
+ *
+ * This callback has same syntax as nonSpecialEntityCallback().
+ *
+ * @param $matches PCRE-style matches array, with 0 the entire match, and
+ * either index 1, 2 or 3 set with a hex value, dec value,
+ * or string (respectively).
+ * @returns Replacement string.
+ */
+ protected function specialEntityCallback($matches) {
+ $entity = $matches[0];
+ $is_num = (@$matches[0][1] === '#');
+ if ($is_num) {
+ $is_hex = (@$entity[2] === 'x');
+ $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2];
+ return isset($this->_special_dec2str[$int]) ?
+ $this->_special_dec2str[$int] :
+ $entity;
+ } else {
+ return isset($this->_special_ent2dec[$matches[3]]) ?
+ $this->_special_ent2dec[$matches[3]] :
+ $entity;
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorCollector.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorCollector.php
new file mode 100644
index 0000000..50d203c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorCollector.php
@@ -0,0 +1,209 @@
+<?php
+
+/**
+ * Error collection class that enables HTML Purifier to report HTML
+ * problems back to the user
+ */
+class HTMLPurifier_ErrorCollector
+{
+
+ /**
+ * Identifiers for the returned error array. These are purposely numeric
+ * so list() can be used.
+ */
+ const LINENO = 0;
+ const SEVERITY = 1;
+ const MESSAGE = 2;
+ const CHILDREN = 3;
+
+ protected $errors;
+ protected $_current;
+ protected $_stacks = array(array());
+ protected $locale;
+ protected $generator;
+ protected $context;
+
+ protected $lines = array();
+
+ public function __construct($context) {
+ $this->locale =& $context->get('Locale');
+ $this->context = $context;
+ $this->_current =& $this->_stacks[0];
+ $this->errors =& $this->_stacks[0];
+ }
+
+ /**
+ * Sends an error message to the collector for later use
+ * @param $severity int Error severity, PHP error style (don't use E_USER_)
+ * @param $msg string Error message text
+ * @param $subst1 string First substitution for $msg
+ * @param $subst2 string ...
+ */
+ public function send($severity, $msg) {
+
+ $args = array();
+ if (func_num_args() > 2) {
+ $args = func_get_args();
+ array_shift($args);
+ unset($args[0]);
+ }
+
+ $token = $this->context->get('CurrentToken', true);
+ $line = $token ? $token->line : $this->context->get('CurrentLine', true);
+ $col = $token ? $token->col : $this->context->get('CurrentCol', true);
+ $attr = $this->context->get('CurrentAttr', true);
+
+ // perform special substitutions, also add custom parameters
+ $subst = array();
+ if (!is_null($token)) {
+ $args['CurrentToken'] = $token;
+ }
+ if (!is_null($attr)) {
+ $subst['$CurrentAttr.Name'] = $attr;
+ if (isset($token->attr[$attr])) $subst['$CurrentAttr.Value'] = $token->attr[$attr];
+ }
+
+ if (empty($args)) {
+ $msg = $this->locale->getMessage($msg);
+ } else {
+ $msg = $this->locale->formatMessage($msg, $args);
+ }
+
+ if (!empty($subst)) $msg = strtr($msg, $subst);
+
+ // (numerically indexed)
+ $error = array(
+ self::LINENO => $line,
+ self::SEVERITY => $severity,
+ self::MESSAGE => $msg,
+ self::CHILDREN => array()
+ );
+ $this->_current[] = $error;
+
+
+ // NEW CODE BELOW ...
+
+ $struct = null;
+ // Top-level errors are either:
+ // TOKEN type, if $value is set appropriately, or
+ // "syntax" type, if $value is null
+ $new_struct = new HTMLPurifier_ErrorStruct();
+ $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN;
+ if ($token) $new_struct->value = clone $token;
+ if (is_int($line) && is_int($col)) {
+ if (isset($this->lines[$line][$col])) {
+ $struct = $this->lines[$line][$col];
+ } else {
+ $struct = $this->lines[$line][$col] = $new_struct;
+ }
+ // These ksorts may present a performance problem
+ ksort($this->lines[$line], SORT_NUMERIC);
+ } else {
+ if (isset($this->lines[-1])) {
+ $struct = $this->lines[-1];
+ } else {
+ $struct = $this->lines[-1] = $new_struct;
+ }
+ }
+ ksort($this->lines, SORT_NUMERIC);
+
+ // Now, check if we need to operate on a lower structure
+ if (!empty($attr)) {
+ $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr);
+ if (!$struct->value) {
+ $struct->value = array($attr, 'PUT VALUE HERE');
+ }
+ }
+ if (!empty($cssprop)) {
+ $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop);
+ if (!$struct->value) {
+ // if we tokenize CSS this might be a little more difficult to do
+ $struct->value = array($cssprop, 'PUT VALUE HERE');
+ }
+ }
+
+ // Ok, structs are all setup, now time to register the error
+ $struct->addError($severity, $msg);
+ }
+
+ /**
+ * Retrieves raw error data for custom formatter to use
+ * @param List of arrays in format of array(line of error,
+ * error severity, error message,
+ * recursive sub-errors array)
+ */
+ public function getRaw() {
+ return $this->errors;
+ }
+
+ /**
+ * Default HTML formatting implementation for error messages
+ * @param $config Configuration array, vital for HTML output nature
+ * @param $errors Errors array to display; used for recursion.
+ */
+ public function getHTMLFormatted($config, $errors = null) {
+ $ret = array();
+
+ $this->generator = new HTMLPurifier_Generator($config, $this->context);
+ if ($errors === null) $errors = $this->errors;
+
+ // 'At line' message needs to be removed
+
+ // generation code for new structure goes here. It needs to be recursive.
+ foreach ($this->lines as $line => $col_array) {
+ if ($line == -1) continue;
+ foreach ($col_array as $col => $struct) {
+ $this->_renderStruct($ret, $struct, $line, $col);
+ }
+ }
+ if (isset($this->lines[-1])) {
+ $this->_renderStruct($ret, $this->lines[-1]);
+ }
+
+ if (empty($errors)) {
+ return '<p>' . $this->locale->getMessage('ErrorCollector: No errors') . '</p>';
+ } else {
+ return '<ul><li>' . implode('</li><li>', $ret) . '</li></ul>';
+ }
+
+ }
+
+ private function _renderStruct(&$ret, $struct, $line = null, $col = null) {
+ $stack = array($struct);
+ $context_stack = array(array());
+ while ($current = array_pop($stack)) {
+ $context = array_pop($context_stack);
+ foreach ($current->errors as $error) {
+ list($severity, $msg) = $error;
+ $string = '';
+ $string .= '<div>';
+ // W3C uses an icon to indicate the severity of the error.
+ $error = $this->locale->getErrorName($severity);
+ $string .= "<span class=\"error e$severity\"><strong>$error</strong></span> ";
+ if (!is_null($line) && !is_null($col)) {
+ $string .= "<em class=\"location\">Line $line, Column $col: </em> ";
+ } else {
+ $string .= '<em class="location">End of Document: </em> ';
+ }
+ $string .= '<strong class="description">' . $this->generator->escape($msg) . '</strong> ';
+ $string .= '</div>';
+ // Here, have a marker for the character on the column appropriate.
+ // Be sure to clip extremely long lines.
+ //$string .= '<pre>';
+ //$string .= '';
+ //$string .= '</pre>';
+ $ret[] = $string;
+ }
+ foreach ($current->children as $type => $array) {
+ $context[] = $current;
+ $stack = array_merge($stack, array_reverse($array, true));
+ for ($i = count($array); $i > 0; $i--) {
+ $context_stack[] = $context;
+ }
+ }
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorStruct.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorStruct.php
new file mode 100644
index 0000000..b8a276e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/ErrorStruct.php
@@ -0,0 +1,60 @@
+<?php
+
+/**
+ * Records errors for particular segments of an HTML document such as tokens,
+ * attributes or CSS properties. They can contain error structs (which apply
+ * to components of what they represent), but their main purpose is to hold
+ * errors applying to whatever struct is being used.
+ */
+class HTMLPurifier_ErrorStruct
+{
+
+ /**
+ * Possible values for $children first-key. Note that top-level structures
+ * are automatically token-level.
+ */
+ const TOKEN = 0;
+ const ATTR = 1;
+ const CSSPROP = 2;
+
+ /**
+ * Type of this struct.
+ */
+ public $type;
+
+ /**
+ * Value of the struct we are recording errors for. There are various
+ * values for this:
+ * - TOKEN: Instance of HTMLPurifier_Token
+ * - ATTR: array('attr-name', 'value')
+ * - CSSPROP: array('prop-name', 'value')
+ */
+ public $value;
+
+ /**
+ * Errors registered for this structure.
+ */
+ public $errors = array();
+
+ /**
+ * Child ErrorStructs that are from this structure. For example, a TOKEN
+ * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional
+ * array in structure: [TYPE]['identifier']
+ */
+ public $children = array();
+
+ public function getChild($type, $id) {
+ if (!isset($this->children[$type][$id])) {
+ $this->children[$type][$id] = new HTMLPurifier_ErrorStruct();
+ $this->children[$type][$id]->type = $type;
+ }
+ return $this->children[$type][$id];
+ }
+
+ public function addError($severity, $message) {
+ $this->errors[] = array($severity, $message);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Exception.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Exception.php
new file mode 100644
index 0000000..defe157
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Exception.php
@@ -0,0 +1,12 @@
+<?php
+
+/**
+ * Global exception class for HTML Purifier; any exceptions we throw
+ * are from here.
+ */
+class HTMLPurifier_Exception extends Exception
+{
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter.php
new file mode 100644
index 0000000..b20369c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter.php
@@ -0,0 +1,46 @@
+<?php
+
+/**
+ * Represents a pre or post processing filter on HTML Purifier's output
+ *
+ * Sometimes, a little ad-hoc fixing of HTML has to be done before
+ * it gets sent through HTML Purifier: you can use filters to acheive
+ * this effect. For instance, YouTube videos can be preserved using
+ * this manner. You could have used a decorator for this task, but
+ * PHP's support for them is not terribly robust, so we're going
+ * to just loop through the filters.
+ *
+ * Filters should be exited first in, last out. If there are three filters,
+ * named 1, 2 and 3, the order of execution should go 1->preFilter,
+ * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter,
+ * 1->postFilter.
+ *
+ * @note Methods are not declared abstract as it is perfectly legitimate
+ * for an implementation not to want anything to happen on a step
+ */
+
+class HTMLPurifier_Filter
+{
+
+ /**
+ * Name of the filter for identification purposes
+ */
+ public $name;
+
+ /**
+ * Pre-processor function, handles HTML before HTML Purifier
+ */
+ public function preFilter($html, $config, $context) {
+ return $html;
+ }
+
+ /**
+ * Post-processor function, handles HTML after HTML Purifier
+ */
+ public function postFilter($html, $config, $context) {
+ return $html;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/ExtractStyleBlocks.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/ExtractStyleBlocks.php
new file mode 100644
index 0000000..c64e461
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/ExtractStyleBlocks.php
@@ -0,0 +1,135 @@
+<?php
+
+/**
+ * This filter extracts <style> blocks from input HTML, cleans them up
+ * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks')
+ * so they can be used elsewhere in the document.
+ *
+ * @note
+ * See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for
+ * sample usage.
+ *
+ * @note
+ * This filter can also be used on stylesheets not included in the
+ * document--something purists would probably prefer. Just directly
+ * call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS()
+ */
+class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter
+{
+
+ public $name = 'ExtractStyleBlocks';
+ private $_styleMatches = array();
+ private $_tidy;
+
+ public function __construct() {
+ $this->_tidy = new csstidy();
+ }
+
+ /**
+ * Save the contents of CSS blocks to style matches
+ * @param $matches preg_replace style $matches array
+ */
+ protected function styleCallback($matches) {
+ $this->_styleMatches[] = $matches[1];
+ }
+
+ /**
+ * Removes inline <style> tags from HTML, saves them for later use
+ * @todo Extend to indicate non-text/css style blocks
+ */
+ public function preFilter($html, $config, $context) {
+ $tidy = $config->get('Filter.ExtractStyleBlocks.TidyImpl');
+ if ($tidy !== null) $this->_tidy = $tidy;
+ $html = preg_replace_callback('#<style(?:\s.*)?>(.+)</style>#isU', array($this, 'styleCallback'), $html);
+ $style_blocks = $this->_styleMatches;
+ $this->_styleMatches = array(); // reset
+ $context->register('StyleBlocks', $style_blocks); // $context must not be reused
+ if ($this->_tidy) {
+ foreach ($style_blocks as &$style) {
+ $style = $this->cleanCSS($style, $config, $context);
+ }
+ }
+ return $html;
+ }
+
+ /**
+ * Takes CSS (the stuff found in <style>) and cleans it.
+ * @warning Requires CSSTidy <http://csstidy.sourceforge.net/>
+ * @param $css CSS styling to clean
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return Cleaned CSS
+ */
+ public function cleanCSS($css, $config, $context) {
+ // prepare scope
+ $scope = $config->get('Filter.ExtractStyleBlocks.Scope');
+ if ($scope !== null) {
+ $scopes = array_map('trim', explode(',', $scope));
+ } else {
+ $scopes = array();
+ }
+ // remove comments from CSS
+ $css = trim($css);
+ if (strncmp('<!--', $css, 4) === 0) {
+ $css = substr($css, 4);
+ }
+ if (strlen($css) > 3 && substr($css, -3) == '-->') {
+ $css = substr($css, 0, -3);
+ }
+ $css = trim($css);
+ $this->_tidy->parse($css);
+ $css_definition = $config->getDefinition('CSS');
+ foreach ($this->_tidy->css as $k => $decls) {
+ // $decls are all CSS declarations inside an @ selector
+ $new_decls = array();
+ foreach ($decls as $selector => $style) {
+ $selector = trim($selector);
+ if ($selector === '') continue; // should not happen
+ if ($selector[0] === '+') {
+ if ($selector !== '' && $selector[0] === '+') continue;
+ }
+ if (!empty($scopes)) {
+ $new_selector = array(); // because multiple ones are possible
+ $selectors = array_map('trim', explode(',', $selector));
+ foreach ($scopes as $s1) {
+ foreach ($selectors as $s2) {
+ $new_selector[] = "$s1 $s2";
+ }
+ }
+ $selector = implode(', ', $new_selector); // now it's a string
+ }
+ foreach ($style as $name => $value) {
+ if (!isset($css_definition->info[$name])) {
+ unset($style[$name]);
+ continue;
+ }
+ $def = $css_definition->info[$name];
+ $ret = $def->validate($value, $config, $context);
+ if ($ret === false) unset($style[$name]);
+ else $style[$name] = $ret;
+ }
+ $new_decls[$selector] = $style;
+ }
+ $this->_tidy->css[$k] = $new_decls;
+ }
+ // remove stuff that shouldn't be used, could be reenabled
+ // after security risks are analyzed
+ $this->_tidy->import = array();
+ $this->_tidy->charset = null;
+ $this->_tidy->namespace = null;
+ $css = $this->_tidy->print->plain();
+ // we are going to escape any special characters <>& to ensure
+ // that no funny business occurs (i.e. </style> in a font-family prop).
+ if ($config->get('Filter.ExtractStyleBlocks.Escaping')) {
+ $css = str_replace(
+ array('<', '>', '&'),
+ array('\3C ', '\3E ', '\26 '),
+ $css
+ );
+ }
+ return $css;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/YouTube.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/YouTube.php
new file mode 100644
index 0000000..4633887
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Filter/YouTube.php
@@ -0,0 +1,39 @@
+<?php
+
+class HTMLPurifier_Filter_YouTube extends HTMLPurifier_Filter
+{
+
+ public $name = 'YouTube';
+
+ public function preFilter($html, $config, $context) {
+ $pre_regex = '#<object[^>]+>.+?'.
+ 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s';
+ $pre_replace = '<span class="youtube-embed">\1</span>';
+ return preg_replace($pre_regex, $pre_replace, $html);
+ }
+
+ public function postFilter($html, $config, $context) {
+ $post_regex = '#<span class="youtube-embed">((?:v|cp)/[A-Za-z0-9\-_=]+)</span>#';
+ return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
+ }
+
+ protected function armorUrl($url) {
+ return str_replace('--', '-&#45;', $url);
+ }
+
+ protected function postFilterCallback($matches) {
+ $url = $this->armorUrl($matches[1]);
+ return '<object width="425" height="350" type="application/x-shockwave-flash" '.
+ 'data="http://www.youtube.com/'.$url.'">'.
+ '<param name="movie" value="http://www.youtube.com/'.$url.'"></param>'.
+ '<!--[if IE]>'.
+ '<embed src="http://www.youtube.com/'.$url.'"'.
+ 'type="application/x-shockwave-flash"'.
+ 'wmode="transparent" width="425" height="350" />'.
+ '<![endif]-->'.
+ '</object>';
+
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Generator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Generator.php
new file mode 100644
index 0000000..3a75b87
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Generator.php
@@ -0,0 +1,254 @@
+<?php
+
+/**
+ * Generates HTML from tokens.
+ * @todo Refactor interface so that configuration/context is determined
+ * upon instantiation, no need for messy generateFromTokens() calls
+ * @todo Make some of the more internal functions protected, and have
+ * unit tests work around that
+ */
+class HTMLPurifier_Generator
+{
+
+ /**
+ * Whether or not generator should produce XML output
+ */
+ private $_xhtml = true;
+
+ /**
+ * :HACK: Whether or not generator should comment the insides of <script> tags
+ */
+ private $_scriptFix = false;
+
+ /**
+ * Cache of HTMLDefinition during HTML output to determine whether or
+ * not attributes should be minimized.
+ */
+ private $_def;
+
+ /**
+ * Cache of %Output.SortAttr
+ */
+ private $_sortAttr;
+
+ /**
+ * Cache of %Output.FlashCompat
+ */
+ private $_flashCompat;
+
+ /**
+ * Cache of %Output.FixInnerHTML
+ */
+ private $_innerHTMLFix;
+
+ /**
+ * Stack for keeping track of object information when outputting IE
+ * compatibility code.
+ */
+ private $_flashStack = array();
+
+ /**
+ * Configuration for the generator
+ */
+ protected $config;
+
+ /**
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ */
+ public function __construct($config, $context) {
+ $this->config = $config;
+ $this->_scriptFix = $config->get('Output.CommentScriptContents');
+ $this->_innerHTMLFix = $config->get('Output.FixInnerHTML');
+ $this->_sortAttr = $config->get('Output.SortAttr');
+ $this->_flashCompat = $config->get('Output.FlashCompat');
+ $this->_def = $config->getHTMLDefinition();
+ $this->_xhtml = $this->_def->doctype->xml;
+ }
+
+ /**
+ * Generates HTML from an array of tokens.
+ * @param $tokens Array of HTMLPurifier_Token
+ * @param $config HTMLPurifier_Config object
+ * @return Generated HTML
+ */
+ public function generateFromTokens($tokens) {
+ if (!$tokens) return '';
+
+ // Basic algorithm
+ $html = '';
+ for ($i = 0, $size = count($tokens); $i < $size; $i++) {
+ if ($this->_scriptFix && $tokens[$i]->name === 'script'
+ && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {
+ // script special case
+ // the contents of the script block must be ONE token
+ // for this to work.
+ $html .= $this->generateFromToken($tokens[$i++]);
+ $html .= $this->generateScriptFromToken($tokens[$i++]);
+ }
+ $html .= $this->generateFromToken($tokens[$i]);
+ }
+
+ // Tidy cleanup
+ if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {
+ $tidy = new Tidy;
+ $tidy->parseString($html, array(
+ 'indent'=> true,
+ 'output-xhtml' => $this->_xhtml,
+ 'show-body-only' => true,
+ 'indent-spaces' => 2,
+ 'wrap' => 68,
+ ), 'utf8');
+ $tidy->cleanRepair();
+ $html = (string) $tidy; // explicit cast necessary
+ }
+
+ // Normalize newlines to system defined value
+ if ($this->config->get('Core.NormalizeNewlines')) {
+ $nl = $this->config->get('Output.Newline');
+ if ($nl === null) $nl = PHP_EOL;
+ if ($nl !== "\n") $html = str_replace("\n", $nl, $html);
+ }
+ return $html;
+ }
+
+ /**
+ * Generates HTML from a single token.
+ * @param $token HTMLPurifier_Token object.
+ * @return Generated HTML
+ */
+ public function generateFromToken($token) {
+ if (!$token instanceof HTMLPurifier_Token) {
+ trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
+ return '';
+
+ } elseif ($token instanceof HTMLPurifier_Token_Start) {
+ $attr = $this->generateAttributes($token->attr, $token->name);
+ if ($this->_flashCompat) {
+ if ($token->name == "object") {
+ $flash = new stdclass();
+ $flash->attr = $token->attr;
+ $flash->param = array();
+ $this->_flashStack[] = $flash;
+ }
+ }
+ return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
+
+ } elseif ($token instanceof HTMLPurifier_Token_End) {
+ $_extra = '';
+ if ($this->_flashCompat) {
+ if ($token->name == "object" && !empty($this->_flashStack)) {
+ // doesn't do anything for now
+ }
+ }
+ return $_extra . '</' . $token->name . '>';
+
+ } elseif ($token instanceof HTMLPurifier_Token_Empty) {
+ if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) {
+ $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];
+ }
+ $attr = $this->generateAttributes($token->attr, $token->name);
+ return '<' . $token->name . ($attr ? ' ' : '') . $attr .
+ ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>
+ . '>';
+
+ } elseif ($token instanceof HTMLPurifier_Token_Text) {
+ return $this->escape($token->data, ENT_NOQUOTES);
+
+ } elseif ($token instanceof HTMLPurifier_Token_Comment) {
+ return '<!--' . $token->data . '-->';
+ } else {
+ return '';
+
+ }
+ }
+
+ /**
+ * Special case processor for the contents of script tags
+ * @warning This runs into problems if there's already a literal
+ * --> somewhere inside the script contents.
+ */
+ public function generateScriptFromToken($token) {
+ if (!$token instanceof HTMLPurifier_Token_Text) return $this->generateFromToken($token);
+ // Thanks <http://lachy.id.au/log/2005/05/script-comments>
+ $data = preg_replace('#//\s*$#', '', $token->data);
+ return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
+ }
+
+ /**
+ * Generates attribute declarations from attribute array.
+ * @note This does not include the leading or trailing space.
+ * @param $assoc_array_of_attributes Attribute array
+ * @param $element Name of element attributes are for, used to check
+ * attribute minimization.
+ * @return Generate HTML fragment for insertion.
+ */
+ public function generateAttributes($assoc_array_of_attributes, $element = false) {
+ $html = '';
+ if ($this->_sortAttr) ksort($assoc_array_of_attributes);
+ foreach ($assoc_array_of_attributes as $key => $value) {
+ if (!$this->_xhtml) {
+ // Remove namespaced attributes
+ if (strpos($key, ':') !== false) continue;
+ // Check if we should minimize the attribute: val="val" -> val
+ if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {
+ $html .= $key . ' ';
+ continue;
+ }
+ }
+ // Workaround for Internet Explorer innerHTML bug.
+ // Essentially, Internet Explorer, when calculating
+ // innerHTML, omits quotes if there are no instances of
+ // angled brackets, quotes or spaces. However, when parsing
+ // HTML (for example, when you assign to innerHTML), it
+ // treats backticks as quotes. Thus,
+ // <img alt="``" />
+ // becomes
+ // <img alt=`` />
+ // becomes
+ // <img alt='' />
+ // Fortunately, all we need to do is trigger an appropriate
+ // quoting style, which we do by adding an extra space.
+ // This also is consistent with the W3C spec, which states
+ // that user agents may ignore leading or trailing
+ // whitespace (in fact, most don't, at least for attributes
+ // like alt, but an extra space at the end is barely
+ // noticeable). Still, we have a configuration knob for
+ // this, since this transformation is not necesary if you
+ // don't process user input with innerHTML or you don't plan
+ // on supporting Internet Explorer.
+ if ($this->_innerHTMLFix) {
+ if (strpos($value, '`') !== false) {
+ // check if correct quoting style would not already be
+ // triggered
+ if (strcspn($value, '"\' <>') === strlen($value)) {
+ // protect!
+ $value .= ' ';
+ }
+ }
+ }
+ $html .= $key.'="'.$this->escape($value).'" ';
+ }
+ return rtrim($html);
+ }
+
+ /**
+ * Escapes raw text data.
+ * @todo This really ought to be protected, but until we have a facility
+ * for properly generating HTML here w/o using tokens, it stays
+ * public.
+ * @param $string String data to escape for HTML.
+ * @param $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is
+ * permissible for non-attribute output.
+ * @return String escaped data.
+ */
+ public function escape($string, $quote = null) {
+ // Workaround for APC bug on Mac Leopard reported by sidepodcast
+ // http://htmlpurifier.org/phorum/read.php?3,4823,4846
+ if ($quote === null) $quote = ENT_COMPAT;
+ return htmlspecialchars($string, $quote, 'UTF-8');
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLDefinition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLDefinition.php
new file mode 100644
index 0000000..2454c9c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLDefinition.php
@@ -0,0 +1,425 @@
+<?php
+
+/**
+ * Definition of the purified HTML that describes allowed children,
+ * attributes, and many other things.
+ *
+ * Conventions:
+ *
+ * All member variables that are prefixed with info
+ * (including the main $info array) are used by HTML Purifier internals
+ * and should not be directly edited when customizing the HTMLDefinition.
+ * They can usually be set via configuration directives or custom
+ * modules.
+ *
+ * On the other hand, member variables without the info prefix are used
+ * internally by the HTMLDefinition and MUST NOT be used by other HTML
+ * Purifier internals. Many of them, however, are public, and may be
+ * edited by userspace code to tweak the behavior of HTMLDefinition.
+ *
+ * @note This class is inspected by Printer_HTMLDefinition; please
+ * update that class if things here change.
+ *
+ * @warning Directives that change this object's structure must be in
+ * the HTML or Attr namespace!
+ */
+class HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition
+{
+
+ // FULLY-PUBLIC VARIABLES ---------------------------------------------
+
+ /**
+ * Associative array of element names to HTMLPurifier_ElementDef
+ */
+ public $info = array();
+
+ /**
+ * Associative array of global attribute name to attribute definition.
+ */
+ public $info_global_attr = array();
+
+ /**
+ * String name of parent element HTML will be going into.
+ */
+ public $info_parent = 'div';
+
+ /**
+ * Definition for parent element, allows parent element to be a
+ * tag that's not allowed inside the HTML fragment.
+ */
+ public $info_parent_def;
+
+ /**
+ * String name of element used to wrap inline elements in block context
+ * @note This is rarely used except for BLOCKQUOTEs in strict mode
+ */
+ public $info_block_wrapper = 'p';
+
+ /**
+ * Associative array of deprecated tag name to HTMLPurifier_TagTransform
+ */
+ public $info_tag_transform = array();
+
+ /**
+ * Indexed list of HTMLPurifier_AttrTransform to be performed before validation.
+ */
+ public $info_attr_transform_pre = array();
+
+ /**
+ * Indexed list of HTMLPurifier_AttrTransform to be performed after validation.
+ */
+ public $info_attr_transform_post = array();
+
+ /**
+ * Nested lookup array of content set name (Block, Inline) to
+ * element name to whether or not it belongs in that content set.
+ */
+ public $info_content_sets = array();
+
+ /**
+ * Indexed list of HTMLPurifier_Injector to be used.
+ */
+ public $info_injector = array();
+
+ /**
+ * Doctype object
+ */
+ public $doctype;
+
+
+
+ // RAW CUSTOMIZATION STUFF --------------------------------------------
+
+ /**
+ * Adds a custom attribute to a pre-existing element
+ * @note This is strictly convenience, and does not have a corresponding
+ * method in HTMLPurifier_HTMLModule
+ * @param $element_name String element name to add attribute to
+ * @param $attr_name String name of attribute
+ * @param $def Attribute definition, can be string or object, see
+ * HTMLPurifier_AttrTypes for details
+ */
+ public function addAttribute($element_name, $attr_name, $def) {
+ $module = $this->getAnonymousModule();
+ if (!isset($module->info[$element_name])) {
+ $element = $module->addBlankElement($element_name);
+ } else {
+ $element = $module->info[$element_name];
+ }
+ $element->attr[$attr_name] = $def;
+ }
+
+ /**
+ * Adds a custom element to your HTML definition
+ * @note See HTMLPurifier_HTMLModule::addElement for detailed
+ * parameter and return value descriptions.
+ */
+ public function addElement($element_name, $type, $contents, $attr_collections, $attributes = array()) {
+ $module = $this->getAnonymousModule();
+ // assume that if the user is calling this, the element
+ // is safe. This may not be a good idea
+ $element = $module->addElement($element_name, $type, $contents, $attr_collections, $attributes);
+ return $element;
+ }
+
+ /**
+ * Adds a blank element to your HTML definition, for overriding
+ * existing behavior
+ * @note See HTMLPurifier_HTMLModule::addBlankElement for detailed
+ * parameter and return value descriptions.
+ */
+ public function addBlankElement($element_name) {
+ $module = $this->getAnonymousModule();
+ $element = $module->addBlankElement($element_name);
+ return $element;
+ }
+
+ /**
+ * Retrieves a reference to the anonymous module, so you can
+ * bust out advanced features without having to make your own
+ * module.
+ */
+ public function getAnonymousModule() {
+ if (!$this->_anonModule) {
+ $this->_anonModule = new HTMLPurifier_HTMLModule();
+ $this->_anonModule->name = 'Anonymous';
+ }
+ return $this->_anonModule;
+ }
+
+ private $_anonModule;
+
+
+ // PUBLIC BUT INTERNAL VARIABLES --------------------------------------
+
+ public $type = 'HTML';
+ public $manager; /**< Instance of HTMLPurifier_HTMLModuleManager */
+
+ /**
+ * Performs low-cost, preliminary initialization.
+ */
+ public function __construct() {
+ $this->manager = new HTMLPurifier_HTMLModuleManager();
+ }
+
+ protected function doSetup($config) {
+ $this->processModules($config);
+ $this->setupConfigStuff($config);
+ unset($this->manager);
+
+ // cleanup some of the element definitions
+ foreach ($this->info as $k => $v) {
+ unset($this->info[$k]->content_model);
+ unset($this->info[$k]->content_model_type);
+ }
+ }
+
+ /**
+ * Extract out the information from the manager
+ */
+ protected function processModules($config) {
+
+ if ($this->_anonModule) {
+ // for user specific changes
+ // this is late-loaded so we don't have to deal with PHP4
+ // reference wonky-ness
+ $this->manager->addModule($this->_anonModule);
+ unset($this->_anonModule);
+ }
+
+ $this->manager->setup($config);
+ $this->doctype = $this->manager->doctype;
+
+ foreach ($this->manager->modules as $module) {
+ foreach($module->info_tag_transform as $k => $v) {
+ if ($v === false) unset($this->info_tag_transform[$k]);
+ else $this->info_tag_transform[$k] = $v;
+ }
+ foreach($module->info_attr_transform_pre as $k => $v) {
+ if ($v === false) unset($this->info_attr_transform_pre[$k]);
+ else $this->info_attr_transform_pre[$k] = $v;
+ }
+ foreach($module->info_attr_transform_post as $k => $v) {
+ if ($v === false) unset($this->info_attr_transform_post[$k]);
+ else $this->info_attr_transform_post[$k] = $v;
+ }
+ foreach ($module->info_injector as $k => $v) {
+ if ($v === false) unset($this->info_injector[$k]);
+ else $this->info_injector[$k] = $v;
+ }
+ }
+
+ $this->info = $this->manager->getElements();
+ $this->info_content_sets = $this->manager->contentSets->lookup;
+
+ }
+
+ /**
+ * Sets up stuff based on config. We need a better way of doing this.
+ */
+ protected function setupConfigStuff($config) {
+
+ $block_wrapper = $config->get('HTML.BlockWrapper');
+ if (isset($this->info_content_sets['Block'][$block_wrapper])) {
+ $this->info_block_wrapper = $block_wrapper;
+ } else {
+ trigger_error('Cannot use non-block element as block wrapper',
+ E_USER_ERROR);
+ }
+
+ $parent = $config->get('HTML.Parent');
+ $def = $this->manager->getElement($parent, true);
+ if ($def) {
+ $this->info_parent = $parent;
+ $this->info_parent_def = $def;
+ } else {
+ trigger_error('Cannot use unrecognized element as parent',
+ E_USER_ERROR);
+ $this->info_parent_def = $this->manager->getElement($this->info_parent, true);
+ }
+
+ // support template text
+ $support = "(for information on implementing this, see the ".
+ "support forums) ";
+
+ // setup allowed elements -----------------------------------------
+
+ $allowed_elements = $config->get('HTML.AllowedElements');
+ $allowed_attributes = $config->get('HTML.AllowedAttributes'); // retrieve early
+
+ if (!is_array($allowed_elements) && !is_array($allowed_attributes)) {
+ $allowed = $config->get('HTML.Allowed');
+ if (is_string($allowed)) {
+ list($allowed_elements, $allowed_attributes) = $this->parseTinyMCEAllowedList($allowed);
+ }
+ }
+
+ if (is_array($allowed_elements)) {
+ foreach ($this->info as $name => $d) {
+ if(!isset($allowed_elements[$name])) unset($this->info[$name]);
+ unset($allowed_elements[$name]);
+ }
+ // emit errors
+ foreach ($allowed_elements as $element => $d) {
+ $element = htmlspecialchars($element); // PHP doesn't escape errors, be careful!
+ trigger_error("Element '$element' is not supported $support", E_USER_WARNING);
+ }
+ }
+
+ // setup allowed attributes ---------------------------------------
+
+ $allowed_attributes_mutable = $allowed_attributes; // by copy!
+ if (is_array($allowed_attributes)) {
+
+ // This actually doesn't do anything, since we went away from
+ // global attributes. It's possible that userland code uses
+ // it, but HTMLModuleManager doesn't!
+ foreach ($this->info_global_attr as $attr => $x) {
+ $keys = array($attr, "*@$attr", "*.$attr");
+ $delete = true;
+ foreach ($keys as $key) {
+ if ($delete && isset($allowed_attributes[$key])) {
+ $delete = false;
+ }
+ if (isset($allowed_attributes_mutable[$key])) {
+ unset($allowed_attributes_mutable[$key]);
+ }
+ }
+ if ($delete) unset($this->info_global_attr[$attr]);
+ }
+
+ foreach ($this->info as $tag => $info) {
+ foreach ($info->attr as $attr => $x) {
+ $keys = array("$tag@$attr", $attr, "*@$attr", "$tag.$attr", "*.$attr");
+ $delete = true;
+ foreach ($keys as $key) {
+ if ($delete && isset($allowed_attributes[$key])) {
+ $delete = false;
+ }
+ if (isset($allowed_attributes_mutable[$key])) {
+ unset($allowed_attributes_mutable[$key]);
+ }
+ }
+ if ($delete) {
+ if ($this->info[$tag]->attr[$attr]->required) {
+ trigger_error("Required attribute '$attr' in element '$tag' was not allowed, which means '$tag' will not be allowed either", E_USER_WARNING);
+ }
+ unset($this->info[$tag]->attr[$attr]);
+ }
+ }
+ }
+ // emit errors
+ foreach ($allowed_attributes_mutable as $elattr => $d) {
+ $bits = preg_split('/[.@]/', $elattr, 2);
+ $c = count($bits);
+ switch ($c) {
+ case 2:
+ if ($bits[0] !== '*') {
+ $element = htmlspecialchars($bits[0]);
+ $attribute = htmlspecialchars($bits[1]);
+ if (!isset($this->info[$element])) {
+ trigger_error("Cannot allow attribute '$attribute' if element '$element' is not allowed/supported $support");
+ } else {
+ trigger_error("Attribute '$attribute' in element '$element' not supported $support",
+ E_USER_WARNING);
+ }
+ break;
+ }
+ // otherwise fall through
+ case 1:
+ $attribute = htmlspecialchars($bits[0]);
+ trigger_error("Global attribute '$attribute' is not ".
+ "supported in any elements $support",
+ E_USER_WARNING);
+ break;
+ }
+ }
+
+ }
+
+ // setup forbidden elements ---------------------------------------
+
+ $forbidden_elements = $config->get('HTML.ForbiddenElements');
+ $forbidden_attributes = $config->get('HTML.ForbiddenAttributes');
+
+ foreach ($this->info as $tag => $info) {
+ if (isset($forbidden_elements[$tag])) {
+ unset($this->info[$tag]);
+ continue;
+ }
+ foreach ($info->attr as $attr => $x) {
+ if (
+ isset($forbidden_attributes["$tag@$attr"]) ||
+ isset($forbidden_attributes["*@$attr"]) ||
+ isset($forbidden_attributes[$attr])
+ ) {
+ unset($this->info[$tag]->attr[$attr]);
+ continue;
+ } // this segment might get removed eventually
+ elseif (isset($forbidden_attributes["$tag.$attr"])) {
+ // $tag.$attr are not user supplied, so no worries!
+ trigger_error("Error with $tag.$attr: tag.attr syntax not supported for HTML.ForbiddenAttributes; use tag@attr instead", E_USER_WARNING);
+ }
+ }
+ }
+ foreach ($forbidden_attributes as $key => $v) {
+ if (strlen($key) < 2) continue;
+ if ($key[0] != '*') continue;
+ if ($key[1] == '.') {
+ trigger_error("Error with $key: *.attr syntax not supported for HTML.ForbiddenAttributes; use attr instead", E_USER_WARNING);
+ }
+ }
+
+ // setup injectors -----------------------------------------------------
+ foreach ($this->info_injector as $i => $injector) {
+ if ($injector->checkNeeded($config) !== false) {
+ // remove injector that does not have it's required
+ // elements/attributes present, and is thus not needed.
+ unset($this->info_injector[$i]);
+ }
+ }
+ }
+
+ /**
+ * Parses a TinyMCE-flavored Allowed Elements and Attributes list into
+ * separate lists for processing. Format is element[attr1|attr2],element2...
+ * @warning Although it's largely drawn from TinyMCE's implementation,
+ * it is different, and you'll probably have to modify your lists
+ * @param $list String list to parse
+ * @param array($allowed_elements, $allowed_attributes)
+ * @todo Give this its own class, probably static interface
+ */
+ public function parseTinyMCEAllowedList($list) {
+
+ $list = str_replace(array(' ', "\t"), '', $list);
+
+ $elements = array();
+ $attributes = array();
+
+ $chunks = preg_split('/(,|[\n\r]+)/', $list);
+ foreach ($chunks as $chunk) {
+ if (empty($chunk)) continue;
+ // remove TinyMCE element control characters
+ if (!strpos($chunk, '[')) {
+ $element = $chunk;
+ $attr = false;
+ } else {
+ list($element, $attr) = explode('[', $chunk);
+ }
+ if ($element !== '*') $elements[$element] = true;
+ if (!$attr) continue;
+ $attr = substr($attr, 0, strlen($attr) - 1); // remove trailing ]
+ $attr = explode('|', $attr);
+ foreach ($attr as $key) {
+ $attributes["$element.$key"] = true;
+ }
+ }
+
+ return array($elements, $attributes);
+
+ }
+
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule.php
new file mode 100644
index 0000000..5aa930c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule.php
@@ -0,0 +1,244 @@
+<?php
+
+/**
+ * Represents an XHTML 1.1 module, with information on elements, tags
+ * and attributes.
+ * @note Even though this is technically XHTML 1.1, it is also used for
+ * regular HTML parsing. We are using modulization as a convenient
+ * way to represent the internals of HTMLDefinition, and our
+ * implementation is by no means conforming and does not directly
+ * use the normative DTDs or XML schemas.
+ * @note The public variables in a module should almost directly
+ * correspond to the variables in HTMLPurifier_HTMLDefinition.
+ * However, the prefix info carries no special meaning in these
+ * objects (include it anyway if that's the correspondence though).
+ * @todo Consider making some member functions protected
+ */
+
+class HTMLPurifier_HTMLModule
+{
+
+ // -- Overloadable ----------------------------------------------------
+
+ /**
+ * Short unique string identifier of the module
+ */
+ public $name;
+
+ /**
+ * Informally, a list of elements this module changes. Not used in
+ * any significant way.
+ */
+ public $elements = array();
+
+ /**
+ * Associative array of element names to element definitions.
+ * Some definitions may be incomplete, to be merged in later
+ * with the full definition.
+ */
+ public $info = array();
+
+ /**
+ * Associative array of content set names to content set additions.
+ * This is commonly used to, say, add an A element to the Inline
+ * content set. This corresponds to an internal variable $content_sets
+ * and NOT info_content_sets member variable of HTMLDefinition.
+ */
+ public $content_sets = array();
+
+ /**
+ * Associative array of attribute collection names to attribute
+ * collection additions. More rarely used for adding attributes to
+ * the global collections. Example is the StyleAttribute module adding
+ * the style attribute to the Core. Corresponds to HTMLDefinition's
+ * attr_collections->info, since the object's data is only info,
+ * with extra behavior associated with it.
+ */
+ public $attr_collections = array();
+
+ /**
+ * Associative array of deprecated tag name to HTMLPurifier_TagTransform
+ */
+ public $info_tag_transform = array();
+
+ /**
+ * List of HTMLPurifier_AttrTransform to be performed before validation.
+ */
+ public $info_attr_transform_pre = array();
+
+ /**
+ * List of HTMLPurifier_AttrTransform to be performed after validation.
+ */
+ public $info_attr_transform_post = array();
+
+ /**
+ * List of HTMLPurifier_Injector to be performed during well-formedness fixing.
+ * An injector will only be invoked if all of it's pre-requisites are met;
+ * if an injector fails setup, there will be no error; it will simply be
+ * silently disabled.
+ */
+ public $info_injector = array();
+
+ /**
+ * Boolean flag that indicates whether or not getChildDef is implemented.
+ * For optimization reasons: may save a call to a function. Be sure
+ * to set it if you do implement getChildDef(), otherwise it will have
+ * no effect!
+ */
+ public $defines_child_def = false;
+
+ /**
+ * Boolean flag whether or not this module is safe. If it is not safe, all
+ * of its members are unsafe. Modules are safe by default (this might be
+ * slightly dangerous, but it doesn't make much sense to force HTML Purifier,
+ * which is based off of safe HTML, to explicitly say, "This is safe," even
+ * though there are modules which are "unsafe")
+ *
+ * @note Previously, safety could be applied at an element level granularity.
+ * We've removed this ability, so in order to add "unsafe" elements
+ * or attributes, a dedicated module with this property set to false
+ * must be used.
+ */
+ public $safe = true;
+
+ /**
+ * Retrieves a proper HTMLPurifier_ChildDef subclass based on
+ * content_model and content_model_type member variables of
+ * the HTMLPurifier_ElementDef class. There is a similar function
+ * in HTMLPurifier_HTMLDefinition.
+ * @param $def HTMLPurifier_ElementDef instance
+ * @return HTMLPurifier_ChildDef subclass
+ */
+ public function getChildDef($def) {return false;}
+
+ // -- Convenience -----------------------------------------------------
+
+ /**
+ * Convenience function that sets up a new element
+ * @param $element Name of element to add
+ * @param $type What content set should element be registered to?
+ * Set as false to skip this step.
+ * @param $contents Allowed children in form of:
+ * "$content_model_type: $content_model"
+ * @param $attr_includes What attribute collections to register to
+ * element?
+ * @param $attr What unique attributes does the element define?
+ * @note See ElementDef for in-depth descriptions of these parameters.
+ * @return Created element definition object, so you
+ * can set advanced parameters
+ */
+ public function addElement($element, $type, $contents, $attr_includes = array(), $attr = array()) {
+ $this->elements[] = $element;
+ // parse content_model
+ list($content_model_type, $content_model) = $this->parseContents($contents);
+ // merge in attribute inclusions
+ $this->mergeInAttrIncludes($attr, $attr_includes);
+ // add element to content sets
+ if ($type) $this->addElementToContentSet($element, $type);
+ // create element
+ $this->info[$element] = HTMLPurifier_ElementDef::create(
+ $content_model, $content_model_type, $attr
+ );
+ // literal object $contents means direct child manipulation
+ if (!is_string($contents)) $this->info[$element]->child = $contents;
+ return $this->info[$element];
+ }
+
+ /**
+ * Convenience function that creates a totally blank, non-standalone
+ * element.
+ * @param $element Name of element to create
+ * @return Created element
+ */
+ public function addBlankElement($element) {
+ if (!isset($this->info[$element])) {
+ $this->elements[] = $element;
+ $this->info[$element] = new HTMLPurifier_ElementDef();
+ $this->info[$element]->standalone = false;
+ } else {
+ trigger_error("Definition for $element already exists in module, cannot redefine");
+ }
+ return $this->info[$element];
+ }
+
+ /**
+ * Convenience function that registers an element to a content set
+ * @param Element to register
+ * @param Name content set (warning: case sensitive, usually upper-case
+ * first letter)
+ */
+ public function addElementToContentSet($element, $type) {
+ if (!isset($this->content_sets[$type])) $this->content_sets[$type] = '';
+ else $this->content_sets[$type] .= ' | ';
+ $this->content_sets[$type] .= $element;
+ }
+
+ /**
+ * Convenience function that transforms single-string contents
+ * into separate content model and content model type
+ * @param $contents Allowed children in form of:
+ * "$content_model_type: $content_model"
+ * @note If contents is an object, an array of two nulls will be
+ * returned, and the callee needs to take the original $contents
+ * and use it directly.
+ */
+ public function parseContents($contents) {
+ if (!is_string($contents)) return array(null, null); // defer
+ switch ($contents) {
+ // check for shorthand content model forms
+ case 'Empty':
+ return array('empty', '');
+ case 'Inline':
+ return array('optional', 'Inline | #PCDATA');
+ case 'Flow':
+ return array('optional', 'Flow | #PCDATA');
+ }
+ list($content_model_type, $content_model) = explode(':', $contents);
+ $content_model_type = strtolower(trim($content_model_type));
+ $content_model = trim($content_model);
+ return array($content_model_type, $content_model);
+ }
+
+ /**
+ * Convenience function that merges a list of attribute includes into
+ * an attribute array.
+ * @param $attr Reference to attr array to modify
+ * @param $attr_includes Array of includes / string include to merge in
+ */
+ public function mergeInAttrIncludes(&$attr, $attr_includes) {
+ if (!is_array($attr_includes)) {
+ if (empty($attr_includes)) $attr_includes = array();
+ else $attr_includes = array($attr_includes);
+ }
+ $attr[0] = $attr_includes;
+ }
+
+ /**
+ * Convenience function that generates a lookup table with boolean
+ * true as value.
+ * @param $list List of values to turn into a lookup
+ * @note You can also pass an arbitrary number of arguments in
+ * place of the regular argument
+ * @return Lookup array equivalent of list
+ */
+ public function makeLookup($list) {
+ if (is_string($list)) $list = func_get_args();
+ $ret = array();
+ foreach ($list as $value) {
+ if (is_null($value)) continue;
+ $ret[$value] = true;
+ }
+ return $ret;
+ }
+
+ /**
+ * Lazy load construction of the module after determining whether
+ * or not it's needed, and also when a finalized configuration object
+ * is available.
+ * @param $config Instance of HTMLPurifier_Config
+ */
+ public function setup($config) {}
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Bdo.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Bdo.php
new file mode 100644
index 0000000..6d767ca
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Bdo.php
@@ -0,0 +1,31 @@
+<?php
+
+/**
+ * XHTML 1.1 Bi-directional Text Module, defines elements that
+ * declare directionality of content. Text Extension Module.
+ */
+class HTMLPurifier_HTMLModule_Bdo extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Bdo';
+ public $attr_collections = array(
+ 'I18N' => array('dir' => false)
+ );
+
+ public function setup($config) {
+ $bdo = $this->addElement(
+ 'bdo', 'Inline', 'Inline', array('Core', 'Lang'),
+ array(
+ 'dir' => 'Enum#ltr,rtl', // required
+ // The Abstract Module specification has the attribute
+ // inclusions wrong for bdo: bdo allows Lang
+ )
+ );
+ $bdo->attr_transform_post['required-dir'] = new HTMLPurifier_AttrTransform_BdoDir();
+
+ $this->attr_collections['I18N']['dir'] = 'Enum#ltr,rtl';
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/CommonAttributes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/CommonAttributes.php
new file mode 100644
index 0000000..f2259f9
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/CommonAttributes.php
@@ -0,0 +1,26 @@
+<?php
+
+class HTMLPurifier_HTMLModule_CommonAttributes extends HTMLPurifier_HTMLModule
+{
+ public $name = 'CommonAttributes';
+
+ public $attr_collections = array(
+ 'Core' => array(
+ 0 => array('Style'),
+ // 'xml:space' => false,
+ 'class' => 'Class',
+ 'id' => 'ID',
+ 'title' => 'CDATA',
+ ),
+ 'Lang' => array(),
+ 'I18N' => array(
+ 0 => array('Lang'), // proprietary, for xml:lang/lang
+ ),
+ 'Common' => array(
+ 0 => array('Core', 'I18N')
+ )
+ );
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Edit.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Edit.php
new file mode 100644
index 0000000..793e568
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Edit.php
@@ -0,0 +1,38 @@
+<?php
+
+/**
+ * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension
+ * Module.
+ */
+class HTMLPurifier_HTMLModule_Edit extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Edit';
+
+ public function setup($config) {
+ $contents = 'Chameleon: #PCDATA | Inline ! #PCDATA | Flow';
+ $attr = array(
+ 'cite' => 'URI',
+ // 'datetime' => 'Datetime', // not implemented
+ );
+ $this->addElement('del', 'Inline', $contents, 'Common', $attr);
+ $this->addElement('ins', 'Inline', $contents, 'Common', $attr);
+ }
+
+ // HTML 4.01 specifies that ins/del must not contain block
+ // elements when used in an inline context, chameleon is
+ // a complicated workaround to acheive this effect
+
+ // Inline context ! Block context (exclamation mark is
+ // separator, see getChildDef for parsing)
+
+ public $defines_child_def = true;
+ public function getChildDef($def) {
+ if ($def->content_model_type != 'chameleon') return false;
+ $value = explode('!', $def->content_model);
+ return new HTMLPurifier_ChildDef_Chameleon($value[0], $value[1]);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Forms.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Forms.php
new file mode 100644
index 0000000..f3629ab
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Forms.php
@@ -0,0 +1,118 @@
+<?php
+
+/**
+ * XHTML 1.1 Forms module, defines all form-related elements found in HTML 4.
+ */
+class HTMLPurifier_HTMLModule_Forms extends HTMLPurifier_HTMLModule
+{
+ public $name = 'Forms';
+ public $safe = false;
+
+ public $content_sets = array(
+ 'Block' => 'Form',
+ 'Inline' => 'Formctrl',
+ );
+
+ public function setup($config) {
+ $form = $this->addElement('form', 'Form',
+ 'Required: Heading | List | Block | fieldset', 'Common', array(
+ 'accept' => 'ContentTypes',
+ 'accept-charset' => 'Charsets',
+ 'action*' => 'URI',
+ 'method' => 'Enum#get,post',
+ // really ContentType, but these two are the only ones used today
+ 'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data',
+ ));
+ $form->excludes = array('form' => true);
+
+ $input = $this->addElement('input', 'Formctrl', 'Empty', 'Common', array(
+ 'accept' => 'ContentTypes',
+ 'accesskey' => 'Character',
+ 'alt' => 'Text',
+ 'checked' => 'Bool#checked',
+ 'disabled' => 'Bool#disabled',
+ 'maxlength' => 'Number',
+ 'name' => 'CDATA',
+ 'readonly' => 'Bool#readonly',
+ 'size' => 'Number',
+ 'src' => 'URI#embeds',
+ 'tabindex' => 'Number',
+ 'type' => 'Enum#text,password,checkbox,button,radio,submit,reset,file,hidden,image',
+ 'value' => 'CDATA',
+ ));
+ $input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input();
+
+ $this->addElement('select', 'Formctrl', 'Required: optgroup | option', 'Common', array(
+ 'disabled' => 'Bool#disabled',
+ 'multiple' => 'Bool#multiple',
+ 'name' => 'CDATA',
+ 'size' => 'Number',
+ 'tabindex' => 'Number',
+ ));
+
+ $this->addElement('option', false, 'Optional: #PCDATA', 'Common', array(
+ 'disabled' => 'Bool#disabled',
+ 'label' => 'Text',
+ 'selected' => 'Bool#selected',
+ 'value' => 'CDATA',
+ ));
+ // It's illegal for there to be more than one selected, but not
+ // be multiple. Also, no selected means undefined behavior. This might
+ // be difficult to implement; perhaps an injector, or a context variable.
+
+ $textarea = $this->addElement('textarea', 'Formctrl', 'Optional: #PCDATA', 'Common', array(
+ 'accesskey' => 'Character',
+ 'cols*' => 'Number',
+ 'disabled' => 'Bool#disabled',
+ 'name' => 'CDATA',
+ 'readonly' => 'Bool#readonly',
+ 'rows*' => 'Number',
+ 'tabindex' => 'Number',
+ ));
+ $textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea();
+
+ $button = $this->addElement('button', 'Formctrl', 'Optional: #PCDATA | Heading | List | Block | Inline', 'Common', array(
+ 'accesskey' => 'Character',
+ 'disabled' => 'Bool#disabled',
+ 'name' => 'CDATA',
+ 'tabindex' => 'Number',
+ 'type' => 'Enum#button,submit,reset',
+ 'value' => 'CDATA',
+ ));
+
+ // For exclusions, ideally we'd specify content sets, not literal elements
+ $button->excludes = $this->makeLookup(
+ 'form', 'fieldset', // Form
+ 'input', 'select', 'textarea', 'label', 'button', // Formctrl
+ 'a' // as per HTML 4.01 spec, this is omitted by modularization
+ );
+
+ // Extra exclusion: img usemap="" is not permitted within this element.
+ // We'll omit this for now, since we don't have any good way of
+ // indicating it yet.
+
+ // This is HIGHLY user-unfriendly; we need a custom child-def for this
+ $this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common');
+
+ $label = $this->addElement('label', 'Formctrl', 'Optional: #PCDATA | Inline', 'Common', array(
+ 'accesskey' => 'Character',
+ // 'for' => 'IDREF', // IDREF not implemented, cannot allow
+ ));
+ $label->excludes = array('label' => true);
+
+ $this->addElement('legend', false, 'Optional: #PCDATA | Inline', 'Common', array(
+ 'accesskey' => 'Character',
+ ));
+
+ $this->addElement('optgroup', false, 'Required: option', 'Common', array(
+ 'disabled' => 'Bool#disabled',
+ 'label*' => 'Text',
+ ));
+
+ // Don't forget an injector for <isindex>. This one's a little complex
+ // because it maps to multiple elements.
+
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Hypertext.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Hypertext.php
new file mode 100644
index 0000000..3bf3f07
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Hypertext.php
@@ -0,0 +1,31 @@
+<?php
+
+/**
+ * XHTML 1.1 Hypertext Module, defines hypertext links. Core Module.
+ */
+class HTMLPurifier_HTMLModule_Hypertext extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Hypertext';
+
+ public function setup($config) {
+ $a = $this->addElement(
+ 'a', 'Inline', 'Inline', 'Common',
+ array(
+ // 'accesskey' => 'Character',
+ // 'charset' => 'Charset',
+ 'href' => 'URI',
+ // 'hreflang' => 'LanguageCode',
+ 'rel' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rel'),
+ 'rev' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rev'),
+ // 'tabindex' => 'Number',
+ // 'type' => 'ContentType',
+ )
+ );
+ $a->formatting = true;
+ $a->excludes = array('a' => true);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Image.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Image.php
new file mode 100644
index 0000000..b70e126
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Image.php
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * XHTML 1.1 Image Module provides basic image embedding.
+ * @note There is specialized code for removing empty images in
+ * HTMLPurifier_Strategy_RemoveForeignElements
+ */
+class HTMLPurifier_HTMLModule_Image extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Image';
+
+ public function setup($config) {
+ $max = $config->get('HTML.MaxImgLength');
+ $img = $this->addElement(
+ 'img', 'Inline', 'Empty', 'Common',
+ array(
+ 'alt*' => 'Text',
+ // According to the spec, it's Length, but percents can
+ // be abused, so we allow only Pixels.
+ 'height' => 'Pixels#' . $max,
+ 'width' => 'Pixels#' . $max,
+ 'longdesc' => 'URI',
+ 'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded
+ )
+ );
+ if ($max === null || $config->get('HTML.Trusted')) {
+ $img->attr['height'] =
+ $img->attr['width'] = 'Length';
+ }
+
+ // kind of strange, but splitting things up would be inefficient
+ $img->attr_transform_pre[] =
+ $img->attr_transform_post[] =
+ new HTMLPurifier_AttrTransform_ImgRequired();
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Legacy.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Legacy.php
new file mode 100644
index 0000000..a7e8594
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Legacy.php
@@ -0,0 +1,143 @@
+<?php
+
+/**
+ * XHTML 1.1 Legacy module defines elements that were previously
+ * deprecated.
+ *
+ * @note Not all legacy elements have been implemented yet, which
+ * is a bit of a reverse problem as compared to browsers! In
+ * addition, this legacy module may implement a bit more than
+ * mandated by XHTML 1.1.
+ *
+ * This module can be used in combination with TransformToStrict in order
+ * to transform as many deprecated elements as possible, but retain
+ * questionably deprecated elements that do not have good alternatives
+ * as well as transform elements that don't have an implementation.
+ * See docs/ref-strictness.txt for more details.
+ */
+
+class HTMLPurifier_HTMLModule_Legacy extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Legacy';
+
+ public function setup($config) {
+
+ $this->addElement('basefont', 'Inline', 'Empty', false, array(
+ 'color' => 'Color',
+ 'face' => 'Text', // extremely broad, we should
+ 'size' => 'Text', // tighten it
+ 'id' => 'ID'
+ ));
+ $this->addElement('center', 'Block', 'Flow', 'Common');
+ $this->addElement('dir', 'Block', 'Required: li', 'Common', array(
+ 'compact' => 'Bool#compact'
+ ));
+ $this->addElement('font', 'Inline', 'Inline', array('Core', 'I18N'), array(
+ 'color' => 'Color',
+ 'face' => 'Text', // extremely broad, we should
+ 'size' => 'Text', // tighten it
+ ));
+ $this->addElement('menu', 'Block', 'Required: li', 'Common', array(
+ 'compact' => 'Bool#compact'
+ ));
+
+ $s = $this->addElement('s', 'Inline', 'Inline', 'Common');
+ $s->formatting = true;
+
+ $strike = $this->addElement('strike', 'Inline', 'Inline', 'Common');
+ $strike->formatting = true;
+
+ $u = $this->addElement('u', 'Inline', 'Inline', 'Common');
+ $u->formatting = true;
+
+ // setup modifications to old elements
+
+ $align = 'Enum#left,right,center,justify';
+
+ $address = $this->addBlankElement('address');
+ $address->content_model = 'Inline | #PCDATA | p';
+ $address->content_model_type = 'optional';
+ $address->child = false;
+
+ $blockquote = $this->addBlankElement('blockquote');
+ $blockquote->content_model = 'Flow | #PCDATA';
+ $blockquote->content_model_type = 'optional';
+ $blockquote->child = false;
+
+ $br = $this->addBlankElement('br');
+ $br->attr['clear'] = 'Enum#left,all,right,none';
+
+ $caption = $this->addBlankElement('caption');
+ $caption->attr['align'] = 'Enum#top,bottom,left,right';
+
+ $div = $this->addBlankElement('div');
+ $div->attr['align'] = $align;
+
+ $dl = $this->addBlankElement('dl');
+ $dl->attr['compact'] = 'Bool#compact';
+
+ for ($i = 1; $i <= 6; $i++) {
+ $h = $this->addBlankElement("h$i");
+ $h->attr['align'] = $align;
+ }
+
+ $hr = $this->addBlankElement('hr');
+ $hr->attr['align'] = $align;
+ $hr->attr['noshade'] = 'Bool#noshade';
+ $hr->attr['size'] = 'Pixels';
+ $hr->attr['width'] = 'Length';
+
+ $img = $this->addBlankElement('img');
+ $img->attr['align'] = 'Enum#top,middle,bottom,left,right';
+ $img->attr['border'] = 'Pixels';
+ $img->attr['hspace'] = 'Pixels';
+ $img->attr['vspace'] = 'Pixels';
+
+ // figure out this integer business
+
+ $li = $this->addBlankElement('li');
+ $li->attr['value'] = new HTMLPurifier_AttrDef_Integer();
+ $li->attr['type'] = 'Enum#s:1,i,I,a,A,disc,square,circle';
+
+ $ol = $this->addBlankElement('ol');
+ $ol->attr['compact'] = 'Bool#compact';
+ $ol->attr['start'] = new HTMLPurifier_AttrDef_Integer();
+ $ol->attr['type'] = 'Enum#s:1,i,I,a,A';
+
+ $p = $this->addBlankElement('p');
+ $p->attr['align'] = $align;
+
+ $pre = $this->addBlankElement('pre');
+ $pre->attr['width'] = 'Number';
+
+ // script omitted
+
+ $table = $this->addBlankElement('table');
+ $table->attr['align'] = 'Enum#left,center,right';
+ $table->attr['bgcolor'] = 'Color';
+
+ $tr = $this->addBlankElement('tr');
+ $tr->attr['bgcolor'] = 'Color';
+
+ $th = $this->addBlankElement('th');
+ $th->attr['bgcolor'] = 'Color';
+ $th->attr['height'] = 'Length';
+ $th->attr['nowrap'] = 'Bool#nowrap';
+ $th->attr['width'] = 'Length';
+
+ $td = $this->addBlankElement('td');
+ $td->attr['bgcolor'] = 'Color';
+ $td->attr['height'] = 'Length';
+ $td->attr['nowrap'] = 'Bool#nowrap';
+ $td->attr['width'] = 'Length';
+
+ $ul = $this->addBlankElement('ul');
+ $ul->attr['compact'] = 'Bool#compact';
+ $ul->attr['type'] = 'Enum#square,disc,circle';
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/List.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/List.php
new file mode 100644
index 0000000..57aad7b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/List.php
@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * XHTML 1.1 List Module, defines list-oriented elements. Core Module.
+ */
+class HTMLPurifier_HTMLModule_List extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'List';
+
+ // According to the abstract schema, the List content set is a fully formed
+ // one or more expr, but it invariably occurs in an optional declaration
+ // so we're not going to do that subtlety. It might cause trouble
+ // if a user defines "List" and expects that multiple lists are
+ // allowed to be specified, but then again, that's not very intuitive.
+ // Furthermore, the actual XML Schema may disagree. Regardless,
+ // we don't have support for such nested expressions without using
+ // the incredibly inefficient and draconic Custom ChildDef.
+
+ public $content_sets = array('Flow' => 'List');
+
+ public function setup($config) {
+ $ol = $this->addElement('ol', 'List', 'Required: li', 'Common');
+ $ol->wrap = "li";
+ $ul = $this->addElement('ul', 'List', 'Required: li', 'Common');
+ $ul->wrap = "li";
+ $this->addElement('dl', 'List', 'Required: dt | dd', 'Common');
+
+ $this->addElement('li', false, 'Flow', 'Common');
+
+ $this->addElement('dd', false, 'Flow', 'Common');
+ $this->addElement('dt', false, 'Inline', 'Common');
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Name.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Name.php
new file mode 100644
index 0000000..31300f3
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Name.php
@@ -0,0 +1,21 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Name extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Name';
+
+ public function setup($config) {
+ $elements = array('a', 'applet', 'form', 'frame', 'iframe', 'img', 'map');
+ foreach ($elements as $name) {
+ $element = $this->addBlankElement($name);
+ $element->attr['name'] = 'CDATA';
+ if (!$config->get('HTML.Attr.Name.UseCDATA')) {
+ $element->attr_transform_post['NameSync'] = new HTMLPurifier_AttrTransform_NameSync();
+ }
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Nofollow.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Nofollow.php
new file mode 100644
index 0000000..1ddc734
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Nofollow.php
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * Module adds the nofollow attribute transformation to a tags. It
+ * is enabled by HTML.Nofollow
+ */
+class HTMLPurifier_HTMLModule_Nofollow extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Nofollow';
+
+ public function setup($config) {
+ $a = $this->addBlankElement('a');
+ $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_Nofollow();
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php
new file mode 100644
index 0000000..7c0fc23
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php
@@ -0,0 +1,14 @@
+<?php
+
+class HTMLPurifier_HTMLModule_NonXMLCommonAttributes extends HTMLPurifier_HTMLModule
+{
+ public $name = 'NonXMLCommonAttributes';
+
+ public $attr_collections = array(
+ 'Lang' => array(
+ 'lang' => 'LanguageCode',
+ )
+ );
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Object.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Object.php
new file mode 100644
index 0000000..069a3df
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Object.php
@@ -0,0 +1,47 @@
+<?php
+
+/**
+ * XHTML 1.1 Object Module, defines elements for generic object inclusion
+ * @warning Users will commonly use <embed> to cater to legacy browsers: this
+ * module does not allow this sort of behavior
+ */
+class HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Object';
+ public $safe = false;
+
+ public function setup($config) {
+
+ $this->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', 'Common',
+ array(
+ 'archive' => 'URI',
+ 'classid' => 'URI',
+ 'codebase' => 'URI',
+ 'codetype' => 'Text',
+ 'data' => 'URI',
+ 'declare' => 'Bool#declare',
+ 'height' => 'Length',
+ 'name' => 'CDATA',
+ 'standby' => 'Text',
+ 'tabindex' => 'Number',
+ 'type' => 'ContentType',
+ 'width' => 'Length'
+ )
+ );
+
+ $this->addElement('param', false, 'Empty', false,
+ array(
+ 'id' => 'ID',
+ 'name*' => 'Text',
+ 'type' => 'Text',
+ 'value' => 'Text',
+ 'valuetype' => 'Enum#data,ref,object'
+ )
+ );
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Presentation.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Presentation.php
new file mode 100644
index 0000000..2359ce8
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Presentation.php
@@ -0,0 +1,36 @@
+<?php
+
+/**
+ * XHTML 1.1 Presentation Module, defines simple presentation-related
+ * markup. Text Extension Module.
+ * @note The official XML Schema and DTD specs further divide this into
+ * two modules:
+ * - Block Presentation (hr)
+ * - Inline Presentation (b, big, i, small, sub, sup, tt)
+ * We have chosen not to heed this distinction, as content_sets
+ * provides satisfactory disambiguation.
+ */
+class HTMLPurifier_HTMLModule_Presentation extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Presentation';
+
+ public function setup($config) {
+ $this->addElement('hr', 'Block', 'Empty', 'Common');
+ $this->addElement('sub', 'Inline', 'Inline', 'Common');
+ $this->addElement('sup', 'Inline', 'Inline', 'Common');
+ $b = $this->addElement('b', 'Inline', 'Inline', 'Common');
+ $b->formatting = true;
+ $big = $this->addElement('big', 'Inline', 'Inline', 'Common');
+ $big->formatting = true;
+ $i = $this->addElement('i', 'Inline', 'Inline', 'Common');
+ $i->formatting = true;
+ $small = $this->addElement('small', 'Inline', 'Inline', 'Common');
+ $small->formatting = true;
+ $tt = $this->addElement('tt', 'Inline', 'Inline', 'Common');
+ $tt->formatting = true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Proprietary.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Proprietary.php
new file mode 100644
index 0000000..944058d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Proprietary.php
@@ -0,0 +1,33 @@
+<?php
+
+/**
+ * Module defines proprietary tags and attributes in HTML.
+ * @warning If this module is enabled, standards-compliance is off!
+ */
+class HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Proprietary';
+
+ public function setup($config) {
+
+ $this->addElement('marquee', 'Inline', 'Flow', 'Common',
+ array(
+ 'direction' => 'Enum#left,right,up,down',
+ 'behavior' => 'Enum#alternate',
+ 'width' => 'Length',
+ 'height' => 'Length',
+ 'scrolldelay' => 'Number',
+ 'scrollamount' => 'Number',
+ 'loop' => 'Number',
+ 'bgcolor' => 'Color',
+ 'hspace' => 'Pixels',
+ 'vspace' => 'Pixels',
+ )
+ );
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Ruby.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Ruby.php
new file mode 100644
index 0000000..5af4ce9
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Ruby.php
@@ -0,0 +1,27 @@
+<?php
+
+/**
+ * XHTML 1.1 Ruby Annotation Module, defines elements that indicate
+ * short runs of text alongside base text for annotation or pronounciation.
+ */
+class HTMLPurifier_HTMLModule_Ruby extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Ruby';
+
+ public function setup($config) {
+ $this->addElement('ruby', 'Inline',
+ 'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',
+ 'Common');
+ $this->addElement('rbc', false, 'Required: rb', 'Common');
+ $this->addElement('rtc', false, 'Required: rt', 'Common');
+ $rb = $this->addElement('rb', false, 'Inline', 'Common');
+ $rb->excludes = array('ruby' => true);
+ $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number'));
+ $rt->excludes = array('ruby' => true);
+ $this->addElement('rp', false, 'Optional: #PCDATA', 'Common');
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeEmbed.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeEmbed.php
new file mode 100644
index 0000000..b054c0c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeEmbed.php
@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * A "safe" embed module. See SafeObject. This is a proprietary element.
+ */
+class HTMLPurifier_HTMLModule_SafeEmbed extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'SafeEmbed';
+
+ public function setup($config) {
+
+ $max = $config->get('HTML.MaxImgLength');
+ $embed = $this->addElement(
+ 'embed', 'Inline', 'Empty', 'Common',
+ array(
+ 'src*' => 'URI#embedded',
+ 'type' => 'Enum#application/x-shockwave-flash',
+ 'width' => 'Pixels#' . $max,
+ 'height' => 'Pixels#' . $max,
+ 'allowscriptaccess' => 'Enum#never',
+ 'allownetworking' => 'Enum#internal',
+ 'flashvars' => 'Text',
+ 'wmode' => 'Enum#window,transparent,opaque',
+ 'name' => 'ID',
+ )
+ );
+ $embed->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeEmbed();
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeObject.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeObject.php
new file mode 100644
index 0000000..acbfa7f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/SafeObject.php
@@ -0,0 +1,52 @@
+<?php
+
+/**
+ * A "safe" object module. In theory, objects permitted by this module will
+ * be safe, and untrusted users can be allowed to embed arbitrary flash objects
+ * (maybe other types too, but only Flash is supported as of right now).
+ * Highly experimental.
+ */
+class HTMLPurifier_HTMLModule_SafeObject extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'SafeObject';
+
+ public function setup($config) {
+
+ // These definitions are not intrinsically safe: the attribute transforms
+ // are a vital part of ensuring safety.
+
+ $max = $config->get('HTML.MaxImgLength');
+ $object = $this->addElement(
+ 'object',
+ 'Inline',
+ 'Optional: param | Flow | #PCDATA',
+ 'Common',
+ array(
+ // While technically not required by the spec, we're forcing
+ // it to this value.
+ 'type' => 'Enum#application/x-shockwave-flash',
+ 'width' => 'Pixels#' . $max,
+ 'height' => 'Pixels#' . $max,
+ 'data' => 'URI#embedded',
+ 'codebase' => new HTMLPurifier_AttrDef_Enum(array(
+ 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0')),
+ )
+ );
+ $object->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeObject();
+
+ $param = $this->addElement('param', false, 'Empty', false,
+ array(
+ 'id' => 'ID',
+ 'name*' => 'Text',
+ 'value' => 'Text'
+ )
+ );
+ $param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam();
+ $this->info_injector[] = 'SafeObject';
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Scripting.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Scripting.php
new file mode 100644
index 0000000..9c95d46
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Scripting.php
@@ -0,0 +1,54 @@
+<?php
+
+/*
+
+WARNING: THIS MODULE IS EXTREMELY DANGEROUS AS IT ENABLES INLINE SCRIPTING
+INSIDE HTML PURIFIER DOCUMENTS. USE ONLY WITH TRUSTED USER INPUT!!!
+
+*/
+
+/**
+ * XHTML 1.1 Scripting module, defines elements that are used to contain
+ * information pertaining to executable scripts or the lack of support
+ * for executable scripts.
+ * @note This module does not contain inline scripting elements
+ */
+class HTMLPurifier_HTMLModule_Scripting extends HTMLPurifier_HTMLModule
+{
+ public $name = 'Scripting';
+ public $elements = array('script', 'noscript');
+ public $content_sets = array('Block' => 'script | noscript', 'Inline' => 'script | noscript');
+ public $safe = false;
+
+ public function setup($config) {
+ // TODO: create custom child-definition for noscript that
+ // auto-wraps stray #PCDATA in a similar manner to
+ // blockquote's custom definition (we would use it but
+ // blockquote's contents are optional while noscript's contents
+ // are required)
+
+ // TODO: convert this to new syntax, main problem is getting
+ // both content sets working
+
+ // In theory, this could be safe, but I don't see any reason to
+ // allow it.
+ $this->info['noscript'] = new HTMLPurifier_ElementDef();
+ $this->info['noscript']->attr = array( 0 => array('Common') );
+ $this->info['noscript']->content_model = 'Heading | List | Block';
+ $this->info['noscript']->content_model_type = 'required';
+
+ $this->info['script'] = new HTMLPurifier_ElementDef();
+ $this->info['script']->attr = array(
+ 'defer' => new HTMLPurifier_AttrDef_Enum(array('defer')),
+ 'src' => new HTMLPurifier_AttrDef_URI(true),
+ 'type' => new HTMLPurifier_AttrDef_Enum(array('text/javascript'))
+ );
+ $this->info['script']->content_model = '#PCDATA';
+ $this->info['script']->content_model_type = 'optional';
+ $this->info['script']->attr_transform_pre['type'] =
+ $this->info['script']->attr_transform_post['type'] =
+ new HTMLPurifier_AttrTransform_ScriptRequired();
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/StyleAttribute.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/StyleAttribute.php
new file mode 100644
index 0000000..7fc37de
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/StyleAttribute.php
@@ -0,0 +1,24 @@
+<?php
+
+/**
+ * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension
+ * Module.
+ */
+class HTMLPurifier_HTMLModule_StyleAttribute extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'StyleAttribute';
+ public $attr_collections = array(
+ // The inclusion routine differs from the Abstract Modules but
+ // is in line with the DTD and XML Schemas.
+ 'Style' => array('style' => false), // see constructor
+ 'Core' => array(0 => array('Style'))
+ );
+
+ public function setup($config) {
+ $this->attr_collections['Style']['style'] = new HTMLPurifier_AttrDef_CSS();
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tables.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tables.php
new file mode 100644
index 0000000..951b822
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tables.php
@@ -0,0 +1,66 @@
+<?php
+
+/**
+ * XHTML 1.1 Tables Module, fully defines accessible table elements.
+ */
+class HTMLPurifier_HTMLModule_Tables extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Tables';
+
+ public function setup($config) {
+
+ $this->addElement('caption', false, 'Inline', 'Common');
+
+ $this->addElement('table', 'Block',
+ new HTMLPurifier_ChildDef_Table(), 'Common',
+ array(
+ 'border' => 'Pixels',
+ 'cellpadding' => 'Length',
+ 'cellspacing' => 'Length',
+ 'frame' => 'Enum#void,above,below,hsides,lhs,rhs,vsides,box,border',
+ 'rules' => 'Enum#none,groups,rows,cols,all',
+ 'summary' => 'Text',
+ 'width' => 'Length'
+ )
+ );
+
+ // common attributes
+ $cell_align = array(
+ 'align' => 'Enum#left,center,right,justify,char',
+ 'charoff' => 'Length',
+ 'valign' => 'Enum#top,middle,bottom,baseline',
+ );
+
+ $cell_t = array_merge(
+ array(
+ 'abbr' => 'Text',
+ 'colspan' => 'Number',
+ 'rowspan' => 'Number',
+ ),
+ $cell_align
+ );
+ $this->addElement('td', false, 'Flow', 'Common', $cell_t);
+ $this->addElement('th', false, 'Flow', 'Common', $cell_t);
+
+ $this->addElement('tr', false, 'Required: td | th', 'Common', $cell_align);
+
+ $cell_col = array_merge(
+ array(
+ 'span' => 'Number',
+ 'width' => 'MultiLength',
+ ),
+ $cell_align
+ );
+ $this->addElement('col', false, 'Empty', 'Common', $cell_col);
+ $this->addElement('colgroup', false, 'Optional: col', 'Common', $cell_col);
+
+ $this->addElement('tbody', false, 'Required: tr', 'Common', $cell_align);
+ $this->addElement('thead', false, 'Required: tr', 'Common', $cell_align);
+ $this->addElement('tfoot', false, 'Required: tr', 'Common', $cell_align);
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Target.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Target.php
new file mode 100644
index 0000000..59c403d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Target.php
@@ -0,0 +1,23 @@
+<?php
+
+/**
+ * XHTML 1.1 Target Module, defines target attribute in link elements.
+ */
+class HTMLPurifier_HTMLModule_Target extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Target';
+
+ public function setup($config) {
+ $elements = array('a');
+ foreach ($elements as $name) {
+ $e = $this->addBlankElement($name);
+ $e->attr = array(
+ 'target' => new HTMLPurifier_AttrDef_HTML_FrameTarget()
+ );
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Text.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Text.php
new file mode 100644
index 0000000..508e1a4
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Text.php
@@ -0,0 +1,71 @@
+<?php
+
+/**
+ * XHTML 1.1 Text Module, defines basic text containers. Core Module.
+ * @note In the normative XML Schema specification, this module
+ * is further abstracted into the following modules:
+ * - Block Phrasal (address, blockquote, pre, h1, h2, h3, h4, h5, h6)
+ * - Block Structural (div, p)
+ * - Inline Phrasal (abbr, acronym, cite, code, dfn, em, kbd, q, samp, strong, var)
+ * - Inline Structural (br, span)
+ * This module, functionally, does not distinguish between these
+ * sub-modules, but the code is internally structured to reflect
+ * these distinctions.
+ */
+class HTMLPurifier_HTMLModule_Text extends HTMLPurifier_HTMLModule
+{
+
+ public $name = 'Text';
+ public $content_sets = array(
+ 'Flow' => 'Heading | Block | Inline'
+ );
+
+ public function setup($config) {
+
+ // Inline Phrasal -------------------------------------------------
+ $this->addElement('abbr', 'Inline', 'Inline', 'Common');
+ $this->addElement('acronym', 'Inline', 'Inline', 'Common');
+ $this->addElement('cite', 'Inline', 'Inline', 'Common');
+ $this->addElement('dfn', 'Inline', 'Inline', 'Common');
+ $this->addElement('kbd', 'Inline', 'Inline', 'Common');
+ $this->addElement('q', 'Inline', 'Inline', 'Common', array('cite' => 'URI'));
+ $this->addElement('samp', 'Inline', 'Inline', 'Common');
+ $this->addElement('var', 'Inline', 'Inline', 'Common');
+
+ $em = $this->addElement('em', 'Inline', 'Inline', 'Common');
+ $em->formatting = true;
+
+ $strong = $this->addElement('strong', 'Inline', 'Inline', 'Common');
+ $strong->formatting = true;
+
+ $code = $this->addElement('code', 'Inline', 'Inline', 'Common');
+ $code->formatting = true;
+
+ // Inline Structural ----------------------------------------------
+ $this->addElement('span', 'Inline', 'Inline', 'Common');
+ $this->addElement('br', 'Inline', 'Empty', 'Core');
+
+ // Block Phrasal --------------------------------------------------
+ $this->addElement('address', 'Block', 'Inline', 'Common');
+ $this->addElement('blockquote', 'Block', 'Optional: Heading | Block | List', 'Common', array('cite' => 'URI') );
+ $pre = $this->addElement('pre', 'Block', 'Inline', 'Common');
+ $pre->excludes = $this->makeLookup(
+ 'img', 'big', 'small', 'object', 'applet', 'font', 'basefont' );
+ $this->addElement('h1', 'Heading', 'Inline', 'Common');
+ $this->addElement('h2', 'Heading', 'Inline', 'Common');
+ $this->addElement('h3', 'Heading', 'Inline', 'Common');
+ $this->addElement('h4', 'Heading', 'Inline', 'Common');
+ $this->addElement('h5', 'Heading', 'Inline', 'Common');
+ $this->addElement('h6', 'Heading', 'Inline', 'Common');
+
+ // Block Structural -----------------------------------------------
+ $p = $this->addElement('p', 'Block', 'Inline', 'Common');
+ $p->autoclose = array_flip(array("address", "blockquote", "center", "dir", "div", "dl", "fieldset", "ol", "p", "ul"));
+
+ $this->addElement('div', 'Block', 'Flow', 'Common');
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy.php
new file mode 100644
index 0000000..4e03e15
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy.php
@@ -0,0 +1,207 @@
+<?php
+
+/**
+ * Abstract class for a set of proprietary modules that clean up (tidy)
+ * poorly written HTML.
+ * @todo Figure out how to protect some of these methods/properties
+ */
+class HTMLPurifier_HTMLModule_Tidy extends HTMLPurifier_HTMLModule
+{
+
+ /**
+ * List of supported levels. Index zero is a special case "no fixes"
+ * level.
+ */
+ public $levels = array(0 => 'none', 'light', 'medium', 'heavy');
+
+ /**
+ * Default level to place all fixes in. Disabled by default
+ */
+ public $defaultLevel = null;
+
+ /**
+ * Lists of fixes used by getFixesForLevel(). Format is:
+ * HTMLModule_Tidy->fixesForLevel[$level] = array('fix-1', 'fix-2');
+ */
+ public $fixesForLevel = array(
+ 'light' => array(),
+ 'medium' => array(),
+ 'heavy' => array()
+ );
+
+ /**
+ * Lazy load constructs the module by determining the necessary
+ * fixes to create and then delegating to the populate() function.
+ * @todo Wildcard matching and error reporting when an added or
+ * subtracted fix has no effect.
+ */
+ public function setup($config) {
+
+ // create fixes, initialize fixesForLevel
+ $fixes = $this->makeFixes();
+ $this->makeFixesForLevel($fixes);
+
+ // figure out which fixes to use
+ $level = $config->get('HTML.TidyLevel');
+ $fixes_lookup = $this->getFixesForLevel($level);
+
+ // get custom fix declarations: these need namespace processing
+ $add_fixes = $config->get('HTML.TidyAdd');
+ $remove_fixes = $config->get('HTML.TidyRemove');
+
+ foreach ($fixes as $name => $fix) {
+ // needs to be refactored a little to implement globbing
+ if (
+ isset($remove_fixes[$name]) ||
+ (!isset($add_fixes[$name]) && !isset($fixes_lookup[$name]))
+ ) {
+ unset($fixes[$name]);
+ }
+ }
+
+ // populate this module with necessary fixes
+ $this->populate($fixes);
+
+ }
+
+ /**
+ * Retrieves all fixes per a level, returning fixes for that specific
+ * level as well as all levels below it.
+ * @param $level String level identifier, see $levels for valid values
+ * @return Lookup up table of fixes
+ */
+ public function getFixesForLevel($level) {
+ if ($level == $this->levels[0]) {
+ return array();
+ }
+ $activated_levels = array();
+ for ($i = 1, $c = count($this->levels); $i < $c; $i++) {
+ $activated_levels[] = $this->levels[$i];
+ if ($this->levels[$i] == $level) break;
+ }
+ if ($i == $c) {
+ trigger_error(
+ 'Tidy level ' . htmlspecialchars($level) . ' not recognized',
+ E_USER_WARNING
+ );
+ return array();
+ }
+ $ret = array();
+ foreach ($activated_levels as $level) {
+ foreach ($this->fixesForLevel[$level] as $fix) {
+ $ret[$fix] = true;
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Dynamically populates the $fixesForLevel member variable using
+ * the fixes array. It may be custom overloaded, used in conjunction
+ * with $defaultLevel, or not used at all.
+ */
+ public function makeFixesForLevel($fixes) {
+ if (!isset($this->defaultLevel)) return;
+ if (!isset($this->fixesForLevel[$this->defaultLevel])) {
+ trigger_error(
+ 'Default level ' . $this->defaultLevel . ' does not exist',
+ E_USER_ERROR
+ );
+ return;
+ }
+ $this->fixesForLevel[$this->defaultLevel] = array_keys($fixes);
+ }
+
+ /**
+ * Populates the module with transforms and other special-case code
+ * based on a list of fixes passed to it
+ * @param $lookup Lookup table of fixes to activate
+ */
+ public function populate($fixes) {
+ foreach ($fixes as $name => $fix) {
+ // determine what the fix is for
+ list($type, $params) = $this->getFixType($name);
+ switch ($type) {
+ case 'attr_transform_pre':
+ case 'attr_transform_post':
+ $attr = $params['attr'];
+ if (isset($params['element'])) {
+ $element = $params['element'];
+ if (empty($this->info[$element])) {
+ $e = $this->addBlankElement($element);
+ } else {
+ $e = $this->info[$element];
+ }
+ } else {
+ $type = "info_$type";
+ $e = $this;
+ }
+ // PHP does some weird parsing when I do
+ // $e->$type[$attr], so I have to assign a ref.
+ $f =& $e->$type;
+ $f[$attr] = $fix;
+ break;
+ case 'tag_transform':
+ $this->info_tag_transform[$params['element']] = $fix;
+ break;
+ case 'child':
+ case 'content_model_type':
+ $element = $params['element'];
+ if (empty($this->info[$element])) {
+ $e = $this->addBlankElement($element);
+ } else {
+ $e = $this->info[$element];
+ }
+ $e->$type = $fix;
+ break;
+ default:
+ trigger_error("Fix type $type not supported", E_USER_ERROR);
+ break;
+ }
+ }
+ }
+
+ /**
+ * Parses a fix name and determines what kind of fix it is, as well
+ * as other information defined by the fix
+ * @param $name String name of fix
+ * @return array(string $fix_type, array $fix_parameters)
+ * @note $fix_parameters is type dependant, see populate() for usage
+ * of these parameters
+ */
+ public function getFixType($name) {
+ // parse it
+ $property = $attr = null;
+ if (strpos($name, '#') !== false) list($name, $property) = explode('#', $name);
+ if (strpos($name, '@') !== false) list($name, $attr) = explode('@', $name);
+
+ // figure out the parameters
+ $params = array();
+ if ($name !== '') $params['element'] = $name;
+ if (!is_null($attr)) $params['attr'] = $attr;
+
+ // special case: attribute transform
+ if (!is_null($attr)) {
+ if (is_null($property)) $property = 'pre';
+ $type = 'attr_transform_' . $property;
+ return array($type, $params);
+ }
+
+ // special case: tag transform
+ if (is_null($property)) {
+ return array('tag_transform', $params);
+ }
+
+ return array($property, $params);
+
+ }
+
+ /**
+ * Defines all fixes the module will perform in a compact
+ * associative array of fix name to fix implementation.
+ */
+ public function makeFixes() {}
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Name.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Name.php
new file mode 100644
index 0000000..e12d1e5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Name.php
@@ -0,0 +1,24 @@
+<?php
+
+/**
+ * Name is deprecated, but allowed in strict doctypes, so onl
+ */
+class HTMLPurifier_HTMLModule_Tidy_Name extends HTMLPurifier_HTMLModule_Tidy
+{
+ public $name = 'Tidy_Name';
+ public $defaultLevel = 'heavy';
+ public function makeFixes() {
+
+ $r = array();
+
+ // @name for img, a -----------------------------------------------
+ // Technically, it's allowed even on strict, so we allow authors to use
+ // it. However, it's deprecated in future versions of XHTML.
+ $r['img@name'] =
+ $r['a@name'] = new HTMLPurifier_AttrTransform_Name();
+
+ return $r;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Proprietary.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Proprietary.php
new file mode 100644
index 0000000..6cbff0c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Proprietary.php
@@ -0,0 +1,24 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_Tidy
+{
+
+ public $name = 'Tidy_Proprietary';
+ public $defaultLevel = 'light';
+
+ public function makeFixes() {
+ $r = array();
+ $r['table@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['td@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['th@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['tr@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['thead@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['tfoot@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['tbody@background'] = new HTMLPurifier_AttrTransform_Background();
+ $r['table@height'] = new HTMLPurifier_AttrTransform_Length('height');
+ return $r;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Strict.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Strict.php
new file mode 100644
index 0000000..29ee91c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Strict.php
@@ -0,0 +1,21 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Tidy_Strict extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4
+{
+ public $name = 'Tidy_Strict';
+ public $defaultLevel = 'light';
+
+ public function makeFixes() {
+ $r = parent::makeFixes();
+ $r['blockquote#content_model_type'] = 'strictblockquote';
+ return $r;
+ }
+
+ public $defines_child_def = true;
+ public function getChildDef($def) {
+ if ($def->content_model_type != 'strictblockquote') return parent::getChildDef($def);
+ return new HTMLPurifier_ChildDef_StrictBlockquote($def->content_model);
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Transitional.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Transitional.php
new file mode 100644
index 0000000..ce0efef
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/Transitional.php
@@ -0,0 +1,9 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Tidy_Transitional extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4
+{
+ public $name = 'Tidy_Transitional';
+ public $defaultLevel = 'heavy';
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTML.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTML.php
new file mode 100644
index 0000000..7058530
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTML.php
@@ -0,0 +1,17 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Tidy_XHTML extends HTMLPurifier_HTMLModule_Tidy
+{
+
+ public $name = 'Tidy_XHTML';
+ public $defaultLevel = 'medium';
+
+ public function makeFixes() {
+ $r = array();
+ $r['@lang'] = new HTMLPurifier_AttrTransform_Lang();
+ return $r;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php
new file mode 100644
index 0000000..e1ded47
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php
@@ -0,0 +1,161 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule_Tidy
+{
+
+ public function makeFixes() {
+
+ $r = array();
+
+ // == deprecated tag transforms ===================================
+
+ $r['font'] = new HTMLPurifier_TagTransform_Font();
+ $r['menu'] = new HTMLPurifier_TagTransform_Simple('ul');
+ $r['dir'] = new HTMLPurifier_TagTransform_Simple('ul');
+ $r['center'] = new HTMLPurifier_TagTransform_Simple('div', 'text-align:center;');
+ $r['u'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:underline;');
+ $r['s'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');
+ $r['strike'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');
+
+ // == deprecated attribute transforms =============================
+
+ $r['caption@align'] =
+ new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
+ // we're following IE's behavior, not Firefox's, due
+ // to the fact that no one supports caption-side:right,
+ // W3C included (with CSS 2.1). This is a slightly
+ // unreasonable attribute!
+ 'left' => 'text-align:left;',
+ 'right' => 'text-align:right;',
+ 'top' => 'caption-side:top;',
+ 'bottom' => 'caption-side:bottom;' // not supported by IE
+ ));
+
+ // @align for img -------------------------------------------------
+ $r['img@align'] =
+ new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
+ 'left' => 'float:left;',
+ 'right' => 'float:right;',
+ 'top' => 'vertical-align:top;',
+ 'middle' => 'vertical-align:middle;',
+ 'bottom' => 'vertical-align:baseline;',
+ ));
+
+ // @align for table -----------------------------------------------
+ $r['table@align'] =
+ new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
+ 'left' => 'float:left;',
+ 'center' => 'margin-left:auto;margin-right:auto;',
+ 'right' => 'float:right;'
+ ));
+
+ // @align for hr -----------------------------------------------
+ $r['hr@align'] =
+ new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
+ // we use both text-align and margin because these work
+ // for different browsers (IE and Firefox, respectively)
+ // and the melange makes for a pretty cross-compatible
+ // solution
+ 'left' => 'margin-left:0;margin-right:auto;text-align:left;',
+ 'center' => 'margin-left:auto;margin-right:auto;text-align:center;',
+ 'right' => 'margin-left:auto;margin-right:0;text-align:right;'
+ ));
+
+ // @align for h1, h2, h3, h4, h5, h6, p, div ----------------------
+ // {{{
+ $align_lookup = array();
+ $align_values = array('left', 'right', 'center', 'justify');
+ foreach ($align_values as $v) $align_lookup[$v] = "text-align:$v;";
+ // }}}
+ $r['h1@align'] =
+ $r['h2@align'] =
+ $r['h3@align'] =
+ $r['h4@align'] =
+ $r['h5@align'] =
+ $r['h6@align'] =
+ $r['p@align'] =
+ $r['div@align'] =
+ new HTMLPurifier_AttrTransform_EnumToCSS('align', $align_lookup);
+
+ // @bgcolor for table, tr, td, th ---------------------------------
+ $r['table@bgcolor'] =
+ $r['td@bgcolor'] =
+ $r['th@bgcolor'] =
+ new HTMLPurifier_AttrTransform_BgColor();
+
+ // @border for img ------------------------------------------------
+ $r['img@border'] = new HTMLPurifier_AttrTransform_Border();
+
+ // @clear for br --------------------------------------------------
+ $r['br@clear'] =
+ new HTMLPurifier_AttrTransform_EnumToCSS('clear', array(
+ 'left' => 'clear:left;',
+ 'right' => 'clear:right;',
+ 'all' => 'clear:both;',
+ 'none' => 'clear:none;',
+ ));
+
+ // @height for td, th ---------------------------------------------
+ $r['td@height'] =
+ $r['th@height'] =
+ new HTMLPurifier_AttrTransform_Length('height');
+
+ // @hspace for img ------------------------------------------------
+ $r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace');
+
+ // @noshade for hr ------------------------------------------------
+ // this transformation is not precise but often good enough.
+ // different browsers use different styles to designate noshade
+ $r['hr@noshade'] =
+ new HTMLPurifier_AttrTransform_BoolToCSS(
+ 'noshade',
+ 'color:#808080;background-color:#808080;border:0;'
+ );
+
+ // @nowrap for td, th ---------------------------------------------
+ $r['td@nowrap'] =
+ $r['th@nowrap'] =
+ new HTMLPurifier_AttrTransform_BoolToCSS(
+ 'nowrap',
+ 'white-space:nowrap;'
+ );
+
+ // @size for hr --------------------------------------------------
+ $r['hr@size'] = new HTMLPurifier_AttrTransform_Length('size', 'height');
+
+ // @type for li, ol, ul -------------------------------------------
+ // {{{
+ $ul_types = array(
+ 'disc' => 'list-style-type:disc;',
+ 'square' => 'list-style-type:square;',
+ 'circle' => 'list-style-type:circle;'
+ );
+ $ol_types = array(
+ '1' => 'list-style-type:decimal;',
+ 'i' => 'list-style-type:lower-roman;',
+ 'I' => 'list-style-type:upper-roman;',
+ 'a' => 'list-style-type:lower-alpha;',
+ 'A' => 'list-style-type:upper-alpha;'
+ );
+ $li_types = $ul_types + $ol_types;
+ // }}}
+
+ $r['ul@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ul_types);
+ $r['ol@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ol_types, true);
+ $r['li@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $li_types, true);
+
+ // @vspace for img ------------------------------------------------
+ $r['img@vspace'] = new HTMLPurifier_AttrTransform_ImgSpace('vspace');
+
+ // @width for hr, td, th ------------------------------------------
+ $r['td@width'] =
+ $r['th@width'] =
+ $r['hr@width'] = new HTMLPurifier_AttrTransform_Length('width');
+
+ return $r;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/XMLCommonAttributes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/XMLCommonAttributes.php
new file mode 100644
index 0000000..df69439
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModule/XMLCommonAttributes.php
@@ -0,0 +1,14 @@
+<?php
+
+class HTMLPurifier_HTMLModule_XMLCommonAttributes extends HTMLPurifier_HTMLModule
+{
+ public $name = 'XMLCommonAttributes';
+
+ public $attr_collections = array(
+ 'Lang' => array(
+ 'xml:lang' => 'LanguageCode',
+ )
+ );
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModuleManager.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModuleManager.php
new file mode 100644
index 0000000..90a620f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/HTMLModuleManager.php
@@ -0,0 +1,403 @@
+<?php
+
+class HTMLPurifier_HTMLModuleManager
+{
+
+ /**
+ * Instance of HTMLPurifier_DoctypeRegistry
+ */
+ public $doctypes;
+
+ /**
+ * Instance of current doctype
+ */
+ public $doctype;
+
+ /**
+ * Instance of HTMLPurifier_AttrTypes
+ */
+ public $attrTypes;
+
+ /**
+ * Active instances of modules for the specified doctype are
+ * indexed, by name, in this array.
+ */
+ public $modules = array();
+
+ /**
+ * Array of recognized HTMLPurifier_Module instances, indexed by
+ * module's class name. This array is usually lazy loaded, but a
+ * user can overload a module by pre-emptively registering it.
+ */
+ public $registeredModules = array();
+
+ /**
+ * List of extra modules that were added by the user using addModule().
+ * These get unconditionally merged into the current doctype, whatever
+ * it may be.
+ */
+ public $userModules = array();
+
+ /**
+ * Associative array of element name to list of modules that have
+ * definitions for the element; this array is dynamically filled.
+ */
+ public $elementLookup = array();
+
+ /** List of prefixes we should use for registering small names */
+ public $prefixes = array('HTMLPurifier_HTMLModule_');
+
+ public $contentSets; /**< Instance of HTMLPurifier_ContentSets */
+ public $attrCollections; /**< Instance of HTMLPurifier_AttrCollections */
+
+ /** If set to true, unsafe elements and attributes will be allowed */
+ public $trusted = false;
+
+ public function __construct() {
+
+ // editable internal objects
+ $this->attrTypes = new HTMLPurifier_AttrTypes();
+ $this->doctypes = new HTMLPurifier_DoctypeRegistry();
+
+ // setup basic modules
+ $common = array(
+ 'CommonAttributes', 'Text', 'Hypertext', 'List',
+ 'Presentation', 'Edit', 'Bdo', 'Tables', 'Image',
+ 'StyleAttribute',
+ // Unsafe:
+ 'Scripting', 'Object', 'Forms',
+ // Sorta legacy, but present in strict:
+ 'Name',
+ );
+ $transitional = array('Legacy', 'Target');
+ $xml = array('XMLCommonAttributes');
+ $non_xml = array('NonXMLCommonAttributes');
+
+ // setup basic doctypes
+ $this->doctypes->register(
+ 'HTML 4.01 Transitional', false,
+ array_merge($common, $transitional, $non_xml),
+ array('Tidy_Transitional', 'Tidy_Proprietary'),
+ array(),
+ '-//W3C//DTD HTML 4.01 Transitional//EN',
+ 'http://www.w3.org/TR/html4/loose.dtd'
+ );
+
+ $this->doctypes->register(
+ 'HTML 4.01 Strict', false,
+ array_merge($common, $non_xml),
+ array('Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),
+ array(),
+ '-//W3C//DTD HTML 4.01//EN',
+ 'http://www.w3.org/TR/html4/strict.dtd'
+ );
+
+ $this->doctypes->register(
+ 'XHTML 1.0 Transitional', true,
+ array_merge($common, $transitional, $xml, $non_xml),
+ array('Tidy_Transitional', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Name'),
+ array(),
+ '-//W3C//DTD XHTML 1.0 Transitional//EN',
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
+ );
+
+ $this->doctypes->register(
+ 'XHTML 1.0 Strict', true,
+ array_merge($common, $xml, $non_xml),
+ array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),
+ array(),
+ '-//W3C//DTD XHTML 1.0 Strict//EN',
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
+ );
+
+ $this->doctypes->register(
+ 'XHTML 1.1', true,
+ array_merge($common, $xml, array('Ruby')),
+ array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Strict', 'Tidy_Name'), // Tidy_XHTML1_1
+ array(),
+ '-//W3C//DTD XHTML 1.1//EN',
+ 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'
+ );
+
+ }
+
+ /**
+ * Registers a module to the recognized module list, useful for
+ * overloading pre-existing modules.
+ * @param $module Mixed: string module name, with or without
+ * HTMLPurifier_HTMLModule prefix, or instance of
+ * subclass of HTMLPurifier_HTMLModule.
+ * @param $overload Boolean whether or not to overload previous modules.
+ * If this is not set, and you do overload a module,
+ * HTML Purifier will complain with a warning.
+ * @note This function will not call autoload, you must instantiate
+ * (and thus invoke) autoload outside the method.
+ * @note If a string is passed as a module name, different variants
+ * will be tested in this order:
+ * - Check for HTMLPurifier_HTMLModule_$name
+ * - Check all prefixes with $name in order they were added
+ * - Check for literal object name
+ * - Throw fatal error
+ * If your object name collides with an internal class, specify
+ * your module manually. All modules must have been included
+ * externally: registerModule will not perform inclusions for you!
+ */
+ public function registerModule($module, $overload = false) {
+ if (is_string($module)) {
+ // attempt to load the module
+ $original_module = $module;
+ $ok = false;
+ foreach ($this->prefixes as $prefix) {
+ $module = $prefix . $original_module;
+ if (class_exists($module)) {
+ $ok = true;
+ break;
+ }
+ }
+ if (!$ok) {
+ $module = $original_module;
+ if (!class_exists($module)) {
+ trigger_error($original_module . ' module does not exist',
+ E_USER_ERROR);
+ return;
+ }
+ }
+ $module = new $module();
+ }
+ if (empty($module->name)) {
+ trigger_error('Module instance of ' . get_class($module) . ' must have name');
+ return;
+ }
+ if (!$overload && isset($this->registeredModules[$module->name])) {
+ trigger_error('Overloading ' . $module->name . ' without explicit overload parameter', E_USER_WARNING);
+ }
+ $this->registeredModules[$module->name] = $module;
+ }
+
+ /**
+ * Adds a module to the current doctype by first registering it,
+ * and then tacking it on to the active doctype
+ */
+ public function addModule($module) {
+ $this->registerModule($module);
+ if (is_object($module)) $module = $module->name;
+ $this->userModules[] = $module;
+ }
+
+ /**
+ * Adds a class prefix that registerModule() will use to resolve a
+ * string name to a concrete class
+ */
+ public function addPrefix($prefix) {
+ $this->prefixes[] = $prefix;
+ }
+
+ /**
+ * Performs processing on modules, after being called you may
+ * use getElement() and getElements()
+ * @param $config Instance of HTMLPurifier_Config
+ */
+ public function setup($config) {
+
+ $this->trusted = $config->get('HTML.Trusted');
+
+ // generate
+ $this->doctype = $this->doctypes->make($config);
+ $modules = $this->doctype->modules;
+
+ // take out the default modules that aren't allowed
+ $lookup = $config->get('HTML.AllowedModules');
+ $special_cases = $config->get('HTML.CoreModules');
+
+ if (is_array($lookup)) {
+ foreach ($modules as $k => $m) {
+ if (isset($special_cases[$m])) continue;
+ if (!isset($lookup[$m])) unset($modules[$k]);
+ }
+ }
+
+ // custom modules
+ if ($config->get('HTML.Proprietary')) {
+ $modules[] = 'Proprietary';
+ }
+ if ($config->get('HTML.SafeObject')) {
+ $modules[] = 'SafeObject';
+ }
+ if ($config->get('HTML.SafeEmbed')) {
+ $modules[] = 'SafeEmbed';
+ }
+ if ($config->get('HTML.Nofollow')) {
+ $modules[] = 'Nofollow';
+ }
+
+ // merge in custom modules
+ $modules = array_merge($modules, $this->userModules);
+
+ foreach ($modules as $module) {
+ $this->processModule($module);
+ $this->modules[$module]->setup($config);
+ }
+
+ foreach ($this->doctype->tidyModules as $module) {
+ $this->processModule($module);
+ $this->modules[$module]->setup($config);
+ }
+
+ // prepare any injectors
+ foreach ($this->modules as $module) {
+ $n = array();
+ foreach ($module->info_injector as $i => $injector) {
+ if (!is_object($injector)) {
+ $class = "HTMLPurifier_Injector_$injector";
+ $injector = new $class;
+ }
+ $n[$injector->name] = $injector;
+ }
+ $module->info_injector = $n;
+ }
+
+ // setup lookup table based on all valid modules
+ foreach ($this->modules as $module) {
+ foreach ($module->info as $name => $def) {
+ if (!isset($this->elementLookup[$name])) {
+ $this->elementLookup[$name] = array();
+ }
+ $this->elementLookup[$name][] = $module->name;
+ }
+ }
+
+ // note the different choice
+ $this->contentSets = new HTMLPurifier_ContentSets(
+ // content set assembly deals with all possible modules,
+ // not just ones deemed to be "safe"
+ $this->modules
+ );
+ $this->attrCollections = new HTMLPurifier_AttrCollections(
+ $this->attrTypes,
+ // there is no way to directly disable a global attribute,
+ // but using AllowedAttributes or simply not including
+ // the module in your custom doctype should be sufficient
+ $this->modules
+ );
+ }
+
+ /**
+ * Takes a module and adds it to the active module collection,
+ * registering it if necessary.
+ */
+ public function processModule($module) {
+ if (!isset($this->registeredModules[$module]) || is_object($module)) {
+ $this->registerModule($module);
+ }
+ $this->modules[$module] = $this->registeredModules[$module];
+ }
+
+ /**
+ * Retrieves merged element definitions.
+ * @return Array of HTMLPurifier_ElementDef
+ */
+ public function getElements() {
+
+ $elements = array();
+ foreach ($this->modules as $module) {
+ if (!$this->trusted && !$module->safe) continue;
+ foreach ($module->info as $name => $v) {
+ if (isset($elements[$name])) continue;
+ $elements[$name] = $this->getElement($name);
+ }
+ }
+
+ // remove dud elements, this happens when an element that
+ // appeared to be safe actually wasn't
+ foreach ($elements as $n => $v) {
+ if ($v === false) unset($elements[$n]);
+ }
+
+ return $elements;
+
+ }
+
+ /**
+ * Retrieves a single merged element definition
+ * @param $name Name of element
+ * @param $trusted Boolean trusted overriding parameter: set to true
+ * if you want the full version of an element
+ * @return Merged HTMLPurifier_ElementDef
+ * @note You may notice that modules are getting iterated over twice (once
+ * in getElements() and once here). This
+ * is because
+ */
+ public function getElement($name, $trusted = null) {
+
+ if (!isset($this->elementLookup[$name])) {
+ return false;
+ }
+
+ // setup global state variables
+ $def = false;
+ if ($trusted === null) $trusted = $this->trusted;
+
+ // iterate through each module that has registered itself to this
+ // element
+ foreach($this->elementLookup[$name] as $module_name) {
+
+ $module = $this->modules[$module_name];
+
+ // refuse to create/merge from a module that is deemed unsafe--
+ // pretend the module doesn't exist--when trusted mode is not on.
+ if (!$trusted && !$module->safe) {
+ continue;
+ }
+
+ // clone is used because, ideally speaking, the original
+ // definition should not be modified. Usually, this will
+ // make no difference, but for consistency's sake
+ $new_def = clone $module->info[$name];
+
+ if (!$def && $new_def->standalone) {
+ $def = $new_def;
+ } elseif ($def) {
+ // This will occur even if $new_def is standalone. In practice,
+ // this will usually result in a full replacement.
+ $def->mergeIn($new_def);
+ } else {
+ // :TODO:
+ // non-standalone definitions that don't have a standalone
+ // to merge into could be deferred to the end
+ continue;
+ }
+
+ // attribute value expansions
+ $this->attrCollections->performInclusions($def->attr);
+ $this->attrCollections->expandIdentifiers($def->attr, $this->attrTypes);
+
+ // descendants_are_inline, for ChildDef_Chameleon
+ if (is_string($def->content_model) &&
+ strpos($def->content_model, 'Inline') !== false) {
+ if ($name != 'del' && $name != 'ins') {
+ // this is for you, ins/del
+ $def->descendants_are_inline = true;
+ }
+ }
+
+ $this->contentSets->generateChildDef($def, $module);
+ }
+
+ // This can occur if there is a blank definition, but no base to
+ // mix it in with
+ if (!$def) return false;
+
+ // add information on required attributes
+ foreach ($def->attr as $attr_name => $attr_def) {
+ if ($attr_def->required) {
+ $def->required_attr[] = $attr_name;
+ }
+ }
+
+ return $def;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/IDAccumulator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/IDAccumulator.php
new file mode 100644
index 0000000..784ce0e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/IDAccumulator.php
@@ -0,0 +1,53 @@
+<?php
+
+/**
+ * Component of HTMLPurifier_AttrContext that accumulates IDs to prevent dupes
+ * @note In Slashdot-speak, dupe means duplicate.
+ * @note The default constructor does not accept $config or $context objects:
+ * use must use the static build() factory method to perform initialization.
+ */
+class HTMLPurifier_IDAccumulator
+{
+
+ /**
+ * Lookup table of IDs we've accumulated.
+ * @public
+ */
+ public $ids = array();
+
+ /**
+ * Builds an IDAccumulator, also initializing the default blacklist
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return Fully initialized HTMLPurifier_IDAccumulator
+ */
+ public static function build($config, $context) {
+ $id_accumulator = new HTMLPurifier_IDAccumulator();
+ $id_accumulator->load($config->get('Attr.IDBlacklist'));
+ return $id_accumulator;
+ }
+
+ /**
+ * Add an ID to the lookup table.
+ * @param $id ID to be added.
+ * @return Bool status, true if success, false if there's a dupe
+ */
+ public function add($id) {
+ if (isset($this->ids[$id])) return false;
+ return $this->ids[$id] = true;
+ }
+
+ /**
+ * Load a list of IDs into the lookup table
+ * @param $array_of_ids Array of IDs to load
+ * @note This function doesn't care about duplicates
+ */
+ public function load($array_of_ids) {
+ foreach ($array_of_ids as $id) {
+ $this->ids[$id] = true;
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector.php
new file mode 100644
index 0000000..52dc809
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector.php
@@ -0,0 +1,239 @@
+<?php
+
+/**
+ * Injects tokens into the document while parsing for well-formedness.
+ * This enables "formatter-like" functionality such as auto-paragraphing,
+ * smiley-ification and linkification to take place.
+ *
+ * A note on how handlers create changes; this is done by assigning a new
+ * value to the $token reference. These values can take a variety of forms and
+ * are best described HTMLPurifier_Strategy_MakeWellFormed->processToken()
+ * documentation.
+ *
+ * @todo Allow injectors to request a re-run on their output. This
+ * would help if an operation is recursive.
+ */
+abstract class HTMLPurifier_Injector
+{
+
+ /**
+ * Advisory name of injector, this is for friendly error messages
+ */
+ public $name;
+
+ /**
+ * Instance of HTMLPurifier_HTMLDefinition
+ */
+ protected $htmlDefinition;
+
+ /**
+ * Reference to CurrentNesting variable in Context. This is an array
+ * list of tokens that we are currently "inside"
+ */
+ protected $currentNesting;
+
+ /**
+ * Reference to InputTokens variable in Context. This is an array
+ * list of the input tokens that are being processed.
+ */
+ protected $inputTokens;
+
+ /**
+ * Reference to InputIndex variable in Context. This is an integer
+ * array index for $this->inputTokens that indicates what token
+ * is currently being processed.
+ */
+ protected $inputIndex;
+
+ /**
+ * Array of elements and attributes this injector creates and therefore
+ * need to be allowed by the definition. Takes form of
+ * array('element' => array('attr', 'attr2'), 'element2')
+ */
+ public $needed = array();
+
+ /**
+ * Index of inputTokens to rewind to.
+ */
+ protected $rewind = false;
+
+ /**
+ * Rewind to a spot to re-perform processing. This is useful if you
+ * deleted a node, and now need to see if this change affected any
+ * earlier nodes. Rewinding does not affect other injectors, and can
+ * result in infinite loops if not used carefully.
+ * @warning HTML Purifier will prevent you from fast-forwarding with this
+ * function.
+ */
+ public function rewind($index) {
+ $this->rewind = $index;
+ }
+
+ /**
+ * Retrieves rewind, and then unsets it.
+ */
+ public function getRewind() {
+ $r = $this->rewind;
+ $this->rewind = false;
+ return $r;
+ }
+
+ /**
+ * Prepares the injector by giving it the config and context objects:
+ * this allows references to important variables to be made within
+ * the injector. This function also checks if the HTML environment
+ * will work with the Injector (see checkNeeded()).
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return Boolean false if success, string of missing needed element/attribute if failure
+ */
+ public function prepare($config, $context) {
+ $this->htmlDefinition = $config->getHTMLDefinition();
+ // Even though this might fail, some unit tests ignore this and
+ // still test checkNeeded, so be careful. Maybe get rid of that
+ // dependency.
+ $result = $this->checkNeeded($config);
+ if ($result !== false) return $result;
+ $this->currentNesting =& $context->get('CurrentNesting');
+ $this->inputTokens =& $context->get('InputTokens');
+ $this->inputIndex =& $context->get('InputIndex');
+ return false;
+ }
+
+ /**
+ * This function checks if the HTML environment
+ * will work with the Injector: if p tags are not allowed, the
+ * Auto-Paragraphing injector should not be enabled.
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return Boolean false if success, string of missing needed element/attribute if failure
+ */
+ public function checkNeeded($config) {
+ $def = $config->getHTMLDefinition();
+ foreach ($this->needed as $element => $attributes) {
+ if (is_int($element)) $element = $attributes;
+ if (!isset($def->info[$element])) return $element;
+ if (!is_array($attributes)) continue;
+ foreach ($attributes as $name) {
+ if (!isset($def->info[$element]->attr[$name])) return "$element.$name";
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Tests if the context node allows a certain element
+ * @param $name Name of element to test for
+ * @return True if element is allowed, false if it is not
+ */
+ public function allowsElement($name) {
+ if (!empty($this->currentNesting)) {
+ $parent_token = array_pop($this->currentNesting);
+ $this->currentNesting[] = $parent_token;
+ $parent = $this->htmlDefinition->info[$parent_token->name];
+ } else {
+ $parent = $this->htmlDefinition->info_parent_def;
+ }
+ if (!isset($parent->child->elements[$name]) || isset($parent->excludes[$name])) {
+ return false;
+ }
+ // check for exclusion
+ for ($i = count($this->currentNesting) - 2; $i >= 0; $i--) {
+ $node = $this->currentNesting[$i];
+ $def = $this->htmlDefinition->info[$node->name];
+ if (isset($def->excludes[$name])) return false;
+ }
+ return true;
+ }
+
+ /**
+ * Iterator function, which starts with the next token and continues until
+ * you reach the end of the input tokens.
+ * @warning Please prevent previous references from interfering with this
+ * functions by setting $i = null beforehand!
+ * @param &$i Current integer index variable for inputTokens
+ * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference
+ */
+ protected function forward(&$i, &$current) {
+ if ($i === null) $i = $this->inputIndex + 1;
+ else $i++;
+ if (!isset($this->inputTokens[$i])) return false;
+ $current = $this->inputTokens[$i];
+ return true;
+ }
+
+ /**
+ * Similar to _forward, but accepts a third parameter $nesting (which
+ * should be initialized at 0) and stops when we hit the end tag
+ * for the node $this->inputIndex starts in.
+ */
+ protected function forwardUntilEndToken(&$i, &$current, &$nesting) {
+ $result = $this->forward($i, $current);
+ if (!$result) return false;
+ if ($nesting === null) $nesting = 0;
+ if ($current instanceof HTMLPurifier_Token_Start) $nesting++;
+ elseif ($current instanceof HTMLPurifier_Token_End) {
+ if ($nesting <= 0) return false;
+ $nesting--;
+ }
+ return true;
+ }
+
+ /**
+ * Iterator function, starts with the previous token and continues until
+ * you reach the beginning of input tokens.
+ * @warning Please prevent previous references from interfering with this
+ * functions by setting $i = null beforehand!
+ * @param &$i Current integer index variable for inputTokens
+ * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference
+ */
+ protected function backward(&$i, &$current) {
+ if ($i === null) $i = $this->inputIndex - 1;
+ else $i--;
+ if ($i < 0) return false;
+ $current = $this->inputTokens[$i];
+ return true;
+ }
+
+ /**
+ * Initializes the iterator at the current position. Use in a do {} while;
+ * loop to force the _forward and _backward functions to start at the
+ * current location.
+ * @warning Please prevent previous references from interfering with this
+ * functions by setting $i = null beforehand!
+ * @param &$i Current integer index variable for inputTokens
+ * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference
+ */
+ protected function current(&$i, &$current) {
+ if ($i === null) $i = $this->inputIndex;
+ $current = $this->inputTokens[$i];
+ }
+
+ /**
+ * Handler that is called when a text token is processed
+ */
+ public function handleText(&$token) {}
+
+ /**
+ * Handler that is called when a start or empty token is processed
+ */
+ public function handleElement(&$token) {}
+
+ /**
+ * Handler that is called when an end token is processed
+ */
+ public function handleEnd(&$token) {
+ $this->notifyEnd($token);
+ }
+
+ /**
+ * Notifier that is called when an end token is processed
+ * @note This differs from handlers in that the token is read-only
+ * @deprecated
+ */
+ public function notifyEnd($token) {}
+
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/AutoParagraph.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/AutoParagraph.php
new file mode 100644
index 0000000..e1e8da5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/AutoParagraph.php
@@ -0,0 +1,345 @@
+<?php
+
+/**
+ * Injector that auto paragraphs text in the root node based on
+ * double-spacing.
+ * @todo Ensure all states are unit tested, including variations as well.
+ * @todo Make a graph of the flow control for this Injector.
+ */
+class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
+{
+
+ public $name = 'AutoParagraph';
+ public $needed = array('p');
+
+ private function _pStart() {
+ $par = new HTMLPurifier_Token_Start('p');
+ $par->armor['MakeWellFormed_TagClosedError'] = true;
+ return $par;
+ }
+
+ public function handleText(&$token) {
+ $text = $token->data;
+ // Does the current parent allow <p> tags?
+ if ($this->allowsElement('p')) {
+ if (empty($this->currentNesting) || strpos($text, "\n\n") !== false) {
+ // Note that we have differing behavior when dealing with text
+ // in the anonymous root node, or a node inside the document.
+ // If the text as a double-newline, the treatment is the same;
+ // if it doesn't, see the next if-block if you're in the document.
+
+ $i = $nesting = null;
+ if (!$this->forwardUntilEndToken($i, $current, $nesting) && $token->is_whitespace) {
+ // State 1.1: ... ^ (whitespace, then document end)
+ // ----
+ // This is a degenerate case
+ } else {
+ if (!$token->is_whitespace || $this->_isInline($current)) {
+ // State 1.2: PAR1
+ // ----
+
+ // State 1.3: PAR1\n\nPAR2
+ // ------------
+
+ // State 1.4: <div>PAR1\n\nPAR2 (see State 2)
+ // ------------
+ $token = array($this->_pStart());
+ $this->_splitText($text, $token);
+ } else {
+ // State 1.5: \n<hr />
+ // --
+ }
+ }
+ } else {
+ // State 2: <div>PAR1... (similar to 1.4)
+ // ----
+
+ // We're in an element that allows paragraph tags, but we're not
+ // sure if we're going to need them.
+ if ($this->_pLookAhead()) {
+ // State 2.1: <div>PAR1<b>PAR1\n\nPAR2
+ // ----
+ // Note: This will always be the first child, since any
+ // previous inline element would have triggered this very
+ // same routine, and found the double newline. One possible
+ // exception would be a comment.
+ $token = array($this->_pStart(), $token);
+ } else {
+ // State 2.2.1: <div>PAR1<div>
+ // ----
+
+ // State 2.2.2: <div>PAR1<b>PAR1</b></div>
+ // ----
+ }
+ }
+ // Is the current parent a <p> tag?
+ } elseif (
+ !empty($this->currentNesting) &&
+ $this->currentNesting[count($this->currentNesting)-1]->name == 'p'
+ ) {
+ // State 3.1: ...<p>PAR1
+ // ----
+
+ // State 3.2: ...<p>PAR1\n\nPAR2
+ // ------------
+ $token = array();
+ $this->_splitText($text, $token);
+ // Abort!
+ } else {
+ // State 4.1: ...<b>PAR1
+ // ----
+
+ // State 4.2: ...<b>PAR1\n\nPAR2
+ // ------------
+ }
+ }
+
+ public function handleElement(&$token) {
+ // We don't have to check if we're already in a <p> tag for block
+ // tokens, because the tag would have been autoclosed by MakeWellFormed.
+ if ($this->allowsElement('p')) {
+ if (!empty($this->currentNesting)) {
+ if ($this->_isInline($token)) {
+ // State 1: <div>...<b>
+ // ---
+
+ // Check if this token is adjacent to the parent token
+ // (seek backwards until token isn't whitespace)
+ $i = null;
+ $this->backward($i, $prev);
+
+ if (!$prev instanceof HTMLPurifier_Token_Start) {
+ // Token wasn't adjacent
+
+ if (
+ $prev instanceof HTMLPurifier_Token_Text &&
+ substr($prev->data, -2) === "\n\n"
+ ) {
+ // State 1.1.4: <div><p>PAR1</p>\n\n<b>
+ // ---
+
+ // Quite frankly, this should be handled by splitText
+ $token = array($this->_pStart(), $token);
+ } else {
+ // State 1.1.1: <div><p>PAR1</p><b>
+ // ---
+
+ // State 1.1.2: <div><br /><b>
+ // ---
+
+ // State 1.1.3: <div>PAR<b>
+ // ---
+ }
+
+ } else {
+ // State 1.2.1: <div><b>
+ // ---
+
+ // Lookahead to see if <p> is needed.
+ if ($this->_pLookAhead()) {
+ // State 1.3.1: <div><b>PAR1\n\nPAR2
+ // ---
+ $token = array($this->_pStart(), $token);
+ } else {
+ // State 1.3.2: <div><b>PAR1</b></div>
+ // ---
+
+ // State 1.3.3: <div><b>PAR1</b><div></div>\n\n</div>
+ // ---
+ }
+ }
+ } else {
+ // State 2.3: ...<div>
+ // -----
+ }
+ } else {
+ if ($this->_isInline($token)) {
+ // State 3.1: <b>
+ // ---
+ // This is where the {p} tag is inserted, not reflected in
+ // inputTokens yet, however.
+ $token = array($this->_pStart(), $token);
+ } else {
+ // State 3.2: <div>
+ // -----
+ }
+
+ $i = null;
+ if ($this->backward($i, $prev)) {
+ if (
+ !$prev instanceof HTMLPurifier_Token_Text
+ ) {
+ // State 3.1.1: ...</p>{p}<b>
+ // ---
+
+ // State 3.2.1: ...</p><div>
+ // -----
+
+ if (!is_array($token)) $token = array($token);
+ array_unshift($token, new HTMLPurifier_Token_Text("\n\n"));
+ } else {
+ // State 3.1.2: ...</p>\n\n{p}<b>
+ // ---
+
+ // State 3.2.2: ...</p>\n\n<div>
+ // -----
+
+ // Note: PAR<ELEM> cannot occur because PAR would have been
+ // wrapped in <p> tags.
+ }
+ }
+ }
+ } else {
+ // State 2.2: <ul><li>
+ // ----
+
+ // State 2.4: <p><b>
+ // ---
+ }
+ }
+
+ /**
+ * Splits up a text in paragraph tokens and appends them
+ * to the result stream that will replace the original
+ * @param $data String text data that will be processed
+ * into paragraphs
+ * @param $result Reference to array of tokens that the
+ * tags will be appended onto
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ */
+ private function _splitText($data, &$result) {
+ $raw_paragraphs = explode("\n\n", $data);
+ $paragraphs = array(); // without empty paragraphs
+ $needs_start = false;
+ $needs_end = false;
+
+ $c = count($raw_paragraphs);
+ if ($c == 1) {
+ // There were no double-newlines, abort quickly. In theory this
+ // should never happen.
+ $result[] = new HTMLPurifier_Token_Text($data);
+ return;
+ }
+ for ($i = 0; $i < $c; $i++) {
+ $par = $raw_paragraphs[$i];
+ if (trim($par) !== '') {
+ $paragraphs[] = $par;
+ } else {
+ if ($i == 0) {
+ // Double newline at the front
+ if (empty($result)) {
+ // The empty result indicates that the AutoParagraph
+ // injector did not add any start paragraph tokens.
+ // This means that we have been in a paragraph for
+ // a while, and the newline means we should start a new one.
+ $result[] = new HTMLPurifier_Token_End('p');
+ $result[] = new HTMLPurifier_Token_Text("\n\n");
+ // However, the start token should only be added if
+ // there is more processing to be done (i.e. there are
+ // real paragraphs in here). If there are none, the
+ // next start paragraph tag will be handled by the
+ // next call to the injector
+ $needs_start = true;
+ } else {
+ // We just started a new paragraph!
+ // Reinstate a double-newline for presentation's sake, since
+ // it was in the source code.
+ array_unshift($result, new HTMLPurifier_Token_Text("\n\n"));
+ }
+ } elseif ($i + 1 == $c) {
+ // Double newline at the end
+ // There should be a trailing </p> when we're finally done.
+ $needs_end = true;
+ }
+ }
+ }
+
+ // Check if this was just a giant blob of whitespace. Move this earlier,
+ // perhaps?
+ if (empty($paragraphs)) {
+ return;
+ }
+
+ // Add the start tag indicated by \n\n at the beginning of $data
+ if ($needs_start) {
+ $result[] = $this->_pStart();
+ }
+
+ // Append the paragraphs onto the result
+ foreach ($paragraphs as $par) {
+ $result[] = new HTMLPurifier_Token_Text($par);
+ $result[] = new HTMLPurifier_Token_End('p');
+ $result[] = new HTMLPurifier_Token_Text("\n\n");
+ $result[] = $this->_pStart();
+ }
+
+ // Remove trailing start token; Injector will handle this later if
+ // it was indeed needed. This prevents from needing to do a lookahead,
+ // at the cost of a lookbehind later.
+ array_pop($result);
+
+ // If there is no need for an end tag, remove all of it and let
+ // MakeWellFormed close it later.
+ if (!$needs_end) {
+ array_pop($result); // removes \n\n
+ array_pop($result); // removes </p>
+ }
+
+ }
+
+ /**
+ * Returns true if passed token is inline (and, ergo, allowed in
+ * paragraph tags)
+ */
+ private function _isInline($token) {
+ return isset($this->htmlDefinition->info['p']->child->elements[$token->name]);
+ }
+
+ /**
+ * Looks ahead in the token list and determines whether or not we need
+ * to insert a <p> tag.
+ */
+ private function _pLookAhead() {
+ $this->current($i, $current);
+ if ($current instanceof HTMLPurifier_Token_Start) $nesting = 1;
+ else $nesting = 0;
+ $ok = false;
+ while ($this->forwardUntilEndToken($i, $current, $nesting)) {
+ $result = $this->_checkNeedsP($current);
+ if ($result !== null) {
+ $ok = $result;
+ break;
+ }
+ }
+ return $ok;
+ }
+
+ /**
+ * Determines if a particular token requires an earlier inline token
+ * to get a paragraph. This should be used with _forwardUntilEndToken
+ */
+ private function _checkNeedsP($current) {
+ if ($current instanceof HTMLPurifier_Token_Start){
+ if (!$this->_isInline($current)) {
+ // <div>PAR1<div>
+ // ----
+ // Terminate early, since we hit a block element
+ return false;
+ }
+ } elseif ($current instanceof HTMLPurifier_Token_Text) {
+ if (strpos($current->data, "\n\n") !== false) {
+ // <div>PAR1<b>PAR1\n\nPAR2
+ // ----
+ return true;
+ } else {
+ // <div>PAR1<b>PAR1...
+ // ----
+ }
+ }
+ return null;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/DisplayLinkURI.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/DisplayLinkURI.php
new file mode 100644
index 0000000..edd5066
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/DisplayLinkURI.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * Injector that displays the URL of an anchor instead of linking to it, in addition to showing the text of the link.
+ */
+class HTMLPurifier_Injector_DisplayLinkURI extends HTMLPurifier_Injector
+{
+
+ public $name = 'DisplayLinkURI';
+ public $needed = array('a');
+
+ public function handleElement(&$token) {
+ }
+
+ public function handleEnd(&$token) {
+ if (isset($token->start->attr['href'])){
+ $url = $token->start->attr['href'];
+ unset($token->start->attr['href']);
+ $token = array($token, new HTMLPurifier_Token_Text(" ($url)"));
+ } else {
+ // nothing to display
+ }
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/Linkify.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/Linkify.php
new file mode 100644
index 0000000..a9724f4
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/Linkify.php
@@ -0,0 +1,46 @@
+<?php
+
+/**
+ * Injector that converts http, https and ftp text URLs to actual links.
+ */
+class HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector
+{
+
+ public $name = 'Linkify';
+ public $needed = array('a' => array('href'));
+
+ public function handleText(&$token) {
+ if (!$this->allowsElement('a')) return;
+
+ if (strpos($token->data, '://') === false) {
+ // our really quick heuristic failed, abort
+ // this may not work so well if we want to match things like
+ // "google.com", but then again, most people don't
+ return;
+ }
+
+ // there is/are URL(s). Let's split the string:
+ // Note: this regex is extremely permissive
+ $bits = preg_split('#((?:https?|ftp)://[^\s\'"<>()]+)#S', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
+
+ $token = array();
+
+ // $i = index
+ // $c = count
+ // $l = is link
+ for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
+ if (!$l) {
+ if ($bits[$i] === '') continue;
+ $token[] = new HTMLPurifier_Token_Text($bits[$i]);
+ } else {
+ $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));
+ $token[] = new HTMLPurifier_Token_Text($bits[$i]);
+ $token[] = new HTMLPurifier_Token_End('a');
+ }
+ }
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/PurifierLinkify.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/PurifierLinkify.php
new file mode 100644
index 0000000..89c02c2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/PurifierLinkify.php
@@ -0,0 +1,45 @@
+<?php
+
+/**
+ * Injector that converts configuration directive syntax %Namespace.Directive
+ * to links
+ */
+class HTMLPurifier_Injector_PurifierLinkify extends HTMLPurifier_Injector
+{
+
+ public $name = 'PurifierLinkify';
+ public $docURL;
+ public $needed = array('a' => array('href'));
+
+ public function prepare($config, $context) {
+ $this->docURL = $config->get('AutoFormat.PurifierLinkify.DocURL');
+ return parent::prepare($config, $context);
+ }
+
+ public function handleText(&$token) {
+ if (!$this->allowsElement('a')) return;
+ if (strpos($token->data, '%') === false) return;
+
+ $bits = preg_split('#%([a-z0-9]+\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
+ $token = array();
+
+ // $i = index
+ // $c = count
+ // $l = is link
+ for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
+ if (!$l) {
+ if ($bits[$i] === '') continue;
+ $token[] = new HTMLPurifier_Token_Text($bits[$i]);
+ } else {
+ $token[] = new HTMLPurifier_Token_Start('a',
+ array('href' => str_replace('%s', $bits[$i], $this->docURL)));
+ $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);
+ $token[] = new HTMLPurifier_Token_End('a');
+ }
+ }
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveEmpty.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveEmpty.php
new file mode 100644
index 0000000..f1d3f4f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveEmpty.php
@@ -0,0 +1,51 @@
+<?php
+
+class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector
+{
+
+ private $context, $config, $attrValidator, $removeNbsp, $removeNbspExceptions;
+
+ public function prepare($config, $context) {
+ parent::prepare($config, $context);
+ $this->config = $config;
+ $this->context = $context;
+ $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');
+ $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');
+ $this->attrValidator = new HTMLPurifier_AttrValidator();
+ }
+
+ public function handleElement(&$token) {
+ if (!$token instanceof HTMLPurifier_Token_Start) return;
+ $next = false;
+ for ($i = $this->inputIndex + 1, $c = count($this->inputTokens); $i < $c; $i++) {
+ $next = $this->inputTokens[$i];
+ if ($next instanceof HTMLPurifier_Token_Text) {
+ if ($next->is_whitespace) continue;
+ if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {
+ $plain = str_replace("\xC2\xA0", "", $next->data);
+ $isWsOrNbsp = $plain === '' || ctype_space($plain);
+ if ($isWsOrNbsp) continue;
+ }
+ }
+ break;
+ }
+ if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {
+ if ($token->name == 'colgroup') return;
+ $this->attrValidator->validateToken($token, $this->config, $this->context);
+ $token->armor['ValidateAttributes'] = true;
+ if (isset($token->attr['id']) || isset($token->attr['name'])) return;
+ $token = $i - $this->inputIndex + 1;
+ for ($b = $this->inputIndex - 1; $b > 0; $b--) {
+ $prev = $this->inputTokens[$b];
+ if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) continue;
+ break;
+ }
+ // This is safe because we removed the token that triggered this.
+ $this->rewind($b - 1);
+ return;
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveSpansWithoutAttributes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveSpansWithoutAttributes.php
new file mode 100644
index 0000000..e2c6c30
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/RemoveSpansWithoutAttributes.php
@@ -0,0 +1,60 @@
+<?php
+
+/**
+ * Injector that removes spans with no attributes
+ */
+class HTMLPurifier_Injector_RemoveSpansWithoutAttributes extends HTMLPurifier_Injector
+{
+ public $name = 'RemoveSpansWithoutAttributes';
+ public $needed = array('span');
+
+ private $attrValidator;
+
+ /**
+ * Used by AttrValidator
+ */
+ private $config;
+ private $context;
+
+ public function prepare($config, $context) {
+ $this->attrValidator = new HTMLPurifier_AttrValidator();
+ $this->config = $config;
+ $this->context = $context;
+ return parent::prepare($config, $context);
+ }
+
+ public function handleElement(&$token) {
+ if ($token->name !== 'span' || !$token instanceof HTMLPurifier_Token_Start) {
+ return;
+ }
+
+ // We need to validate the attributes now since this doesn't normally
+ // happen until after MakeWellFormed. If all the attributes are removed
+ // the span needs to be removed too.
+ $this->attrValidator->validateToken($token, $this->config, $this->context);
+ $token->armor['ValidateAttributes'] = true;
+
+ if (!empty($token->attr)) {
+ return;
+ }
+
+ $nesting = 0;
+ $spanContentTokens = array();
+ while ($this->forwardUntilEndToken($i, $current, $nesting)) {}
+
+ if ($current instanceof HTMLPurifier_Token_End && $current->name === 'span') {
+ // Mark closing span tag for deletion
+ $current->markForDeletion = true;
+ // Delete open span tag
+ $token = false;
+ }
+ }
+
+ public function handleEnd(&$token) {
+ if ($token->markForDeletion) {
+ $token = false;
+ }
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/SafeObject.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/SafeObject.php
new file mode 100644
index 0000000..4d6c977
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Injector/SafeObject.php
@@ -0,0 +1,91 @@
+<?php
+
+/**
+ * Adds important param elements to inside of object in order to make
+ * things safe.
+ */
+class HTMLPurifier_Injector_SafeObject extends HTMLPurifier_Injector
+{
+ public $name = 'SafeObject';
+ public $needed = array('object', 'param');
+
+ protected $objectStack = array();
+ protected $paramStack = array();
+
+ // Keep this synchronized with AttrTransform/SafeParam.php
+ protected $addParam = array(
+ 'allowScriptAccess' => 'never',
+ 'allowNetworking' => 'internal',
+ );
+ protected $allowedParam = array(
+ 'wmode' => true,
+ 'movie' => true,
+ 'flashvars' => true,
+ 'src' => true,
+ 'allowFullScreen' => true, // if omitted, assume to be 'false'
+ );
+
+ public function prepare($config, $context) {
+ parent::prepare($config, $context);
+ }
+
+ public function handleElement(&$token) {
+ if ($token->name == 'object') {
+ $this->objectStack[] = $token;
+ $this->paramStack[] = array();
+ $new = array($token);
+ foreach ($this->addParam as $name => $value) {
+ $new[] = new HTMLPurifier_Token_Empty('param', array('name' => $name, 'value' => $value));
+ }
+ $token = $new;
+ } elseif ($token->name == 'param') {
+ $nest = count($this->currentNesting) - 1;
+ if ($nest >= 0 && $this->currentNesting[$nest]->name === 'object') {
+ $i = count($this->objectStack) - 1;
+ if (!isset($token->attr['name'])) {
+ $token = false;
+ return;
+ }
+ $n = $token->attr['name'];
+ // We need this fix because YouTube doesn't supply a data
+ // attribute, which we need if a type is specified. This is
+ // *very* Flash specific.
+ if (!isset($this->objectStack[$i]->attr['data']) &&
+ ($token->attr['name'] == 'movie' || $token->attr['name'] == 'src')) {
+ $this->objectStack[$i]->attr['data'] = $token->attr['value'];
+ }
+ // Check if the parameter is the correct value but has not
+ // already been added
+ if (
+ !isset($this->paramStack[$i][$n]) &&
+ isset($this->addParam[$n]) &&
+ $token->attr['name'] === $this->addParam[$n]
+ ) {
+ // keep token, and add to param stack
+ $this->paramStack[$i][$n] = true;
+ } elseif (isset($this->allowedParam[$n])) {
+ // keep token, don't do anything to it
+ // (could possibly check for duplicates here)
+ } else {
+ $token = false;
+ }
+ } else {
+ // not directly inside an object, DENY!
+ $token = false;
+ }
+ }
+ }
+
+ public function handleEnd(&$token) {
+ // This is the WRONG way of handling the object and param stacks;
+ // we should be inserting them directly on the relevant object tokens
+ // so that the global stack handling handles it.
+ if ($token->name == 'object') {
+ array_pop($this->objectStack);
+ array_pop($this->paramStack);
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language.php
new file mode 100644
index 0000000..28082f5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language.php
@@ -0,0 +1,163 @@
+<?php
+
+/**
+ * Represents a language and defines localizable string formatting and
+ * other functions, as well as the localized messages for HTML Purifier.
+ */
+class HTMLPurifier_Language
+{
+
+ /**
+ * ISO 639 language code of language. Prefers shortest possible version
+ */
+ public $code = 'en';
+
+ /**
+ * Fallback language code
+ */
+ public $fallback = false;
+
+ /**
+ * Array of localizable messages
+ */
+ public $messages = array();
+
+ /**
+ * Array of localizable error codes
+ */
+ public $errorNames = array();
+
+ /**
+ * True if no message file was found for this language, so English
+ * is being used instead. Check this if you'd like to notify the
+ * user that they've used a non-supported language.
+ */
+ public $error = false;
+
+ /**
+ * Has the language object been loaded yet?
+ * @todo Make it private, fix usage in HTMLPurifier_LanguageTest
+ */
+ public $_loaded = false;
+
+ /**
+ * Instances of HTMLPurifier_Config and HTMLPurifier_Context
+ */
+ protected $config, $context;
+
+ public function __construct($config, $context) {
+ $this->config = $config;
+ $this->context = $context;
+ }
+
+ /**
+ * Loads language object with necessary info from factory cache
+ * @note This is a lazy loader
+ */
+ public function load() {
+ if ($this->_loaded) return;
+ $factory = HTMLPurifier_LanguageFactory::instance();
+ $factory->loadLanguage($this->code);
+ foreach ($factory->keys as $key) {
+ $this->$key = $factory->cache[$this->code][$key];
+ }
+ $this->_loaded = true;
+ }
+
+ /**
+ * Retrieves a localised message.
+ * @param $key string identifier of message
+ * @return string localised message
+ */
+ public function getMessage($key) {
+ if (!$this->_loaded) $this->load();
+ if (!isset($this->messages[$key])) return "[$key]";
+ return $this->messages[$key];
+ }
+
+ /**
+ * Retrieves a localised error name.
+ * @param $int integer error number, corresponding to PHP's error
+ * reporting
+ * @return string localised message
+ */
+ public function getErrorName($int) {
+ if (!$this->_loaded) $this->load();
+ if (!isset($this->errorNames[$int])) return "[Error: $int]";
+ return $this->errorNames[$int];
+ }
+
+ /**
+ * Converts an array list into a string readable representation
+ */
+ public function listify($array) {
+ $sep = $this->getMessage('Item separator');
+ $sep_last = $this->getMessage('Item separator last');
+ $ret = '';
+ for ($i = 0, $c = count($array); $i < $c; $i++) {
+ if ($i == 0) {
+ } elseif ($i + 1 < $c) {
+ $ret .= $sep;
+ } else {
+ $ret .= $sep_last;
+ }
+ $ret .= $array[$i];
+ }
+ return $ret;
+ }
+
+ /**
+ * Formats a localised message with passed parameters
+ * @param $key string identifier of message
+ * @param $args Parameters to substitute in
+ * @return string localised message
+ * @todo Implement conditionals? Right now, some messages make
+ * reference to line numbers, but those aren't always available
+ */
+ public function formatMessage($key, $args = array()) {
+ if (!$this->_loaded) $this->load();
+ if (!isset($this->messages[$key])) return "[$key]";
+ $raw = $this->messages[$key];
+ $subst = array();
+ $generator = false;
+ foreach ($args as $i => $value) {
+ if (is_object($value)) {
+ if ($value instanceof HTMLPurifier_Token) {
+ // factor this out some time
+ if (!$generator) $generator = $this->context->get('Generator');
+ if (isset($value->name)) $subst['$'.$i.'.Name'] = $value->name;
+ if (isset($value->data)) $subst['$'.$i.'.Data'] = $value->data;
+ $subst['$'.$i.'.Compact'] =
+ $subst['$'.$i.'.Serialized'] = $generator->generateFromToken($value);
+ // a more complex algorithm for compact representation
+ // could be introduced for all types of tokens. This
+ // may need to be factored out into a dedicated class
+ if (!empty($value->attr)) {
+ $stripped_token = clone $value;
+ $stripped_token->attr = array();
+ $subst['$'.$i.'.Compact'] = $generator->generateFromToken($stripped_token);
+ }
+ $subst['$'.$i.'.Line'] = $value->line ? $value->line : 'unknown';
+ }
+ continue;
+ } elseif (is_array($value)) {
+ $keys = array_keys($value);
+ if (array_keys($keys) === $keys) {
+ // list
+ $subst['$'.$i] = $this->listify($value);
+ } else {
+ // associative array
+ // no $i implementation yet, sorry
+ $subst['$'.$i.'.Keys'] = $this->listify($keys);
+ $subst['$'.$i.'.Values'] = $this->listify(array_values($value));
+ }
+ continue;
+ }
+ $subst['$' . $i] = $value;
+ }
+ return strtr($raw, $subst);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/classes/en-x-test.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/classes/en-x-test.php
new file mode 100644
index 0000000..d2f9baa
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/classes/en-x-test.php
@@ -0,0 +1,12 @@
+<?php
+
+// private class for unit testing
+
+class HTMLPurifier_Language_en_x_test extends HTMLPurifier_Language
+{
+
+
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-test.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-test.php
new file mode 100644
index 0000000..e6a174a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-test.php
@@ -0,0 +1,11 @@
+<?php
+
+// private language message file for unit testing purposes
+
+$fallback = 'en';
+
+$messages = array(
+ 'HTMLPurifier' => 'HTML Purifier X'
+);
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-testmini.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-testmini.php
new file mode 100644
index 0000000..ed8560f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en-x-testmini.php
@@ -0,0 +1,12 @@
+<?php
+
+// private language message file for unit testing purposes
+// this language file has no class associated with it
+
+$fallback = 'en';
+
+$messages = array(
+ 'HTMLPurifier' => 'HTML Purifier XNone'
+);
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en.php
new file mode 100644
index 0000000..0f9bd73
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Language/messages/en.php
@@ -0,0 +1,63 @@
+<?php
+
+$fallback = false;
+
+$messages = array(
+
+'HTMLPurifier' => 'HTML Purifier',
+
+// for unit testing purposes
+'LanguageFactoryTest: Pizza' => 'Pizza',
+'LanguageTest: List' => '$1',
+'LanguageTest: Hash' => '$1.Keys; $1.Values',
+
+'Item separator' => ', ',
+'Item separator last' => ' and ', // non-Harvard style
+
+'ErrorCollector: No errors' => 'No errors detected. However, because error reporting is still incomplete, there may have been errors that the error collector was not notified of; please inspect the output HTML carefully.',
+'ErrorCollector: At line' => ' at line $line',
+'ErrorCollector: Incidental errors' => 'Incidental errors',
+
+'Lexer: Unclosed comment' => 'Unclosed comment',
+'Lexer: Unescaped lt' => 'Unescaped less-than sign (<) should be &lt;',
+'Lexer: Missing gt' => 'Missing greater-than sign (>), previous less-than sign (<) should be escaped',
+'Lexer: Missing attribute key' => 'Attribute declaration has no key',
+'Lexer: Missing end quote' => 'Attribute declaration has no end quote',
+'Lexer: Extracted body' => 'Removed document metadata tags',
+
+'Strategy_RemoveForeignElements: Tag transform' => '<$1> element transformed into $CurrentToken.Serialized',
+'Strategy_RemoveForeignElements: Missing required attribute' => '$CurrentToken.Compact element missing required attribute $1',
+'Strategy_RemoveForeignElements: Foreign element to text' => 'Unrecognized $CurrentToken.Serialized tag converted to text',
+'Strategy_RemoveForeignElements: Foreign element removed' => 'Unrecognized $CurrentToken.Serialized tag removed',
+'Strategy_RemoveForeignElements: Comment removed' => 'Comment containing "$CurrentToken.Data" removed',
+'Strategy_RemoveForeignElements: Foreign meta element removed' => 'Unrecognized $CurrentToken.Serialized meta tag and all descendants removed',
+'Strategy_RemoveForeignElements: Token removed to end' => 'Tags and text starting from $1 element where removed to end',
+'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' => 'Trailing hyphen(s) in comment removed',
+'Strategy_RemoveForeignElements: Hyphens in comment collapsed' => 'Double hyphens in comments are not allowed, and were collapsed into single hyphens',
+
+'Strategy_MakeWellFormed: Unnecessary end tag removed' => 'Unnecessary $CurrentToken.Serialized tag removed',
+'Strategy_MakeWellFormed: Unnecessary end tag to text' => 'Unnecessary $CurrentToken.Serialized tag converted to text',
+'Strategy_MakeWellFormed: Tag auto closed' => '$1.Compact started on line $1.Line auto-closed by $CurrentToken.Compact',
+'Strategy_MakeWellFormed: Tag carryover' => '$1.Compact started on line $1.Line auto-continued into $CurrentToken.Compact',
+'Strategy_MakeWellFormed: Stray end tag removed' => 'Stray $CurrentToken.Serialized tag removed',
+'Strategy_MakeWellFormed: Stray end tag to text' => 'Stray $CurrentToken.Serialized tag converted to text',
+'Strategy_MakeWellFormed: Tag closed by element end' => '$1.Compact tag started on line $1.Line closed by end of $CurrentToken.Serialized',
+'Strategy_MakeWellFormed: Tag closed by document end' => '$1.Compact tag started on line $1.Line closed by end of document',
+
+'Strategy_FixNesting: Node removed' => '$CurrentToken.Compact node removed',
+'Strategy_FixNesting: Node excluded' => '$CurrentToken.Compact node removed due to descendant exclusion by ancestor element',
+'Strategy_FixNesting: Node reorganized' => 'Contents of $CurrentToken.Compact node reorganized to enforce its content model',
+'Strategy_FixNesting: Node contents removed' => 'Contents of $CurrentToken.Compact node removed',
+
+'AttrValidator: Attributes transformed' => 'Attributes on $CurrentToken.Compact transformed from $1.Keys to $2.Keys',
+'AttrValidator: Attribute removed' => '$CurrentAttr.Name attribute on $CurrentToken.Compact removed',
+
+);
+
+$errorNames = array(
+ E_ERROR => 'Error',
+ E_WARNING => 'Warning',
+ E_NOTICE => 'Notice'
+);
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/LanguageFactory.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/LanguageFactory.php
new file mode 100644
index 0000000..90b8857
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/LanguageFactory.php
@@ -0,0 +1,198 @@
+<?php
+
+/**
+ * Class responsible for generating HTMLPurifier_Language objects, managing
+ * caching and fallbacks.
+ * @note Thanks to MediaWiki for the general logic, although this version
+ * has been entirely rewritten
+ * @todo Serialized cache for languages
+ */
+class HTMLPurifier_LanguageFactory
+{
+
+ /**
+ * Cache of language code information used to load HTMLPurifier_Language objects
+ * Structure is: $factory->cache[$language_code][$key] = $value
+ * @value array map
+ */
+ public $cache;
+
+ /**
+ * Valid keys in the HTMLPurifier_Language object. Designates which
+ * variables to slurp out of a message file.
+ * @value array list
+ */
+ public $keys = array('fallback', 'messages', 'errorNames');
+
+ /**
+ * Instance of HTMLPurifier_AttrDef_Lang to validate language codes
+ * @value object HTMLPurifier_AttrDef_Lang
+ */
+ protected $validator;
+
+ /**
+ * Cached copy of dirname(__FILE__), directory of current file without
+ * trailing slash
+ * @value string filename
+ */
+ protected $dir;
+
+ /**
+ * Keys whose contents are a hash map and can be merged
+ * @value array lookup
+ */
+ protected $mergeable_keys_map = array('messages' => true, 'errorNames' => true);
+
+ /**
+ * Keys whose contents are a list and can be merged
+ * @value array lookup
+ */
+ protected $mergeable_keys_list = array();
+
+ /**
+ * Retrieve sole instance of the factory.
+ * @param $prototype Optional prototype to overload sole instance with,
+ * or bool true to reset to default factory.
+ */
+ public static function instance($prototype = null) {
+ static $instance = null;
+ if ($prototype !== null) {
+ $instance = $prototype;
+ } elseif ($instance === null || $prototype == true) {
+ $instance = new HTMLPurifier_LanguageFactory();
+ $instance->setup();
+ }
+ return $instance;
+ }
+
+ /**
+ * Sets up the singleton, much like a constructor
+ * @note Prevents people from getting this outside of the singleton
+ */
+ public function setup() {
+ $this->validator = new HTMLPurifier_AttrDef_Lang();
+ $this->dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier';
+ }
+
+ /**
+ * Creates a language object, handles class fallbacks
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @param $code Code to override configuration with. Private parameter.
+ */
+ public function create($config, $context, $code = false) {
+
+ // validate language code
+ if ($code === false) {
+ $code = $this->validator->validate(
+ $config->get('Core.Language'), $config, $context
+ );
+ } else {
+ $code = $this->validator->validate($code, $config, $context);
+ }
+ if ($code === false) $code = 'en'; // malformed code becomes English
+
+ $pcode = str_replace('-', '_', $code); // make valid PHP classname
+ static $depth = 0; // recursion protection
+
+ if ($code == 'en') {
+ $lang = new HTMLPurifier_Language($config, $context);
+ } else {
+ $class = 'HTMLPurifier_Language_' . $pcode;
+ $file = $this->dir . '/Language/classes/' . $code . '.php';
+ if (file_exists($file) || class_exists($class, false)) {
+ $lang = new $class($config, $context);
+ } else {
+ // Go fallback
+ $raw_fallback = $this->getFallbackFor($code);
+ $fallback = $raw_fallback ? $raw_fallback : 'en';
+ $depth++;
+ $lang = $this->create($config, $context, $fallback);
+ if (!$raw_fallback) {
+ $lang->error = true;
+ }
+ $depth--;
+ }
+ }
+
+ $lang->code = $code;
+
+ return $lang;
+
+ }
+
+ /**
+ * Returns the fallback language for language
+ * @note Loads the original language into cache
+ * @param $code string language code
+ */
+ public function getFallbackFor($code) {
+ $this->loadLanguage($code);
+ return $this->cache[$code]['fallback'];
+ }
+
+ /**
+ * Loads language into the cache, handles message file and fallbacks
+ * @param $code string language code
+ */
+ public function loadLanguage($code) {
+ static $languages_seen = array(); // recursion guard
+
+ // abort if we've already loaded it
+ if (isset($this->cache[$code])) return;
+
+ // generate filename
+ $filename = $this->dir . '/Language/messages/' . $code . '.php';
+
+ // default fallback : may be overwritten by the ensuing include
+ $fallback = ($code != 'en') ? 'en' : false;
+
+ // load primary localisation
+ if (!file_exists($filename)) {
+ // skip the include: will rely solely on fallback
+ $filename = $this->dir . '/Language/messages/en.php';
+ $cache = array();
+ } else {
+ include $filename;
+ $cache = compact($this->keys);
+ }
+
+ // load fallback localisation
+ if (!empty($fallback)) {
+
+ // infinite recursion guard
+ if (isset($languages_seen[$code])) {
+ trigger_error('Circular fallback reference in language ' .
+ $code, E_USER_ERROR);
+ $fallback = 'en';
+ }
+ $language_seen[$code] = true;
+
+ // load the fallback recursively
+ $this->loadLanguage($fallback);
+ $fallback_cache = $this->cache[$fallback];
+
+ // merge fallback with current language
+ foreach ( $this->keys as $key ) {
+ if (isset($cache[$key]) && isset($fallback_cache[$key])) {
+ if (isset($this->mergeable_keys_map[$key])) {
+ $cache[$key] = $cache[$key] + $fallback_cache[$key];
+ } elseif (isset($this->mergeable_keys_list[$key])) {
+ $cache[$key] = array_merge( $fallback_cache[$key], $cache[$key] );
+ }
+ } else {
+ $cache[$key] = $fallback_cache[$key];
+ }
+ }
+
+ }
+
+ // save to cache for later retrieval
+ $this->cache[$code] = $cache;
+
+ return;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Length.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Length.php
new file mode 100644
index 0000000..b92eadb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Length.php
@@ -0,0 +1,115 @@
+<?php
+
+/**
+ * Represents a measurable length, with a string numeric magnitude
+ * and a unit. This object is immutable.
+ */
+class HTMLPurifier_Length
+{
+
+ /**
+ * String numeric magnitude.
+ */
+ protected $n;
+
+ /**
+ * String unit. False is permitted if $n = 0.
+ */
+ protected $unit;
+
+ /**
+ * Whether or not this length is valid. Null if not calculated yet.
+ */
+ protected $isValid;
+
+ /**
+ * Lookup array of units recognized by CSS 2.1
+ */
+ protected static $allowedUnits = array(
+ 'em' => true, 'ex' => true, 'px' => true, 'in' => true,
+ 'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true
+ );
+
+ /**
+ * @param number $n Magnitude
+ * @param string $u Unit
+ */
+ public function __construct($n = '0', $u = false) {
+ $this->n = (string) $n;
+ $this->unit = $u !== false ? (string) $u : false;
+ }
+
+ /**
+ * @param string $s Unit string, like '2em' or '3.4in'
+ * @warning Does not perform validation.
+ */
+ static public function make($s) {
+ if ($s instanceof HTMLPurifier_Length) return $s;
+ $n_length = strspn($s, '1234567890.+-');
+ $n = substr($s, 0, $n_length);
+ $unit = substr($s, $n_length);
+ if ($unit === '') $unit = false;
+ return new HTMLPurifier_Length($n, $unit);
+ }
+
+ /**
+ * Validates the number and unit.
+ */
+ protected function validate() {
+ // Special case:
+ if ($this->n === '+0' || $this->n === '-0') $this->n = '0';
+ if ($this->n === '0' && $this->unit === false) return true;
+ if (!ctype_lower($this->unit)) $this->unit = strtolower($this->unit);
+ if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) return false;
+ // Hack:
+ $def = new HTMLPurifier_AttrDef_CSS_Number();
+ $result = $def->validate($this->n, false, false);
+ if ($result === false) return false;
+ $this->n = $result;
+ return true;
+ }
+
+ /**
+ * Returns string representation of number.
+ */
+ public function toString() {
+ if (!$this->isValid()) return false;
+ return $this->n . $this->unit;
+ }
+
+ /**
+ * Retrieves string numeric magnitude.
+ */
+ public function getN() {return $this->n;}
+
+ /**
+ * Retrieves string unit.
+ */
+ public function getUnit() {return $this->unit;}
+
+ /**
+ * Returns true if this length unit is valid.
+ */
+ public function isValid() {
+ if ($this->isValid === null) $this->isValid = $this->validate();
+ return $this->isValid;
+ }
+
+ /**
+ * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.
+ * @warning If both values are too large or small, this calculation will
+ * not work properly
+ */
+ public function compareTo($l) {
+ if ($l === false) return false;
+ if ($l->unit !== $this->unit) {
+ $converter = new HTMLPurifier_UnitConverter();
+ $l = $converter->convert($l, $this->unit);
+ if ($l === false) return false;
+ }
+ return $this->n - $l->n;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer.php
new file mode 100644
index 0000000..4607cf0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer.php
@@ -0,0 +1,326 @@
+<?php
+
+/**
+ * Forgivingly lexes HTML (SGML-style) markup into tokens.
+ *
+ * A lexer parses a string of SGML-style markup and converts them into
+ * corresponding tokens. It doesn't check for well-formedness, although its
+ * internal mechanism may make this automatic (such as the case of
+ * HTMLPurifier_Lexer_DOMLex). There are several implementations to choose
+ * from.
+ *
+ * A lexer is HTML-oriented: it might work with XML, but it's not
+ * recommended, as we adhere to a subset of the specification for optimization
+ * reasons. This might change in the future. Also, most tokenizers are not
+ * expected to handle DTDs or PIs.
+ *
+ * This class should not be directly instantiated, but you may use create() to
+ * retrieve a default copy of the lexer. Being a supertype, this class
+ * does not actually define any implementation, but offers commonly used
+ * convenience functions for subclasses.
+ *
+ * @note The unit tests will instantiate this class for testing purposes, as
+ * many of the utility functions require a class to be instantiated.
+ * This means that, even though this class is not runnable, it will
+ * not be declared abstract.
+ *
+ * @par
+ *
+ * @note
+ * We use tokens rather than create a DOM representation because DOM would:
+ *
+ * @par
+ * -# Require more processing and memory to create,
+ * -# Is not streamable, and
+ * -# Has the entire document structure (html and body not needed).
+ *
+ * @par
+ * However, DOM is helpful in that it makes it easy to move around nodes
+ * without a lot of lookaheads to see when a tag is closed. This is a
+ * limitation of the token system and some workarounds would be nice.
+ */
+class HTMLPurifier_Lexer
+{
+
+ /**
+ * Whether or not this lexer implements line-number/column-number tracking.
+ * If it does, set to true.
+ */
+ public $tracksLineNumbers = false;
+
+ // -- STATIC ----------------------------------------------------------
+
+ /**
+ * Retrieves or sets the default Lexer as a Prototype Factory.
+ *
+ * By default HTMLPurifier_Lexer_DOMLex will be returned. There are
+ * a few exceptions involving special features that only DirectLex
+ * implements.
+ *
+ * @note The behavior of this class has changed, rather than accepting
+ * a prototype object, it now accepts a configuration object.
+ * To specify your own prototype, set %Core.LexerImpl to it.
+ * This change in behavior de-singletonizes the lexer object.
+ *
+ * @param $config Instance of HTMLPurifier_Config
+ * @return Concrete lexer.
+ */
+ public static function create($config) {
+
+ if (!($config instanceof HTMLPurifier_Config)) {
+ $lexer = $config;
+ trigger_error("Passing a prototype to
+ HTMLPurifier_Lexer::create() is deprecated, please instead
+ use %Core.LexerImpl", E_USER_WARNING);
+ } else {
+ $lexer = $config->get('Core.LexerImpl');
+ }
+
+ $needs_tracking =
+ $config->get('Core.MaintainLineNumbers') ||
+ $config->get('Core.CollectErrors');
+
+ $inst = null;
+ if (is_object($lexer)) {
+ $inst = $lexer;
+ } else {
+
+ if (is_null($lexer)) { do {
+ // auto-detection algorithm
+
+ if ($needs_tracking) {
+ $lexer = 'DirectLex';
+ break;
+ }
+
+ if (
+ class_exists('DOMDocument') &&
+ method_exists('DOMDocument', 'loadHTML') &&
+ !extension_loaded('domxml')
+ ) {
+ // check for DOM support, because while it's part of the
+ // core, it can be disabled compile time. Also, the PECL
+ // domxml extension overrides the default DOM, and is evil
+ // and nasty and we shan't bother to support it
+ $lexer = 'DOMLex';
+ } else {
+ $lexer = 'DirectLex';
+ }
+
+ } while(0); } // do..while so we can break
+
+ // instantiate recognized string names
+ switch ($lexer) {
+ case 'DOMLex':
+ $inst = new HTMLPurifier_Lexer_DOMLex();
+ break;
+ case 'DirectLex':
+ $inst = new HTMLPurifier_Lexer_DirectLex();
+ break;
+ case 'PH5P':
+ $inst = new HTMLPurifier_Lexer_PH5P();
+ break;
+ default:
+ throw new HTMLPurifier_Exception("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer));
+ }
+ }
+
+ if (!$inst) throw new HTMLPurifier_Exception('No lexer was instantiated');
+
+ // once PHP DOM implements native line numbers, or we
+ // hack out something using XSLT, remove this stipulation
+ if ($needs_tracking && !$inst->tracksLineNumbers) {
+ throw new HTMLPurifier_Exception('Cannot use lexer that does not support line numbers with Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)');
+ }
+
+ return $inst;
+
+ }
+
+ // -- CONVENIENCE MEMBERS ---------------------------------------------
+
+ public function __construct() {
+ $this->_entity_parser = new HTMLPurifier_EntityParser();
+ }
+
+ /**
+ * Most common entity to raw value conversion table for special entities.
+ */
+ protected $_special_entity2str =
+ array(
+ '&quot;' => '"',
+ '&amp;' => '&',
+ '&lt;' => '<',
+ '&gt;' => '>',
+ '&#39;' => "'",
+ '&#039;' => "'",
+ '&#x27;' => "'"
+ );
+
+ /**
+ * Parses special entities into the proper characters.
+ *
+ * This string will translate escaped versions of the special characters
+ * into the correct ones.
+ *
+ * @warning
+ * You should be able to treat the output of this function as
+ * completely parsed, but that's only because all other entities should
+ * have been handled previously in substituteNonSpecialEntities()
+ *
+ * @param $string String character data to be parsed.
+ * @returns Parsed character data.
+ */
+ public function parseData($string) {
+
+ // following functions require at least one character
+ if ($string === '') return '';
+
+ // subtracts amps that cannot possibly be escaped
+ $num_amp = substr_count($string, '&') - substr_count($string, '& ') -
+ ($string[strlen($string)-1] === '&' ? 1 : 0);
+
+ if (!$num_amp) return $string; // abort if no entities
+ $num_esc_amp = substr_count($string, '&amp;');
+ $string = strtr($string, $this->_special_entity2str);
+
+ // code duplication for sake of optimization, see above
+ $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -
+ ($string[strlen($string)-1] === '&' ? 1 : 0);
+
+ if ($num_amp_2 <= $num_esc_amp) return $string;
+
+ // hmm... now we have some uncommon entities. Use the callback.
+ $string = $this->_entity_parser->substituteSpecialEntities($string);
+ return $string;
+ }
+
+ /**
+ * Lexes an HTML string into tokens.
+ *
+ * @param $string String HTML.
+ * @return HTMLPurifier_Token array representation of HTML.
+ */
+ public function tokenizeHTML($string, $config, $context) {
+ trigger_error('Call to abstract class', E_USER_ERROR);
+ }
+
+ /**
+ * Translates CDATA sections into regular sections (through escaping).
+ *
+ * @param $string HTML string to process.
+ * @returns HTML with CDATA sections escaped.
+ */
+ protected static function escapeCDATA($string) {
+ return preg_replace_callback(
+ '/<!\[CDATA\[(.+?)\]\]>/s',
+ array('HTMLPurifier_Lexer', 'CDATACallback'),
+ $string
+ );
+ }
+
+ /**
+ * Special CDATA case that is especially convoluted for <script>
+ */
+ protected static function escapeCommentedCDATA($string) {
+ return preg_replace_callback(
+ '#<!--//--><!\[CDATA\[//><!--(.+?)//--><!\]\]>#s',
+ array('HTMLPurifier_Lexer', 'CDATACallback'),
+ $string
+ );
+ }
+
+ /**
+ * Special Internet Explorer conditional comments should be removed.
+ */
+ protected static function removeIEConditional($string) {
+ return preg_replace(
+ '#<!--\[if [^>]+\]>.*?<!\[endif\]-->#si', // probably should generalize for all strings
+ '',
+ $string
+ );
+ }
+
+ /**
+ * Callback function for escapeCDATA() that does the work.
+ *
+ * @warning Though this is public in order to let the callback happen,
+ * calling it directly is not recommended.
+ * @params $matches PCRE matches array, with index 0 the entire match
+ * and 1 the inside of the CDATA section.
+ * @returns Escaped internals of the CDATA section.
+ */
+ protected static function CDATACallback($matches) {
+ // not exactly sure why the character set is needed, but whatever
+ return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
+ }
+
+ /**
+ * Takes a piece of HTML and normalizes it by converting entities, fixing
+ * encoding, extracting bits, and other good stuff.
+ * @todo Consider making protected
+ */
+ public function normalize($html, $config, $context) {
+
+ // normalize newlines to \n
+ if ($config->get('Core.NormalizeNewlines')) {
+ $html = str_replace("\r\n", "\n", $html);
+ $html = str_replace("\r", "\n", $html);
+ }
+
+ if ($config->get('HTML.Trusted')) {
+ // escape convoluted CDATA
+ $html = $this->escapeCommentedCDATA($html);
+ }
+
+ // escape CDATA
+ $html = $this->escapeCDATA($html);
+
+ $html = $this->removeIEConditional($html);
+
+ // extract body from document if applicable
+ if ($config->get('Core.ConvertDocumentToFragment')) {
+ $e = false;
+ if ($config->get('Core.CollectErrors')) {
+ $e =& $context->get('ErrorCollector');
+ }
+ $new_html = $this->extractBody($html);
+ if ($e && $new_html != $html) {
+ $e->send(E_WARNING, 'Lexer: Extracted body');
+ }
+ $html = $new_html;
+ }
+
+ // expand entities that aren't the big five
+ $html = $this->_entity_parser->substituteNonSpecialEntities($html);
+
+ // clean into wellformed UTF-8 string for an SGML context: this has
+ // to be done after entity expansion because the entities sometimes
+ // represent non-SGML characters (horror, horror!)
+ $html = HTMLPurifier_Encoder::cleanUTF8($html);
+
+ // if processing instructions are to removed, remove them now
+ if ($config->get('Core.RemoveProcessingInstructions')) {
+ $html = preg_replace('#<\?.+?\?>#s', '', $html);
+ }
+
+ return $html;
+ }
+
+ /**
+ * Takes a string of HTML (fragment or document) and returns the content
+ * @todo Consider making protected
+ */
+ public function extractBody($html) {
+ $matches = array();
+ $result = preg_match('!<body[^>]*>(.*)</body>!is', $html, $matches);
+ if ($result) {
+ return $matches[1];
+ } else {
+ return $html;
+ }
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DOMLex.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DOMLex.php
new file mode 100644
index 0000000..0913297
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DOMLex.php
@@ -0,0 +1,243 @@
+<?php
+
+/**
+ * Parser that uses PHP 5's DOM extension (part of the core).
+ *
+ * In PHP 5, the DOM XML extension was revamped into DOM and added to the core.
+ * It gives us a forgiving HTML parser, which we use to transform the HTML
+ * into a DOM, and then into the tokens. It is blazingly fast (for large
+ * documents, it performs twenty times faster than
+ * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.
+ *
+ * @note Any empty elements will have empty tokens associated with them, even if
+ * this is prohibited by the spec. This is cannot be fixed until the spec
+ * comes into play.
+ *
+ * @note PHP's DOM extension does not actually parse any entities, we use
+ * our own function to do that.
+ *
+ * @warning DOM tends to drop whitespace, which may wreak havoc on indenting.
+ * If this is a huge problem, due to the fact that HTML is hand
+ * edited and you are unable to get a parser cache that caches the
+ * the output of HTML Purifier while keeping the original HTML lying
+ * around, you may want to run Tidy on the resulting output or use
+ * HTMLPurifier_DirectLex
+ */
+
+class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
+{
+
+ private $factory;
+
+ public function __construct() {
+ // setup the factory
+ parent::__construct();
+ $this->factory = new HTMLPurifier_TokenFactory();
+ }
+
+ public function tokenizeHTML($html, $config, $context) {
+
+ $html = $this->normalize($html, $config, $context);
+
+ // attempt to armor stray angled brackets that cannot possibly
+ // form tags and thus are probably being used as emoticons
+ if ($config->get('Core.AggressivelyFixLt')) {
+ $char = '[^a-z!\/]';
+ $comment = "/<!--(.*?)(-->|\z)/is";
+ $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
+ do {
+ $old = $html;
+ $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
+ } while ($html !== $old);
+ $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
+ }
+
+ // preprocess html, essential for UTF-8
+ $html = $this->wrapHTML($html, $config, $context);
+
+ $doc = new DOMDocument();
+ $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
+
+ set_error_handler(array($this, 'muteErrorHandler'));
+ $doc->loadHTML($html);
+ restore_error_handler();
+
+ $tokens = array();
+ $this->tokenizeDOM(
+ $doc->getElementsByTagName('html')->item(0)-> // <html>
+ getElementsByTagName('body')->item(0)-> // <body>
+ getElementsByTagName('div')->item(0) // <div>
+ , $tokens);
+ return $tokens;
+ }
+
+ /**
+ * Iterative function that tokenizes a node, putting it into an accumulator.
+ * To iterate is human, to recurse divine - L. Peter Deutsch
+ * @param $node DOMNode to be tokenized.
+ * @param $tokens Array-list of already tokenized tokens.
+ * @returns Tokens of node appended to previously passed tokens.
+ */
+ protected function tokenizeDOM($node, &$tokens) {
+
+ $level = 0;
+ $nodes = array($level => array($node));
+ $closingNodes = array();
+ do {
+ while (!empty($nodes[$level])) {
+ $node = array_shift($nodes[$level]); // FIFO
+ $collect = $level > 0 ? true : false;
+ $needEndingTag = $this->createStartNode($node, $tokens, $collect);
+ if ($needEndingTag) {
+ $closingNodes[$level][] = $node;
+ }
+ if ($node->childNodes && $node->childNodes->length) {
+ $level++;
+ $nodes[$level] = array();
+ foreach ($node->childNodes as $childNode) {
+ array_push($nodes[$level], $childNode);
+ }
+ }
+ }
+ $level--;
+ if ($level && isset($closingNodes[$level])) {
+ while($node = array_pop($closingNodes[$level])) {
+ $this->createEndNode($node, $tokens);
+ }
+ }
+ } while ($level > 0);
+ }
+
+ /**
+ * @param $node DOMNode to be tokenized.
+ * @param $tokens Array-list of already tokenized tokens.
+ * @param $collect Says whether or start and close are collected, set to
+ * false at first recursion because it's the implicit DIV
+ * tag you're dealing with.
+ * @returns bool if the token needs an endtoken
+ */
+ protected function createStartNode($node, &$tokens, $collect) {
+ // intercept non element nodes. WE MUST catch all of them,
+ // but we're not getting the character reference nodes because
+ // those should have been preprocessed
+ if ($node->nodeType === XML_TEXT_NODE) {
+ $tokens[] = $this->factory->createText($node->data);
+ return false;
+ } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {
+ // undo libxml's special treatment of <script> and <style> tags
+ $last = end($tokens);
+ $data = $node->data;
+ // (note $node->tagname is already normalized)
+ if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {
+ $new_data = trim($data);
+ if (substr($new_data, 0, 4) === '<!--') {
+ $data = substr($new_data, 4);
+ if (substr($data, -3) === '-->') {
+ $data = substr($data, 0, -3);
+ } else {
+ // Highly suspicious! Not sure what to do...
+ }
+ }
+ }
+ $tokens[] = $this->factory->createText($this->parseData($data));
+ return false;
+ } elseif ($node->nodeType === XML_COMMENT_NODE) {
+ // this is code is only invoked for comments in script/style in versions
+ // of libxml pre-2.6.28 (regular comments, of course, are still
+ // handled regularly)
+ $tokens[] = $this->factory->createComment($node->data);
+ return false;
+ } elseif (
+ // not-well tested: there may be other nodes we have to grab
+ $node->nodeType !== XML_ELEMENT_NODE
+ ) {
+ return false;
+ }
+
+ $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();
+
+ // We still have to make sure that the element actually IS empty
+ if (!$node->childNodes->length) {
+ if ($collect) {
+ $tokens[] = $this->factory->createEmpty($node->tagName, $attr);
+ }
+ return false;
+ } else {
+ if ($collect) {
+ $tokens[] = $this->factory->createStart(
+ $tag_name = $node->tagName, // somehow, it get's dropped
+ $attr
+ );
+ }
+ return true;
+ }
+ }
+
+ protected function createEndNode($node, &$tokens) {
+ $tokens[] = $this->factory->createEnd($node->tagName);
+ }
+
+
+ /**
+ * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
+ *
+ * @param $attribute_list DOMNamedNodeMap of DOMAttr objects.
+ * @returns Associative array of attributes.
+ */
+ protected function transformAttrToAssoc($node_map) {
+ // NamedNodeMap is documented very well, so we're using undocumented
+ // features, namely, the fact that it implements Iterator and
+ // has a ->length attribute
+ if ($node_map->length === 0) return array();
+ $array = array();
+ foreach ($node_map as $attr) {
+ $array[$attr->name] = $attr->value;
+ }
+ return $array;
+ }
+
+ /**
+ * An error handler that mutes all errors
+ */
+ public function muteErrorHandler($errno, $errstr) {}
+
+ /**
+ * Callback function for undoing escaping of stray angled brackets
+ * in comments
+ */
+ public function callbackUndoCommentSubst($matches) {
+ return '<!--' . strtr($matches[1], array('&amp;'=>'&','&lt;'=>'<')) . $matches[2];
+ }
+
+ /**
+ * Callback function that entity-izes ampersands in comments so that
+ * callbackUndoCommentSubst doesn't clobber them
+ */
+ public function callbackArmorCommentEntities($matches) {
+ return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
+ }
+
+ /**
+ * Wraps an HTML fragment in the necessary HTML
+ */
+ protected function wrapHTML($html, $config, $context) {
+ $def = $config->getDefinition('HTML');
+ $ret = '';
+
+ if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
+ $ret .= '<!DOCTYPE html ';
+ if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
+ if (!empty($def->doctype->dtdSystem)) $ret .= '"' . $def->doctype->dtdSystem . '" ';
+ $ret .= '>';
+ }
+
+ $ret .= '<html><head>';
+ $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ // No protection if $html contains a stray </div>!
+ $ret .= '</head><body><div>'.$html.'</div></body></html>';
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DirectLex.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DirectLex.php
new file mode 100644
index 0000000..652135a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/DirectLex.php
@@ -0,0 +1,490 @@
+<?php
+
+/**
+ * Our in-house implementation of a parser.
+ *
+ * A pure PHP parser, DirectLex has absolutely no dependencies, making
+ * it a reasonably good default for PHP4. Written with efficiency in mind,
+ * it can be four times faster than HTMLPurifier_Lexer_PEARSax3, although it
+ * pales in comparison to HTMLPurifier_Lexer_DOMLex.
+ *
+ * @todo Reread XML spec and document differences.
+ */
+class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
+{
+
+ public $tracksLineNumbers = true;
+
+ /**
+ * Whitespace characters for str(c)spn.
+ */
+ protected $_whitespace = "\x20\x09\x0D\x0A";
+
+ /**
+ * Callback function for script CDATA fudge
+ * @param $matches, in form of array(opening tag, contents, closing tag)
+ */
+ protected function scriptCallback($matches) {
+ return $matches[1] . htmlspecialchars($matches[2], ENT_COMPAT, 'UTF-8') . $matches[3];
+ }
+
+ public function tokenizeHTML($html, $config, $context) {
+
+ // special normalization for script tags without any armor
+ // our "armor" heurstic is a < sign any number of whitespaces after
+ // the first script tag
+ if ($config->get('HTML.Trusted')) {
+ $html = preg_replace_callback('#(<script[^>]*>)(\s*[^<].+?)(</script>)#si',
+ array($this, 'scriptCallback'), $html);
+ }
+
+ $html = $this->normalize($html, $config, $context);
+
+ $cursor = 0; // our location in the text
+ $inside_tag = false; // whether or not we're parsing the inside of a tag
+ $array = array(); // result array
+
+ // This is also treated to mean maintain *column* numbers too
+ $maintain_line_numbers = $config->get('Core.MaintainLineNumbers');
+
+ if ($maintain_line_numbers === null) {
+ // automatically determine line numbering by checking
+ // if error collection is on
+ $maintain_line_numbers = $config->get('Core.CollectErrors');
+ }
+
+ if ($maintain_line_numbers) {
+ $current_line = 1;
+ $current_col = 0;
+ $length = strlen($html);
+ } else {
+ $current_line = false;
+ $current_col = false;
+ $length = false;
+ }
+ $context->register('CurrentLine', $current_line);
+ $context->register('CurrentCol', $current_col);
+ $nl = "\n";
+ // how often to manually recalculate. This will ALWAYS be right,
+ // but it's pretty wasteful. Set to 0 to turn off
+ $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval');
+
+ $e = false;
+ if ($config->get('Core.CollectErrors')) {
+ $e =& $context->get('ErrorCollector');
+ }
+
+ // for testing synchronization
+ $loops = 0;
+
+ while(++$loops) {
+
+ // $cursor is either at the start of a token, or inside of
+ // a tag (i.e. there was a < immediately before it), as indicated
+ // by $inside_tag
+
+ if ($maintain_line_numbers) {
+
+ // $rcursor, however, is always at the start of a token.
+ $rcursor = $cursor - (int) $inside_tag;
+
+ // Column number is cheap, so we calculate it every round.
+ // We're interested at the *end* of the newline string, so
+ // we need to add strlen($nl) == 1 to $nl_pos before subtracting it
+ // from our "rcursor" position.
+ $nl_pos = strrpos($html, $nl, $rcursor - $length);
+ $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1);
+
+ // recalculate lines
+ if (
+ $synchronize_interval && // synchronization is on
+ $cursor > 0 && // cursor is further than zero
+ $loops % $synchronize_interval === 0 // time to synchronize!
+ ) {
+ $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);
+ }
+
+ }
+
+ $position_next_lt = strpos($html, '<', $cursor);
+ $position_next_gt = strpos($html, '>', $cursor);
+
+ // triggers on "<b>asdf</b>" but not "asdf <b></b>"
+ // special case to set up context
+ if ($position_next_lt === $cursor) {
+ $inside_tag = true;
+ $cursor++;
+ }
+
+ if (!$inside_tag && $position_next_lt !== false) {
+ // We are not inside tag and there still is another tag to parse
+ $token = new
+ HTMLPurifier_Token_Text(
+ $this->parseData(
+ substr(
+ $html, $cursor, $position_next_lt - $cursor
+ )
+ )
+ );
+ if ($maintain_line_numbers) {
+ $token->rawPosition($current_line, $current_col);
+ $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor);
+ }
+ $array[] = $token;
+ $cursor = $position_next_lt + 1;
+ $inside_tag = true;
+ continue;
+ } elseif (!$inside_tag) {
+ // We are not inside tag but there are no more tags
+ // If we're already at the end, break
+ if ($cursor === strlen($html)) break;
+ // Create Text of rest of string
+ $token = new
+ HTMLPurifier_Token_Text(
+ $this->parseData(
+ substr(
+ $html, $cursor
+ )
+ )
+ );
+ if ($maintain_line_numbers) $token->rawPosition($current_line, $current_col);
+ $array[] = $token;
+ break;
+ } elseif ($inside_tag && $position_next_gt !== false) {
+ // We are in tag and it is well formed
+ // Grab the internals of the tag
+ $strlen_segment = $position_next_gt - $cursor;
+
+ if ($strlen_segment < 1) {
+ // there's nothing to process!
+ $token = new HTMLPurifier_Token_Text('<');
+ $cursor++;
+ continue;
+ }
+
+ $segment = substr($html, $cursor, $strlen_segment);
+
+ if ($segment === false) {
+ // somehow, we attempted to access beyond the end of
+ // the string, defense-in-depth, reported by Nate Abele
+ break;
+ }
+
+ // Check if it's a comment
+ if (
+ substr($segment, 0, 3) === '!--'
+ ) {
+ // re-determine segment length, looking for -->
+ $position_comment_end = strpos($html, '-->', $cursor);
+ if ($position_comment_end === false) {
+ // uh oh, we have a comment that extends to
+ // infinity. Can't be helped: set comment
+ // end position to end of string
+ if ($e) $e->send(E_WARNING, 'Lexer: Unclosed comment');
+ $position_comment_end = strlen($html);
+ $end = true;
+ } else {
+ $end = false;
+ }
+ $strlen_segment = $position_comment_end - $cursor;
+ $segment = substr($html, $cursor, $strlen_segment);
+ $token = new
+ HTMLPurifier_Token_Comment(
+ substr(
+ $segment, 3, $strlen_segment - 3
+ )
+ );
+ if ($maintain_line_numbers) {
+ $token->rawPosition($current_line, $current_col);
+ $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment);
+ }
+ $array[] = $token;
+ $cursor = $end ? $position_comment_end : $position_comment_end + 3;
+ $inside_tag = false;
+ continue;
+ }
+
+ // Check if it's an end tag
+ $is_end_tag = (strpos($segment,'/') === 0);
+ if ($is_end_tag) {
+ $type = substr($segment, 1);
+ $token = new HTMLPurifier_Token_End($type);
+ if ($maintain_line_numbers) {
+ $token->rawPosition($current_line, $current_col);
+ $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
+ }
+ $array[] = $token;
+ $inside_tag = false;
+ $cursor = $position_next_gt + 1;
+ continue;
+ }
+
+ // Check leading character is alnum, if not, we may
+ // have accidently grabbed an emoticon. Translate into
+ // text and go our merry way
+ if (!ctype_alpha($segment[0])) {
+ // XML: $segment[0] !== '_' && $segment[0] !== ':'
+ if ($e) $e->send(E_NOTICE, 'Lexer: Unescaped lt');
+ $token = new HTMLPurifier_Token_Text('<');
+ if ($maintain_line_numbers) {
+ $token->rawPosition($current_line, $current_col);
+ $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
+ }
+ $array[] = $token;
+ $inside_tag = false;
+ continue;
+ }
+
+ // Check if it is explicitly self closing, if so, remove
+ // trailing slash. Remember, we could have a tag like <br>, so
+ // any later token processing scripts must convert improperly
+ // classified EmptyTags from StartTags.
+ $is_self_closing = (strrpos($segment,'/') === $strlen_segment-1);
+ if ($is_self_closing) {
+ $strlen_segment--;
+ $segment = substr($segment, 0, $strlen_segment);
+ }
+
+ // Check if there are any attributes
+ $position_first_space = strcspn($segment, $this->_whitespace);
+
+ if ($position_first_space >= $strlen_segment) {
+ if ($is_self_closing) {
+ $token = new HTMLPurifier_Token_Empty($segment);
+ } else {
+ $token = new HTMLPurifier_Token_Start($segment);
+ }
+ if ($maintain_line_numbers) {
+ $token->rawPosition($current_line, $current_col);
+ $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
+ }
+ $array[] = $token;
+ $inside_tag = false;
+ $cursor = $position_next_gt + 1;
+ continue;
+ }
+
+ // Grab out all the data
+ $type = substr($segment, 0, $position_first_space);
+ $attribute_string =
+ trim(
+ substr(
+ $segment, $position_first_space
+ )
+ );
+ if ($attribute_string) {
+ $attr = $this->parseAttributeString(
+ $attribute_string
+ , $config, $context
+ );
+ } else {
+ $attr = array();
+ }
+
+ if ($is_self_closing) {
+ $token = new HTMLPurifier_Token_Empty($type, $attr);
+ } else {
+ $token = new HTMLPurifier_Token_Start($type, $attr);
+ }
+ if ($maintain_line_numbers) {
+ $token->rawPosition($current_line, $current_col);
+ $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
+ }
+ $array[] = $token;
+ $cursor = $position_next_gt + 1;
+ $inside_tag = false;
+ continue;
+ } else {
+ // inside tag, but there's no ending > sign
+ if ($e) $e->send(E_WARNING, 'Lexer: Missing gt');
+ $token = new
+ HTMLPurifier_Token_Text(
+ '<' .
+ $this->parseData(
+ substr($html, $cursor)
+ )
+ );
+ if ($maintain_line_numbers) $token->rawPosition($current_line, $current_col);
+ // no cursor scroll? Hmm...
+ $array[] = $token;
+ break;
+ }
+ break;
+ }
+
+ $context->destroy('CurrentLine');
+ $context->destroy('CurrentCol');
+ return $array;
+ }
+
+ /**
+ * PHP 5.0.x compatible substr_count that implements offset and length
+ */
+ protected function substrCount($haystack, $needle, $offset, $length) {
+ static $oldVersion;
+ if ($oldVersion === null) {
+ $oldVersion = version_compare(PHP_VERSION, '5.1', '<');
+ }
+ if ($oldVersion) {
+ $haystack = substr($haystack, $offset, $length);
+ return substr_count($haystack, $needle);
+ } else {
+ return substr_count($haystack, $needle, $offset, $length);
+ }
+ }
+
+ /**
+ * Takes the inside of an HTML tag and makes an assoc array of attributes.
+ *
+ * @param $string Inside of tag excluding name.
+ * @returns Assoc array of attributes.
+ */
+ public function parseAttributeString($string, $config, $context) {
+ $string = (string) $string; // quick typecast
+
+ if ($string == '') return array(); // no attributes
+
+ $e = false;
+ if ($config->get('Core.CollectErrors')) {
+ $e =& $context->get('ErrorCollector');
+ }
+
+ // let's see if we can abort as quickly as possible
+ // one equal sign, no spaces => one attribute
+ $num_equal = substr_count($string, '=');
+ $has_space = strpos($string, ' ');
+ if ($num_equal === 0 && !$has_space) {
+ // bool attribute
+ return array($string => $string);
+ } elseif ($num_equal === 1 && !$has_space) {
+ // only one attribute
+ list($key, $quoted_value) = explode('=', $string);
+ $quoted_value = trim($quoted_value);
+ if (!$key) {
+ if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');
+ return array();
+ }
+ if (!$quoted_value) return array($key => '');
+ $first_char = @$quoted_value[0];
+ $last_char = @$quoted_value[strlen($quoted_value)-1];
+
+ $same_quote = ($first_char == $last_char);
+ $open_quote = ($first_char == '"' || $first_char == "'");
+
+ if ( $same_quote && $open_quote) {
+ // well behaved
+ $value = substr($quoted_value, 1, strlen($quoted_value) - 2);
+ } else {
+ // not well behaved
+ if ($open_quote) {
+ if ($e) $e->send(E_ERROR, 'Lexer: Missing end quote');
+ $value = substr($quoted_value, 1);
+ } else {
+ $value = $quoted_value;
+ }
+ }
+ if ($value === false) $value = '';
+ return array($key => $this->parseData($value));
+ }
+
+ // setup loop environment
+ $array = array(); // return assoc array of attributes
+ $cursor = 0; // current position in string (moves forward)
+ $size = strlen($string); // size of the string (stays the same)
+
+ // if we have unquoted attributes, the parser expects a terminating
+ // space, so let's guarantee that there's always a terminating space.
+ $string .= ' ';
+
+ while(true) {
+
+ if ($cursor >= $size) {
+ break;
+ }
+
+ $cursor += ($value = strspn($string, $this->_whitespace, $cursor));
+ // grab the key
+
+ $key_begin = $cursor; //we're currently at the start of the key
+
+ // scroll past all characters that are the key (not whitespace or =)
+ $cursor += strcspn($string, $this->_whitespace . '=', $cursor);
+
+ $key_end = $cursor; // now at the end of the key
+
+ $key = substr($string, $key_begin, $key_end - $key_begin);
+
+ if (!$key) {
+ if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');
+ $cursor += strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop
+ continue; // empty key
+ }
+
+ // scroll past all whitespace
+ $cursor += strspn($string, $this->_whitespace, $cursor);
+
+ if ($cursor >= $size) {
+ $array[$key] = $key;
+ break;
+ }
+
+ // if the next character is an equal sign, we've got a regular
+ // pair, otherwise, it's a bool attribute
+ $first_char = @$string[$cursor];
+
+ if ($first_char == '=') {
+ // key="value"
+
+ $cursor++;
+ $cursor += strspn($string, $this->_whitespace, $cursor);
+
+ if ($cursor === false) {
+ $array[$key] = '';
+ break;
+ }
+
+ // we might be in front of a quote right now
+
+ $char = @$string[$cursor];
+
+ if ($char == '"' || $char == "'") {
+ // it's quoted, end bound is $char
+ $cursor++;
+ $value_begin = $cursor;
+ $cursor = strpos($string, $char, $cursor);
+ $value_end = $cursor;
+ } else {
+ // it's not quoted, end bound is whitespace
+ $value_begin = $cursor;
+ $cursor += strcspn($string, $this->_whitespace, $cursor);
+ $value_end = $cursor;
+ }
+
+ // we reached a premature end
+ if ($cursor === false) {
+ $cursor = $size;
+ $value_end = $cursor;
+ }
+
+ $value = substr($string, $value_begin, $value_end - $value_begin);
+ if ($value === false) $value = '';
+ $array[$key] = $this->parseData($value);
+ $cursor++;
+
+ } else {
+ // boolattr
+ if ($key !== '') {
+ $array[$key] = $key;
+ } else {
+ // purely theoretical
+ if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');
+ }
+
+ }
+ }
+ return $array;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PEARSax3.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PEARSax3.php
new file mode 100644
index 0000000..f988473
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PEARSax3.php
@@ -0,0 +1,139 @@
+<?php
+
+/**
+ * Proof-of-concept lexer that uses the PEAR package XML_HTMLSax3 to parse HTML.
+ *
+ * PEAR, not suprisingly, also has a SAX parser for HTML. I don't know
+ * very much about implementation, but it's fairly well written. However, that
+ * abstraction comes at a price: performance. You need to have it installed,
+ * and if the API changes, it might break our adapter. Not sure whether or not
+ * it's UTF-8 aware, but it has some entity parsing trouble (in all areas,
+ * text and attributes).
+ *
+ * Quite personally, I don't recommend using the PEAR class, and the defaults
+ * don't use it. The unit tests do perform the tests on the SAX parser too, but
+ * whatever it does for poorly formed HTML is up to it.
+ *
+ * @todo Generalize so that XML_HTMLSax is also supported.
+ *
+ * @warning Entity-resolution inside attributes is broken.
+ */
+
+class HTMLPurifier_Lexer_PEARSax3 extends HTMLPurifier_Lexer
+{
+
+ /**
+ * Internal accumulator array for SAX parsers.
+ */
+ protected $tokens = array();
+ protected $last_token_was_empty;
+
+ private $parent_handler;
+ private $stack = array();
+
+ public function tokenizeHTML($string, $config, $context) {
+
+ $this->tokens = array();
+ $this->last_token_was_empty = false;
+
+ $string = $this->normalize($string, $config, $context);
+
+ $this->parent_handler = set_error_handler(array($this, 'muteStrictErrorHandler'));
+
+ $parser = new XML_HTMLSax3();
+ $parser->set_object($this);
+ $parser->set_element_handler('openHandler','closeHandler');
+ $parser->set_data_handler('dataHandler');
+ $parser->set_escape_handler('escapeHandler');
+
+ // doesn't seem to work correctly for attributes
+ $parser->set_option('XML_OPTION_ENTITIES_PARSED', 1);
+
+ $parser->parse($string);
+
+ restore_error_handler();
+
+ return $this->tokens;
+
+ }
+
+ /**
+ * Open tag event handler, interface is defined by PEAR package.
+ */
+ public function openHandler(&$parser, $name, $attrs, $closed) {
+ // entities are not resolved in attrs
+ foreach ($attrs as $key => $attr) {
+ $attrs[$key] = $this->parseData($attr);
+ }
+ if ($closed) {
+ $this->tokens[] = new HTMLPurifier_Token_Empty($name, $attrs);
+ $this->last_token_was_empty = true;
+ } else {
+ $this->tokens[] = new HTMLPurifier_Token_Start($name, $attrs);
+ }
+ $this->stack[] = $name;
+ return true;
+ }
+
+ /**
+ * Close tag event handler, interface is defined by PEAR package.
+ */
+ public function closeHandler(&$parser, $name) {
+ // HTMLSax3 seems to always send empty tags an extra close tag
+ // check and ignore if you see it:
+ // [TESTME] to make sure it doesn't overreach
+ if ($this->last_token_was_empty) {
+ $this->last_token_was_empty = false;
+ return true;
+ }
+ $this->tokens[] = new HTMLPurifier_Token_End($name);
+ if (!empty($this->stack)) array_pop($this->stack);
+ return true;
+ }
+
+ /**
+ * Data event handler, interface is defined by PEAR package.
+ */
+ public function dataHandler(&$parser, $data) {
+ $this->last_token_was_empty = false;
+ $this->tokens[] = new HTMLPurifier_Token_Text($data);
+ return true;
+ }
+
+ /**
+ * Escaped text handler, interface is defined by PEAR package.
+ */
+ public function escapeHandler(&$parser, $data) {
+ if (strpos($data, '--') === 0) {
+ // remove trailing and leading double-dashes
+ $data = substr($data, 2);
+ if (strlen($data) >= 2 && substr($data, -2) == "--") {
+ $data = substr($data, 0, -2);
+ }
+ if (isset($this->stack[sizeof($this->stack) - 1]) &&
+ $this->stack[sizeof($this->stack) - 1] == "style") {
+ $this->tokens[] = new HTMLPurifier_Token_Text($data);
+ } else {
+ $this->tokens[] = new HTMLPurifier_Token_Comment($data);
+ }
+ $this->last_token_was_empty = false;
+ }
+ // CDATA is handled elsewhere, but if it was handled here:
+ //if (strpos($data, '[CDATA[') === 0) {
+ // $this->tokens[] = new HTMLPurifier_Token_Text(
+ // substr($data, 7, strlen($data) - 9) );
+ //}
+ return true;
+ }
+
+ /**
+ * An error handler that mutes strict errors
+ */
+ public function muteStrictErrorHandler($errno, $errstr, $errfile=null, $errline=null, $errcontext=null) {
+ if ($errno == E_STRICT) return;
+ return call_user_func($this->parent_handler, $errno, $errstr, $errfile, $errline, $errcontext);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PH5P.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PH5P.php
new file mode 100644
index 0000000..a43c56f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Lexer/PH5P.php
@@ -0,0 +1,3904 @@
+<?php
+
+/**
+ * Experimental HTML5-based parser using Jeroen van der Meer's PH5P library.
+ * Occupies space in the HTML5 pseudo-namespace, which may cause conflicts.
+ *
+ * @note
+ * Recent changes to PHP's DOM extension have resulted in some fatal
+ * error conditions with the original version of PH5P. Pending changes,
+ * this lexer will punt to DirectLex if DOM throughs an exception.
+ */
+
+class HTMLPurifier_Lexer_PH5P extends HTMLPurifier_Lexer_DOMLex {
+
+ public function tokenizeHTML($html, $config, $context) {
+ $new_html = $this->normalize($html, $config, $context);
+ $new_html = $this->wrapHTML($new_html, $config, $context);
+ try {
+ $parser = new HTML5($new_html);
+ $doc = $parser->save();
+ } catch (DOMException $e) {
+ // Uh oh, it failed. Punt to DirectLex.
+ $lexer = new HTMLPurifier_Lexer_DirectLex();
+ $context->register('PH5PError', $e); // save the error, so we can detect it
+ return $lexer->tokenizeHTML($html, $config, $context); // use original HTML
+ }
+ $tokens = array();
+ $this->tokenizeDOM(
+ $doc->getElementsByTagName('html')->item(0)-> // <html>
+ getElementsByTagName('body')->item(0)-> // <body>
+ getElementsByTagName('div')->item(0) // <div>
+ , $tokens);
+ return $tokens;
+ }
+
+}
+
+/*
+
+Copyright 2007 Jeroen van der Meer <http://jero.net/>
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+*/
+
+class HTML5 {
+ private $data;
+ private $char;
+ private $EOF;
+ private $state;
+ private $tree;
+ private $token;
+ private $content_model;
+ private $escape = false;
+ private $entities = array('AElig;','AElig','AMP;','AMP','Aacute;','Aacute',
+ 'Acirc;','Acirc','Agrave;','Agrave','Alpha;','Aring;','Aring','Atilde;',
+ 'Atilde','Auml;','Auml','Beta;','COPY;','COPY','Ccedil;','Ccedil','Chi;',
+ 'Dagger;','Delta;','ETH;','ETH','Eacute;','Eacute','Ecirc;','Ecirc','Egrave;',
+ 'Egrave','Epsilon;','Eta;','Euml;','Euml','GT;','GT','Gamma;','Iacute;',
+ 'Iacute','Icirc;','Icirc','Igrave;','Igrave','Iota;','Iuml;','Iuml','Kappa;',
+ 'LT;','LT','Lambda;','Mu;','Ntilde;','Ntilde','Nu;','OElig;','Oacute;',
+ 'Oacute','Ocirc;','Ocirc','Ograve;','Ograve','Omega;','Omicron;','Oslash;',
+ 'Oslash','Otilde;','Otilde','Ouml;','Ouml','Phi;','Pi;','Prime;','Psi;',
+ 'QUOT;','QUOT','REG;','REG','Rho;','Scaron;','Sigma;','THORN;','THORN',
+ 'TRADE;','Tau;','Theta;','Uacute;','Uacute','Ucirc;','Ucirc','Ugrave;',
+ 'Ugrave','Upsilon;','Uuml;','Uuml','Xi;','Yacute;','Yacute','Yuml;','Zeta;',
+ 'aacute;','aacute','acirc;','acirc','acute;','acute','aelig;','aelig',
+ 'agrave;','agrave','alefsym;','alpha;','amp;','amp','and;','ang;','apos;',
+ 'aring;','aring','asymp;','atilde;','atilde','auml;','auml','bdquo;','beta;',
+ 'brvbar;','brvbar','bull;','cap;','ccedil;','ccedil','cedil;','cedil',
+ 'cent;','cent','chi;','circ;','clubs;','cong;','copy;','copy','crarr;',
+ 'cup;','curren;','curren','dArr;','dagger;','darr;','deg;','deg','delta;',
+ 'diams;','divide;','divide','eacute;','eacute','ecirc;','ecirc','egrave;',
+ 'egrave','empty;','emsp;','ensp;','epsilon;','equiv;','eta;','eth;','eth',
+ 'euml;','euml','euro;','exist;','fnof;','forall;','frac12;','frac12',
+ 'frac14;','frac14','frac34;','frac34','frasl;','gamma;','ge;','gt;','gt',
+ 'hArr;','harr;','hearts;','hellip;','iacute;','iacute','icirc;','icirc',
+ 'iexcl;','iexcl','igrave;','igrave','image;','infin;','int;','iota;',
+ 'iquest;','iquest','isin;','iuml;','iuml','kappa;','lArr;','lambda;','lang;',
+ 'laquo;','laquo','larr;','lceil;','ldquo;','le;','lfloor;','lowast;','loz;',
+ 'lrm;','lsaquo;','lsquo;','lt;','lt','macr;','macr','mdash;','micro;','micro',
+ 'middot;','middot','minus;','mu;','nabla;','nbsp;','nbsp','ndash;','ne;',
+ 'ni;','not;','not','notin;','nsub;','ntilde;','ntilde','nu;','oacute;',
+ 'oacute','ocirc;','ocirc','oelig;','ograve;','ograve','oline;','omega;',
+ 'omicron;','oplus;','or;','ordf;','ordf','ordm;','ordm','oslash;','oslash',
+ 'otilde;','otilde','otimes;','ouml;','ouml','para;','para','part;','permil;',
+ 'perp;','phi;','pi;','piv;','plusmn;','plusmn','pound;','pound','prime;',
+ 'prod;','prop;','psi;','quot;','quot','rArr;','radic;','rang;','raquo;',
+ 'raquo','rarr;','rceil;','rdquo;','real;','reg;','reg','rfloor;','rho;',
+ 'rlm;','rsaquo;','rsquo;','sbquo;','scaron;','sdot;','sect;','sect','shy;',
+ 'shy','sigma;','sigmaf;','sim;','spades;','sub;','sube;','sum;','sup1;',
+ 'sup1','sup2;','sup2','sup3;','sup3','sup;','supe;','szlig;','szlig','tau;',
+ 'there4;','theta;','thetasym;','thinsp;','thorn;','thorn','tilde;','times;',
+ 'times','trade;','uArr;','uacute;','uacute','uarr;','ucirc;','ucirc',
+ 'ugrave;','ugrave','uml;','uml','upsih;','upsilon;','uuml;','uuml','weierp;',
+ 'xi;','yacute;','yacute','yen;','yen','yuml;','yuml','zeta;','zwj;','zwnj;');
+
+ const PCDATA = 0;
+ const RCDATA = 1;
+ const CDATA = 2;
+ const PLAINTEXT = 3;
+
+ const DOCTYPE = 0;
+ const STARTTAG = 1;
+ const ENDTAG = 2;
+ const COMMENT = 3;
+ const CHARACTR = 4;
+ const EOF = 5;
+
+ public function __construct($data) {
+
+ $this->data = $data;
+ $this->char = -1;
+ $this->EOF = strlen($data);
+ $this->tree = new HTML5TreeConstructer;
+ $this->content_model = self::PCDATA;
+
+ $this->state = 'data';
+
+ while($this->state !== null) {
+ $this->{$this->state.'State'}();
+ }
+ }
+
+ public function save() {
+ return $this->tree->save();
+ }
+
+ private function char() {
+ return ($this->char < $this->EOF)
+ ? $this->data[$this->char]
+ : false;
+ }
+
+ private function character($s, $l = 0) {
+ if($s + $l < $this->EOF) {
+ if($l === 0) {
+ return $this->data[$s];
+ } else {
+ return substr($this->data, $s, $l);
+ }
+ }
+ }
+
+ private function characters($char_class, $start) {
+ return preg_replace('#^(['.$char_class.']+).*#s', '\\1', substr($this->data, $start));
+ }
+
+ private function dataState() {
+ // Consume the next input character
+ $this->char++;
+ $char = $this->char();
+
+ if($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) {
+ /* U+0026 AMPERSAND (&)
+ When the content model flag is set to one of the PCDATA or RCDATA
+ states: switch to the entity data state. Otherwise: treat it as per
+ the "anything else" entry below. */
+ $this->state = 'entityData';
+
+ } elseif($char === '-') {
+ /* If the content model flag is set to either the RCDATA state or
+ the CDATA state, and the escape flag is false, and there are at
+ least three characters before this one in the input stream, and the
+ last four characters in the input stream, including this one, are
+ U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS,
+ and U+002D HYPHEN-MINUS ("<!--"), then set the escape flag to true. */
+ if(($this->content_model === self::RCDATA || $this->content_model ===
+ self::CDATA) && $this->escape === false &&
+ $this->char >= 3 && $this->character($this->char - 4, 4) === '<!--') {
+ $this->escape = true;
+ }
+
+ /* In any case, emit the input character as a character token. Stay
+ in the data state. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => $char
+ ));
+
+ /* U+003C LESS-THAN SIGN (<) */
+ } elseif($char === '<' && ($this->content_model === self::PCDATA ||
+ (($this->content_model === self::RCDATA ||
+ $this->content_model === self::CDATA) && $this->escape === false))) {
+ /* When the content model flag is set to the PCDATA state: switch
+ to the tag open state.
+
+ When the content model flag is set to either the RCDATA state or
+ the CDATA state and the escape flag is false: switch to the tag
+ open state.
+
+ Otherwise: treat it as per the "anything else" entry below. */
+ $this->state = 'tagOpen';
+
+ /* U+003E GREATER-THAN SIGN (>) */
+ } elseif($char === '>') {
+ /* If the content model flag is set to either the RCDATA state or
+ the CDATA state, and the escape flag is true, and the last three
+ characters in the input stream including this one are U+002D
+ HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN ("-->"),
+ set the escape flag to false. */
+ if(($this->content_model === self::RCDATA ||
+ $this->content_model === self::CDATA) && $this->escape === true &&
+ $this->character($this->char, 3) === '-->') {
+ $this->escape = false;
+ }
+
+ /* In any case, emit the input character as a character token.
+ Stay in the data state. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => $char
+ ));
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Emit an end-of-file token. */
+ $this->EOF();
+
+ } elseif($this->content_model === self::PLAINTEXT) {
+ /* When the content model flag is set to the PLAINTEXT state
+ THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of
+ the text and emit it as a character token. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => substr($this->data, $this->char)
+ ));
+
+ $this->EOF();
+
+ } else {
+ /* Anything else
+ THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that
+ otherwise would also be treated as a character token and emit it
+ as a single character token. Stay in the data state. */
+ $len = strcspn($this->data, '<&', $this->char);
+ $char = substr($this->data, $this->char, $len);
+ $this->char += $len - 1;
+
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => $char
+ ));
+
+ $this->state = 'data';
+ }
+ }
+
+ private function entityDataState() {
+ // Attempt to consume an entity.
+ $entity = $this->entity();
+
+ // If nothing is returned, emit a U+0026 AMPERSAND character token.
+ // Otherwise, emit the character token that was returned.
+ $char = (!$entity) ? '&' : $entity;
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => $char
+ ));
+
+ // Finally, switch to the data state.
+ $this->state = 'data';
+ }
+
+ private function tagOpenState() {
+ switch($this->content_model) {
+ case self::RCDATA:
+ case self::CDATA:
+ /* If the next input character is a U+002F SOLIDUS (/) character,
+ consume it and switch to the close tag open state. If the next
+ input character is not a U+002F SOLIDUS (/) character, emit a
+ U+003C LESS-THAN SIGN character token and switch to the data
+ state to process the next input character. */
+ if($this->character($this->char + 1) === '/') {
+ $this->char++;
+ $this->state = 'closeTagOpen';
+
+ } else {
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => '<'
+ ));
+
+ $this->state = 'data';
+ }
+ break;
+
+ case self::PCDATA:
+ // If the content model flag is set to the PCDATA state
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->char();
+
+ if($char === '!') {
+ /* U+0021 EXCLAMATION MARK (!)
+ Switch to the markup declaration open state. */
+ $this->state = 'markupDeclarationOpen';
+
+ } elseif($char === '/') {
+ /* U+002F SOLIDUS (/)
+ Switch to the close tag open state. */
+ $this->state = 'closeTagOpen';
+
+ } elseif(preg_match('/^[A-Za-z]$/', $char)) {
+ /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
+ Create a new start tag token, set its tag name to the lowercase
+ version of the input character (add 0x0020 to the character's code
+ point), then switch to the tag name state. (Don't emit the token
+ yet; further details will be filled in before it is emitted.) */
+ $this->token = array(
+ 'name' => strtolower($char),
+ 'type' => self::STARTTAG,
+ 'attr' => array()
+ );
+
+ $this->state = 'tagName';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Parse error. Emit a U+003C LESS-THAN SIGN character token and a
+ U+003E GREATER-THAN SIGN character token. Switch to the data state. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => '<>'
+ ));
+
+ $this->state = 'data';
+
+ } elseif($char === '?') {
+ /* U+003F QUESTION MARK (?)
+ Parse error. Switch to the bogus comment state. */
+ $this->state = 'bogusComment';
+
+ } else {
+ /* Anything else
+ Parse error. Emit a U+003C LESS-THAN SIGN character token and
+ reconsume the current input character in the data state. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => '<'
+ ));
+
+ $this->char--;
+ $this->state = 'data';
+ }
+ break;
+ }
+ }
+
+ private function closeTagOpenState() {
+ $next_node = strtolower($this->characters('A-Za-z', $this->char + 1));
+ $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName;
+
+ if(($this->content_model === self::RCDATA || $this->content_model === self::CDATA) &&
+ (!$the_same || ($the_same && (!preg_match('/[\t\n\x0b\x0c >\/]/',
+ $this->character($this->char + 1 + strlen($next_node))) || $this->EOF === $this->char)))) {
+ /* If the content model flag is set to the RCDATA or CDATA states then
+ examine the next few characters. If they do not match the tag name of
+ the last start tag token emitted (case insensitively), or if they do but
+ they are not immediately followed by one of the following characters:
+ * U+0009 CHARACTER TABULATION
+ * U+000A LINE FEED (LF)
+ * U+000B LINE TABULATION
+ * U+000C FORM FEED (FF)
+ * U+0020 SPACE
+ * U+003E GREATER-THAN SIGN (>)
+ * U+002F SOLIDUS (/)
+ * EOF
+ ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character
+ token, a U+002F SOLIDUS character token, and switch to the data state
+ to process the next input character. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => '</'
+ ));
+
+ $this->state = 'data';
+
+ } else {
+ /* Otherwise, if the content model flag is set to the PCDATA state,
+ or if the next few characters do match that tag name, consume the
+ next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if(preg_match('/^[A-Za-z]$/', $char)) {
+ /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
+ Create a new end tag token, set its tag name to the lowercase version
+ of the input character (add 0x0020 to the character's code point), then
+ switch to the tag name state. (Don't emit the token yet; further details
+ will be filled in before it is emitted.) */
+ $this->token = array(
+ 'name' => strtolower($char),
+ 'type' => self::ENDTAG
+ );
+
+ $this->state = 'tagName';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Parse error. Switch to the data state. */
+ $this->state = 'data';
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F
+ SOLIDUS character token. Reconsume the EOF character in the data state. */
+ $this->emitToken(array(
+ 'type' => self::CHARACTR,
+ 'data' => '</'
+ ));
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ /* Parse error. Switch to the bogus comment state. */
+ $this->state = 'bogusComment';
+ }
+ }
+ }
+
+ private function tagNameState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ /* U+0009 CHARACTER TABULATION
+ U+000A LINE FEED (LF)
+ U+000B LINE TABULATION
+ U+000C FORM FEED (FF)
+ U+0020 SPACE
+ Switch to the before attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Emit the current tag token. Switch to the data state. */
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit the current tag token. Reconsume the EOF
+ character in the data state. */
+ $this->emitToken($this->token);
+
+ $this->char--;
+ $this->state = 'data';
+
+ } elseif($char === '/') {
+ /* U+002F SOLIDUS (/)
+ Parse error unless this is a permitted slash. Switch to the before
+ attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } else {
+ /* Anything else
+ Append the current input character to the current tag token's tag name.
+ Stay in the tag name state. */
+ $this->token['name'] .= strtolower($char);
+ $this->state = 'tagName';
+ }
+ }
+
+ private function beforeAttributeNameState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ /* U+0009 CHARACTER TABULATION
+ U+000A LINE FEED (LF)
+ U+000B LINE TABULATION
+ U+000C FORM FEED (FF)
+ U+0020 SPACE
+ Stay in the before attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Emit the current tag token. Switch to the data state. */
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($char === '/') {
+ /* U+002F SOLIDUS (/)
+ Parse error unless this is a permitted slash. Stay in the before
+ attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit the current tag token. Reconsume the EOF
+ character in the data state. */
+ $this->emitToken($this->token);
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Start a new attribute in the current tag token. Set that attribute's
+ name to the current input character, and its value to the empty string.
+ Switch to the attribute name state. */
+ $this->token['attr'][] = array(
+ 'name' => strtolower($char),
+ 'value' => null
+ );
+
+ $this->state = 'attributeName';
+ }
+ }
+
+ private function attributeNameState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ /* U+0009 CHARACTER TABULATION
+ U+000A LINE FEED (LF)
+ U+000B LINE TABULATION
+ U+000C FORM FEED (FF)
+ U+0020 SPACE
+ Stay in the before attribute name state. */
+ $this->state = 'afterAttributeName';
+
+ } elseif($char === '=') {
+ /* U+003D EQUALS SIGN (=)
+ Switch to the before attribute value state. */
+ $this->state = 'beforeAttributeValue';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Emit the current tag token. Switch to the data state. */
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
+ /* U+002F SOLIDUS (/)
+ Parse error unless this is a permitted slash. Switch to the before
+ attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit the current tag token. Reconsume the EOF
+ character in the data state. */
+ $this->emitToken($this->token);
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Append the current input character to the current attribute's name.
+ Stay in the attribute name state. */
+ $last = count($this->token['attr']) - 1;
+ $this->token['attr'][$last]['name'] .= strtolower($char);
+
+ $this->state = 'attributeName';
+ }
+ }
+
+ private function afterAttributeNameState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ /* U+0009 CHARACTER TABULATION
+ U+000A LINE FEED (LF)
+ U+000B LINE TABULATION
+ U+000C FORM FEED (FF)
+ U+0020 SPACE
+ Stay in the after attribute name state. */
+ $this->state = 'afterAttributeName';
+
+ } elseif($char === '=') {
+ /* U+003D EQUALS SIGN (=)
+ Switch to the before attribute value state. */
+ $this->state = 'beforeAttributeValue';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Emit the current tag token. Switch to the data state. */
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
+ /* U+002F SOLIDUS (/)
+ Parse error unless this is a permitted slash. Switch to the
+ before attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit the current tag token. Reconsume the EOF
+ character in the data state. */
+ $this->emitToken($this->token);
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Start a new attribute in the current tag token. Set that attribute's
+ name to the current input character, and its value to the empty string.
+ Switch to the attribute name state. */
+ $this->token['attr'][] = array(
+ 'name' => strtolower($char),
+ 'value' => null
+ );
+
+ $this->state = 'attributeName';
+ }
+ }
+
+ private function beforeAttributeValueState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ /* U+0009 CHARACTER TABULATION
+ U+000A LINE FEED (LF)
+ U+000B LINE TABULATION
+ U+000C FORM FEED (FF)
+ U+0020 SPACE
+ Stay in the before attribute value state. */
+ $this->state = 'beforeAttributeValue';
+
+ } elseif($char === '"') {
+ /* U+0022 QUOTATION MARK (")
+ Switch to the attribute value (double-quoted) state. */
+ $this->state = 'attributeValueDoubleQuoted';
+
+ } elseif($char === '&') {
+ /* U+0026 AMPERSAND (&)
+ Switch to the attribute value (unquoted) state and reconsume
+ this input character. */
+ $this->char--;
+ $this->state = 'attributeValueUnquoted';
+
+ } elseif($char === '\'') {
+ /* U+0027 APOSTROPHE (')
+ Switch to the attribute value (single-quoted) state. */
+ $this->state = 'attributeValueSingleQuoted';
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Emit the current tag token. Switch to the data state. */
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Append the current input character to the current attribute's value.
+ Switch to the attribute value (unquoted) state. */
+ $last = count($this->token['attr']) - 1;
+ $this->token['attr'][$last]['value'] .= $char;
+
+ $this->state = 'attributeValueUnquoted';
+ }
+ }
+
+ private function attributeValueDoubleQuotedState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if($char === '"') {
+ /* U+0022 QUOTATION MARK (")
+ Switch to the before attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($char === '&') {
+ /* U+0026 AMPERSAND (&)
+ Switch to the entity in attribute value state. */
+ $this->entityInAttributeValueState('double');
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit the current tag token. Reconsume the character
+ in the data state. */
+ $this->emitToken($this->token);
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Append the current input character to the current attribute's value.
+ Stay in the attribute value (double-quoted) state. */
+ $last = count($this->token['attr']) - 1;
+ $this->token['attr'][$last]['value'] .= $char;
+
+ $this->state = 'attributeValueDoubleQuoted';
+ }
+ }
+
+ private function attributeValueSingleQuotedState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if($char === '\'') {
+ /* U+0022 QUOTATION MARK (')
+ Switch to the before attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($char === '&') {
+ /* U+0026 AMPERSAND (&)
+ Switch to the entity in attribute value state. */
+ $this->entityInAttributeValueState('single');
+
+ } elseif($this->char === $this->EOF) {
+ /* EOF
+ Parse error. Emit the current tag token. Reconsume the character
+ in the data state. */
+ $this->emitToken($this->token);
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Append the current input character to the current attribute's value.
+ Stay in the attribute value (single-quoted) state. */
+ $last = count($this->token['attr']) - 1;
+ $this->token['attr'][$last]['value'] .= $char;
+
+ $this->state = 'attributeValueSingleQuoted';
+ }
+ }
+
+ private function attributeValueUnquotedState() {
+ // Consume the next input character:
+ $this->char++;
+ $char = $this->character($this->char);
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ /* U+0009 CHARACTER TABULATION
+ U+000A LINE FEED (LF)
+ U+000B LINE TABULATION
+ U+000C FORM FEED (FF)
+ U+0020 SPACE
+ Switch to the before attribute name state. */
+ $this->state = 'beforeAttributeName';
+
+ } elseif($char === '&') {
+ /* U+0026 AMPERSAND (&)
+ Switch to the entity in attribute value state. */
+ $this->entityInAttributeValueState();
+
+ } elseif($char === '>') {
+ /* U+003E GREATER-THAN SIGN (>)
+ Emit the current tag token. Switch to the data state. */
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } else {
+ /* Anything else
+ Append the current input character to the current attribute's value.
+ Stay in the attribute value (unquoted) state. */
+ $last = count($this->token['attr']) - 1;
+ $this->token['attr'][$last]['value'] .= $char;
+
+ $this->state = 'attributeValueUnquoted';
+ }
+ }
+
+ private function entityInAttributeValueState() {
+ // Attempt to consume an entity.
+ $entity = $this->entity();
+
+ // If nothing is returned, append a U+0026 AMPERSAND character to the
+ // current attribute's value. Otherwise, emit the character token that
+ // was returned.
+ $char = (!$entity)
+ ? '&'
+ : $entity;
+
+ $last = count($this->token['attr']) - 1;
+ $this->token['attr'][$last]['value'] .= $char;
+ }
+
+ private function bogusCommentState() {
+ /* Consume every character up to the first U+003E GREATER-THAN SIGN
+ character (>) or the end of the file (EOF), whichever comes first. Emit
+ a comment token whose data is the concatenation of all the characters
+ starting from and including the character that caused the state machine
+ to switch into the bogus comment state, up to and including the last
+ consumed character before the U+003E character, if any, or up to the
+ end of the file otherwise. (If the comment was started by the end of
+ the file (EOF), the token is empty.) */
+ $data = $this->characters('^>', $this->char);
+ $this->emitToken(array(
+ 'data' => $data,
+ 'type' => self::COMMENT
+ ));
+
+ $this->char += strlen($data);
+
+ /* Switch to the data state. */
+ $this->state = 'data';
+
+ /* If the end of the file was reached, reconsume the EOF character. */
+ if($this->char === $this->EOF) {
+ $this->char = $this->EOF - 1;
+ }
+ }
+
+ private function markupDeclarationOpenState() {
+ /* If the next two characters are both U+002D HYPHEN-MINUS (-)
+ characters, consume those two characters, create a comment token whose
+ data is the empty string, and switch to the comment state. */
+ if($this->character($this->char + 1, 2) === '--') {
+ $this->char += 2;
+ $this->state = 'comment';
+ $this->token = array(
+ 'data' => null,
+ 'type' => self::COMMENT
+ );
+
+ /* Otherwise if the next seven chacacters are a case-insensitive match
+ for the word "DOCTYPE", then consume those characters and switch to the
+ DOCTYPE state. */
+ } elseif(strtolower($this->character($this->char + 1, 7)) === 'doctype') {
+ $this->char += 7;
+ $this->state = 'doctype';
+
+ /* Otherwise, is is a parse error. Switch to the bogus comment state.
+ The next character that is consumed, if any, is the first character
+ that will be in the comment. */
+ } else {
+ $this->char++;
+ $this->state = 'bogusComment';
+ }
+ }
+
+ private function commentState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ /* U+002D HYPHEN-MINUS (-) */
+ if($char === '-') {
+ /* Switch to the comment dash state */
+ $this->state = 'commentDash';
+
+ /* EOF */
+ } elseif($this->char === $this->EOF) {
+ /* Parse error. Emit the comment token. Reconsume the EOF character
+ in the data state. */
+ $this->emitToken($this->token);
+ $this->char--;
+ $this->state = 'data';
+
+ /* Anything else */
+ } else {
+ /* Append the input character to the comment token's data. Stay in
+ the comment state. */
+ $this->token['data'] .= $char;
+ }
+ }
+
+ private function commentDashState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ /* U+002D HYPHEN-MINUS (-) */
+ if($char === '-') {
+ /* Switch to the comment end state */
+ $this->state = 'commentEnd';
+
+ /* EOF */
+ } elseif($this->char === $this->EOF) {
+ /* Parse error. Emit the comment token. Reconsume the EOF character
+ in the data state. */
+ $this->emitToken($this->token);
+ $this->char--;
+ $this->state = 'data';
+
+ /* Anything else */
+ } else {
+ /* Append a U+002D HYPHEN-MINUS (-) character and the input
+ character to the comment token's data. Switch to the comment state. */
+ $this->token['data'] .= '-'.$char;
+ $this->state = 'comment';
+ }
+ }
+
+ private function commentEndState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if($char === '>') {
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($char === '-') {
+ $this->token['data'] .= '-';
+
+ } elseif($this->char === $this->EOF) {
+ $this->emitToken($this->token);
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ $this->token['data'] .= '--'.$char;
+ $this->state = 'comment';
+ }
+ }
+
+ private function doctypeState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ $this->state = 'beforeDoctypeName';
+
+ } else {
+ $this->char--;
+ $this->state = 'beforeDoctypeName';
+ }
+ }
+
+ private function beforeDoctypeNameState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ // Stay in the before DOCTYPE name state.
+
+ } elseif(preg_match('/^[a-z]$/', $char)) {
+ $this->token = array(
+ 'name' => strtoupper($char),
+ 'type' => self::DOCTYPE,
+ 'error' => true
+ );
+
+ $this->state = 'doctypeName';
+
+ } elseif($char === '>') {
+ $this->emitToken(array(
+ 'name' => null,
+ 'type' => self::DOCTYPE,
+ 'error' => true
+ ));
+
+ $this->state = 'data';
+
+ } elseif($this->char === $this->EOF) {
+ $this->emitToken(array(
+ 'name' => null,
+ 'type' => self::DOCTYPE,
+ 'error' => true
+ ));
+
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ $this->token = array(
+ 'name' => $char,
+ 'type' => self::DOCTYPE,
+ 'error' => true
+ );
+
+ $this->state = 'doctypeName';
+ }
+ }
+
+ private function doctypeNameState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ $this->state = 'AfterDoctypeName';
+
+ } elseif($char === '>') {
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif(preg_match('/^[a-z]$/', $char)) {
+ $this->token['name'] .= strtoupper($char);
+
+ } elseif($this->char === $this->EOF) {
+ $this->emitToken($this->token);
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ $this->token['name'] .= $char;
+ }
+
+ $this->token['error'] = ($this->token['name'] === 'HTML')
+ ? false
+ : true;
+ }
+
+ private function afterDoctypeNameState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+ // Stay in the DOCTYPE name state.
+
+ } elseif($char === '>') {
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($this->char === $this->EOF) {
+ $this->emitToken($this->token);
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ $this->token['error'] = true;
+ $this->state = 'bogusDoctype';
+ }
+ }
+
+ private function bogusDoctypeState() {
+ /* Consume the next input character: */
+ $this->char++;
+ $char = $this->char();
+
+ if($char === '>') {
+ $this->emitToken($this->token);
+ $this->state = 'data';
+
+ } elseif($this->char === $this->EOF) {
+ $this->emitToken($this->token);
+ $this->char--;
+ $this->state = 'data';
+
+ } else {
+ // Stay in the bogus DOCTYPE state.
+ }
+ }
+
+ private function entity() {
+ $start = $this->char;
+
+ // This section defines how to consume an entity. This definition is
+ // used when parsing entities in text and in attributes.
+
+ // The behaviour depends on the identity of the next character (the
+ // one immediately after the U+0026 AMPERSAND character):
+
+ switch($this->character($this->char + 1)) {
+ // U+0023 NUMBER SIGN (#)
+ case '#':
+
+ // The behaviour further depends on the character after the
+ // U+0023 NUMBER SIGN:
+ switch($this->character($this->char + 1)) {
+ // U+0078 LATIN SMALL LETTER X
+ // U+0058 LATIN CAPITAL LETTER X
+ case 'x':
+ case 'X':
+ // Follow the steps below, but using the range of
+ // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
+ // NINE, U+0061 LATIN SMALL LETTER A through to U+0066
+ // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER
+ // A, through to U+0046 LATIN CAPITAL LETTER F (in other
+ // words, 0-9, A-F, a-f).
+ $char = 1;
+ $char_class = '0-9A-Fa-f';
+ break;
+
+ // Anything else
+ default:
+ // Follow the steps below, but using the range of
+ // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
+ // NINE (i.e. just 0-9).
+ $char = 0;
+ $char_class = '0-9';
+ break;
+ }
+
+ // Consume as many characters as match the range of characters
+ // given above.
+ $this->char++;
+ $e_name = $this->characters($char_class, $this->char + $char + 1);
+ $entity = $this->character($start, $this->char);
+ $cond = strlen($e_name) > 0;
+
+ // The rest of the parsing happens bellow.
+ break;
+
+ // Anything else
+ default:
+ // Consume the maximum number of characters possible, with the
+ // consumed characters case-sensitively matching one of the
+ // identifiers in the first column of the entities table.
+ $e_name = $this->characters('0-9A-Za-z;', $this->char + 1);
+ $len = strlen($e_name);
+
+ for($c = 1; $c <= $len; $c++) {
+ $id = substr($e_name, 0, $c);
+ $this->char++;
+
+ if(in_array($id, $this->entities)) {
+ if ($e_name[$c-1] !== ';') {
+ if ($c < $len && $e_name[$c] == ';') {
+ $this->char++; // consume extra semicolon
+ }
+ }
+ $entity = $id;
+ break;
+ }
+ }
+
+ $cond = isset($entity);
+ // The rest of the parsing happens bellow.
+ break;
+ }
+
+ if(!$cond) {
+ // If no match can be made, then this is a parse error. No
+ // characters are consumed, and nothing is returned.
+ $this->char = $start;
+ return false;
+ }
+
+ // Return a character token for the character corresponding to the
+ // entity name (as given by the second column of the entities table).
+ return html_entity_decode('&'.$entity.';', ENT_QUOTES, 'UTF-8');
+ }
+
+ private function emitToken($token) {
+ $emit = $this->tree->emitToken($token);
+
+ if(is_int($emit)) {
+ $this->content_model = $emit;
+
+ } elseif($token['type'] === self::ENDTAG) {
+ $this->content_model = self::PCDATA;
+ }
+ }
+
+ private function EOF() {
+ $this->state = null;
+ $this->tree->emitToken(array(
+ 'type' => self::EOF
+ ));
+ }
+}
+
+class HTML5TreeConstructer {
+ public $stack = array();
+
+ private $phase;
+ private $mode;
+ private $dom;
+ private $foster_parent = null;
+ private $a_formatting = array();
+
+ private $head_pointer = null;
+ private $form_pointer = null;
+
+ private $scoping = array('button','caption','html','marquee','object','table','td','th');
+ private $formatting = array('a','b','big','em','font','i','nobr','s','small','strike','strong','tt','u');
+ private $special = array('address','area','base','basefont','bgsound',
+ 'blockquote','body','br','center','col','colgroup','dd','dir','div','dl',
+ 'dt','embed','fieldset','form','frame','frameset','h1','h2','h3','h4','h5',
+ 'h6','head','hr','iframe','image','img','input','isindex','li','link',
+ 'listing','menu','meta','noembed','noframes','noscript','ol','optgroup',
+ 'option','p','param','plaintext','pre','script','select','spacer','style',
+ 'tbody','textarea','tfoot','thead','title','tr','ul','wbr');
+
+ // The different phases.
+ const INIT_PHASE = 0;
+ const ROOT_PHASE = 1;
+ const MAIN_PHASE = 2;
+ const END_PHASE = 3;
+
+ // The different insertion modes for the main phase.
+ const BEFOR_HEAD = 0;
+ const IN_HEAD = 1;
+ const AFTER_HEAD = 2;
+ const IN_BODY = 3;
+ const IN_TABLE = 4;
+ const IN_CAPTION = 5;
+ const IN_CGROUP = 6;
+ const IN_TBODY = 7;
+ const IN_ROW = 8;
+ const IN_CELL = 9;
+ const IN_SELECT = 10;
+ const AFTER_BODY = 11;
+ const IN_FRAME = 12;
+ const AFTR_FRAME = 13;
+
+ // The different types of elements.
+ const SPECIAL = 0;
+ const SCOPING = 1;
+ const FORMATTING = 2;
+ const PHRASING = 3;
+
+ const MARKER = 0;
+
+ public function __construct() {
+ $this->phase = self::INIT_PHASE;
+ $this->mode = self::BEFOR_HEAD;
+ $this->dom = new DOMDocument;
+
+ $this->dom->encoding = 'UTF-8';
+ $this->dom->preserveWhiteSpace = true;
+ $this->dom->substituteEntities = true;
+ $this->dom->strictErrorChecking = false;
+ }
+
+ // Process tag tokens
+ public function emitToken($token) {
+ switch($this->phase) {
+ case self::INIT_PHASE: return $this->initPhase($token); break;
+ case self::ROOT_PHASE: return $this->rootElementPhase($token); break;
+ case self::MAIN_PHASE: return $this->mainPhase($token); break;
+ case self::END_PHASE : return $this->trailingEndPhase($token); break;
+ }
+ }
+
+ private function initPhase($token) {
+ /* Initially, the tree construction stage must handle each token
+ emitted from the tokenisation stage as follows: */
+
+ /* A DOCTYPE token that is marked as being in error
+ A comment token
+ A start tag token
+ An end tag token
+ A character token that is not one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE
+ An end-of-file token */
+ if((isset($token['error']) && $token['error']) ||
+ $token['type'] === HTML5::COMMENT ||
+ $token['type'] === HTML5::STARTTAG ||
+ $token['type'] === HTML5::ENDTAG ||
+ $token['type'] === HTML5::EOF ||
+ ($token['type'] === HTML5::CHARACTR && isset($token['data']) &&
+ !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']))) {
+ /* This specification does not define how to handle this case. In
+ particular, user agents may ignore the entirety of this specification
+ altogether for such documents, and instead invoke special parse modes
+ with a greater emphasis on backwards compatibility. */
+
+ $this->phase = self::ROOT_PHASE;
+ return $this->rootElementPhase($token);
+
+ /* A DOCTYPE token marked as being correct */
+ } elseif(isset($token['error']) && !$token['error']) {
+ /* Append a DocumentType node to the Document node, with the name
+ attribute set to the name given in the DOCTYPE token (which will be
+ "HTML"), and the other attributes specific to DocumentType objects
+ set to null, empty lists, or the empty string as appropriate. */
+ $doctype = new DOMDocumentType(null, null, 'HTML');
+
+ /* Then, switch to the root element phase of the tree construction
+ stage. */
+ $this->phase = self::ROOT_PHASE;
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ } elseif(isset($token['data']) && preg_match('/^[\t\n\x0b\x0c ]+$/',
+ $token['data'])) {
+ /* Append that character to the Document node. */
+ $text = $this->dom->createTextNode($token['data']);
+ $this->dom->appendChild($text);
+ }
+ }
+
+ private function rootElementPhase($token) {
+ /* After the initial phase, as each token is emitted from the tokenisation
+ stage, it must be processed as described in this section. */
+
+ /* A DOCTYPE token */
+ if($token['type'] === HTML5::DOCTYPE) {
+ // Parse error. Ignore the token.
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the Document object with the data
+ attribute set to the data given in the comment token. */
+ $comment = $this->dom->createComment($token['data']);
+ $this->dom->appendChild($comment);
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ } elseif($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append that character to the Document node. */
+ $text = $this->dom->createTextNode($token['data']);
+ $this->dom->appendChild($text);
+
+ /* A character token that is not one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED
+ (FF), or U+0020 SPACE
+ A start tag token
+ An end tag token
+ An end-of-file token */
+ } elseif(($token['type'] === HTML5::CHARACTR &&
+ !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
+ $token['type'] === HTML5::STARTTAG ||
+ $token['type'] === HTML5::ENDTAG ||
+ $token['type'] === HTML5::EOF) {
+ /* Create an HTMLElement node with the tag name html, in the HTML
+ namespace. Append it to the Document object. Switch to the main
+ phase and reprocess the current token. */
+ $html = $this->dom->createElement('html');
+ $this->dom->appendChild($html);
+ $this->stack[] = $html;
+
+ $this->phase = self::MAIN_PHASE;
+ return $this->mainPhase($token);
+ }
+ }
+
+ private function mainPhase($token) {
+ /* Tokens in the main phase must be handled as follows: */
+
+ /* A DOCTYPE token */
+ if($token['type'] === HTML5::DOCTYPE) {
+ // Parse error. Ignore the token.
+
+ /* A start tag token with the tag name "html" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') {
+ /* If this start tag token was not the first start tag token, then
+ it is a parse error. */
+
+ /* For each attribute on the token, check to see if the attribute
+ is already present on the top element of the stack of open elements.
+ If it is not, add the attribute and its corresponding value to that
+ element. */
+ foreach($token['attr'] as $attr) {
+ if(!$this->stack[0]->hasAttribute($attr['name'])) {
+ $this->stack[0]->setAttribute($attr['name'], $attr['value']);
+ }
+ }
+
+ /* An end-of-file token */
+ } elseif($token['type'] === HTML5::EOF) {
+ /* Generate implied end tags. */
+ $this->generateImpliedEndTags();
+
+ /* Anything else. */
+ } else {
+ /* Depends on the insertion mode: */
+ switch($this->mode) {
+ case self::BEFOR_HEAD: return $this->beforeHead($token); break;
+ case self::IN_HEAD: return $this->inHead($token); break;
+ case self::AFTER_HEAD: return $this->afterHead($token); break;
+ case self::IN_BODY: return $this->inBody($token); break;
+ case self::IN_TABLE: return $this->inTable($token); break;
+ case self::IN_CAPTION: return $this->inCaption($token); break;
+ case self::IN_CGROUP: return $this->inColumnGroup($token); break;
+ case self::IN_TBODY: return $this->inTableBody($token); break;
+ case self::IN_ROW: return $this->inRow($token); break;
+ case self::IN_CELL: return $this->inCell($token); break;
+ case self::IN_SELECT: return $this->inSelect($token); break;
+ case self::AFTER_BODY: return $this->afterBody($token); break;
+ case self::IN_FRAME: return $this->inFrameset($token); break;
+ case self::AFTR_FRAME: return $this->afterFrameset($token); break;
+ case self::END_PHASE: return $this->trailingEndPhase($token); break;
+ }
+ }
+ }
+
+ private function beforeHead($token) {
+ /* Handle the token as follows: */
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append the character to the current node. */
+ $this->insertText($token['data']);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data attribute
+ set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+
+ /* A start tag token with the tag name "head" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') {
+ /* Create an element for the token, append the new element to the
+ current node and push it onto the stack of open elements. */
+ $element = $this->insertElement($token);
+
+ /* Set the head element pointer to this new element node. */
+ $this->head_pointer = $element;
+
+ /* Change the insertion mode to "in head". */
+ $this->mode = self::IN_HEAD;
+
+ /* A start tag token whose tag name is one of: "base", "link", "meta",
+ "script", "style", "title". Or an end tag with the tag name "html".
+ Or a character token that is not one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE. Or any other start tag token */
+ } elseif($token['type'] === HTML5::STARTTAG ||
+ ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') ||
+ ($token['type'] === HTML5::CHARACTR && !preg_match('/^[\t\n\x0b\x0c ]$/',
+ $token['data']))) {
+ /* Act as if a start tag token with the tag name "head" and no
+ attributes had been seen, then reprocess the current token. */
+ $this->beforeHead(array(
+ 'name' => 'head',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ return $this->inHead($token);
+
+ /* Any other end tag */
+ } elseif($token['type'] === HTML5::ENDTAG) {
+ /* Parse error. Ignore the token. */
+ }
+ }
+
+ private function inHead($token) {
+ /* Handle the token as follows: */
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE.
+
+ THIS DIFFERS FROM THE SPEC: If the current node is either a title, style
+ or script element, append the character to the current node regardless
+ of its content. */
+ if(($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || (
+ $token['type'] === HTML5::CHARACTR && in_array(end($this->stack)->nodeName,
+ array('title', 'style', 'script')))) {
+ /* Append the character to the current node. */
+ $this->insertText($token['data']);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data attribute
+ set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ in_array($token['name'], array('title', 'style', 'script'))) {
+ array_pop($this->stack);
+ return HTML5::PCDATA;
+
+ /* A start tag with the tag name "title" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') {
+ /* Create an element for the token and append the new element to the
+ node pointed to by the head element pointer, or, if that is null
+ (innerHTML case), to the current node. */
+ if($this->head_pointer !== null) {
+ $element = $this->insertElement($token, false);
+ $this->head_pointer->appendChild($element);
+
+ } else {
+ $element = $this->insertElement($token);
+ }
+
+ /* Switch the tokeniser's content model flag to the RCDATA state. */
+ return HTML5::RCDATA;
+
+ /* A start tag with the tag name "style" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') {
+ /* Create an element for the token and append the new element to the
+ node pointed to by the head element pointer, or, if that is null
+ (innerHTML case), to the current node. */
+ if($this->head_pointer !== null) {
+ $element = $this->insertElement($token, false);
+ $this->head_pointer->appendChild($element);
+
+ } else {
+ $this->insertElement($token);
+ }
+
+ /* Switch the tokeniser's content model flag to the CDATA state. */
+ return HTML5::CDATA;
+
+ /* A start tag with the tag name "script" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') {
+ /* Create an element for the token. */
+ $element = $this->insertElement($token, false);
+ $this->head_pointer->appendChild($element);
+
+ /* Switch the tokeniser's content model flag to the CDATA state. */
+ return HTML5::CDATA;
+
+ /* A start tag with the tag name "base", "link", or "meta" */
+ } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('base', 'link', 'meta'))) {
+ /* Create an element for the token and append the new element to the
+ node pointed to by the head element pointer, or, if that is null
+ (innerHTML case), to the current node. */
+ if($this->head_pointer !== null) {
+ $element = $this->insertElement($token, false);
+ $this->head_pointer->appendChild($element);
+ array_pop($this->stack);
+
+ } else {
+ $this->insertElement($token);
+ }
+
+ /* An end tag with the tag name "head" */
+ } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') {
+ /* If the current node is a head element, pop the current node off
+ the stack of open elements. */
+ if($this->head_pointer->isSameNode(end($this->stack))) {
+ array_pop($this->stack);
+
+ /* Otherwise, this is a parse error. */
+ } else {
+ // k
+ }
+
+ /* Change the insertion mode to "after head". */
+ $this->mode = self::AFTER_HEAD;
+
+ /* A start tag with the tag name "head" or an end tag except "html". */
+ } elseif(($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') ||
+ ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html')) {
+ // Parse error. Ignore the token.
+
+ /* Anything else */
+ } else {
+ /* If the current node is a head element, act as if an end tag
+ token with the tag name "head" had been seen. */
+ if($this->head_pointer->isSameNode(end($this->stack))) {
+ $this->inHead(array(
+ 'name' => 'head',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ /* Otherwise, change the insertion mode to "after head". */
+ } else {
+ $this->mode = self::AFTER_HEAD;
+ }
+
+ /* Then, reprocess the current token. */
+ return $this->afterHead($token);
+ }
+ }
+
+ private function afterHead($token) {
+ /* Handle the token as follows: */
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append the character to the current node. */
+ $this->insertText($token['data']);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data attribute
+ set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+
+ /* A start tag token with the tag name "body" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') {
+ /* Insert a body element for the token. */
+ $this->insertElement($token);
+
+ /* Change the insertion mode to "in body". */
+ $this->mode = self::IN_BODY;
+
+ /* A start tag token with the tag name "frameset" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') {
+ /* Insert a frameset element for the token. */
+ $this->insertElement($token);
+
+ /* Change the insertion mode to "in frameset". */
+ $this->mode = self::IN_FRAME;
+
+ /* A start tag token whose tag name is one of: "base", "link", "meta",
+ "script", "style", "title" */
+ } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('base', 'link', 'meta', 'script', 'style', 'title'))) {
+ /* Parse error. Switch the insertion mode back to "in head" and
+ reprocess the token. */
+ $this->mode = self::IN_HEAD;
+ return $this->inHead($token);
+
+ /* Anything else */
+ } else {
+ /* Act as if a start tag token with the tag name "body" and no
+ attributes had been seen, and then reprocess the current token. */
+ $this->afterHead(array(
+ 'name' => 'body',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ return $this->inBody($token);
+ }
+ }
+
+ private function inBody($token) {
+ /* Handle the token as follows: */
+
+ switch($token['type']) {
+ /* A character token */
+ case HTML5::CHARACTR:
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Append the token's character to the current node. */
+ $this->insertText($token['data']);
+ break;
+
+ /* A comment token */
+ case HTML5::COMMENT:
+ /* Append a Comment node to the current node with the data
+ attribute set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+ break;
+
+ case HTML5::STARTTAG:
+ switch($token['name']) {
+ /* A start tag token whose tag name is one of: "script",
+ "style" */
+ case 'script': case 'style':
+ /* Process the token as if the insertion mode had been "in
+ head". */
+ return $this->inHead($token);
+ break;
+
+ /* A start tag token whose tag name is one of: "base", "link",
+ "meta", "title" */
+ case 'base': case 'link': case 'meta': case 'title':
+ /* Parse error. Process the token as if the insertion mode
+ had been "in head". */
+ return $this->inHead($token);
+ break;
+
+ /* A start tag token with the tag name "body" */
+ case 'body':
+ /* Parse error. If the second element on the stack of open
+ elements is not a body element, or, if the stack of open
+ elements has only one node on it, then ignore the token.
+ (innerHTML case) */
+ if(count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') {
+ // Ignore
+
+ /* Otherwise, for each attribute on the token, check to see
+ if the attribute is already present on the body element (the
+ second element) on the stack of open elements. If it is not,
+ add the attribute and its corresponding value to that
+ element. */
+ } else {
+ foreach($token['attr'] as $attr) {
+ if(!$this->stack[1]->hasAttribute($attr['name'])) {
+ $this->stack[1]->setAttribute($attr['name'], $attr['value']);
+ }
+ }
+ }
+ break;
+
+ /* A start tag whose tag name is one of: "address",
+ "blockquote", "center", "dir", "div", "dl", "fieldset",
+ "listing", "menu", "ol", "p", "ul" */
+ case 'address': case 'blockquote': case 'center': case 'dir':
+ case 'div': case 'dl': case 'fieldset': case 'listing':
+ case 'menu': case 'ol': case 'p': case 'ul':
+ /* If the stack of open elements has a p element in scope,
+ then act as if an end tag with the tag name p had been
+ seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+ break;
+
+ /* A start tag whose tag name is "form" */
+ case 'form':
+ /* If the form element pointer is not null, ignore the
+ token with a parse error. */
+ if($this->form_pointer !== null) {
+ // Ignore.
+
+ /* Otherwise: */
+ } else {
+ /* If the stack of open elements has a p element in
+ scope, then act as if an end tag with the tag name p
+ had been seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token, and set the
+ form element pointer to point to the element created. */
+ $element = $this->insertElement($token);
+ $this->form_pointer = $element;
+ }
+ break;
+
+ /* A start tag whose tag name is "li", "dd" or "dt" */
+ case 'li': case 'dd': case 'dt':
+ /* If the stack of open elements has a p element in scope,
+ then act as if an end tag with the tag name p had been
+ seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ $stack_length = count($this->stack) - 1;
+
+ for($n = $stack_length; 0 <= $n; $n--) {
+ /* 1. Initialise node to be the current node (the
+ bottommost node of the stack). */
+ $stop = false;
+ $node = $this->stack[$n];
+ $cat = $this->getElementCategory($node->tagName);
+
+ /* 2. If node is an li, dd or dt element, then pop all
+ the nodes from the current node up to node, including
+ node, then stop this algorithm. */
+ if($token['name'] === $node->tagName || ($token['name'] !== 'li'
+ && ($node->tagName === 'dd' || $node->tagName === 'dt'))) {
+ for($x = $stack_length; $x >= $n ; $x--) {
+ array_pop($this->stack);
+ }
+
+ break;
+ }
+
+ /* 3. If node is not in the formatting category, and is
+ not in the phrasing category, and is not an address or
+ div element, then stop this algorithm. */
+ if($cat !== self::FORMATTING && $cat !== self::PHRASING &&
+ $node->tagName !== 'address' && $node->tagName !== 'div') {
+ break;
+ }
+ }
+
+ /* Finally, insert an HTML element with the same tag
+ name as the token's. */
+ $this->insertElement($token);
+ break;
+
+ /* A start tag token whose tag name is "plaintext" */
+ case 'plaintext':
+ /* If the stack of open elements has a p element in scope,
+ then act as if an end tag with the tag name p had been
+ seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ return HTML5::PLAINTEXT;
+ break;
+
+ /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4",
+ "h5", "h6" */
+ case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
+ /* If the stack of open elements has a p element in scope,
+ then act as if an end tag with the tag name p had been seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* If the stack of open elements has in scope an element whose
+ tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
+ this is a parse error; pop elements from the stack until an
+ element with one of those tag names has been popped from the
+ stack. */
+ while($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) {
+ array_pop($this->stack);
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+ break;
+
+ /* A start tag whose tag name is "a" */
+ case 'a':
+ /* If the list of active formatting elements contains
+ an element whose tag name is "a" between the end of the
+ list and the last marker on the list (or the start of
+ the list if there is no marker on the list), then this
+ is a parse error; act as if an end tag with the tag name
+ "a" had been seen, then remove that element from the list
+ of active formatting elements and the stack of open
+ elements if the end tag didn't already remove it (it
+ might not have if the element is not in table scope). */
+ $leng = count($this->a_formatting);
+
+ for($n = $leng - 1; $n >= 0; $n--) {
+ if($this->a_formatting[$n] === self::MARKER) {
+ break;
+
+ } elseif($this->a_formatting[$n]->nodeName === 'a') {
+ $this->emitToken(array(
+ 'name' => 'a',
+ 'type' => HTML5::ENDTAG
+ ));
+ break;
+ }
+ }
+
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $el = $this->insertElement($token);
+
+ /* Add that element to the list of active formatting
+ elements. */
+ $this->a_formatting[] = $el;
+ break;
+
+ /* A start tag whose tag name is one of: "b", "big", "em", "font",
+ "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
+ case 'b': case 'big': case 'em': case 'font': case 'i':
+ case 'nobr': case 's': case 'small': case 'strike':
+ case 'strong': case 'tt': case 'u':
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $el = $this->insertElement($token);
+
+ /* Add that element to the list of active formatting
+ elements. */
+ $this->a_formatting[] = $el;
+ break;
+
+ /* A start tag token whose tag name is "button" */
+ case 'button':
+ /* If the stack of open elements has a button element in scope,
+ then this is a parse error; act as if an end tag with the tag
+ name "button" had been seen, then reprocess the token. (We don't
+ do that. Unnecessary.) */
+ if($this->elementInScope('button')) {
+ $this->inBody(array(
+ 'name' => 'button',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Insert a marker at the end of the list of active
+ formatting elements. */
+ $this->a_formatting[] = self::MARKER;
+ break;
+
+ /* A start tag token whose tag name is one of: "marquee", "object" */
+ case 'marquee': case 'object':
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Insert a marker at the end of the list of active
+ formatting elements. */
+ $this->a_formatting[] = self::MARKER;
+ break;
+
+ /* A start tag token whose tag name is "xmp" */
+ case 'xmp':
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Switch the content model flag to the CDATA state. */
+ return HTML5::CDATA;
+ break;
+
+ /* A start tag whose tag name is "table" */
+ case 'table':
+ /* If the stack of open elements has a p element in scope,
+ then act as if an end tag with the tag name p had been seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Change the insertion mode to "in table". */
+ $this->mode = self::IN_TABLE;
+ break;
+
+ /* A start tag whose tag name is one of: "area", "basefont",
+ "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */
+ case 'area': case 'basefont': case 'bgsound': case 'br':
+ case 'embed': case 'img': case 'param': case 'spacer':
+ case 'wbr':
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Immediately pop the current node off the stack of open elements. */
+ array_pop($this->stack);
+ break;
+
+ /* A start tag whose tag name is "hr" */
+ case 'hr':
+ /* If the stack of open elements has a p element in scope,
+ then act as if an end tag with the tag name p had been seen. */
+ if($this->elementInScope('p')) {
+ $this->emitToken(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Immediately pop the current node off the stack of open elements. */
+ array_pop($this->stack);
+ break;
+
+ /* A start tag whose tag name is "image" */
+ case 'image':
+ /* Parse error. Change the token's tag name to "img" and
+ reprocess it. (Don't ask.) */
+ $token['name'] = 'img';
+ return $this->inBody($token);
+ break;
+
+ /* A start tag whose tag name is "input" */
+ case 'input':
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an input element for the token. */
+ $element = $this->insertElement($token, false);
+
+ /* If the form element pointer is not null, then associate the
+ input element with the form element pointed to by the form
+ element pointer. */
+ $this->form_pointer !== null
+ ? $this->form_pointer->appendChild($element)
+ : end($this->stack)->appendChild($element);
+
+ /* Pop that input element off the stack of open elements. */
+ array_pop($this->stack);
+ break;
+
+ /* A start tag whose tag name is "isindex" */
+ case 'isindex':
+ /* Parse error. */
+ // w/e
+
+ /* If the form element pointer is not null,
+ then ignore the token. */
+ if($this->form_pointer === null) {
+ /* Act as if a start tag token with the tag name "form" had
+ been seen. */
+ $this->inBody(array(
+ 'name' => 'body',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ /* Act as if a start tag token with the tag name "hr" had
+ been seen. */
+ $this->inBody(array(
+ 'name' => 'hr',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ /* Act as if a start tag token with the tag name "p" had
+ been seen. */
+ $this->inBody(array(
+ 'name' => 'p',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ /* Act as if a start tag token with the tag name "label"
+ had been seen. */
+ $this->inBody(array(
+ 'name' => 'label',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ /* Act as if a stream of character tokens had been seen. */
+ $this->insertText('This is a searchable index. '.
+ 'Insert your search keywords here: ');
+
+ /* Act as if a start tag token with the tag name "input"
+ had been seen, with all the attributes from the "isindex"
+ token, except with the "name" attribute set to the value
+ "isindex" (ignoring any explicit "name" attribute). */
+ $attr = $token['attr'];
+ $attr[] = array('name' => 'name', 'value' => 'isindex');
+
+ $this->inBody(array(
+ 'name' => 'input',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => $attr
+ ));
+
+ /* Act as if a stream of character tokens had been seen
+ (see below for what they should say). */
+ $this->insertText('This is a searchable index. '.
+ 'Insert your search keywords here: ');
+
+ /* Act as if an end tag token with the tag name "label"
+ had been seen. */
+ $this->inBody(array(
+ 'name' => 'label',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ /* Act as if an end tag token with the tag name "p" had
+ been seen. */
+ $this->inBody(array(
+ 'name' => 'p',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ /* Act as if a start tag token with the tag name "hr" had
+ been seen. */
+ $this->inBody(array(
+ 'name' => 'hr',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ /* Act as if an end tag token with the tag name "form" had
+ been seen. */
+ $this->inBody(array(
+ 'name' => 'form',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+ break;
+
+ /* A start tag whose tag name is "textarea" */
+ case 'textarea':
+ $this->insertElement($token);
+
+ /* Switch the tokeniser's content model flag to the
+ RCDATA state. */
+ return HTML5::RCDATA;
+ break;
+
+ /* A start tag whose tag name is one of: "iframe", "noembed",
+ "noframes" */
+ case 'iframe': case 'noembed': case 'noframes':
+ $this->insertElement($token);
+
+ /* Switch the tokeniser's content model flag to the CDATA state. */
+ return HTML5::CDATA;
+ break;
+
+ /* A start tag whose tag name is "select" */
+ case 'select':
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Change the insertion mode to "in select". */
+ $this->mode = self::IN_SELECT;
+ break;
+
+ /* A start or end tag whose tag name is one of: "caption", "col",
+ "colgroup", "frame", "frameset", "head", "option", "optgroup",
+ "tbody", "td", "tfoot", "th", "thead", "tr". */
+ case 'caption': case 'col': case 'colgroup': case 'frame':
+ case 'frameset': case 'head': case 'option': case 'optgroup':
+ case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead':
+ case 'tr':
+ // Parse error. Ignore the token.
+ break;
+
+ /* A start or end tag whose tag name is one of: "event-source",
+ "section", "nav", "article", "aside", "header", "footer",
+ "datagrid", "command" */
+ case 'event-source': case 'section': case 'nav': case 'article':
+ case 'aside': case 'header': case 'footer': case 'datagrid':
+ case 'command':
+ // Work in progress!
+ break;
+
+ /* A start tag token not covered by the previous entries */
+ default:
+ /* Reconstruct the active formatting elements, if any. */
+ $this->reconstructActiveFormattingElements();
+
+ $this->insertElement($token, true, true);
+ break;
+ }
+ break;
+
+ case HTML5::ENDTAG:
+ switch($token['name']) {
+ /* An end tag with the tag name "body" */
+ case 'body':
+ /* If the second element in the stack of open elements is
+ not a body element, this is a parse error. Ignore the token.
+ (innerHTML case) */
+ if(count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') {
+ // Ignore.
+
+ /* If the current node is not the body element, then this
+ is a parse error. */
+ } elseif(end($this->stack)->nodeName !== 'body') {
+ // Parse error.
+ }
+
+ /* Change the insertion mode to "after body". */
+ $this->mode = self::AFTER_BODY;
+ break;
+
+ /* An end tag with the tag name "html" */
+ case 'html':
+ /* Act as if an end tag with tag name "body" had been seen,
+ then, if that token wasn't ignored, reprocess the current
+ token. */
+ $this->inBody(array(
+ 'name' => 'body',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->afterBody($token);
+ break;
+
+ /* An end tag whose tag name is one of: "address", "blockquote",
+ "center", "dir", "div", "dl", "fieldset", "listing", "menu",
+ "ol", "pre", "ul" */
+ case 'address': case 'blockquote': case 'center': case 'dir':
+ case 'div': case 'dl': case 'fieldset': case 'listing':
+ case 'menu': case 'ol': case 'pre': case 'ul':
+ /* If the stack of open elements has an element in scope
+ with the same tag name as that of the token, then generate
+ implied end tags. */
+ if($this->elementInScope($token['name'])) {
+ $this->generateImpliedEndTags();
+
+ /* Now, if the current node is not an element with
+ the same tag name as that of the token, then this
+ is a parse error. */
+ // w/e
+
+ /* If the stack of open elements has an element in
+ scope with the same tag name as that of the token,
+ then pop elements from this stack until an element
+ with that tag name has been popped from the stack. */
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ if($this->stack[$n]->nodeName === $token['name']) {
+ $n = -1;
+ }
+
+ array_pop($this->stack);
+ }
+ }
+ break;
+
+ /* An end tag whose tag name is "form" */
+ case 'form':
+ /* If the stack of open elements has an element in scope
+ with the same tag name as that of the token, then generate
+ implied end tags. */
+ if($this->elementInScope($token['name'])) {
+ $this->generateImpliedEndTags();
+
+ }
+
+ if(end($this->stack)->nodeName !== $token['name']) {
+ /* Now, if the current node is not an element with the
+ same tag name as that of the token, then this is a parse
+ error. */
+ // w/e
+
+ } else {
+ /* Otherwise, if the current node is an element with
+ the same tag name as that of the token pop that element
+ from the stack. */
+ array_pop($this->stack);
+ }
+
+ /* In any case, set the form element pointer to null. */
+ $this->form_pointer = null;
+ break;
+
+ /* An end tag whose tag name is "p" */
+ case 'p':
+ /* If the stack of open elements has a p element in scope,
+ then generate implied end tags, except for p elements. */
+ if($this->elementInScope('p')) {
+ $this->generateImpliedEndTags(array('p'));
+
+ /* If the current node is not a p element, then this is
+ a parse error. */
+ // k
+
+ /* If the stack of open elements has a p element in
+ scope, then pop elements from this stack until the stack
+ no longer has a p element in scope. */
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ if($this->elementInScope('p')) {
+ array_pop($this->stack);
+
+ } else {
+ break;
+ }
+ }
+ }
+ break;
+
+ /* An end tag whose tag name is "dd", "dt", or "li" */
+ case 'dd': case 'dt': case 'li':
+ /* If the stack of open elements has an element in scope
+ whose tag name matches the tag name of the token, then
+ generate implied end tags, except for elements with the
+ same tag name as the token. */
+ if($this->elementInScope($token['name'])) {
+ $this->generateImpliedEndTags(array($token['name']));
+
+ /* If the current node is not an element with the same
+ tag name as the token, then this is a parse error. */
+ // w/e
+
+ /* If the stack of open elements has an element in scope
+ whose tag name matches the tag name of the token, then
+ pop elements from this stack until an element with that
+ tag name has been popped from the stack. */
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ if($this->stack[$n]->nodeName === $token['name']) {
+ $n = -1;
+ }
+
+ array_pop($this->stack);
+ }
+ }
+ break;
+
+ /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4",
+ "h5", "h6" */
+ case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
+ $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
+
+ /* If the stack of open elements has in scope an element whose
+ tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
+ generate implied end tags. */
+ if($this->elementInScope($elements)) {
+ $this->generateImpliedEndTags();
+
+ /* Now, if the current node is not an element with the same
+ tag name as that of the token, then this is a parse error. */
+ // w/e
+
+ /* If the stack of open elements has in scope an element
+ whose tag name is one of "h1", "h2", "h3", "h4", "h5", or
+ "h6", then pop elements from the stack until an element
+ with one of those tag names has been popped from the stack. */
+ while($this->elementInScope($elements)) {
+ array_pop($this->stack);
+ }
+ }
+ break;
+
+ /* An end tag whose tag name is one of: "a", "b", "big", "em",
+ "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
+ case 'a': case 'b': case 'big': case 'em': case 'font':
+ case 'i': case 'nobr': case 's': case 'small': case 'strike':
+ case 'strong': case 'tt': case 'u':
+ /* 1. Let the formatting element be the last element in
+ the list of active formatting elements that:
+ * is between the end of the list and the last scope
+ marker in the list, if any, or the start of the list
+ otherwise, and
+ * has the same tag name as the token.
+ */
+ while(true) {
+ for($a = count($this->a_formatting) - 1; $a >= 0; $a--) {
+ if($this->a_formatting[$a] === self::MARKER) {
+ break;
+
+ } elseif($this->a_formatting[$a]->tagName === $token['name']) {
+ $formatting_element = $this->a_formatting[$a];
+ $in_stack = in_array($formatting_element, $this->stack, true);
+ $fe_af_pos = $a;
+ break;
+ }
+ }
+
+ /* If there is no such node, or, if that node is
+ also in the stack of open elements but the element
+ is not in scope, then this is a parse error. Abort
+ these steps. The token is ignored. */
+ if(!isset($formatting_element) || ($in_stack &&
+ !$this->elementInScope($token['name']))) {
+ break;
+
+ /* Otherwise, if there is such a node, but that node
+ is not in the stack of open elements, then this is a
+ parse error; remove the element from the list, and
+ abort these steps. */
+ } elseif(isset($formatting_element) && !$in_stack) {
+ unset($this->a_formatting[$fe_af_pos]);
+ $this->a_formatting = array_merge($this->a_formatting);
+ break;
+ }
+
+ /* 2. Let the furthest block be the topmost node in the
+ stack of open elements that is lower in the stack
+ than the formatting element, and is not an element in
+ the phrasing or formatting categories. There might
+ not be one. */
+ $fe_s_pos = array_search($formatting_element, $this->stack, true);
+ $length = count($this->stack);
+
+ for($s = $fe_s_pos + 1; $s < $length; $s++) {
+ $category = $this->getElementCategory($this->stack[$s]->nodeName);
+
+ if($category !== self::PHRASING && $category !== self::FORMATTING) {
+ $furthest_block = $this->stack[$s];
+ }
+ }
+
+ /* 3. If there is no furthest block, then the UA must
+ skip the subsequent steps and instead just pop all
+ the nodes from the bottom of the stack of open
+ elements, from the current node up to the formatting
+ element, and remove the formatting element from the
+ list of active formatting elements. */
+ if(!isset($furthest_block)) {
+ for($n = $length - 1; $n >= $fe_s_pos; $n--) {
+ array_pop($this->stack);
+ }
+
+ unset($this->a_formatting[$fe_af_pos]);
+ $this->a_formatting = array_merge($this->a_formatting);
+ break;
+ }
+
+ /* 4. Let the common ancestor be the element
+ immediately above the formatting element in the stack
+ of open elements. */
+ $common_ancestor = $this->stack[$fe_s_pos - 1];
+
+ /* 5. If the furthest block has a parent node, then
+ remove the furthest block from its parent node. */
+ if($furthest_block->parentNode !== null) {
+ $furthest_block->parentNode->removeChild($furthest_block);
+ }
+
+ /* 6. Let a bookmark note the position of the
+ formatting element in the list of active formatting
+ elements relative to the elements on either side
+ of it in the list. */
+ $bookmark = $fe_af_pos;
+
+ /* 7. Let node and last node be the furthest block.
+ Follow these steps: */
+ $node = $furthest_block;
+ $last_node = $furthest_block;
+
+ while(true) {
+ for($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) {
+ /* 7.1 Let node be the element immediately
+ prior to node in the stack of open elements. */
+ $node = $this->stack[$n];
+
+ /* 7.2 If node is not in the list of active
+ formatting elements, then remove node from
+ the stack of open elements and then go back
+ to step 1. */
+ if(!in_array($node, $this->a_formatting, true)) {
+ unset($this->stack[$n]);
+ $this->stack = array_merge($this->stack);
+
+ } else {
+ break;
+ }
+ }
+
+ /* 7.3 Otherwise, if node is the formatting
+ element, then go to the next step in the overall
+ algorithm. */
+ if($node === $formatting_element) {
+ break;
+
+ /* 7.4 Otherwise, if last node is the furthest
+ block, then move the aforementioned bookmark to
+ be immediately after the node in the list of
+ active formatting elements. */
+ } elseif($last_node === $furthest_block) {
+ $bookmark = array_search($node, $this->a_formatting, true) + 1;
+ }
+
+ /* 7.5 If node has any children, perform a
+ shallow clone of node, replace the entry for
+ node in the list of active formatting elements
+ with an entry for the clone, replace the entry
+ for node in the stack of open elements with an
+ entry for the clone, and let node be the clone. */
+ if($node->hasChildNodes()) {
+ $clone = $node->cloneNode();
+ $s_pos = array_search($node, $this->stack, true);
+ $a_pos = array_search($node, $this->a_formatting, true);
+
+ $this->stack[$s_pos] = $clone;
+ $this->a_formatting[$a_pos] = $clone;
+ $node = $clone;
+ }
+
+ /* 7.6 Insert last node into node, first removing
+ it from its previous parent node if any. */
+ if($last_node->parentNode !== null) {
+ $last_node->parentNode->removeChild($last_node);
+ }
+
+ $node->appendChild($last_node);
+
+ /* 7.7 Let last node be node. */
+ $last_node = $node;
+ }
+
+ /* 8. Insert whatever last node ended up being in
+ the previous step into the common ancestor node,
+ first removing it from its previous parent node if
+ any. */
+ if($last_node->parentNode !== null) {
+ $last_node->parentNode->removeChild($last_node);
+ }
+
+ $common_ancestor->appendChild($last_node);
+
+ /* 9. Perform a shallow clone of the formatting
+ element. */
+ $clone = $formatting_element->cloneNode();
+
+ /* 10. Take all of the child nodes of the furthest
+ block and append them to the clone created in the
+ last step. */
+ while($furthest_block->hasChildNodes()) {
+ $child = $furthest_block->firstChild;
+ $furthest_block->removeChild($child);
+ $clone->appendChild($child);
+ }
+
+ /* 11. Append that clone to the furthest block. */
+ $furthest_block->appendChild($clone);
+
+ /* 12. Remove the formatting element from the list
+ of active formatting elements, and insert the clone
+ into the list of active formatting elements at the
+ position of the aforementioned bookmark. */
+ $fe_af_pos = array_search($formatting_element, $this->a_formatting, true);
+ unset($this->a_formatting[$fe_af_pos]);
+ $this->a_formatting = array_merge($this->a_formatting);
+
+ $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1);
+ $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting));
+ $this->a_formatting = array_merge($af_part1, array($clone), $af_part2);
+
+ /* 13. Remove the formatting element from the stack
+ of open elements, and insert the clone into the stack
+ of open elements immediately after (i.e. in a more
+ deeply nested position than) the position of the
+ furthest block in that stack. */
+ $fe_s_pos = array_search($formatting_element, $this->stack, true);
+ $fb_s_pos = array_search($furthest_block, $this->stack, true);
+ unset($this->stack[$fe_s_pos]);
+
+ $s_part1 = array_slice($this->stack, 0, $fb_s_pos);
+ $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack));
+ $this->stack = array_merge($s_part1, array($clone), $s_part2);
+
+ /* 14. Jump back to step 1 in this series of steps. */
+ unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block);
+ }
+ break;
+
+ /* An end tag token whose tag name is one of: "button",
+ "marquee", "object" */
+ case 'button': case 'marquee': case 'object':
+ /* If the stack of open elements has an element in scope whose
+ tag name matches the tag name of the token, then generate implied
+ tags. */
+ if($this->elementInScope($token['name'])) {
+ $this->generateImpliedEndTags();
+
+ /* Now, if the current node is not an element with the same
+ tag name as the token, then this is a parse error. */
+ // k
+
+ /* Now, if the stack of open elements has an element in scope
+ whose tag name matches the tag name of the token, then pop
+ elements from the stack until that element has been popped from
+ the stack, and clear the list of active formatting elements up
+ to the last marker. */
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ if($this->stack[$n]->nodeName === $token['name']) {
+ $n = -1;
+ }
+
+ array_pop($this->stack);
+ }
+
+ $marker = end(array_keys($this->a_formatting, self::MARKER, true));
+
+ for($n = count($this->a_formatting) - 1; $n > $marker; $n--) {
+ array_pop($this->a_formatting);
+ }
+ }
+ break;
+
+ /* Or an end tag whose tag name is one of: "area", "basefont",
+ "bgsound", "br", "embed", "hr", "iframe", "image", "img",
+ "input", "isindex", "noembed", "noframes", "param", "select",
+ "spacer", "table", "textarea", "wbr" */
+ case 'area': case 'basefont': case 'bgsound': case 'br':
+ case 'embed': case 'hr': case 'iframe': case 'image':
+ case 'img': case 'input': case 'isindex': case 'noembed':
+ case 'noframes': case 'param': case 'select': case 'spacer':
+ case 'table': case 'textarea': case 'wbr':
+ // Parse error. Ignore the token.
+ break;
+
+ /* An end tag token not covered by the previous entries */
+ default:
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ /* Initialise node to be the current node (the bottommost
+ node of the stack). */
+ $node = end($this->stack);
+
+ /* If node has the same tag name as the end tag token,
+ then: */
+ if($token['name'] === $node->nodeName) {
+ /* Generate implied end tags. */
+ $this->generateImpliedEndTags();
+
+ /* If the tag name of the end tag token does not
+ match the tag name of the current node, this is a
+ parse error. */
+ // k
+
+ /* Pop all the nodes from the current node up to
+ node, including node, then stop this algorithm. */
+ for($x = count($this->stack) - $n; $x >= $n; $x--) {
+ array_pop($this->stack);
+ }
+
+ } else {
+ $category = $this->getElementCategory($node);
+
+ if($category !== self::SPECIAL && $category !== self::SCOPING) {
+ /* Otherwise, if node is in neither the formatting
+ category nor the phrasing category, then this is a
+ parse error. Stop this algorithm. The end tag token
+ is ignored. */
+ return false;
+ }
+ }
+ }
+ break;
+ }
+ break;
+ }
+ }
+
+ private function inTable($token) {
+ $clear = array('html', 'table');
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append the character to the current node. */
+ $text = $this->dom->createTextNode($token['data']);
+ end($this->stack)->appendChild($text);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data
+ attribute set to the data given in the comment token. */
+ $comment = $this->dom->createComment($token['data']);
+ end($this->stack)->appendChild($comment);
+
+ /* A start tag whose tag name is "caption" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ $token['name'] === 'caption') {
+ /* Clear the stack back to a table context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Insert a marker at the end of the list of active
+ formatting elements. */
+ $this->a_formatting[] = self::MARKER;
+
+ /* Insert an HTML element for the token, then switch the
+ insertion mode to "in caption". */
+ $this->insertElement($token);
+ $this->mode = self::IN_CAPTION;
+
+ /* A start tag whose tag name is "colgroup" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ $token['name'] === 'colgroup') {
+ /* Clear the stack back to a table context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Insert an HTML element for the token, then switch the
+ insertion mode to "in column group". */
+ $this->insertElement($token);
+ $this->mode = self::IN_CGROUP;
+
+ /* A start tag whose tag name is "col" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ $token['name'] === 'col') {
+ $this->inTable(array(
+ 'name' => 'colgroup',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ $this->inColumnGroup($token);
+
+ /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */
+ } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('tbody', 'tfoot', 'thead'))) {
+ /* Clear the stack back to a table context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Insert an HTML element for the token, then switch the insertion
+ mode to "in table body". */
+ $this->insertElement($token);
+ $this->mode = self::IN_TBODY;
+
+ /* A start tag whose tag name is one of: "td", "th", "tr" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ in_array($token['name'], array('td', 'th', 'tr'))) {
+ /* Act as if a start tag token with the tag name "tbody" had been
+ seen, then reprocess the current token. */
+ $this->inTable(array(
+ 'name' => 'tbody',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ return $this->inTableBody($token);
+
+ /* A start tag whose tag name is "table" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ $token['name'] === 'table') {
+ /* Parse error. Act as if an end tag token with the tag name "table"
+ had been seen, then, if that token wasn't ignored, reprocess the
+ current token. */
+ $this->inTable(array(
+ 'name' => 'table',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->mainPhase($token);
+
+ /* An end tag whose tag name is "table" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ $token['name'] === 'table') {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as the token, this is a parse error.
+ Ignore the token. (innerHTML case) */
+ if(!$this->elementInScope($token['name'], true)) {
+ return false;
+
+ /* Otherwise: */
+ } else {
+ /* Generate implied end tags. */
+ $this->generateImpliedEndTags();
+
+ /* Now, if the current node is not a table element, then this
+ is a parse error. */
+ // w/e
+
+ /* Pop elements from this stack until a table element has been
+ popped from the stack. */
+ while(true) {
+ $current = end($this->stack)->nodeName;
+ array_pop($this->stack);
+
+ if($current === 'table') {
+ break;
+ }
+ }
+
+ /* Reset the insertion mode appropriately. */
+ $this->resetInsertionMode();
+ }
+
+ /* An end tag whose tag name is one of: "body", "caption", "col",
+ "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
+ } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+ array('body', 'caption', 'col', 'colgroup', 'html', 'tbody', 'td',
+ 'tfoot', 'th', 'thead', 'tr'))) {
+ // Parse error. Ignore the token.
+
+ /* Anything else */
+ } else {
+ /* Parse error. Process the token as if the insertion mode was "in
+ body", with the following exception: */
+
+ /* If the current node is a table, tbody, tfoot, thead, or tr
+ element, then, whenever a node would be inserted into the current
+ node, it must instead be inserted into the foster parent element. */
+ if(in_array(end($this->stack)->nodeName,
+ array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
+ /* The foster parent element is the parent element of the last
+ table element in the stack of open elements, if there is a
+ table element and it has such a parent element. If there is no
+ table element in the stack of open elements (innerHTML case),
+ then the foster parent element is the first element in the
+ stack of open elements (the html element). Otherwise, if there
+ is a table element in the stack of open elements, but the last
+ table element in the stack of open elements has no parent, or
+ its parent node is not an element, then the foster parent
+ element is the element before the last table element in the
+ stack of open elements. */
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ if($this->stack[$n]->nodeName === 'table') {
+ $table = $this->stack[$n];
+ break;
+ }
+ }
+
+ if(isset($table) && $table->parentNode !== null) {
+ $this->foster_parent = $table->parentNode;
+
+ } elseif(!isset($table)) {
+ $this->foster_parent = $this->stack[0];
+
+ } elseif(isset($table) && ($table->parentNode === null ||
+ $table->parentNode->nodeType !== XML_ELEMENT_NODE)) {
+ $this->foster_parent = $this->stack[$n - 1];
+ }
+ }
+
+ $this->inBody($token);
+ }
+ }
+
+ private function inCaption($token) {
+ /* An end tag whose tag name is "caption" */
+ if($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as the token, this is a parse error.
+ Ignore the token. (innerHTML case) */
+ if(!$this->elementInScope($token['name'], true)) {
+ // Ignore
+
+ /* Otherwise: */
+ } else {
+ /* Generate implied end tags. */
+ $this->generateImpliedEndTags();
+
+ /* Now, if the current node is not a caption element, then this
+ is a parse error. */
+ // w/e
+
+ /* Pop elements from this stack until a caption element has
+ been popped from the stack. */
+ while(true) {
+ $node = end($this->stack)->nodeName;
+ array_pop($this->stack);
+
+ if($node === 'caption') {
+ break;
+ }
+ }
+
+ /* Clear the list of active formatting elements up to the last
+ marker. */
+ $this->clearTheActiveFormattingElementsUpToTheLastMarker();
+
+ /* Switch the insertion mode to "in table". */
+ $this->mode = self::IN_TABLE;
+ }
+
+ /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+ "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag
+ name is "table" */
+ } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+ 'thead', 'tr'))) || ($token['type'] === HTML5::ENDTAG &&
+ $token['name'] === 'table')) {
+ /* Parse error. Act as if an end tag with the tag name "caption"
+ had been seen, then, if that token wasn't ignored, reprocess the
+ current token. */
+ $this->inCaption(array(
+ 'name' => 'caption',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->inTable($token);
+
+ /* An end tag whose tag name is one of: "body", "col", "colgroup",
+ "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
+ } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+ array('body', 'col', 'colgroup', 'html', 'tbody', 'tfoot', 'th',
+ 'thead', 'tr'))) {
+ // Parse error. Ignore the token.
+
+ /* Anything else */
+ } else {
+ /* Process the token as if the insertion mode was "in body". */
+ $this->inBody($token);
+ }
+ }
+
+ private function inColumnGroup($token) {
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append the character to the current node. */
+ $text = $this->dom->createTextNode($token['data']);
+ end($this->stack)->appendChild($text);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data
+ attribute set to the data given in the comment token. */
+ $comment = $this->dom->createComment($token['data']);
+ end($this->stack)->appendChild($comment);
+
+ /* A start tag whose tag name is "col" */
+ } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') {
+ /* Insert a col element for the token. Immediately pop the current
+ node off the stack of open elements. */
+ $this->insertElement($token);
+ array_pop($this->stack);
+
+ /* An end tag whose tag name is "colgroup" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ $token['name'] === 'colgroup') {
+ /* If the current node is the root html element, then this is a
+ parse error, ignore the token. (innerHTML case) */
+ if(end($this->stack)->nodeName === 'html') {
+ // Ignore
+
+ /* Otherwise, pop the current node (which will be a colgroup
+ element) from the stack of open elements. Switch the insertion
+ mode to "in table". */
+ } else {
+ array_pop($this->stack);
+ $this->mode = self::IN_TABLE;
+ }
+
+ /* An end tag whose tag name is "col" */
+ } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') {
+ /* Parse error. Ignore the token. */
+
+ /* Anything else */
+ } else {
+ /* Act as if an end tag with the tag name "colgroup" had been seen,
+ and then, if that token wasn't ignored, reprocess the current token. */
+ $this->inColumnGroup(array(
+ 'name' => 'colgroup',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->inTable($token);
+ }
+ }
+
+ private function inTableBody($token) {
+ $clear = array('tbody', 'tfoot', 'thead', 'html');
+
+ /* A start tag whose tag name is "tr" */
+ if($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') {
+ /* Clear the stack back to a table body context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Insert a tr element for the token, then switch the insertion
+ mode to "in row". */
+ $this->insertElement($token);
+ $this->mode = self::IN_ROW;
+
+ /* A start tag whose tag name is one of: "th", "td" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ ($token['name'] === 'th' || $token['name'] === 'td')) {
+ /* Parse error. Act as if a start tag with the tag name "tr" had
+ been seen, then reprocess the current token. */
+ $this->inTableBody(array(
+ 'name' => 'tr',
+ 'type' => HTML5::STARTTAG,
+ 'attr' => array()
+ ));
+
+ return $this->inRow($token);
+
+ /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as the token, this is a parse error.
+ Ignore the token. */
+ if(!$this->elementInScope($token['name'], true)) {
+ // Ignore
+
+ /* Otherwise: */
+ } else {
+ /* Clear the stack back to a table body context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Pop the current node from the stack of open elements. Switch
+ the insertion mode to "in table". */
+ array_pop($this->stack);
+ $this->mode = self::IN_TABLE;
+ }
+
+ /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+ "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */
+ } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead'))) ||
+ ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')) {
+ /* If the stack of open elements does not have a tbody, thead, or
+ tfoot element in table scope, this is a parse error. Ignore the
+ token. (innerHTML case) */
+ if(!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) {
+ // Ignore.
+
+ /* Otherwise: */
+ } else {
+ /* Clear the stack back to a table body context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Act as if an end tag with the same tag name as the current
+ node ("tbody", "tfoot", or "thead") had been seen, then
+ reprocess the current token. */
+ $this->inTableBody(array(
+ 'name' => end($this->stack)->nodeName,
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->mainPhase($token);
+ }
+
+ /* An end tag whose tag name is one of: "body", "caption", "col",
+ "colgroup", "html", "td", "th", "tr" */
+ } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+ array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
+ /* Parse error. Ignore the token. */
+
+ /* Anything else */
+ } else {
+ /* Process the token as if the insertion mode was "in table". */
+ $this->inTable($token);
+ }
+ }
+
+ private function inRow($token) {
+ $clear = array('tr', 'html');
+
+ /* A start tag whose tag name is one of: "th", "td" */
+ if($token['type'] === HTML5::STARTTAG &&
+ ($token['name'] === 'th' || $token['name'] === 'td')) {
+ /* Clear the stack back to a table row context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Insert an HTML element for the token, then switch the insertion
+ mode to "in cell". */
+ $this->insertElement($token);
+ $this->mode = self::IN_CELL;
+
+ /* Insert a marker at the end of the list of active formatting
+ elements. */
+ $this->a_formatting[] = self::MARKER;
+
+ /* An end tag whose tag name is "tr" */
+ } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as the token, this is a parse error.
+ Ignore the token. (innerHTML case) */
+ if(!$this->elementInScope($token['name'], true)) {
+ // Ignore.
+
+ /* Otherwise: */
+ } else {
+ /* Clear the stack back to a table row context. */
+ $this->clearStackToTableContext($clear);
+
+ /* Pop the current node (which will be a tr element) from the
+ stack of open elements. Switch the insertion mode to "in table
+ body". */
+ array_pop($this->stack);
+ $this->mode = self::IN_TBODY;
+ }
+
+ /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+ "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */
+ } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr'))) {
+ /* Act as if an end tag with the tag name "tr" had been seen, then,
+ if that token wasn't ignored, reprocess the current token. */
+ $this->inRow(array(
+ 'name' => 'tr',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->inCell($token);
+
+ /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as the token, this is a parse error.
+ Ignore the token. */
+ if(!$this->elementInScope($token['name'], true)) {
+ // Ignore.
+
+ /* Otherwise: */
+ } else {
+ /* Otherwise, act as if an end tag with the tag name "tr" had
+ been seen, then reprocess the current token. */
+ $this->inRow(array(
+ 'name' => 'tr',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ return $this->inCell($token);
+ }
+
+ /* An end tag whose tag name is one of: "body", "caption", "col",
+ "colgroup", "html", "td", "th" */
+ } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+ array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
+ /* Parse error. Ignore the token. */
+
+ /* Anything else */
+ } else {
+ /* Process the token as if the insertion mode was "in table". */
+ $this->inTable($token);
+ }
+ }
+
+ private function inCell($token) {
+ /* An end tag whose tag name is one of: "td", "th" */
+ if($token['type'] === HTML5::ENDTAG &&
+ ($token['name'] === 'td' || $token['name'] === 'th')) {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as that of the token, then this is a
+ parse error and the token must be ignored. */
+ if(!$this->elementInScope($token['name'], true)) {
+ // Ignore.
+
+ /* Otherwise: */
+ } else {
+ /* Generate implied end tags, except for elements with the same
+ tag name as the token. */
+ $this->generateImpliedEndTags(array($token['name']));
+
+ /* Now, if the current node is not an element with the same tag
+ name as the token, then this is a parse error. */
+ // k
+
+ /* Pop elements from this stack until an element with the same
+ tag name as the token has been popped from the stack. */
+ while(true) {
+ $node = end($this->stack)->nodeName;
+ array_pop($this->stack);
+
+ if($node === $token['name']) {
+ break;
+ }
+ }
+
+ /* Clear the list of active formatting elements up to the last
+ marker. */
+ $this->clearTheActiveFormattingElementsUpToTheLastMarker();
+
+ /* Switch the insertion mode to "in row". (The current node
+ will be a tr element at this point.) */
+ $this->mode = self::IN_ROW;
+ }
+
+ /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+ "tbody", "td", "tfoot", "th", "thead", "tr" */
+ } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+ 'thead', 'tr'))) {
+ /* If the stack of open elements does not have a td or th element
+ in table scope, then this is a parse error; ignore the token.
+ (innerHTML case) */
+ if(!$this->elementInScope(array('td', 'th'), true)) {
+ // Ignore.
+
+ /* Otherwise, close the cell (see below) and reprocess the current
+ token. */
+ } else {
+ $this->closeCell();
+ return $this->inRow($token);
+ }
+
+ /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+ "tbody", "td", "tfoot", "th", "thead", "tr" */
+ } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+ array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+ 'thead', 'tr'))) {
+ /* If the stack of open elements does not have a td or th element
+ in table scope, then this is a parse error; ignore the token.
+ (innerHTML case) */
+ if(!$this->elementInScope(array('td', 'th'), true)) {
+ // Ignore.
+
+ /* Otherwise, close the cell (see below) and reprocess the current
+ token. */
+ } else {
+ $this->closeCell();
+ return $this->inRow($token);
+ }
+
+ /* An end tag whose tag name is one of: "body", "caption", "col",
+ "colgroup", "html" */
+ } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+ array('body', 'caption', 'col', 'colgroup', 'html'))) {
+ /* Parse error. Ignore the token. */
+
+ /* An end tag whose tag name is one of: "table", "tbody", "tfoot",
+ "thead", "tr" */
+ } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+ array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as that of the token (which can only
+ happen for "tbody", "tfoot" and "thead", or, in the innerHTML case),
+ then this is a parse error and the token must be ignored. */
+ if(!$this->elementInScope($token['name'], true)) {
+ // Ignore.
+
+ /* Otherwise, close the cell (see below) and reprocess the current
+ token. */
+ } else {
+ $this->closeCell();
+ return $this->inRow($token);
+ }
+
+ /* Anything else */
+ } else {
+ /* Process the token as if the insertion mode was "in body". */
+ $this->inBody($token);
+ }
+ }
+
+ private function inSelect($token) {
+ /* Handle the token as follows: */
+
+ /* A character token */
+ if($token['type'] === HTML5::CHARACTR) {
+ /* Append the token's character to the current node. */
+ $this->insertText($token['data']);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data
+ attribute set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+
+ /* A start tag token whose tag name is "option" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ $token['name'] === 'option') {
+ /* If the current node is an option element, act as if an end tag
+ with the tag name "option" had been seen. */
+ if(end($this->stack)->nodeName === 'option') {
+ $this->inSelect(array(
+ 'name' => 'option',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* A start tag token whose tag name is "optgroup" */
+ } elseif($token['type'] === HTML5::STARTTAG &&
+ $token['name'] === 'optgroup') {
+ /* If the current node is an option element, act as if an end tag
+ with the tag name "option" had been seen. */
+ if(end($this->stack)->nodeName === 'option') {
+ $this->inSelect(array(
+ 'name' => 'option',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* If the current node is an optgroup element, act as if an end tag
+ with the tag name "optgroup" had been seen. */
+ if(end($this->stack)->nodeName === 'optgroup') {
+ $this->inSelect(array(
+ 'name' => 'optgroup',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* An end tag token whose tag name is "optgroup" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ $token['name'] === 'optgroup') {
+ /* First, if the current node is an option element, and the node
+ immediately before it in the stack of open elements is an optgroup
+ element, then act as if an end tag with the tag name "option" had
+ been seen. */
+ $elements_in_stack = count($this->stack);
+
+ if($this->stack[$elements_in_stack - 1]->nodeName === 'option' &&
+ $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup') {
+ $this->inSelect(array(
+ 'name' => 'option',
+ 'type' => HTML5::ENDTAG
+ ));
+ }
+
+ /* If the current node is an optgroup element, then pop that node
+ from the stack of open elements. Otherwise, this is a parse error,
+ ignore the token. */
+ if($this->stack[$elements_in_stack - 1] === 'optgroup') {
+ array_pop($this->stack);
+ }
+
+ /* An end tag token whose tag name is "option" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ $token['name'] === 'option') {
+ /* If the current node is an option element, then pop that node
+ from the stack of open elements. Otherwise, this is a parse error,
+ ignore the token. */
+ if(end($this->stack)->nodeName === 'option') {
+ array_pop($this->stack);
+ }
+
+ /* An end tag whose tag name is "select" */
+ } elseif($token['type'] === HTML5::ENDTAG &&
+ $token['name'] === 'select') {
+ /* If the stack of open elements does not have an element in table
+ scope with the same tag name as the token, this is a parse error.
+ Ignore the token. (innerHTML case) */
+ if(!$this->elementInScope($token['name'], true)) {
+ // w/e
+
+ /* Otherwise: */
+ } else {
+ /* Pop elements from the stack of open elements until a select
+ element has been popped from the stack. */
+ while(true) {
+ $current = end($this->stack)->nodeName;
+ array_pop($this->stack);
+
+ if($current === 'select') {
+ break;
+ }
+ }
+
+ /* Reset the insertion mode appropriately. */
+ $this->resetInsertionMode();
+ }
+
+ /* A start tag whose tag name is "select" */
+ } elseif($token['name'] === 'select' &&
+ $token['type'] === HTML5::STARTTAG) {
+ /* Parse error. Act as if the token had been an end tag with the
+ tag name "select" instead. */
+ $this->inSelect(array(
+ 'name' => 'select',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ /* An end tag whose tag name is one of: "caption", "table", "tbody",
+ "tfoot", "thead", "tr", "td", "th" */
+ } elseif(in_array($token['name'], array('caption', 'table', 'tbody',
+ 'tfoot', 'thead', 'tr', 'td', 'th')) && $token['type'] === HTML5::ENDTAG) {
+ /* Parse error. */
+ // w/e
+
+ /* If the stack of open elements has an element in table scope with
+ the same tag name as that of the token, then act as if an end tag
+ with the tag name "select" had been seen, and reprocess the token.
+ Otherwise, ignore the token. */
+ if($this->elementInScope($token['name'], true)) {
+ $this->inSelect(array(
+ 'name' => 'select',
+ 'type' => HTML5::ENDTAG
+ ));
+
+ $this->mainPhase($token);
+ }
+
+ /* Anything else */
+ } else {
+ /* Parse error. Ignore the token. */
+ }
+ }
+
+ private function afterBody($token) {
+ /* Handle the token as follows: */
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Process the token as it would be processed if the insertion mode
+ was "in body". */
+ $this->inBody($token);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the first element in the stack of open
+ elements (the html element), with the data attribute set to the
+ data given in the comment token. */
+ $comment = $this->dom->createComment($token['data']);
+ $this->stack[0]->appendChild($comment);
+
+ /* An end tag with the tag name "html" */
+ } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {
+ /* If the parser was originally created in order to handle the
+ setting of an element's innerHTML attribute, this is a parse error;
+ ignore the token. (The element will be an html element in this
+ case.) (innerHTML case) */
+
+ /* Otherwise, switch to the trailing end phase. */
+ $this->phase = self::END_PHASE;
+
+ /* Anything else */
+ } else {
+ /* Parse error. Set the insertion mode to "in body" and reprocess
+ the token. */
+ $this->mode = self::IN_BODY;
+ return $this->inBody($token);
+ }
+ }
+
+ private function inFrameset($token) {
+ /* Handle the token as follows: */
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append the character to the current node. */
+ $this->insertText($token['data']);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data
+ attribute set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+
+ /* A start tag with the tag name "frameset" */
+ } elseif($token['name'] === 'frameset' &&
+ $token['type'] === HTML5::STARTTAG) {
+ $this->insertElement($token);
+
+ /* An end tag with the tag name "frameset" */
+ } elseif($token['name'] === 'frameset' &&
+ $token['type'] === HTML5::ENDTAG) {
+ /* If the current node is the root html element, then this is a
+ parse error; ignore the token. (innerHTML case) */
+ if(end($this->stack)->nodeName === 'html') {
+ // Ignore
+
+ } else {
+ /* Otherwise, pop the current node from the stack of open
+ elements. */
+ array_pop($this->stack);
+
+ /* If the parser was not originally created in order to handle
+ the setting of an element's innerHTML attribute (innerHTML case),
+ and the current node is no longer a frameset element, then change
+ the insertion mode to "after frameset". */
+ $this->mode = self::AFTR_FRAME;
+ }
+
+ /* A start tag with the tag name "frame" */
+ } elseif($token['name'] === 'frame' &&
+ $token['type'] === HTML5::STARTTAG) {
+ /* Insert an HTML element for the token. */
+ $this->insertElement($token);
+
+ /* Immediately pop the current node off the stack of open elements. */
+ array_pop($this->stack);
+
+ /* A start tag with the tag name "noframes" */
+ } elseif($token['name'] === 'noframes' &&
+ $token['type'] === HTML5::STARTTAG) {
+ /* Process the token as if the insertion mode had been "in body". */
+ $this->inBody($token);
+
+ /* Anything else */
+ } else {
+ /* Parse error. Ignore the token. */
+ }
+ }
+
+ private function afterFrameset($token) {
+ /* Handle the token as follows: */
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
+ if($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Append the character to the current node. */
+ $this->insertText($token['data']);
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the current node with the data
+ attribute set to the data given in the comment token. */
+ $this->insertComment($token['data']);
+
+ /* An end tag with the tag name "html" */
+ } elseif($token['name'] === 'html' &&
+ $token['type'] === HTML5::ENDTAG) {
+ /* Switch to the trailing end phase. */
+ $this->phase = self::END_PHASE;
+
+ /* A start tag with the tag name "noframes" */
+ } elseif($token['name'] === 'noframes' &&
+ $token['type'] === HTML5::STARTTAG) {
+ /* Process the token as if the insertion mode had been "in body". */
+ $this->inBody($token);
+
+ /* Anything else */
+ } else {
+ /* Parse error. Ignore the token. */
+ }
+ }
+
+ private function trailingEndPhase($token) {
+ /* After the main phase, as each token is emitted from the tokenisation
+ stage, it must be processed as described in this section. */
+
+ /* A DOCTYPE token */
+ if($token['type'] === HTML5::DOCTYPE) {
+ // Parse error. Ignore the token.
+
+ /* A comment token */
+ } elseif($token['type'] === HTML5::COMMENT) {
+ /* Append a Comment node to the Document object with the data
+ attribute set to the data given in the comment token. */
+ $comment = $this->dom->createComment($token['data']);
+ $this->dom->appendChild($comment);
+
+ /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE */
+ } elseif($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+ /* Process the token as it would be processed in the main phase. */
+ $this->mainPhase($token);
+
+ /* A character token that is not one of U+0009 CHARACTER TABULATION,
+ U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+ or U+0020 SPACE. Or a start tag token. Or an end tag token. */
+ } elseif(($token['type'] === HTML5::CHARACTR &&
+ preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
+ $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG) {
+ /* Parse error. Switch back to the main phase and reprocess the
+ token. */
+ $this->phase = self::MAIN_PHASE;
+ return $this->mainPhase($token);
+
+ /* An end-of-file token */
+ } elseif($token['type'] === HTML5::EOF) {
+ /* OMG DONE!! */
+ }
+ }
+
+ private function insertElement($token, $append = true, $check = false) {
+ // Proprietary workaround for libxml2's limitations with tag names
+ if ($check) {
+ // Slightly modified HTML5 tag-name modification,
+ // removing anything that's not an ASCII letter, digit, or hyphen
+ $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']);
+ // Remove leading hyphens and numbers
+ $token['name'] = ltrim($token['name'], '-0..9');
+ // In theory, this should ever be needed, but just in case
+ if ($token['name'] === '') $token['name'] = 'span'; // arbitrary generic choice
+ }
+
+ $el = $this->dom->createElement($token['name']);
+
+ foreach($token['attr'] as $attr) {
+ if(!$el->hasAttribute($attr['name'])) {
+ $el->setAttribute($attr['name'], $attr['value']);
+ }
+ }
+
+ $this->appendToRealParent($el);
+ $this->stack[] = $el;
+
+ return $el;
+ }
+
+ private function insertText($data) {
+ $text = $this->dom->createTextNode($data);
+ $this->appendToRealParent($text);
+ }
+
+ private function insertComment($data) {
+ $comment = $this->dom->createComment($data);
+ $this->appendToRealParent($comment);
+ }
+
+ private function appendToRealParent($node) {
+ if($this->foster_parent === null) {
+ end($this->stack)->appendChild($node);
+
+ } elseif($this->foster_parent !== null) {
+ /* If the foster parent element is the parent element of the
+ last table element in the stack of open elements, then the new
+ node must be inserted immediately before the last table element
+ in the stack of open elements in the foster parent element;
+ otherwise, the new node must be appended to the foster parent
+ element. */
+ for($n = count($this->stack) - 1; $n >= 0; $n--) {
+ if($this->stack[$n]->nodeName === 'table' &&
+ $this->stack[$n]->parentNode !== null) {
+ $table = $this->stack[$n];
+ break;
+ }
+ }
+
+ if(isset($table) && $this->foster_parent->isSameNode($table->parentNode))
+ $this->foster_parent->insertBefore($node, $table);
+ else
+ $this->foster_parent->appendChild($node);
+
+ $this->foster_parent = null;
+ }
+ }
+
+ private function elementInScope($el, $table = false) {
+ if(is_array($el)) {
+ foreach($el as $element) {
+ if($this->elementInScope($element, $table)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ $leng = count($this->stack);
+
+ for($n = 0; $n < $leng; $n++) {
+ /* 1. Initialise node to be the current node (the bottommost node of
+ the stack). */
+ $node = $this->stack[$leng - 1 - $n];
+
+ if($node->tagName === $el) {
+ /* 2. If node is the target node, terminate in a match state. */
+ return true;
+
+ } elseif($node->tagName === 'table') {
+ /* 3. Otherwise, if node is a table element, terminate in a failure
+ state. */
+ return false;
+
+ } elseif($table === true && in_array($node->tagName, array('caption', 'td',
+ 'th', 'button', 'marquee', 'object'))) {
+ /* 4. Otherwise, if the algorithm is the "has an element in scope"
+ variant (rather than the "has an element in table scope" variant),
+ and node is one of the following, terminate in a failure state. */
+ return false;
+
+ } elseif($node === $node->ownerDocument->documentElement) {
+ /* 5. Otherwise, if node is an html element (root element), terminate
+ in a failure state. (This can only happen if the node is the topmost
+ node of the stack of open elements, and prevents the next step from
+ being invoked if there are no more elements in the stack.) */
+ return false;
+ }
+
+ /* Otherwise, set node to the previous entry in the stack of open
+ elements and return to step 2. (This will never fail, since the loop
+ will always terminate in the previous step if the top of the stack
+ is reached.) */
+ }
+ }
+
+ private function reconstructActiveFormattingElements() {
+ /* 1. If there are no entries in the list of active formatting elements,
+ then there is nothing to reconstruct; stop this algorithm. */
+ $formatting_elements = count($this->a_formatting);
+
+ if($formatting_elements === 0) {
+ return false;
+ }
+
+ /* 3. Let entry be the last (most recently added) element in the list
+ of active formatting elements. */
+ $entry = end($this->a_formatting);
+
+ /* 2. If the last (most recently added) entry in the list of active
+ formatting elements is a marker, or if it is an element that is in the
+ stack of open elements, then there is nothing to reconstruct; stop this
+ algorithm. */
+ if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
+ return false;
+ }
+
+ for($a = $formatting_elements - 1; $a >= 0; true) {
+ /* 4. If there are no entries before entry in the list of active
+ formatting elements, then jump to step 8. */
+ if($a === 0) {
+ $step_seven = false;
+ break;
+ }
+
+ /* 5. Let entry be the entry one earlier than entry in the list of
+ active formatting elements. */
+ $a--;
+ $entry = $this->a_formatting[$a];
+
+ /* 6. If entry is neither a marker nor an element that is also in
+ thetack of open elements, go to step 4. */
+ if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
+ break;
+ }
+ }
+
+ while(true) {
+ /* 7. Let entry be the element one later than entry in the list of
+ active formatting elements. */
+ if(isset($step_seven) && $step_seven === true) {
+ $a++;
+ $entry = $this->a_formatting[$a];
+ }
+
+ /* 8. Perform a shallow clone of the element entry to obtain clone. */
+ $clone = $entry->cloneNode();
+
+ /* 9. Append clone to the current node and push it onto the stack
+ of open elements so that it is the new current node. */
+ end($this->stack)->appendChild($clone);
+ $this->stack[] = $clone;
+
+ /* 10. Replace the entry for entry in the list with an entry for
+ clone. */
+ $this->a_formatting[$a] = $clone;
+
+ /* 11. If the entry for clone in the list of active formatting
+ elements is not the last entry in the list, return to step 7. */
+ if(end($this->a_formatting) !== $clone) {
+ $step_seven = true;
+ } else {
+ break;
+ }
+ }
+ }
+
+ private function clearTheActiveFormattingElementsUpToTheLastMarker() {
+ /* When the steps below require the UA to clear the list of active
+ formatting elements up to the last marker, the UA must perform the
+ following steps: */
+
+ while(true) {
+ /* 1. Let entry be the last (most recently added) entry in the list
+ of active formatting elements. */
+ $entry = end($this->a_formatting);
+
+ /* 2. Remove entry from the list of active formatting elements. */
+ array_pop($this->a_formatting);
+
+ /* 3. If entry was a marker, then stop the algorithm at this point.
+ The list has been cleared up to the last marker. */
+ if($entry === self::MARKER) {
+ break;
+ }
+ }
+ }
+
+ private function generateImpliedEndTags($exclude = array()) {
+ /* When the steps below require the UA to generate implied end tags,
+ then, if the current node is a dd element, a dt element, an li element,
+ a p element, a td element, a th element, or a tr element, the UA must
+ act as if an end tag with the respective tag name had been seen and
+ then generate implied end tags again. */
+ $node = end($this->stack);
+ $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude);
+
+ while(in_array(end($this->stack)->nodeName, $elements)) {
+ array_pop($this->stack);
+ }
+ }
+
+ private function getElementCategory($node) {
+ $name = $node->tagName;
+ if(in_array($name, $this->special))
+ return self::SPECIAL;
+
+ elseif(in_array($name, $this->scoping))
+ return self::SCOPING;
+
+ elseif(in_array($name, $this->formatting))
+ return self::FORMATTING;
+
+ else
+ return self::PHRASING;
+ }
+
+ private function clearStackToTableContext($elements) {
+ /* When the steps above require the UA to clear the stack back to a
+ table context, it means that the UA must, while the current node is not
+ a table element or an html element, pop elements from the stack of open
+ elements. If this causes any elements to be popped from the stack, then
+ this is a parse error. */
+ while(true) {
+ $node = end($this->stack)->nodeName;
+
+ if(in_array($node, $elements)) {
+ break;
+ } else {
+ array_pop($this->stack);
+ }
+ }
+ }
+
+ private function resetInsertionMode() {
+ /* 1. Let last be false. */
+ $last = false;
+ $leng = count($this->stack);
+
+ for($n = $leng - 1; $n >= 0; $n--) {
+ /* 2. Let node be the last node in the stack of open elements. */
+ $node = $this->stack[$n];
+
+ /* 3. If node is the first node in the stack of open elements, then
+ set last to true. If the element whose innerHTML attribute is being
+ set is neither a td element nor a th element, then set node to the
+ element whose innerHTML attribute is being set. (innerHTML case) */
+ if($this->stack[0]->isSameNode($node)) {
+ $last = true;
+ }
+
+ /* 4. If node is a select element, then switch the insertion mode to
+ "in select" and abort these steps. (innerHTML case) */
+ if($node->nodeName === 'select') {
+ $this->mode = self::IN_SELECT;
+ break;
+
+ /* 5. If node is a td or th element, then switch the insertion mode
+ to "in cell" and abort these steps. */
+ } elseif($node->nodeName === 'td' || $node->nodeName === 'th') {
+ $this->mode = self::IN_CELL;
+ break;
+
+ /* 6. If node is a tr element, then switch the insertion mode to
+ "in row" and abort these steps. */
+ } elseif($node->nodeName === 'tr') {
+ $this->mode = self::IN_ROW;
+ break;
+
+ /* 7. If node is a tbody, thead, or tfoot element, then switch the
+ insertion mode to "in table body" and abort these steps. */
+ } elseif(in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) {
+ $this->mode = self::IN_TBODY;
+ break;
+
+ /* 8. If node is a caption element, then switch the insertion mode
+ to "in caption" and abort these steps. */
+ } elseif($node->nodeName === 'caption') {
+ $this->mode = self::IN_CAPTION;
+ break;
+
+ /* 9. If node is a colgroup element, then switch the insertion mode
+ to "in column group" and abort these steps. (innerHTML case) */
+ } elseif($node->nodeName === 'colgroup') {
+ $this->mode = self::IN_CGROUP;
+ break;
+
+ /* 10. If node is a table element, then switch the insertion mode
+ to "in table" and abort these steps. */
+ } elseif($node->nodeName === 'table') {
+ $this->mode = self::IN_TABLE;
+ break;
+
+ /* 11. If node is a head element, then switch the insertion mode
+ to "in body" ("in body"! not "in head"!) and abort these steps.
+ (innerHTML case) */
+ } elseif($node->nodeName === 'head') {
+ $this->mode = self::IN_BODY;
+ break;
+
+ /* 12. If node is a body element, then switch the insertion mode to
+ "in body" and abort these steps. */
+ } elseif($node->nodeName === 'body') {
+ $this->mode = self::IN_BODY;
+ break;
+
+ /* 13. If node is a frameset element, then switch the insertion
+ mode to "in frameset" and abort these steps. (innerHTML case) */
+ } elseif($node->nodeName === 'frameset') {
+ $this->mode = self::IN_FRAME;
+ break;
+
+ /* 14. If node is an html element, then: if the head element
+ pointer is null, switch the insertion mode to "before head",
+ otherwise, switch the insertion mode to "after head". In either
+ case, abort these steps. (innerHTML case) */
+ } elseif($node->nodeName === 'html') {
+ $this->mode = ($this->head_pointer === null)
+ ? self::BEFOR_HEAD
+ : self::AFTER_HEAD;
+
+ break;
+
+ /* 15. If last is true, then set the insertion mode to "in body"
+ and abort these steps. (innerHTML case) */
+ } elseif($last) {
+ $this->mode = self::IN_BODY;
+ break;
+ }
+ }
+ }
+
+ private function closeCell() {
+ /* If the stack of open elements has a td or th element in table scope,
+ then act as if an end tag token with that tag name had been seen. */
+ foreach(array('td', 'th') as $cell) {
+ if($this->elementInScope($cell, true)) {
+ $this->inCell(array(
+ 'name' => $cell,
+ 'type' => HTML5::ENDTAG
+ ));
+
+ break;
+ }
+ }
+ }
+
+ public function save() {
+ return $this->dom;
+ }
+}
+?>
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PercentEncoder.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PercentEncoder.php
new file mode 100644
index 0000000..8420e07
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PercentEncoder.php
@@ -0,0 +1,98 @@
+<?php
+
+/**
+ * Class that handles operations involving percent-encoding in URIs.
+ *
+ * @warning
+ * Be careful when reusing instances of PercentEncoder. The object
+ * you use for normalize() SHOULD NOT be used for encode(), or
+ * vice-versa.
+ */
+class HTMLPurifier_PercentEncoder
+{
+
+ /**
+ * Reserved characters to preserve when using encode().
+ */
+ protected $preserve = array();
+
+ /**
+ * String of characters that should be preserved while using encode().
+ */
+ public function __construct($preserve = false) {
+ // unreserved letters, ought to const-ify
+ for ($i = 48; $i <= 57; $i++) $this->preserve[$i] = true; // digits
+ for ($i = 65; $i <= 90; $i++) $this->preserve[$i] = true; // upper-case
+ for ($i = 97; $i <= 122; $i++) $this->preserve[$i] = true; // lower-case
+ $this->preserve[45] = true; // Dash -
+ $this->preserve[46] = true; // Period .
+ $this->preserve[95] = true; // Underscore _
+ $this->preserve[126]= true; // Tilde ~
+
+ // extra letters not to escape
+ if ($preserve !== false) {
+ for ($i = 0, $c = strlen($preserve); $i < $c; $i++) {
+ $this->preserve[ord($preserve[$i])] = true;
+ }
+ }
+ }
+
+ /**
+ * Our replacement for urlencode, it encodes all non-reserved characters,
+ * as well as any extra characters that were instructed to be preserved.
+ * @note
+ * Assumes that the string has already been normalized, making any
+ * and all percent escape sequences valid. Percents will not be
+ * re-escaped, regardless of their status in $preserve
+ * @param $string String to be encoded
+ * @return Encoded string.
+ */
+ public function encode($string) {
+ $ret = '';
+ for ($i = 0, $c = strlen($string); $i < $c; $i++) {
+ if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])]) ) {
+ $ret .= '%' . sprintf('%02X', $int);
+ } else {
+ $ret .= $string[$i];
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Fix up percent-encoding by decoding unreserved characters and normalizing.
+ * @warning This function is affected by $preserve, even though the
+ * usual desired behavior is for this not to preserve those
+ * characters. Be careful when reusing instances of PercentEncoder!
+ * @param $string String to normalize
+ */
+ public function normalize($string) {
+ if ($string == '') return '';
+ $parts = explode('%', $string);
+ $ret = array_shift($parts);
+ foreach ($parts as $part) {
+ $length = strlen($part);
+ if ($length < 2) {
+ $ret .= '%25' . $part;
+ continue;
+ }
+ $encoding = substr($part, 0, 2);
+ $text = substr($part, 2);
+ if (!ctype_xdigit($encoding)) {
+ $ret .= '%25' . $part;
+ continue;
+ }
+ $int = hexdec($encoding);
+ if (isset($this->preserve[$int])) {
+ $ret .= chr($int) . $text;
+ continue;
+ }
+ $encoding = strtoupper($encoding);
+ $ret .= '%' . $encoding . $text;
+ }
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer.php
new file mode 100644
index 0000000..84e8611
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer.php
@@ -0,0 +1,176 @@
+<?php
+
+// OUT OF DATE, NEEDS UPDATING!
+// USE XMLWRITER!
+
+class HTMLPurifier_Printer
+{
+
+ /**
+ * Instance of HTMLPurifier_Generator for HTML generation convenience funcs
+ */
+ protected $generator;
+
+ /**
+ * Instance of HTMLPurifier_Config, for easy access
+ */
+ protected $config;
+
+ /**
+ * Initialize $generator.
+ */
+ public function __construct() {
+ }
+
+ /**
+ * Give generator necessary configuration if possible
+ */
+ public function prepareGenerator($config) {
+ $all = $config->getAll();
+ $context = new HTMLPurifier_Context();
+ $this->generator = new HTMLPurifier_Generator($config, $context);
+ }
+
+ /**
+ * Main function that renders object or aspect of that object
+ * @note Parameters vary depending on printer
+ */
+ // function render() {}
+
+ /**
+ * Returns a start tag
+ * @param $tag Tag name
+ * @param $attr Attribute array
+ */
+ protected function start($tag, $attr = array()) {
+ return $this->generator->generateFromToken(
+ new HTMLPurifier_Token_Start($tag, $attr ? $attr : array())
+ );
+ }
+
+ /**
+ * Returns an end teg
+ * @param $tag Tag name
+ */
+ protected function end($tag) {
+ return $this->generator->generateFromToken(
+ new HTMLPurifier_Token_End($tag)
+ );
+ }
+
+ /**
+ * Prints a complete element with content inside
+ * @param $tag Tag name
+ * @param $contents Element contents
+ * @param $attr Tag attributes
+ * @param $escape Bool whether or not to escape contents
+ */
+ protected function element($tag, $contents, $attr = array(), $escape = true) {
+ return $this->start($tag, $attr) .
+ ($escape ? $this->escape($contents) : $contents) .
+ $this->end($tag);
+ }
+
+ protected function elementEmpty($tag, $attr = array()) {
+ return $this->generator->generateFromToken(
+ new HTMLPurifier_Token_Empty($tag, $attr)
+ );
+ }
+
+ protected function text($text) {
+ return $this->generator->generateFromToken(
+ new HTMLPurifier_Token_Text($text)
+ );
+ }
+
+ /**
+ * Prints a simple key/value row in a table.
+ * @param $name Key
+ * @param $value Value
+ */
+ protected function row($name, $value) {
+ if (is_bool($value)) $value = $value ? 'On' : 'Off';
+ return
+ $this->start('tr') . "\n" .
+ $this->element('th', $name) . "\n" .
+ $this->element('td', $value) . "\n" .
+ $this->end('tr')
+ ;
+ }
+
+ /**
+ * Escapes a string for HTML output.
+ * @param $string String to escape
+ */
+ protected function escape($string) {
+ $string = HTMLPurifier_Encoder::cleanUTF8($string);
+ $string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
+ return $string;
+ }
+
+ /**
+ * Takes a list of strings and turns them into a single list
+ * @param $array List of strings
+ * @param $polite Bool whether or not to add an end before the last
+ */
+ protected function listify($array, $polite = false) {
+ if (empty($array)) return 'None';
+ $ret = '';
+ $i = count($array);
+ foreach ($array as $value) {
+ $i--;
+ $ret .= $value;
+ if ($i > 0 && !($polite && $i == 1)) $ret .= ', ';
+ if ($polite && $i == 1) $ret .= 'and ';
+ }
+ return $ret;
+ }
+
+ /**
+ * Retrieves the class of an object without prefixes, as well as metadata
+ * @param $obj Object to determine class of
+ * @param $prefix Further prefix to remove
+ */
+ protected function getClass($obj, $sec_prefix = '') {
+ static $five = null;
+ if ($five === null) $five = version_compare(PHP_VERSION, '5', '>=');
+ $prefix = 'HTMLPurifier_' . $sec_prefix;
+ if (!$five) $prefix = strtolower($prefix);
+ $class = str_replace($prefix, '', get_class($obj));
+ $lclass = strtolower($class);
+ $class .= '(';
+ switch ($lclass) {
+ case 'enum':
+ $values = array();
+ foreach ($obj->valid_values as $value => $bool) {
+ $values[] = $value;
+ }
+ $class .= implode(', ', $values);
+ break;
+ case 'css_composite':
+ $values = array();
+ foreach ($obj->defs as $def) {
+ $values[] = $this->getClass($def, $sec_prefix);
+ }
+ $class .= implode(', ', $values);
+ break;
+ case 'css_multiple':
+ $class .= $this->getClass($obj->single, $sec_prefix) . ', ';
+ $class .= $obj->max;
+ break;
+ case 'css_denyelementdecorator':
+ $class .= $this->getClass($obj->def, $sec_prefix) . ', ';
+ $class .= $obj->element;
+ break;
+ case 'css_importantdecorator':
+ $class .= $this->getClass($obj->def, $sec_prefix);
+ if ($obj->allow) $class .= ', !important';
+ break;
+ }
+ $class .= ')';
+ return $class;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/CSSDefinition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/CSSDefinition.php
new file mode 100644
index 0000000..0714580
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/CSSDefinition.php
@@ -0,0 +1,38 @@
+<?php
+
+class HTMLPurifier_Printer_CSSDefinition extends HTMLPurifier_Printer
+{
+
+ protected $def;
+
+ public function render($config) {
+ $this->def = $config->getCSSDefinition();
+ $ret = '';
+
+ $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));
+ $ret .= $this->start('table');
+
+ $ret .= $this->element('caption', 'Properties ($info)');
+
+ $ret .= $this->start('thead');
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Property', array('class' => 'heavy'));
+ $ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;'));
+ $ret .= $this->end('tr');
+ $ret .= $this->end('thead');
+
+ ksort($this->def->info);
+ foreach ($this->def->info as $property => $obj) {
+ $name = $this->getClass($obj, 'AttrDef_');
+ $ret .= $this->row($property, $name);
+ }
+
+ $ret .= $this->end('table');
+ $ret .= $this->end('div');
+
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.css b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.css
new file mode 100644
index 0000000..7af30fc
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.css
@@ -0,0 +1,10 @@
+
+.hp-config {}
+
+.hp-config tbody th {text-align:right; padding-right:0.5em;}
+.hp-config thead, .hp-config .namespace {background:#3C578C; color:#FFF;}
+.hp-config .namespace th {text-align:center;}
+.hp-config .verbose {display:none;}
+.hp-config .controls {text-align:center;}
+
+/* vim: et sw=4 sts=4 */
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.js b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.js
new file mode 100644
index 0000000..83e0655
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.js
@@ -0,0 +1,5 @@
+function toggleWriteability(id_of_patient, checked) {
+ document.getElementById(id_of_patient).disabled = checked;
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.css b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.css
new file mode 100644
index 0000000..c9dea49
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.css
@@ -0,0 +1,2 @@
+
+.hp-config tbody th{text-align:right;padding-right:.5em}.hp-config thead,.hp-config .namespace{background:#3c578c;color:#FFF}.hp-config .namespace th{text-align:center}.hp-config .verbose{display:none}.hp-config .controls{text-align:center} \ No newline at end of file
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.js b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.js
new file mode 100644
index 0000000..0321f65
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.min.js
@@ -0,0 +1,2 @@
+
+function toggleWriteability(a,b){document.getElementById(a).disabled=b}; \ No newline at end of file
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.php
new file mode 100644
index 0000000..b41476f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/ConfigForm.php
@@ -0,0 +1,368 @@
+<?php
+
+/**
+ * @todo Rewrite to use Interchange objects
+ */
+class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
+{
+
+ /**
+ * Printers for specific fields
+ */
+ protected $fields = array();
+
+ /**
+ * Documentation URL, can have fragment tagged on end
+ */
+ protected $docURL;
+
+ /**
+ * Name of form element to stuff config in
+ */
+ protected $name;
+
+ /**
+ * Whether or not to compress directive names, clipping them off
+ * after a certain amount of letters. False to disable or integer letters
+ * before clipping.
+ */
+ protected $compress = false;
+
+ /**
+ * @param $name Form element name for directives to be stuffed into
+ * @param $doc_url String documentation URL, will have fragment tagged on
+ * @param $compress Integer max length before compressing a directive name, set to false to turn off
+ */
+ public function __construct(
+ $name, $doc_url = null, $compress = false
+ ) {
+ parent::__construct();
+ $this->docURL = $doc_url;
+ $this->name = $name;
+ $this->compress = $compress;
+ // initialize sub-printers
+ $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default();
+ $this->fields[HTMLPurifier_VarParser::BOOL] = new HTMLPurifier_Printer_ConfigForm_bool();
+ }
+
+ /**
+ * Sets default column and row size for textareas in sub-printers
+ * @param $cols Integer columns of textarea, null to use default
+ * @param $rows Integer rows of textarea, null to use default
+ */
+ public function setTextareaDimensions($cols = null, $rows = null) {
+ if ($cols) $this->fields['default']->cols = $cols;
+ if ($rows) $this->fields['default']->rows = $rows;
+ }
+
+ /**
+ * Retrieves styling, in case it is not accessible by webserver
+ */
+ public static function getCSS() {
+ return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css');
+ }
+
+ /**
+ * Retrieves JavaScript, in case it is not accessible by webserver
+ */
+ public static function getJavaScript() {
+ return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js');
+ }
+
+ /**
+ * Returns HTML output for a configuration form
+ * @param $config Configuration object of current form state, or an array
+ * where [0] has an HTML namespace and [1] is being rendered.
+ * @param $allowed Optional namespace(s) and directives to restrict form to.
+ */
+ public function render($config, $allowed = true, $render_controls = true) {
+ if (is_array($config) && isset($config[0])) {
+ $gen_config = $config[0];
+ $config = $config[1];
+ } else {
+ $gen_config = $config;
+ }
+
+ $this->config = $config;
+ $this->genConfig = $gen_config;
+ $this->prepareGenerator($gen_config);
+
+ $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def);
+ $all = array();
+ foreach ($allowed as $key) {
+ list($ns, $directive) = $key;
+ $all[$ns][$directive] = $config->get($ns .'.'. $directive);
+ }
+
+ $ret = '';
+ $ret .= $this->start('table', array('class' => 'hp-config'));
+ $ret .= $this->start('thead');
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive'));
+ $ret .= $this->element('th', 'Value', array('class' => 'hp-value'));
+ $ret .= $this->end('tr');
+ $ret .= $this->end('thead');
+ foreach ($all as $ns => $directives) {
+ $ret .= $this->renderNamespace($ns, $directives);
+ }
+ if ($render_controls) {
+ $ret .= $this->start('tbody');
+ $ret .= $this->start('tr');
+ $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls'));
+ $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit'));
+ $ret .= '[<a href="?">Reset</a>]';
+ $ret .= $this->end('td');
+ $ret .= $this->end('tr');
+ $ret .= $this->end('tbody');
+ }
+ $ret .= $this->end('table');
+ return $ret;
+ }
+
+ /**
+ * Renders a single namespace
+ * @param $ns String namespace name
+ * @param $directive Associative array of directives to values
+ */
+ protected function renderNamespace($ns, $directives) {
+ $ret = '';
+ $ret .= $this->start('tbody', array('class' => 'namespace'));
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', $ns, array('colspan' => 2));
+ $ret .= $this->end('tr');
+ $ret .= $this->end('tbody');
+ $ret .= $this->start('tbody');
+ foreach ($directives as $directive => $value) {
+ $ret .= $this->start('tr');
+ $ret .= $this->start('th');
+ if ($this->docURL) {
+ $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL);
+ $ret .= $this->start('a', array('href' => $url));
+ }
+ $attr = array('for' => "{$this->name}:$ns.$directive");
+
+ // crop directive name if it's too long
+ if (!$this->compress || (strlen($directive) < $this->compress)) {
+ $directive_disp = $directive;
+ } else {
+ $directive_disp = substr($directive, 0, $this->compress - 2) . '...';
+ $attr['title'] = $directive;
+ }
+
+ $ret .= $this->element(
+ 'label',
+ $directive_disp,
+ // component printers must create an element with this id
+ $attr
+ );
+ if ($this->docURL) $ret .= $this->end('a');
+ $ret .= $this->end('th');
+
+ $ret .= $this->start('td');
+ $def = $this->config->def->info["$ns.$directive"];
+ if (is_int($def)) {
+ $allow_null = $def < 0;
+ $type = abs($def);
+ } else {
+ $type = $def->type;
+ $allow_null = isset($def->allow_null);
+ }
+ if (!isset($this->fields[$type])) $type = 0; // default
+ $type_obj = $this->fields[$type];
+ if ($allow_null) {
+ $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj);
+ }
+ $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config));
+ $ret .= $this->end('td');
+ $ret .= $this->end('tr');
+ }
+ $ret .= $this->end('tbody');
+ return $ret;
+ }
+
+}
+
+/**
+ * Printer decorator for directives that accept null
+ */
+class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer {
+ /**
+ * Printer being decorated
+ */
+ protected $obj;
+ /**
+ * @param $obj Printer to decorate
+ */
+ public function __construct($obj) {
+ parent::__construct();
+ $this->obj = $obj;
+ }
+ public function render($ns, $directive, $value, $name, $config) {
+ if (is_array($config) && isset($config[0])) {
+ $gen_config = $config[0];
+ $config = $config[1];
+ } else {
+ $gen_config = $config;
+ }
+ $this->prepareGenerator($gen_config);
+
+ $ret = '';
+ $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive"));
+ $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
+ $ret .= $this->text(' Null/Disabled');
+ $ret .= $this->end('label');
+ $attr = array(
+ 'type' => 'checkbox',
+ 'value' => '1',
+ 'class' => 'null-toggle',
+ 'name' => "$name"."[Null_$ns.$directive]",
+ 'id' => "$name:Null_$ns.$directive",
+ 'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!!
+ );
+ if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) {
+ // modify inline javascript slightly
+ $attr['onclick'] = "toggleWriteability('$name:Yes_$ns.$directive',checked);toggleWriteability('$name:No_$ns.$directive',checked)";
+ }
+ if ($value === null) $attr['checked'] = 'checked';
+ $ret .= $this->elementEmpty('input', $attr);
+ $ret .= $this->text(' or ');
+ $ret .= $this->elementEmpty('br');
+ $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config));
+ return $ret;
+ }
+}
+
+/**
+ * Swiss-army knife configuration form field printer
+ */
+class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer {
+ public $cols = 18;
+ public $rows = 5;
+ public function render($ns, $directive, $value, $name, $config) {
+ if (is_array($config) && isset($config[0])) {
+ $gen_config = $config[0];
+ $config = $config[1];
+ } else {
+ $gen_config = $config;
+ }
+ $this->prepareGenerator($gen_config);
+ // this should probably be split up a little
+ $ret = '';
+ $def = $config->def->info["$ns.$directive"];
+ if (is_int($def)) {
+ $type = abs($def);
+ } else {
+ $type = $def->type;
+ }
+ if (is_array($value)) {
+ switch ($type) {
+ case HTMLPurifier_VarParser::LOOKUP:
+ $array = $value;
+ $value = array();
+ foreach ($array as $val => $b) {
+ $value[] = $val;
+ }
+ case HTMLPurifier_VarParser::ALIST:
+ $value = implode(PHP_EOL, $value);
+ break;
+ case HTMLPurifier_VarParser::HASH:
+ $nvalue = '';
+ foreach ($value as $i => $v) {
+ $nvalue .= "$i:$v" . PHP_EOL;
+ }
+ $value = $nvalue;
+ break;
+ default:
+ $value = '';
+ }
+ }
+ if ($type === HTMLPurifier_VarParser::MIXED) {
+ return 'Not supported';
+ $value = serialize($value);
+ }
+ $attr = array(
+ 'name' => "$name"."[$ns.$directive]",
+ 'id' => "$name:$ns.$directive"
+ );
+ if ($value === null) $attr['disabled'] = 'disabled';
+ if (isset($def->allowed)) {
+ $ret .= $this->start('select', $attr);
+ foreach ($def->allowed as $val => $b) {
+ $attr = array();
+ if ($value == $val) $attr['selected'] = 'selected';
+ $ret .= $this->element('option', $val, $attr);
+ }
+ $ret .= $this->end('select');
+ } elseif (
+ $type === HTMLPurifier_VarParser::TEXT ||
+ $type === HTMLPurifier_VarParser::ITEXT ||
+ $type === HTMLPurifier_VarParser::ALIST ||
+ $type === HTMLPurifier_VarParser::HASH ||
+ $type === HTMLPurifier_VarParser::LOOKUP
+ ) {
+ $attr['cols'] = $this->cols;
+ $attr['rows'] = $this->rows;
+ $ret .= $this->start('textarea', $attr);
+ $ret .= $this->text($value);
+ $ret .= $this->end('textarea');
+ } else {
+ $attr['value'] = $value;
+ $attr['type'] = 'text';
+ $ret .= $this->elementEmpty('input', $attr);
+ }
+ return $ret;
+ }
+}
+
+/**
+ * Bool form field printer
+ */
+class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer {
+ public function render($ns, $directive, $value, $name, $config) {
+ if (is_array($config) && isset($config[0])) {
+ $gen_config = $config[0];
+ $config = $config[1];
+ } else {
+ $gen_config = $config;
+ }
+ $this->prepareGenerator($gen_config);
+ $ret = '';
+ $ret .= $this->start('div', array('id' => "$name:$ns.$directive"));
+
+ $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive"));
+ $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
+ $ret .= $this->text(' Yes');
+ $ret .= $this->end('label');
+
+ $attr = array(
+ 'type' => 'radio',
+ 'name' => "$name"."[$ns.$directive]",
+ 'id' => "$name:Yes_$ns.$directive",
+ 'value' => '1'
+ );
+ if ($value === true) $attr['checked'] = 'checked';
+ if ($value === null) $attr['disabled'] = 'disabled';
+ $ret .= $this->elementEmpty('input', $attr);
+
+ $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive"));
+ $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
+ $ret .= $this->text(' No');
+ $ret .= $this->end('label');
+
+ $attr = array(
+ 'type' => 'radio',
+ 'name' => "$name"."[$ns.$directive]",
+ 'id' => "$name:No_$ns.$directive",
+ 'value' => '0'
+ );
+ if ($value === false) $attr['checked'] = 'checked';
+ if ($value === null) $attr['disabled'] = 'disabled';
+ $ret .= $this->elementEmpty('input', $attr);
+
+ $ret .= $this->end('div');
+
+ return $ret;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/HTMLDefinition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/HTMLDefinition.php
new file mode 100644
index 0000000..e17ddd5
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Printer/HTMLDefinition.php
@@ -0,0 +1,272 @@
+<?php
+
+class HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer
+{
+
+ /**
+ * Instance of HTMLPurifier_HTMLDefinition, for easy access
+ */
+ protected $def;
+
+ public function render($config) {
+ $ret = '';
+ $this->config =& $config;
+
+ $this->def = $config->getHTMLDefinition();
+
+ $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));
+
+ $ret .= $this->renderDoctype();
+ $ret .= $this->renderEnvironment();
+ $ret .= $this->renderContentSets();
+ $ret .= $this->renderInfo();
+
+ $ret .= $this->end('div');
+
+ return $ret;
+ }
+
+ /**
+ * Renders the Doctype table
+ */
+ protected function renderDoctype() {
+ $doctype = $this->def->doctype;
+ $ret = '';
+ $ret .= $this->start('table');
+ $ret .= $this->element('caption', 'Doctype');
+ $ret .= $this->row('Name', $doctype->name);
+ $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No');
+ $ret .= $this->row('Default Modules', implode($doctype->modules, ', '));
+ $ret .= $this->row('Default Tidy Modules', implode($doctype->tidyModules, ', '));
+ $ret .= $this->end('table');
+ return $ret;
+ }
+
+
+ /**
+ * Renders environment table, which is miscellaneous info
+ */
+ protected function renderEnvironment() {
+ $def = $this->def;
+
+ $ret = '';
+
+ $ret .= $this->start('table');
+ $ret .= $this->element('caption', 'Environment');
+
+ $ret .= $this->row('Parent of fragment', $def->info_parent);
+ $ret .= $this->renderChildren($def->info_parent_def->child);
+ $ret .= $this->row('Block wrap name', $def->info_block_wrapper);
+
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Global attributes');
+ $ret .= $this->element('td', $this->listifyAttr($def->info_global_attr),0,0);
+ $ret .= $this->end('tr');
+
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Tag transforms');
+ $list = array();
+ foreach ($def->info_tag_transform as $old => $new) {
+ $new = $this->getClass($new, 'TagTransform_');
+ $list[] = "<$old> with $new";
+ }
+ $ret .= $this->element('td', $this->listify($list));
+ $ret .= $this->end('tr');
+
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Pre-AttrTransform');
+ $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre));
+ $ret .= $this->end('tr');
+
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Post-AttrTransform');
+ $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post));
+ $ret .= $this->end('tr');
+
+ $ret .= $this->end('table');
+ return $ret;
+ }
+
+ /**
+ * Renders the Content Sets table
+ */
+ protected function renderContentSets() {
+ $ret = '';
+ $ret .= $this->start('table');
+ $ret .= $this->element('caption', 'Content Sets');
+ foreach ($this->def->info_content_sets as $name => $lookup) {
+ $ret .= $this->heavyHeader($name);
+ $ret .= $this->start('tr');
+ $ret .= $this->element('td', $this->listifyTagLookup($lookup));
+ $ret .= $this->end('tr');
+ }
+ $ret .= $this->end('table');
+ return $ret;
+ }
+
+ /**
+ * Renders the Elements ($info) table
+ */
+ protected function renderInfo() {
+ $ret = '';
+ $ret .= $this->start('table');
+ $ret .= $this->element('caption', 'Elements ($info)');
+ ksort($this->def->info);
+ $ret .= $this->heavyHeader('Allowed tags', 2);
+ $ret .= $this->start('tr');
+ $ret .= $this->element('td', $this->listifyTagLookup($this->def->info), array('colspan' => 2));
+ $ret .= $this->end('tr');
+ foreach ($this->def->info as $name => $def) {
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', "<$name>", array('class'=>'heavy', 'colspan' => 2));
+ $ret .= $this->end('tr');
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Inline content');
+ $ret .= $this->element('td', $def->descendants_are_inline ? 'Yes' : 'No');
+ $ret .= $this->end('tr');
+ if (!empty($def->excludes)) {
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Excludes');
+ $ret .= $this->element('td', $this->listifyTagLookup($def->excludes));
+ $ret .= $this->end('tr');
+ }
+ if (!empty($def->attr_transform_pre)) {
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Pre-AttrTransform');
+ $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_pre));
+ $ret .= $this->end('tr');
+ }
+ if (!empty($def->attr_transform_post)) {
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Post-AttrTransform');
+ $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_post));
+ $ret .= $this->end('tr');
+ }
+ if (!empty($def->auto_close)) {
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Auto closed by');
+ $ret .= $this->element('td', $this->listifyTagLookup($def->auto_close));
+ $ret .= $this->end('tr');
+ }
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', 'Allowed attributes');
+ $ret .= $this->element('td',$this->listifyAttr($def->attr), array(), 0);
+ $ret .= $this->end('tr');
+
+ if (!empty($def->required_attr)) {
+ $ret .= $this->row('Required attributes', $this->listify($def->required_attr));
+ }
+
+ $ret .= $this->renderChildren($def->child);
+ }
+ $ret .= $this->end('table');
+ return $ret;
+ }
+
+ /**
+ * Renders a row describing the allowed children of an element
+ * @param $def HTMLPurifier_ChildDef of pertinent element
+ */
+ protected function renderChildren($def) {
+ $context = new HTMLPurifier_Context();
+ $ret = '';
+ $ret .= $this->start('tr');
+ $elements = array();
+ $attr = array();
+ if (isset($def->elements)) {
+ if ($def->type == 'strictblockquote') {
+ $def->validateChildren(array(), $this->config, $context);
+ }
+ $elements = $def->elements;
+ }
+ if ($def->type == 'chameleon') {
+ $attr['rowspan'] = 2;
+ } elseif ($def->type == 'empty') {
+ $elements = array();
+ } elseif ($def->type == 'table') {
+ $elements = array_flip(array('col', 'caption', 'colgroup', 'thead',
+ 'tfoot', 'tbody', 'tr'));
+ }
+ $ret .= $this->element('th', 'Allowed children', $attr);
+
+ if ($def->type == 'chameleon') {
+
+ $ret .= $this->element('td',
+ '<em>Block</em>: ' .
+ $this->escape($this->listifyTagLookup($def->block->elements)),0,0);
+ $ret .= $this->end('tr');
+ $ret .= $this->start('tr');
+ $ret .= $this->element('td',
+ '<em>Inline</em>: ' .
+ $this->escape($this->listifyTagLookup($def->inline->elements)),0,0);
+
+ } elseif ($def->type == 'custom') {
+
+ $ret .= $this->element('td', '<em>'.ucfirst($def->type).'</em>: ' .
+ $def->dtd_regex);
+
+ } else {
+ $ret .= $this->element('td',
+ '<em>'.ucfirst($def->type).'</em>: ' .
+ $this->escape($this->listifyTagLookup($elements)),0,0);
+ }
+ $ret .= $this->end('tr');
+ return $ret;
+ }
+
+ /**
+ * Listifies a tag lookup table.
+ * @param $array Tag lookup array in form of array('tagname' => true)
+ */
+ protected function listifyTagLookup($array) {
+ ksort($array);
+ $list = array();
+ foreach ($array as $name => $discard) {
+ if ($name !== '#PCDATA' && !isset($this->def->info[$name])) continue;
+ $list[] = $name;
+ }
+ return $this->listify($list);
+ }
+
+ /**
+ * Listifies a list of objects by retrieving class names and internal state
+ * @param $array List of objects
+ * @todo Also add information about internal state
+ */
+ protected function listifyObjectList($array) {
+ ksort($array);
+ $list = array();
+ foreach ($array as $discard => $obj) {
+ $list[] = $this->getClass($obj, 'AttrTransform_');
+ }
+ return $this->listify($list);
+ }
+
+ /**
+ * Listifies a hash of attributes to AttrDef classes
+ * @param $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef)
+ */
+ protected function listifyAttr($array) {
+ ksort($array);
+ $list = array();
+ foreach ($array as $name => $obj) {
+ if ($obj === false) continue;
+ $list[] = "$name&nbsp;=&nbsp;<i>" . $this->getClass($obj, 'AttrDef_') . '</i>';
+ }
+ return $this->listify($list);
+ }
+
+ /**
+ * Creates a heavy header row
+ */
+ protected function heavyHeader($text, $num = 1) {
+ $ret = '';
+ $ret .= $this->start('tr');
+ $ret .= $this->element('th', $text, array('colspan' => $num, 'class' => 'heavy'));
+ $ret .= $this->end('tr');
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyList.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyList.php
new file mode 100644
index 0000000..088e071
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyList.php
@@ -0,0 +1,86 @@
+<?php
+
+/**
+ * Generic property list implementation
+ */
+class HTMLPurifier_PropertyList
+{
+ /**
+ * Internal data-structure for properties
+ */
+ protected $data = array();
+
+ /**
+ * Parent plist
+ */
+ protected $parent;
+
+ protected $cache;
+
+ public function __construct($parent = null) {
+ $this->parent = $parent;
+ }
+
+ /**
+ * Recursively retrieves the value for a key
+ */
+ public function get($name) {
+ if ($this->has($name)) return $this->data[$name];
+ // possible performance bottleneck, convert to iterative if necessary
+ if ($this->parent) return $this->parent->get($name);
+ throw new HTMLPurifier_Exception("Key '$name' not found");
+ }
+
+ /**
+ * Sets the value of a key, for this plist
+ */
+ public function set($name, $value) {
+ $this->data[$name] = $value;
+ }
+
+ /**
+ * Returns true if a given key exists
+ */
+ public function has($name) {
+ return array_key_exists($name, $this->data);
+ }
+
+ /**
+ * Resets a value to the value of it's parent, usually the default. If
+ * no value is specified, the entire plist is reset.
+ */
+ public function reset($name = null) {
+ if ($name == null) $this->data = array();
+ else unset($this->data[$name]);
+ }
+
+ /**
+ * Squashes this property list and all of its property lists into a single
+ * array, and returns the array. This value is cached by default.
+ * @param $force If true, ignores the cache and regenerates the array.
+ */
+ public function squash($force = false) {
+ if ($this->cache !== null && !$force) return $this->cache;
+ if ($this->parent) {
+ return $this->cache = array_merge($this->parent->squash($force), $this->data);
+ } else {
+ return $this->cache = $this->data;
+ }
+ }
+
+ /**
+ * Returns the parent plist.
+ */
+ public function getParent() {
+ return $this->parent;
+ }
+
+ /**
+ * Sets the parent plist.
+ */
+ public function setParent($plist) {
+ $this->parent = $plist;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyListIterator.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyListIterator.php
new file mode 100644
index 0000000..d5084d0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/PropertyListIterator.php
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * Property list iterator. Do not instantiate this class directly.
+ */
+class HTMLPurifier_PropertyListIterator extends FilterIterator
+{
+
+ protected $l;
+ protected $filter;
+
+ /**
+ * @param $data Array of data to iterate over
+ * @param $filter Optional prefix to only allow values of
+ */
+ public function __construct(Iterator $iterator, $filter = null) {
+ parent::__construct($iterator);
+ $this->l = strlen($filter);
+ $this->filter = $filter;
+ }
+
+ public function accept() {
+ $key = $this->getInnerIterator()->key();
+ if( strncmp($key, $this->filter, $this->l) !== 0 ) {
+ return false;
+ }
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy.php
new file mode 100644
index 0000000..a805053
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * Supertype for classes that define a strategy for modifying/purifying tokens.
+ *
+ * While HTMLPurifier's core purpose is fixing HTML into something proper,
+ * strategies provide plug points for extra configuration or even extra
+ * features, such as custom tags, custom parsing of text, etc.
+ */
+
+
+abstract class HTMLPurifier_Strategy
+{
+
+ /**
+ * Executes the strategy on the tokens.
+ *
+ * @param $tokens Array of HTMLPurifier_Token objects to be operated on.
+ * @param $config Configuration options
+ * @returns Processed array of token objects.
+ */
+ abstract public function execute($tokens, $config, $context);
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Composite.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Composite.php
new file mode 100644
index 0000000..ccfb896
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Composite.php
@@ -0,0 +1,25 @@
+<?php
+
+/**
+ * Composite strategy that runs multiple strategies on tokens.
+ */
+abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy
+{
+
+ /**
+ * List of strategies to run tokens through.
+ */
+ protected $strategies = array();
+
+ abstract public function __construct();
+
+ public function execute($tokens, $config, $context) {
+ foreach ($this->strategies as $strategy) {
+ $tokens = $strategy->execute($tokens, $config, $context);
+ }
+ return $tokens;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Core.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Core.php
new file mode 100644
index 0000000..6df0123
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/Core.php
@@ -0,0 +1,18 @@
+<?php
+
+/**
+ * Core strategy composed of the big four strategies.
+ */
+class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite
+{
+
+ public function __construct() {
+ $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements();
+ $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed();
+ $this->strategies[] = new HTMLPurifier_Strategy_FixNesting();
+ $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes();
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/FixNesting.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/FixNesting.php
new file mode 100644
index 0000000..8a4f9ce
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/FixNesting.php
@@ -0,0 +1,328 @@
+<?php
+
+/**
+ * Takes a well formed list of tokens and fixes their nesting.
+ *
+ * HTML elements dictate which elements are allowed to be their children,
+ * for example, you can't have a p tag in a span tag. Other elements have
+ * much more rigorous definitions: tables, for instance, require a specific
+ * order for their elements. There are also constraints not expressible by
+ * document type definitions, such as the chameleon nature of ins/del
+ * tags and global child exclusions.
+ *
+ * The first major objective of this strategy is to iterate through all the
+ * nodes (not tokens) of the list of tokens and determine whether or not
+ * their children conform to the element's definition. If they do not, the
+ * child definition may optionally supply an amended list of elements that
+ * is valid or require that the entire node be deleted (and the previous
+ * node rescanned).
+ *
+ * The second objective is to ensure that explicitly excluded elements of
+ * an element do not appear in its children. Code that accomplishes this
+ * task is pervasive through the strategy, though the two are distinct tasks
+ * and could, theoretically, be seperated (although it's not recommended).
+ *
+ * @note Whether or not unrecognized children are silently dropped or
+ * translated into text depends on the child definitions.
+ *
+ * @todo Enable nodes to be bubbled out of the structure.
+ */
+
+class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy
+{
+
+ public function execute($tokens, $config, $context) {
+ //####################################################################//
+ // Pre-processing
+
+ // get a copy of the HTML definition
+ $definition = $config->getHTMLDefinition();
+
+ // insert implicit "parent" node, will be removed at end.
+ // DEFINITION CALL
+ $parent_name = $definition->info_parent;
+ array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));
+ $tokens[] = new HTMLPurifier_Token_End($parent_name);
+
+ // setup the context variable 'IsInline', for chameleon processing
+ // is 'false' when we are not inline, 'true' when it must always
+ // be inline, and an integer when it is inline for a certain
+ // branch of the document tree
+ $is_inline = $definition->info_parent_def->descendants_are_inline;
+ $context->register('IsInline', $is_inline);
+
+ // setup error collector
+ $e =& $context->get('ErrorCollector', true);
+
+ //####################################################################//
+ // Loop initialization
+
+ // stack that contains the indexes of all parents,
+ // $stack[count($stack)-1] being the current parent
+ $stack = array();
+
+ // stack that contains all elements that are excluded
+ // it is organized by parent elements, similar to $stack,
+ // but it is only populated when an element with exclusions is
+ // processed, i.e. there won't be empty exclusions.
+ $exclude_stack = array();
+
+ // variable that contains the start token while we are processing
+ // nodes. This enables error reporting to do its job
+ $start_token = false;
+ $context->register('CurrentToken', $start_token);
+
+ //####################################################################//
+ // Loop
+
+ // iterate through all start nodes. Determining the start node
+ // is complicated so it has been omitted from the loop construct
+ for ($i = 0, $size = count($tokens) ; $i < $size; ) {
+
+ //################################################################//
+ // Gather information on children
+
+ // child token accumulator
+ $child_tokens = array();
+
+ // scroll to the end of this node, report number, and collect
+ // all children
+ for ($j = $i, $depth = 0; ; $j++) {
+ if ($tokens[$j] instanceof HTMLPurifier_Token_Start) {
+ $depth++;
+ // skip token assignment on first iteration, this is the
+ // token we currently are on
+ if ($depth == 1) continue;
+ } elseif ($tokens[$j] instanceof HTMLPurifier_Token_End) {
+ $depth--;
+ // skip token assignment on last iteration, this is the
+ // end token of the token we're currently on
+ if ($depth == 0) break;
+ }
+ $child_tokens[] = $tokens[$j];
+ }
+
+ // $i is index of start token
+ // $j is index of end token
+
+ $start_token = $tokens[$i]; // to make token available via CurrentToken
+
+ //################################################################//
+ // Gather information on parent
+
+ // calculate parent information
+ if ($count = count($stack)) {
+ $parent_index = $stack[$count-1];
+ $parent_name = $tokens[$parent_index]->name;
+ if ($parent_index == 0) {
+ $parent_def = $definition->info_parent_def;
+ } else {
+ $parent_def = $definition->info[$parent_name];
+ }
+ } else {
+ // processing as if the parent were the "root" node
+ // unknown info, it won't be used anyway, in the future,
+ // we may want to enforce one element only (this is
+ // necessary for HTML Purifier to clean entire documents
+ $parent_index = $parent_name = $parent_def = null;
+ }
+
+ // calculate context
+ if ($is_inline === false) {
+ // check if conditions make it inline
+ if (!empty($parent_def) && $parent_def->descendants_are_inline) {
+ $is_inline = $count - 1;
+ }
+ } else {
+ // check if we're out of inline
+ if ($count === $is_inline) {
+ $is_inline = false;
+ }
+ }
+
+ //################################################################//
+ // Determine whether element is explicitly excluded SGML-style
+
+ // determine whether or not element is excluded by checking all
+ // parent exclusions. The array should not be very large, two
+ // elements at most.
+ $excluded = false;
+ if (!empty($exclude_stack)) {
+ foreach ($exclude_stack as $lookup) {
+ if (isset($lookup[$tokens[$i]->name])) {
+ $excluded = true;
+ // no need to continue processing
+ break;
+ }
+ }
+ }
+
+ //################################################################//
+ // Perform child validation
+
+ if ($excluded) {
+ // there is an exclusion, remove the entire node
+ $result = false;
+ $excludes = array(); // not used, but good to initialize anyway
+ } else {
+ // DEFINITION CALL
+ if ($i === 0) {
+ // special processing for the first node
+ $def = $definition->info_parent_def;
+ } else {
+ $def = $definition->info[$tokens[$i]->name];
+
+ }
+
+ if (!empty($def->child)) {
+ // have DTD child def validate children
+ $result = $def->child->validateChildren(
+ $child_tokens, $config, $context);
+ } else {
+ // weird, no child definition, get rid of everything
+ $result = false;
+ }
+
+ // determine whether or not this element has any exclusions
+ $excludes = $def->excludes;
+ }
+
+ // $result is now a bool or array
+
+ //################################################################//
+ // Process result by interpreting $result
+
+ if ($result === true || $child_tokens === $result) {
+ // leave the node as is
+
+ // register start token as a parental node start
+ $stack[] = $i;
+
+ // register exclusions if there are any
+ if (!empty($excludes)) $exclude_stack[] = $excludes;
+
+ // move cursor to next possible start node
+ $i++;
+
+ } elseif($result === false) {
+ // remove entire node
+
+ if ($e) {
+ if ($excluded) {
+ $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
+ } else {
+ $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
+ }
+ }
+
+ // calculate length of inner tokens and current tokens
+ $length = $j - $i + 1;
+
+ // perform removal
+ array_splice($tokens, $i, $length);
+
+ // update size
+ $size -= $length;
+
+ // there is no start token to register,
+ // current node is now the next possible start node
+ // unless it turns out that we need to do a double-check
+
+ // this is a rought heuristic that covers 100% of HTML's
+ // cases and 99% of all other cases. A child definition
+ // that would be tricked by this would be something like:
+ // ( | a b c) where it's all or nothing. Fortunately,
+ // our current implementation claims that that case would
+ // not allow empty, even if it did
+ if (!$parent_def->child->allow_empty) {
+ // we need to do a double-check
+ $i = $parent_index;
+ array_pop($stack);
+ }
+
+ // PROJECTED OPTIMIZATION: Process all children elements before
+ // reprocessing parent node.
+
+ } else {
+ // replace node with $result
+
+ // calculate length of inner tokens
+ $length = $j - $i - 1;
+
+ if ($e) {
+ if (empty($result) && $length) {
+ $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
+ } else {
+ $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
+ }
+ }
+
+ // perform replacement
+ array_splice($tokens, $i + 1, $length, $result);
+
+ // update size
+ $size -= $length;
+ $size += count($result);
+
+ // register start token as a parental node start
+ $stack[] = $i;
+
+ // register exclusions if there are any
+ if (!empty($excludes)) $exclude_stack[] = $excludes;
+
+ // move cursor to next possible start node
+ $i++;
+
+ }
+
+ //################################################################//
+ // Scroll to next start node
+
+ // We assume, at this point, that $i is the index of the token
+ // that is the first possible new start point for a node.
+
+ // Test if the token indeed is a start tag, if not, move forward
+ // and test again.
+ $size = count($tokens);
+ while ($i < $size and !$tokens[$i] instanceof HTMLPurifier_Token_Start) {
+ if ($tokens[$i] instanceof HTMLPurifier_Token_End) {
+ // pop a token index off the stack if we ended a node
+ array_pop($stack);
+ // pop an exclusion lookup off exclusion stack if
+ // we ended node and that node had exclusions
+ if ($i == 0 || $i == $size - 1) {
+ // use specialized var if it's the super-parent
+ $s_excludes = $definition->info_parent_def->excludes;
+ } else {
+ $s_excludes = $definition->info[$tokens[$i]->name]->excludes;
+ }
+ if ($s_excludes) {
+ array_pop($exclude_stack);
+ }
+ }
+ $i++;
+ }
+
+ }
+
+ //####################################################################//
+ // Post-processing
+
+ // remove implicit parent tokens at the beginning and end
+ array_shift($tokens);
+ array_pop($tokens);
+
+ // remove context variables
+ $context->destroy('IsInline');
+ $context->destroy('CurrentToken');
+
+ //####################################################################//
+ // Return
+
+ return $tokens;
+
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/MakeWellFormed.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/MakeWellFormed.php
new file mode 100644
index 0000000..9581a51
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/MakeWellFormed.php
@@ -0,0 +1,532 @@
+<?php
+
+/**
+ * Takes tokens makes them well-formed (balance end tags, etc.)
+ *
+ * Specification of the armor attributes this strategy uses:
+ *
+ * - MakeWellFormed_TagClosedError: This armor field is used to
+ * suppress tag closed errors for certain tokens [TagClosedSuppress],
+ * in particular, if a tag was generated automatically by HTML
+ * Purifier, we may rely on our infrastructure to close it for us
+ * and shouldn't report an error to the user [TagClosedAuto].
+ */
+class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
+{
+
+ /**
+ * Array stream of tokens being processed.
+ */
+ protected $tokens;
+
+ /**
+ * Current index in $tokens.
+ */
+ protected $t;
+
+ /**
+ * Current nesting of elements.
+ */
+ protected $stack;
+
+ /**
+ * Injectors active in this stream processing.
+ */
+ protected $injectors;
+
+ /**
+ * Current instance of HTMLPurifier_Config.
+ */
+ protected $config;
+
+ /**
+ * Current instance of HTMLPurifier_Context.
+ */
+ protected $context;
+
+ public function execute($tokens, $config, $context) {
+
+ $definition = $config->getHTMLDefinition();
+
+ // local variables
+ $generator = new HTMLPurifier_Generator($config, $context);
+ $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
+ // used for autoclose early abortion
+ $global_parent_allowed_elements = array();
+ if (isset($definition->info[$definition->info_parent])) {
+ // may be unset under testing circumstances
+ $global_parent_allowed_elements = $definition->info[$definition->info_parent]->child->getAllowedElements($config);
+ }
+ $e = $context->get('ErrorCollector', true);
+ $t = false; // token index
+ $i = false; // injector index
+ $token = false; // the current token
+ $reprocess = false; // whether or not to reprocess the same token
+ $stack = array();
+
+ // member variables
+ $this->stack =& $stack;
+ $this->t =& $t;
+ $this->tokens =& $tokens;
+ $this->config = $config;
+ $this->context = $context;
+
+ // context variables
+ $context->register('CurrentNesting', $stack);
+ $context->register('InputIndex', $t);
+ $context->register('InputTokens', $tokens);
+ $context->register('CurrentToken', $token);
+
+ // -- begin INJECTOR --
+
+ $this->injectors = array();
+
+ $injectors = $config->getBatch('AutoFormat');
+ $def_injectors = $definition->info_injector;
+ $custom_injectors = $injectors['Custom'];
+ unset($injectors['Custom']); // special case
+ foreach ($injectors as $injector => $b) {
+ // XXX: Fix with a legitimate lookup table of enabled filters
+ if (strpos($injector, '.') !== false) continue;
+ $injector = "HTMLPurifier_Injector_$injector";
+ if (!$b) continue;
+ $this->injectors[] = new $injector;
+ }
+ foreach ($def_injectors as $injector) {
+ // assumed to be objects
+ $this->injectors[] = $injector;
+ }
+ foreach ($custom_injectors as $injector) {
+ if (!$injector) continue;
+ if (is_string($injector)) {
+ $injector = "HTMLPurifier_Injector_$injector";
+ $injector = new $injector;
+ }
+ $this->injectors[] = $injector;
+ }
+
+ // give the injectors references to the definition and context
+ // variables for performance reasons
+ foreach ($this->injectors as $ix => $injector) {
+ $error = $injector->prepare($config, $context);
+ if (!$error) continue;
+ array_splice($this->injectors, $ix, 1); // rm the injector
+ trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
+ }
+
+ // -- end INJECTOR --
+
+ // a note on reprocessing:
+ // In order to reduce code duplication, whenever some code needs
+ // to make HTML changes in order to make things "correct", the
+ // new HTML gets sent through the purifier, regardless of its
+ // status. This means that if we add a start token, because it
+ // was totally necessary, we don't have to update nesting; we just
+ // punt ($reprocess = true; continue;) and it does that for us.
+
+ // isset is in loop because $tokens size changes during loop exec
+ for (
+ $t = 0;
+ $t == 0 || isset($tokens[$t - 1]);
+ // only increment if we don't need to reprocess
+ $reprocess ? $reprocess = false : $t++
+ ) {
+
+ // check for a rewind
+ if (is_int($i) && $i >= 0) {
+ // possibility: disable rewinding if the current token has a
+ // rewind set on it already. This would offer protection from
+ // infinite loop, but might hinder some advanced rewinding.
+ $rewind_to = $this->injectors[$i]->getRewind();
+ if (is_int($rewind_to) && $rewind_to < $t) {
+ if ($rewind_to < 0) $rewind_to = 0;
+ while ($t > $rewind_to) {
+ $t--;
+ $prev = $tokens[$t];
+ // indicate that other injectors should not process this token,
+ // but we need to reprocess it
+ unset($prev->skip[$i]);
+ $prev->rewind = $i;
+ if ($prev instanceof HTMLPurifier_Token_Start) array_pop($this->stack);
+ elseif ($prev instanceof HTMLPurifier_Token_End) $this->stack[] = $prev->start;
+ }
+ }
+ $i = false;
+ }
+
+ // handle case of document end
+ if (!isset($tokens[$t])) {
+ // kill processing if stack is empty
+ if (empty($this->stack)) break;
+
+ // peek
+ $top_nesting = array_pop($this->stack);
+ $this->stack[] = $top_nesting;
+
+ // send error [TagClosedSuppress]
+ if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
+ $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
+ }
+
+ // append, don't splice, since this is the end
+ $tokens[] = new HTMLPurifier_Token_End($top_nesting->name);
+
+ // punt!
+ $reprocess = true;
+ continue;
+ }
+
+ $token = $tokens[$t];
+
+ //echo '<br>'; printTokens($tokens, $t); printTokens($this->stack);
+ //flush();
+
+ // quick-check: if it's not a tag, no need to process
+ if (empty($token->is_tag)) {
+ if ($token instanceof HTMLPurifier_Token_Text) {
+ foreach ($this->injectors as $i => $injector) {
+ if (isset($token->skip[$i])) continue;
+ if ($token->rewind !== null && $token->rewind !== $i) continue;
+ $injector->handleText($token);
+ $this->processToken($token, $i);
+ $reprocess = true;
+ break;
+ }
+ }
+ // another possibility is a comment
+ continue;
+ }
+
+ if (isset($definition->info[$token->name])) {
+ $type = $definition->info[$token->name]->child->type;
+ } else {
+ $type = false; // Type is unknown, treat accordingly
+ }
+
+ // quick tag checks: anything that's *not* an end tag
+ $ok = false;
+ if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
+ // claims to be a start tag but is empty
+ $token = new HTMLPurifier_Token_Empty($token->name, $token->attr, $token->line, $token->col, $token->armor);
+ $ok = true;
+ } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
+ // claims to be empty but really is a start tag
+ $this->swap(new HTMLPurifier_Token_End($token->name));
+ $this->insertBefore(new HTMLPurifier_Token_Start($token->name, $token->attr, $token->line, $token->col, $token->armor));
+ // punt (since we had to modify the input stream in a non-trivial way)
+ $reprocess = true;
+ continue;
+ } elseif ($token instanceof HTMLPurifier_Token_Empty) {
+ // real empty token
+ $ok = true;
+ } elseif ($token instanceof HTMLPurifier_Token_Start) {
+ // start tag
+
+ // ...unless they also have to close their parent
+ if (!empty($this->stack)) {
+
+ // Performance note: you might think that it's rather
+ // inefficient, recalculating the autoclose information
+ // for every tag that a token closes (since when we
+ // do an autoclose, we push a new token into the
+ // stream and then /process/ that, before
+ // re-processing this token.) But this is
+ // necessary, because an injector can make an
+ // arbitrary transformations to the autoclosing
+ // tokens we introduce, so things may have changed
+ // in the meantime. Also, doing the inefficient thing is
+ // "easy" to reason about (for certain perverse definitions
+ // of "easy")
+
+ $parent = array_pop($this->stack);
+ $this->stack[] = $parent;
+
+ if (isset($definition->info[$parent->name])) {
+ $elements = $definition->info[$parent->name]->child->getAllowedElements($config);
+ $autoclose = !isset($elements[$token->name]);
+ } else {
+ $autoclose = false;
+ }
+
+ if ($autoclose && $definition->info[$token->name]->wrap) {
+ // Check if an element can be wrapped by another
+ // element to make it valid in a context (for
+ // example, <ul><ul> needs a <li> in between)
+ $wrapname = $definition->info[$token->name]->wrap;
+ $wrapdef = $definition->info[$wrapname];
+ $elements = $wrapdef->child->getAllowedElements($config);
+ $parent_elements = $definition->info[$parent->name]->child->getAllowedElements($config);
+ if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) {
+ $newtoken = new HTMLPurifier_Token_Start($wrapname);
+ $this->insertBefore($newtoken);
+ $reprocess = true;
+ continue;
+ }
+ }
+
+ $carryover = false;
+ if ($autoclose && $definition->info[$parent->name]->formatting) {
+ $carryover = true;
+ }
+
+ if ($autoclose) {
+ // check if this autoclose is doomed to fail
+ // (this rechecks $parent, which his harmless)
+ $autoclose_ok = isset($global_parent_allowed_elements[$token->name]);
+ if (!$autoclose_ok) {
+ foreach ($this->stack as $ancestor) {
+ $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config);
+ if (isset($elements[$token->name])) {
+ $autoclose_ok = true;
+ break;
+ }
+ if ($definition->info[$token->name]->wrap) {
+ $wrapname = $definition->info[$token->name]->wrap;
+ $wrapdef = $definition->info[$wrapname];
+ $wrap_elements = $wrapdef->child->getAllowedElements($config);
+ if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) {
+ $autoclose_ok = true;
+ break;
+ }
+ }
+ }
+ }
+ if ($autoclose_ok) {
+ // errors need to be updated
+ $new_token = new HTMLPurifier_Token_End($parent->name);
+ $new_token->start = $parent;
+ if ($carryover) {
+ $element = clone $parent;
+ // [TagClosedAuto]
+ $element->armor['MakeWellFormed_TagClosedError'] = true;
+ $element->carryover = true;
+ $this->processToken(array($new_token, $token, $element));
+ } else {
+ $this->insertBefore($new_token);
+ }
+ // [TagClosedSuppress]
+ if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {
+ if (!$carryover) {
+ $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
+ } else {
+ $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);
+ }
+ }
+ } else {
+ $this->remove();
+ }
+ $reprocess = true;
+ continue;
+ }
+
+ }
+ $ok = true;
+ }
+
+ if ($ok) {
+ foreach ($this->injectors as $i => $injector) {
+ if (isset($token->skip[$i])) continue;
+ if ($token->rewind !== null && $token->rewind !== $i) continue;
+ $injector->handleElement($token);
+ $this->processToken($token, $i);
+ $reprocess = true;
+ break;
+ }
+ if (!$reprocess) {
+ // ah, nothing interesting happened; do normal processing
+ $this->swap($token);
+ if ($token instanceof HTMLPurifier_Token_Start) {
+ $this->stack[] = $token;
+ } elseif ($token instanceof HTMLPurifier_Token_End) {
+ throw new HTMLPurifier_Exception('Improper handling of end tag in start code; possible error in MakeWellFormed');
+ }
+ }
+ continue;
+ }
+
+ // sanity check: we should be dealing with a closing tag
+ if (!$token instanceof HTMLPurifier_Token_End) {
+ throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
+ }
+
+ // make sure that we have something open
+ if (empty($this->stack)) {
+ if ($escape_invalid_tags) {
+ if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
+ $this->swap(new HTMLPurifier_Token_Text(
+ $generator->generateFromToken($token)
+ ));
+ } else {
+ $this->remove();
+ if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
+ }
+ $reprocess = true;
+ continue;
+ }
+
+ // first, check for the simplest case: everything closes neatly.
+ // Eventually, everything passes through here; if there are problems
+ // we modify the input stream accordingly and then punt, so that
+ // the tokens get processed again.
+ $current_parent = array_pop($this->stack);
+ if ($current_parent->name == $token->name) {
+ $token->start = $current_parent;
+ foreach ($this->injectors as $i => $injector) {
+ if (isset($token->skip[$i])) continue;
+ if ($token->rewind !== null && $token->rewind !== $i) continue;
+ $injector->handleEnd($token);
+ $this->processToken($token, $i);
+ $this->stack[] = $current_parent;
+ $reprocess = true;
+ break;
+ }
+ continue;
+ }
+
+ // okay, so we're trying to close the wrong tag
+
+ // undo the pop previous pop
+ $this->stack[] = $current_parent;
+
+ // scroll back the entire nest, trying to find our tag.
+ // (feature could be to specify how far you'd like to go)
+ $size = count($this->stack);
+ // -2 because -1 is the last element, but we already checked that
+ $skipped_tags = false;
+ for ($j = $size - 2; $j >= 0; $j--) {
+ if ($this->stack[$j]->name == $token->name) {
+ $skipped_tags = array_slice($this->stack, $j);
+ break;
+ }
+ }
+
+ // we didn't find the tag, so remove
+ if ($skipped_tags === false) {
+ if ($escape_invalid_tags) {
+ $this->swap(new HTMLPurifier_Token_Text(
+ $generator->generateFromToken($token)
+ ));
+ if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
+ } else {
+ $this->remove();
+ if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
+ }
+ $reprocess = true;
+ continue;
+ }
+
+ // do errors, in REVERSE $j order: a,b,c with </a></b></c>
+ $c = count($skipped_tags);
+ if ($e) {
+ for ($j = $c - 1; $j > 0; $j--) {
+ // notice we exclude $j == 0, i.e. the current ending tag, from
+ // the errors... [TagClosedSuppress]
+ if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
+ $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
+ }
+ }
+ }
+
+ // insert tags, in FORWARD $j order: c,b,a with </a></b></c>
+ $replace = array($token);
+ for ($j = 1; $j < $c; $j++) {
+ // ...as well as from the insertions
+ $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
+ $new_token->start = $skipped_tags[$j];
+ array_unshift($replace, $new_token);
+ if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {
+ // [TagClosedAuto]
+ $element = clone $skipped_tags[$j];
+ $element->carryover = true;
+ $element->armor['MakeWellFormed_TagClosedError'] = true;
+ $replace[] = $element;
+ }
+ }
+ $this->processToken($replace);
+ $reprocess = true;
+ continue;
+ }
+
+ $context->destroy('CurrentNesting');
+ $context->destroy('InputTokens');
+ $context->destroy('InputIndex');
+ $context->destroy('CurrentToken');
+
+ unset($this->injectors, $this->stack, $this->tokens, $this->t);
+ return $tokens;
+ }
+
+ /**
+ * Processes arbitrary token values for complicated substitution patterns.
+ * In general:
+ *
+ * If $token is an array, it is a list of tokens to substitute for the
+ * current token. These tokens then get individually processed. If there
+ * is a leading integer in the list, that integer determines how many
+ * tokens from the stream should be removed.
+ *
+ * If $token is a regular token, it is swapped with the current token.
+ *
+ * If $token is false, the current token is deleted.
+ *
+ * If $token is an integer, that number of tokens (with the first token
+ * being the current one) will be deleted.
+ *
+ * @param $token Token substitution value
+ * @param $injector Injector that performed the substitution; default is if
+ * this is not an injector related operation.
+ */
+ protected function processToken($token, $injector = -1) {
+
+ // normalize forms of token
+ if (is_object($token)) $token = array(1, $token);
+ if (is_int($token)) $token = array($token);
+ if ($token === false) $token = array(1);
+ if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');
+ if (!is_int($token[0])) array_unshift($token, 1);
+ if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
+
+ // $token is now an array with the following form:
+ // array(number nodes to delete, new node 1, new node 2, ...)
+
+ $delete = array_shift($token);
+ $old = array_splice($this->tokens, $this->t, $delete, $token);
+
+ if ($injector > -1) {
+ // determine appropriate skips
+ $oldskip = isset($old[0]) ? $old[0]->skip : array();
+ foreach ($token as $object) {
+ $object->skip = $oldskip;
+ $object->skip[$injector] = true;
+ }
+ }
+
+ }
+
+ /**
+ * Inserts a token before the current token. Cursor now points to
+ * this token. You must reprocess after this.
+ */
+ private function insertBefore($token) {
+ array_splice($this->tokens, $this->t, 0, array($token));
+ }
+
+ /**
+ * Removes current token. Cursor now points to new token occupying previously
+ * occupied space. You must reprocess after this.
+ */
+ private function remove() {
+ array_splice($this->tokens, $this->t, 1);
+ }
+
+ /**
+ * Swap current token with new token. Cursor points to new token (no
+ * change). You must reprocess after this.
+ */
+ private function swap($token) {
+ $this->tokens[$this->t] = $token;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/RemoveForeignElements.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/RemoveForeignElements.php
new file mode 100644
index 0000000..7da8314
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/RemoveForeignElements.php
@@ -0,0 +1,171 @@
+<?php
+
+/**
+ * Removes all unrecognized tags from the list of tokens.
+ *
+ * This strategy iterates through all the tokens and removes unrecognized
+ * tokens. If a token is not recognized but a TagTransform is defined for
+ * that element, the element will be transformed accordingly.
+ */
+
+class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy
+{
+
+ public function execute($tokens, $config, $context) {
+ $definition = $config->getHTMLDefinition();
+ $generator = new HTMLPurifier_Generator($config, $context);
+ $result = array();
+
+ $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
+ $remove_invalid_img = $config->get('Core.RemoveInvalidImg');
+
+ // currently only used to determine if comments should be kept
+ $trusted = $config->get('HTML.Trusted');
+
+ $remove_script_contents = $config->get('Core.RemoveScriptContents');
+ $hidden_elements = $config->get('Core.HiddenElements');
+
+ // remove script contents compatibility
+ if ($remove_script_contents === true) {
+ $hidden_elements['script'] = true;
+ } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {
+ unset($hidden_elements['script']);
+ }
+
+ $attr_validator = new HTMLPurifier_AttrValidator();
+
+ // removes tokens until it reaches a closing tag with its value
+ $remove_until = false;
+
+ // converts comments into text tokens when this is equal to a tag name
+ $textify_comments = false;
+
+ $token = false;
+ $context->register('CurrentToken', $token);
+
+ $e = false;
+ if ($config->get('Core.CollectErrors')) {
+ $e =& $context->get('ErrorCollector');
+ }
+
+ foreach($tokens as $token) {
+ if ($remove_until) {
+ if (empty($token->is_tag) || $token->name !== $remove_until) {
+ continue;
+ }
+ }
+ if (!empty( $token->is_tag )) {
+ // DEFINITION CALL
+
+ // before any processing, try to transform the element
+ if (
+ isset($definition->info_tag_transform[$token->name])
+ ) {
+ $original_name = $token->name;
+ // there is a transformation for this tag
+ // DEFINITION CALL
+ $token = $definition->
+ info_tag_transform[$token->name]->
+ transform($token, $config, $context);
+ if ($e) $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);
+ }
+
+ if (isset($definition->info[$token->name])) {
+
+ // mostly everything's good, but
+ // we need to make sure required attributes are in order
+ if (
+ ($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) &&
+ $definition->info[$token->name]->required_attr &&
+ ($token->name != 'img' || $remove_invalid_img) // ensure config option still works
+ ) {
+ $attr_validator->validateToken($token, $config, $context);
+ $ok = true;
+ foreach ($definition->info[$token->name]->required_attr as $name) {
+ if (!isset($token->attr[$name])) {
+ $ok = false;
+ break;
+ }
+ }
+ if (!$ok) {
+ if ($e) $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Missing required attribute', $name);
+ continue;
+ }
+ $token->armor['ValidateAttributes'] = true;
+ }
+
+ if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {
+ $textify_comments = $token->name;
+ } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {
+ $textify_comments = false;
+ }
+
+ } elseif ($escape_invalid_tags) {
+ // invalid tag, generate HTML representation and insert in
+ if ($e) $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');
+ $token = new HTMLPurifier_Token_Text(
+ $generator->generateFromToken($token)
+ );
+ } else {
+ // check if we need to destroy all of the tag's children
+ // CAN BE GENERICIZED
+ if (isset($hidden_elements[$token->name])) {
+ if ($token instanceof HTMLPurifier_Token_Start) {
+ $remove_until = $token->name;
+ } elseif ($token instanceof HTMLPurifier_Token_Empty) {
+ // do nothing: we're still looking
+ } else {
+ $remove_until = false;
+ }
+ if ($e) $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');
+ } else {
+ if ($e) $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');
+ }
+ continue;
+ }
+ } elseif ($token instanceof HTMLPurifier_Token_Comment) {
+ // textify comments in script tags when they are allowed
+ if ($textify_comments !== false) {
+ $data = $token->data;
+ $token = new HTMLPurifier_Token_Text($data);
+ } elseif ($trusted) {
+ // keep, but perform comment cleaning
+ if ($e) {
+ // perform check whether or not there's a trailing hyphen
+ if (substr($token->data, -1) == '-') {
+ $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed');
+ }
+ }
+ $token->data = rtrim($token->data, '-');
+ $found_double_hyphen = false;
+ while (strpos($token->data, '--') !== false) {
+ if ($e && !$found_double_hyphen) {
+ $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed');
+ }
+ $found_double_hyphen = true; // prevent double-erroring
+ $token->data = str_replace('--', '-', $token->data);
+ }
+ } else {
+ // strip comments
+ if ($e) $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');
+ continue;
+ }
+ } elseif ($token instanceof HTMLPurifier_Token_Text) {
+ } else {
+ continue;
+ }
+ $result[] = $token;
+ }
+ if ($remove_until && $e) {
+ // we removed tokens until the end, throw error
+ $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until);
+ }
+
+ $context->destroy('CurrentToken');
+
+ return $result;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/ValidateAttributes.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/ValidateAttributes.php
new file mode 100644
index 0000000..bcadacb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Strategy/ValidateAttributes.php
@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * Validate all attributes in the tokens.
+ */
+
+class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy
+{
+
+ public function execute($tokens, $config, $context) {
+
+ // setup validator
+ $validator = new HTMLPurifier_AttrValidator();
+
+ $token = false;
+ $context->register('CurrentToken', $token);
+
+ foreach ($tokens as $key => $token) {
+
+ // only process tokens that have attributes,
+ // namely start and empty tags
+ if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) continue;
+
+ // skip tokens that are armored
+ if (!empty($token->armor['ValidateAttributes'])) continue;
+
+ // note that we have no facilities here for removing tokens
+ $validator->validateToken($token, $config, $context);
+
+ $tokens[$key] = $token; // for PHP 4
+ }
+ $context->destroy('CurrentToken');
+
+ return $tokens;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHash.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHash.php
new file mode 100644
index 0000000..465f496
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHash.php
@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * This is in almost every respect equivalent to an array except
+ * that it keeps track of which keys were accessed.
+ *
+ * @warning For the sake of backwards compatibility with early versions
+ * of PHP 5, you must not use the $hash[$key] syntax; if you do
+ * our version of offsetGet is never called.
+ */
+class HTMLPurifier_StringHash extends ArrayObject
+{
+ protected $accessed = array();
+
+ /**
+ * Retrieves a value, and logs the access.
+ */
+ public function offsetGet($index) {
+ $this->accessed[$index] = true;
+ return parent::offsetGet($index);
+ }
+
+ /**
+ * Returns a lookup array of all array indexes that have been accessed.
+ * @return Array in form array($index => true).
+ */
+ public function getAccessed() {
+ return $this->accessed;
+ }
+
+ /**
+ * Resets the access array.
+ */
+ public function resetAccessed() {
+ $this->accessed = array();
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHashParser.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHashParser.php
new file mode 100644
index 0000000..3a30015
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/StringHashParser.php
@@ -0,0 +1,110 @@
+<?php
+
+/**
+ * Parses string hash files. File format is as such:
+ *
+ * DefaultKeyValue
+ * KEY: Value
+ * KEY2: Value2
+ * --MULTILINE-KEY--
+ * Multiline
+ * value.
+ *
+ * Which would output something similar to:
+ *
+ * array(
+ * 'ID' => 'DefaultKeyValue',
+ * 'KEY' => 'Value',
+ * 'KEY2' => 'Value2',
+ * 'MULTILINE-KEY' => "Multiline\nvalue.\n",
+ * )
+ *
+ * We use this as an easy to use file-format for configuration schema
+ * files, but the class itself is usage agnostic.
+ *
+ * You can use ---- to forcibly terminate parsing of a single string-hash;
+ * this marker is used in multi string-hashes to delimit boundaries.
+ */
+class HTMLPurifier_StringHashParser
+{
+
+ public $default = 'ID';
+
+ /**
+ * Parses a file that contains a single string-hash.
+ */
+ public function parseFile($file) {
+ if (!file_exists($file)) return false;
+ $fh = fopen($file, 'r');
+ if (!$fh) return false;
+ $ret = $this->parseHandle($fh);
+ fclose($fh);
+ return $ret;
+ }
+
+ /**
+ * Parses a file that contains multiple string-hashes delimited by '----'
+ */
+ public function parseMultiFile($file) {
+ if (!file_exists($file)) return false;
+ $ret = array();
+ $fh = fopen($file, 'r');
+ if (!$fh) return false;
+ while (!feof($fh)) {
+ $ret[] = $this->parseHandle($fh);
+ }
+ fclose($fh);
+ return $ret;
+ }
+
+ /**
+ * Internal parser that acepts a file handle.
+ * @note While it's possible to simulate in-memory parsing by using
+ * custom stream wrappers, if such a use-case arises we should
+ * factor out the file handle into its own class.
+ * @param $fh File handle with pointer at start of valid string-hash
+ * block.
+ */
+ protected function parseHandle($fh) {
+ $state = false;
+ $single = false;
+ $ret = array();
+ do {
+ $line = fgets($fh);
+ if ($line === false) break;
+ $line = rtrim($line, "\n\r");
+ if (!$state && $line === '') continue;
+ if ($line === '----') break;
+ if (strncmp('--#', $line, 3) === 0) {
+ // Comment
+ continue;
+ } elseif (strncmp('--', $line, 2) === 0) {
+ // Multiline declaration
+ $state = trim($line, '- ');
+ if (!isset($ret[$state])) $ret[$state] = '';
+ continue;
+ } elseif (!$state) {
+ $single = true;
+ if (strpos($line, ':') !== false) {
+ // Single-line declaration
+ list($state, $line) = explode(':', $line, 2);
+ $line = trim($line);
+ } else {
+ // Use default declaration
+ $state = $this->default;
+ }
+ }
+ if ($single) {
+ $ret[$state] = $line;
+ $single = false;
+ $state = false;
+ } else {
+ $ret[$state] .= "$line\n";
+ }
+ } while (!feof($fh));
+ return $ret;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform.php
new file mode 100644
index 0000000..d112b40
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform.php
@@ -0,0 +1,36 @@
+<?php
+
+/**
+ * Defines a mutation of an obsolete tag into a valid tag.
+ */
+abstract class HTMLPurifier_TagTransform
+{
+
+ /**
+ * Tag name to transform the tag to.
+ */
+ public $transform_to;
+
+ /**
+ * Transforms the obsolete tag into the valid tag.
+ * @param $tag Tag to be transformed.
+ * @param $config Mandatory HTMLPurifier_Config object
+ * @param $context Mandatory HTMLPurifier_Context object
+ */
+ abstract public function transform($tag, $config, $context);
+
+ /**
+ * Prepends CSS properties to the style attribute, creating the
+ * attribute if it doesn't exist.
+ * @warning Copied over from AttrTransform, be sure to keep in sync
+ * @param $attr Attribute array to process (passed by reference)
+ * @param $css CSS to prepend
+ */
+ protected function prependCSS(&$attr, $css) {
+ $attr['style'] = isset($attr['style']) ? $attr['style'] : '';
+ $attr['style'] = $css . $attr['style'];
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Font.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Font.php
new file mode 100644
index 0000000..1358288
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Font.php
@@ -0,0 +1,98 @@
+<?php
+
+/**
+ * Transforms FONT tags to the proper form (SPAN with CSS styling)
+ *
+ * This transformation takes the three proprietary attributes of FONT and
+ * transforms them into their corresponding CSS attributes. These are color,
+ * face, and size.
+ *
+ * @note Size is an interesting case because it doesn't map cleanly to CSS.
+ * Thanks to
+ * http://style.cleverchimp.com/font_size_intervals/altintervals.html
+ * for reasonable mappings.
+ * @warning This doesn't work completely correctly; specifically, this
+ * TagTransform operates before well-formedness is enforced, so
+ * the "active formatting elements" algorithm doesn't get applied.
+ */
+class HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform
+{
+
+ public $transform_to = 'span';
+
+ protected $_size_lookup = array(
+ '0' => 'xx-small',
+ '1' => 'xx-small',
+ '2' => 'small',
+ '3' => 'medium',
+ '4' => 'large',
+ '5' => 'x-large',
+ '6' => 'xx-large',
+ '7' => '300%',
+ '-1' => 'smaller',
+ '-2' => '60%',
+ '+1' => 'larger',
+ '+2' => '150%',
+ '+3' => '200%',
+ '+4' => '300%'
+ );
+
+ public function transform($tag, $config, $context) {
+
+ if ($tag instanceof HTMLPurifier_Token_End) {
+ $new_tag = clone $tag;
+ $new_tag->name = $this->transform_to;
+ return $new_tag;
+ }
+
+ $attr = $tag->attr;
+ $prepend_style = '';
+
+ // handle color transform
+ if (isset($attr['color'])) {
+ $prepend_style .= 'color:' . $attr['color'] . ';';
+ unset($attr['color']);
+ }
+
+ // handle face transform
+ if (isset($attr['face'])) {
+ $prepend_style .= 'font-family:' . $attr['face'] . ';';
+ unset($attr['face']);
+ }
+
+ // handle size transform
+ if (isset($attr['size'])) {
+ // normalize large numbers
+ if ($attr['size'] !== '') {
+ if ($attr['size']{0} == '+' || $attr['size']{0} == '-') {
+ $size = (int) $attr['size'];
+ if ($size < -2) $attr['size'] = '-2';
+ if ($size > 4) $attr['size'] = '+4';
+ } else {
+ $size = (int) $attr['size'];
+ if ($size > 7) $attr['size'] = '7';
+ }
+ }
+ if (isset($this->_size_lookup[$attr['size']])) {
+ $prepend_style .= 'font-size:' .
+ $this->_size_lookup[$attr['size']] . ';';
+ }
+ unset($attr['size']);
+ }
+
+ if ($prepend_style) {
+ $attr['style'] = isset($attr['style']) ?
+ $prepend_style . $attr['style'] :
+ $prepend_style;
+ }
+
+ $new_tag = clone $tag;
+ $new_tag->name = $this->transform_to;
+ $new_tag->attr = $attr;
+
+ return $new_tag;
+
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Simple.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Simple.php
new file mode 100644
index 0000000..4c4f22b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TagTransform/Simple.php
@@ -0,0 +1,35 @@
+<?php
+
+/**
+ * Simple transformation, just change tag name to something else,
+ * and possibly add some styling. This will cover most of the deprecated
+ * tag cases.
+ */
+class HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform
+{
+
+ protected $style;
+
+ /**
+ * @param $transform_to Tag name to transform to.
+ * @param $style CSS style to add to the tag
+ */
+ public function __construct($transform_to, $style = null) {
+ $this->transform_to = $transform_to;
+ $this->style = $style;
+ }
+
+ public function transform($tag, $config, $context) {
+ $new_tag = clone $tag;
+ $new_tag->name = $this->transform_to;
+ if (!is_null($this->style) &&
+ ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty)
+ ) {
+ $this->prependCSS($new_tag->attr, $this->style);
+ }
+ return $new_tag;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token.php
new file mode 100644
index 0000000..667ded1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token.php
@@ -0,0 +1,57 @@
+<?php
+
+/**
+ * Abstract base token class that all others inherit from.
+ */
+class HTMLPurifier_Token {
+ public $line; /**< Line number node was on in source document. Null if unknown. */
+ public $col; /**< Column of line node was on in source document. Null if unknown. */
+
+ /**
+ * Lookup array of processing that this token is exempt from.
+ * Currently, valid values are "ValidateAttributes" and
+ * "MakeWellFormed_TagClosedError"
+ */
+ public $armor = array();
+
+ /**
+ * Used during MakeWellFormed.
+ */
+ public $skip;
+ public $rewind;
+ public $carryover;
+
+ public function __get($n) {
+ if ($n === 'type') {
+ trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);
+ switch (get_class($this)) {
+ case 'HTMLPurifier_Token_Start': return 'start';
+ case 'HTMLPurifier_Token_Empty': return 'empty';
+ case 'HTMLPurifier_Token_End': return 'end';
+ case 'HTMLPurifier_Token_Text': return 'text';
+ case 'HTMLPurifier_Token_Comment': return 'comment';
+ default: return null;
+ }
+ }
+ }
+
+ /**
+ * Sets the position of the token in the source document.
+ */
+ public function position($l = null, $c = null) {
+ $this->line = $l;
+ $this->col = $c;
+ }
+
+ /**
+ * Convenience function for DirectLex settings line/col position.
+ */
+ public function rawPosition($l, $c) {
+ if ($c === -1) $l++;
+ $this->line = $l;
+ $this->col = $c;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Comment.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Comment.php
new file mode 100644
index 0000000..28f1e81
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Comment.php
@@ -0,0 +1,22 @@
+<?php
+
+/**
+ * Concrete comment token class. Generally will be ignored.
+ */
+class HTMLPurifier_Token_Comment extends HTMLPurifier_Token
+{
+ public $data; /**< Character data within comment. */
+ public $is_whitespace = true;
+ /**
+ * Transparent constructor.
+ *
+ * @param $data String comment data.
+ */
+ public function __construct($data, $line = null, $col = null) {
+ $this->data = $data;
+ $this->line = $line;
+ $this->col = $col;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Empty.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Empty.php
new file mode 100644
index 0000000..0b1ee9b
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Empty.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * Concrete empty token class.
+ */
+class HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag
+{
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/End.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/End.php
new file mode 100644
index 0000000..2adb767
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/End.php
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * Concrete end token class.
+ *
+ * @warning This class accepts attributes even though end tags cannot. This
+ * is for optimization reasons, as under normal circumstances, the Lexers
+ * do not pass attributes.
+ */
+class HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag
+{
+ /**
+ * Token that started this node. Added by MakeWellFormed. Please
+ * do not edit this!
+ */
+ public $start;
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Start.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Start.php
new file mode 100644
index 0000000..ec4f423
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Start.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * Concrete start token class.
+ */
+class HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag
+{
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Tag.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Tag.php
new file mode 100644
index 0000000..9268427
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Tag.php
@@ -0,0 +1,57 @@
+<?php
+
+/**
+ * Abstract class of a tag token (start, end or empty), and its behavior.
+ */
+class HTMLPurifier_Token_Tag extends HTMLPurifier_Token
+{
+ /**
+ * Static bool marker that indicates the class is a tag.
+ *
+ * This allows us to check objects with <tt>!empty($obj->is_tag)</tt>
+ * without having to use a function call <tt>is_a()</tt>.
+ */
+ public $is_tag = true;
+
+ /**
+ * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.
+ *
+ * @note Strictly speaking, XML tags are case sensitive, so we shouldn't
+ * be lower-casing them, but these tokens cater to HTML tags, which are
+ * insensitive.
+ */
+ public $name;
+
+ /**
+ * Associative array of the tag's attributes.
+ */
+ public $attr = array();
+
+ /**
+ * Non-overloaded constructor, which lower-cases passed tag name.
+ *
+ * @param $name String name.
+ * @param $attr Associative array of attributes.
+ */
+ public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) {
+ $this->name = ctype_lower($name) ? $name : strtolower($name);
+ foreach ($attr as $key => $value) {
+ // normalization only necessary when key is not lowercase
+ if (!ctype_lower($key)) {
+ $new_key = strtolower($key);
+ if (!isset($attr[$new_key])) {
+ $attr[$new_key] = $attr[$key];
+ }
+ if ($new_key !== $key) {
+ unset($attr[$key]);
+ }
+ }
+ }
+ $this->attr = $attr;
+ $this->line = $line;
+ $this->col = $col;
+ $this->armor = $armor;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Text.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Text.php
new file mode 100644
index 0000000..a775cf0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/Token/Text.php
@@ -0,0 +1,33 @@
+<?php
+
+/**
+ * Concrete text token class.
+ *
+ * Text tokens comprise of regular parsed character data (PCDATA) and raw
+ * character data (from the CDATA sections). Internally, their
+ * data is parsed with all entities expanded. Surprisingly, the text token
+ * does have a "tag name" called #PCDATA, which is how the DTD represents it
+ * in permissible child nodes.
+ */
+class HTMLPurifier_Token_Text extends HTMLPurifier_Token
+{
+
+ public $name = '#PCDATA'; /**< PCDATA tag name compatible with DTD. */
+ public $data; /**< Parsed character data of text. */
+ public $is_whitespace; /**< Bool indicating if node is whitespace. */
+
+ /**
+ * Constructor, accepts data and determines if it is whitespace.
+ *
+ * @param $data String parsed character data.
+ */
+ public function __construct($data, $line = null, $col = null) {
+ $this->data = $data;
+ $this->is_whitespace = ctype_space($data);
+ $this->line = $line;
+ $this->col = $col;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TokenFactory.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TokenFactory.php
new file mode 100644
index 0000000..7bdd9f7
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/TokenFactory.php
@@ -0,0 +1,94 @@
+<?php
+
+/**
+ * Factory for token generation.
+ *
+ * @note Doing some benchmarking indicates that the new operator is much
+ * slower than the clone operator (even discounting the cost of the
+ * constructor). This class is for that optimization.
+ * Other then that, there's not much point as we don't
+ * maintain parallel HTMLPurifier_Token hierarchies (the main reason why
+ * you'd want to use an abstract factory).
+ * @todo Port DirectLex to use this
+ */
+class HTMLPurifier_TokenFactory
+{
+
+ /**
+ * Prototypes that will be cloned.
+ * @private
+ */
+ // p stands for prototype
+ private $p_start, $p_end, $p_empty, $p_text, $p_comment;
+
+ /**
+ * Generates blank prototypes for cloning.
+ */
+ public function __construct() {
+ $this->p_start = new HTMLPurifier_Token_Start('', array());
+ $this->p_end = new HTMLPurifier_Token_End('');
+ $this->p_empty = new HTMLPurifier_Token_Empty('', array());
+ $this->p_text = new HTMLPurifier_Token_Text('');
+ $this->p_comment= new HTMLPurifier_Token_Comment('');
+ }
+
+ /**
+ * Creates a HTMLPurifier_Token_Start.
+ * @param $name Tag name
+ * @param $attr Associative array of attributes
+ * @return Generated HTMLPurifier_Token_Start
+ */
+ public function createStart($name, $attr = array()) {
+ $p = clone $this->p_start;
+ $p->__construct($name, $attr);
+ return $p;
+ }
+
+ /**
+ * Creates a HTMLPurifier_Token_End.
+ * @param $name Tag name
+ * @return Generated HTMLPurifier_Token_End
+ */
+ public function createEnd($name) {
+ $p = clone $this->p_end;
+ $p->__construct($name);
+ return $p;
+ }
+
+ /**
+ * Creates a HTMLPurifier_Token_Empty.
+ * @param $name Tag name
+ * @param $attr Associative array of attributes
+ * @return Generated HTMLPurifier_Token_Empty
+ */
+ public function createEmpty($name, $attr = array()) {
+ $p = clone $this->p_empty;
+ $p->__construct($name, $attr);
+ return $p;
+ }
+
+ /**
+ * Creates a HTMLPurifier_Token_Text.
+ * @param $data Data of text token
+ * @return Generated HTMLPurifier_Token_Text
+ */
+ public function createText($data) {
+ $p = clone $this->p_text;
+ $p->__construct($data);
+ return $p;
+ }
+
+ /**
+ * Creates a HTMLPurifier_Token_Comment.
+ * @param $data Data of comment token
+ * @return Generated HTMLPurifier_Token_Comment
+ */
+ public function createComment($data) {
+ $p = clone $this->p_comment;
+ $p->__construct($data);
+ return $p;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URI.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URI.php
new file mode 100644
index 0000000..dad5a06
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URI.php
@@ -0,0 +1,204 @@
+<?php
+
+/**
+ * HTML Purifier's internal representation of a URI.
+ * @note
+ * Internal data-structures are completely escaped. If the data needs
+ * to be used in a non-URI context (which is very unlikely), be sure
+ * to decode it first. The URI may not necessarily be well-formed until
+ * validate() is called.
+ */
+class HTMLPurifier_URI
+{
+
+ public $scheme, $userinfo, $host, $port, $path, $query, $fragment;
+
+ /**
+ * @note Automatically normalizes scheme and port
+ */
+ public function __construct($scheme, $userinfo, $host, $port, $path, $query, $fragment) {
+ $this->scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme);
+ $this->userinfo = $userinfo;
+ $this->host = $host;
+ $this->port = is_null($port) ? $port : (int) $port;
+ $this->path = $path;
+ $this->query = $query;
+ $this->fragment = $fragment;
+ }
+
+ /**
+ * Retrieves a scheme object corresponding to the URI's scheme/default
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return Scheme object appropriate for validating this URI
+ */
+ public function getSchemeObj($config, $context) {
+ $registry = HTMLPurifier_URISchemeRegistry::instance();
+ if ($this->scheme !== null) {
+ $scheme_obj = $registry->getScheme($this->scheme, $config, $context);
+ if (!$scheme_obj) return false; // invalid scheme, clean it out
+ } else {
+ // no scheme: retrieve the default one
+ $def = $config->getDefinition('URI');
+ $scheme_obj = $registry->getScheme($def->defaultScheme, $config, $context);
+ if (!$scheme_obj) {
+ // something funky happened to the default scheme object
+ trigger_error(
+ 'Default scheme object "' . $def->defaultScheme . '" was not readable',
+ E_USER_WARNING
+ );
+ return false;
+ }
+ }
+ return $scheme_obj;
+ }
+
+ /**
+ * Generic validation method applicable for all schemes. May modify
+ * this URI in order to get it into a compliant form.
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return True if validation/filtering succeeds, false if failure
+ */
+ public function validate($config, $context) {
+
+ // ABNF definitions from RFC 3986
+ $chars_sub_delims = '!$&\'()*+,;=';
+ $chars_gen_delims = ':/?#[]@';
+ $chars_pchar = $chars_sub_delims . ':@';
+
+ // validate host
+ if (!is_null($this->host)) {
+ $host_def = new HTMLPurifier_AttrDef_URI_Host();
+ $this->host = $host_def->validate($this->host, $config, $context);
+ if ($this->host === false) $this->host = null;
+ }
+
+ // validate scheme
+ // NOTE: It's not appropriate to check whether or not this
+ // scheme is in our registry, since a URIFilter may convert a
+ // URI that we don't allow into one we do. So instead, we just
+ // check if the scheme can be dropped because there is no host
+ // and it is our default scheme.
+ if (!is_null($this->scheme) && is_null($this->host) || $this->host === '') {
+ // support for relative paths is pretty abysmal when the
+ // scheme is present, so axe it when possible
+ $def = $config->getDefinition('URI');
+ if ($def->defaultScheme === $this->scheme) {
+ $this->scheme = null;
+ }
+ }
+
+ // validate username
+ if (!is_null($this->userinfo)) {
+ $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':');
+ $this->userinfo = $encoder->encode($this->userinfo);
+ }
+
+ // validate port
+ if (!is_null($this->port)) {
+ if ($this->port < 1 || $this->port > 65535) $this->port = null;
+ }
+
+ // validate path
+ $path_parts = array();
+ $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/');
+ if (!is_null($this->host)) { // this catches $this->host === ''
+ // path-abempty (hier and relative)
+ // http://www.example.com/my/path
+ // //www.example.com/my/path (looks odd, but works, and
+ // recognized by most browsers)
+ // (this set is valid or invalid on a scheme by scheme
+ // basis, so we'll deal with it later)
+ // file:///my/path
+ // ///my/path
+ $this->path = $segments_encoder->encode($this->path);
+ } elseif ($this->path !== '') {
+ if ($this->path[0] === '/') {
+ // path-absolute (hier and relative)
+ // http:/my/path
+ // /my/path
+ if (strlen($this->path) >= 2 && $this->path[1] === '/') {
+ // This could happen if both the host gets stripped
+ // out
+ // http://my/path
+ // //my/path
+ $this->path = '';
+ } else {
+ $this->path = $segments_encoder->encode($this->path);
+ }
+ } elseif (!is_null($this->scheme)) {
+ // path-rootless (hier)
+ // http:my/path
+ // Short circuit evaluation means we don't need to check nz
+ $this->path = $segments_encoder->encode($this->path);
+ } else {
+ // path-noscheme (relative)
+ // my/path
+ // (once again, not checking nz)
+ $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');
+ $c = strpos($this->path, '/');
+ if ($c !== false) {
+ $this->path =
+ $segment_nc_encoder->encode(substr($this->path, 0, $c)) .
+ $segments_encoder->encode(substr($this->path, $c));
+ } else {
+ $this->path = $segment_nc_encoder->encode($this->path);
+ }
+ }
+ } else {
+ // path-empty (hier and relative)
+ $this->path = ''; // just to be safe
+ }
+
+ // qf = query and fragment
+ $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?');
+
+ if (!is_null($this->query)) {
+ $this->query = $qf_encoder->encode($this->query);
+ }
+
+ if (!is_null($this->fragment)) {
+ $this->fragment = $qf_encoder->encode($this->fragment);
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Convert URI back to string
+ * @return String URI appropriate for output
+ */
+ public function toString() {
+ // reconstruct authority
+ $authority = null;
+ // there is a rendering difference between a null authority
+ // (http:foo-bar) and an empty string authority
+ // (http:///foo-bar).
+ if (!is_null($this->host)) {
+ $authority = '';
+ if(!is_null($this->userinfo)) $authority .= $this->userinfo . '@';
+ $authority .= $this->host;
+ if(!is_null($this->port)) $authority .= ':' . $this->port;
+ }
+
+ // Reconstruct the result
+ // One might wonder about parsing quirks from browsers after
+ // this reconstruction. Unfortunately, parsing behavior depends
+ // on what *scheme* was employed (file:///foo is handled *very*
+ // differently than http:///foo), so unfortunately we have to
+ // defer to the schemes to do the right thing.
+ $result = '';
+ if (!is_null($this->scheme)) $result .= $this->scheme . ':';
+ if (!is_null($authority)) $result .= '//' . $authority;
+ $result .= $this->path;
+ if (!is_null($this->query)) $result .= '?' . $this->query;
+ if (!is_null($this->fragment)) $result .= '#' . $this->fragment;
+
+ return $result;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIDefinition.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIDefinition.php
new file mode 100644
index 0000000..b980e0a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIDefinition.php
@@ -0,0 +1,93 @@
+<?php
+
+class HTMLPurifier_URIDefinition extends HTMLPurifier_Definition
+{
+
+ public $type = 'URI';
+ protected $filters = array();
+ protected $postFilters = array();
+ protected $registeredFilters = array();
+
+ /**
+ * HTMLPurifier_URI object of the base specified at %URI.Base
+ */
+ public $base;
+
+ /**
+ * String host to consider "home" base, derived off of $base
+ */
+ public $host;
+
+ /**
+ * Name of default scheme based on %URI.DefaultScheme and %URI.Base
+ */
+ public $defaultScheme;
+
+ public function __construct() {
+ $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternal());
+ $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources());
+ $this->registerFilter(new HTMLPurifier_URIFilter_HostBlacklist());
+ $this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute());
+ $this->registerFilter(new HTMLPurifier_URIFilter_Munge());
+ }
+
+ public function registerFilter($filter) {
+ $this->registeredFilters[$filter->name] = $filter;
+ }
+
+ public function addFilter($filter, $config) {
+ $r = $filter->prepare($config);
+ if ($r === false) return; // null is ok, for backwards compat
+ if ($filter->post) {
+ $this->postFilters[$filter->name] = $filter;
+ } else {
+ $this->filters[$filter->name] = $filter;
+ }
+ }
+
+ protected function doSetup($config) {
+ $this->setupMemberVariables($config);
+ $this->setupFilters($config);
+ }
+
+ protected function setupFilters($config) {
+ foreach ($this->registeredFilters as $name => $filter) {
+ $conf = $config->get('URI.' . $name);
+ if ($conf !== false && $conf !== null) {
+ $this->addFilter($filter, $config);
+ }
+ }
+ unset($this->registeredFilters);
+ }
+
+ protected function setupMemberVariables($config) {
+ $this->host = $config->get('URI.Host');
+ $base_uri = $config->get('URI.Base');
+ if (!is_null($base_uri)) {
+ $parser = new HTMLPurifier_URIParser();
+ $this->base = $parser->parse($base_uri);
+ $this->defaultScheme = $this->base->scheme;
+ if (is_null($this->host)) $this->host = $this->base->host;
+ }
+ if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI.DefaultScheme');
+ }
+
+ public function filter(&$uri, $config, $context) {
+ foreach ($this->filters as $name => $f) {
+ $result = $f->filter($uri, $config, $context);
+ if (!$result) return false;
+ }
+ return true;
+ }
+
+ public function postFilter(&$uri, $config, $context) {
+ foreach ($this->postFilters as $name => $f) {
+ $result = $f->filter($uri, $config, $context);
+ if (!$result) return false;
+ }
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter.php
new file mode 100644
index 0000000..5faf0ae
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter.php
@@ -0,0 +1,45 @@
+<?php
+
+/**
+ * Chainable filters for custom URI processing.
+ *
+ * These filters can perform custom actions on a URI filter object,
+ * including transformation or blacklisting.
+ *
+ * @warning This filter is called before scheme object validation occurs.
+ * Make sure, if you require a specific scheme object, you
+ * you check that it exists. This allows filters to convert
+ * proprietary URI schemes into regular ones.
+ */
+abstract class HTMLPurifier_URIFilter
+{
+
+ /**
+ * Unique identifier of filter
+ */
+ public $name;
+
+ /**
+ * True if this filter should be run after scheme validation.
+ */
+ public $post = false;
+
+ /**
+ * Performs initialization for the filter
+ */
+ public function prepare($config) {return true;}
+
+ /**
+ * Filter a URI object
+ * @param $uri Reference to URI object variable
+ * @param $config Instance of HTMLPurifier_Config
+ * @param $context Instance of HTMLPurifier_Context
+ * @return bool Whether or not to continue processing: false indicates
+ * URL is no good, true indicates continue processing. Note that
+ * all changes are committed directly on the URI object
+ */
+ abstract public function filter(&$uri, $config, $context);
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternal.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternal.php
new file mode 100644
index 0000000..0b23dcf
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternal.php
@@ -0,0 +1,23 @@
+<?php
+
+class HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter
+{
+ public $name = 'DisableExternal';
+ protected $ourHostParts = false;
+ public function prepare($config) {
+ $our_host = $config->getDefinition('URI')->host;
+ if ($our_host !== null) $this->ourHostParts = array_reverse(explode('.', $our_host));
+ }
+ public function filter(&$uri, $config, $context) {
+ if (is_null($uri->host)) return true;
+ if ($this->ourHostParts === false) return false;
+ $host_parts = array_reverse(explode('.', $uri->host));
+ foreach ($this->ourHostParts as $i => $x) {
+ if (!isset($host_parts[$i])) return false;
+ if ($host_parts[$i] != $this->ourHostParts[$i]) return false;
+ }
+ return true;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternalResources.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternalResources.php
new file mode 100644
index 0000000..4423ffa
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableExternalResources.php
@@ -0,0 +1,12 @@
+<?php
+
+class HTMLPurifier_URIFilter_DisableExternalResources extends HTMLPurifier_URIFilter_DisableExternal
+{
+ public $name = 'DisableExternalResources';
+ public function filter(&$uri, $config, $context) {
+ if (!$context->get('EmbeddedURI', true)) return true;
+ return parent::filter($uri, $config, $context);
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableResources.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableResources.php
new file mode 100644
index 0000000..5f7c3a0
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/DisableResources.php
@@ -0,0 +1,11 @@
+<?php
+
+class HTMLPurifier_URIFilter_DisableResources extends HTMLPurifier_URIFilter
+{
+ public $name = 'DisableResources';
+ public function filter(&$uri, $config, $context) {
+ return !$context->get('EmbeddedURI', true);
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/HostBlacklist.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/HostBlacklist.php
new file mode 100644
index 0000000..073ba5a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/HostBlacklist.php
@@ -0,0 +1,21 @@
+<?php
+
+class HTMLPurifier_URIFilter_HostBlacklist extends HTMLPurifier_URIFilter
+{
+ public $name = 'HostBlacklist';
+ protected $blacklist = array();
+ public function prepare($config) {
+ $this->blacklist = $config->get('URI.HostBlacklist');
+ return true;
+ }
+ public function filter(&$uri, $config, $context) {
+ foreach($this->blacklist as $blacklisted_host_fragment) {
+ if (strpos($uri->host, $blacklisted_host_fragment) !== false) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/MakeAbsolute.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/MakeAbsolute.php
new file mode 100644
index 0000000..c1a2e03
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/MakeAbsolute.php
@@ -0,0 +1,114 @@
+<?php
+
+// does not support network paths
+
+class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter
+{
+ public $name = 'MakeAbsolute';
+ protected $base;
+ protected $basePathStack = array();
+ public function prepare($config) {
+ $def = $config->getDefinition('URI');
+ $this->base = $def->base;
+ if (is_null($this->base)) {
+ trigger_error('URI.MakeAbsolute is being ignored due to lack of value for URI.Base configuration', E_USER_WARNING);
+ return false;
+ }
+ $this->base->fragment = null; // fragment is invalid for base URI
+ $stack = explode('/', $this->base->path);
+ array_pop($stack); // discard last segment
+ $stack = $this->_collapseStack($stack); // do pre-parsing
+ $this->basePathStack = $stack;
+ return true;
+ }
+ public function filter(&$uri, $config, $context) {
+ if (is_null($this->base)) return true; // abort early
+ if (
+ $uri->path === '' && is_null($uri->scheme) &&
+ is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)
+ ) {
+ // reference to current document
+ $uri = clone $this->base;
+ return true;
+ }
+ if (!is_null($uri->scheme)) {
+ // absolute URI already: don't change
+ if (!is_null($uri->host)) return true;
+ $scheme_obj = $uri->getSchemeObj($config, $context);
+ if (!$scheme_obj) {
+ // scheme not recognized
+ return false;
+ }
+ if (!$scheme_obj->hierarchical) {
+ // non-hierarchal URI with explicit scheme, don't change
+ return true;
+ }
+ // special case: had a scheme but always is hierarchical and had no authority
+ }
+ if (!is_null($uri->host)) {
+ // network path, don't bother
+ return true;
+ }
+ if ($uri->path === '') {
+ $uri->path = $this->base->path;
+ } elseif ($uri->path[0] !== '/') {
+ // relative path, needs more complicated processing
+ $stack = explode('/', $uri->path);
+ $new_stack = array_merge($this->basePathStack, $stack);
+ if ($new_stack[0] !== '' && !is_null($this->base->host)) {
+ array_unshift($new_stack, '');
+ }
+ $new_stack = $this->_collapseStack($new_stack);
+ $uri->path = implode('/', $new_stack);
+ } else {
+ // absolute path, but still we should collapse
+ $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path)));
+ }
+ // re-combine
+ $uri->scheme = $this->base->scheme;
+ if (is_null($uri->userinfo)) $uri->userinfo = $this->base->userinfo;
+ if (is_null($uri->host)) $uri->host = $this->base->host;
+ if (is_null($uri->port)) $uri->port = $this->base->port;
+ return true;
+ }
+
+ /**
+ * Resolve dots and double-dots in a path stack
+ */
+ private function _collapseStack($stack) {
+ $result = array();
+ $is_folder = false;
+ for ($i = 0; isset($stack[$i]); $i++) {
+ $is_folder = false;
+ // absorb an internally duplicated slash
+ if ($stack[$i] == '' && $i && isset($stack[$i+1])) continue;
+ if ($stack[$i] == '..') {
+ if (!empty($result)) {
+ $segment = array_pop($result);
+ if ($segment === '' && empty($result)) {
+ // error case: attempted to back out too far:
+ // restore the leading slash
+ $result[] = '';
+ } elseif ($segment === '..') {
+ $result[] = '..'; // cannot remove .. with ..
+ }
+ } else {
+ // relative path, preserve the double-dots
+ $result[] = '..';
+ }
+ $is_folder = true;
+ continue;
+ }
+ if ($stack[$i] == '.') {
+ // silently absorb
+ $is_folder = true;
+ continue;
+ }
+ $result[] = $stack[$i];
+ }
+ if ($is_folder) $result[] = '';
+ return $result;
+ }
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/Munge.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/Munge.php
new file mode 100644
index 0000000..4e9e7a1
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIFilter/Munge.php
@@ -0,0 +1,58 @@
+<?php
+
+class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter
+{
+ public $name = 'Munge';
+ public $post = true;
+ private $target, $parser, $doEmbed, $secretKey;
+
+ protected $replace = array();
+
+ public function prepare($config) {
+ $this->target = $config->get('URI.' . $this->name);
+ $this->parser = new HTMLPurifier_URIParser();
+ $this->doEmbed = $config->get('URI.MungeResources');
+ $this->secretKey = $config->get('URI.MungeSecretKey');
+ return true;
+ }
+ public function filter(&$uri, $config, $context) {
+ if ($context->get('EmbeddedURI', true) && !$this->doEmbed) return true;
+
+ $scheme_obj = $uri->getSchemeObj($config, $context);
+ if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it
+ if (is_null($uri->host) || empty($scheme_obj->browsable)) {
+ return true;
+ }
+ // don't redirect if target host is our host
+ if ($uri->host === $config->getDefinition('URI')->host) {
+ return true;
+ }
+
+ $this->makeReplace($uri, $config, $context);
+ $this->replace = array_map('rawurlencode', $this->replace);
+
+ $new_uri = strtr($this->target, $this->replace);
+ $new_uri = $this->parser->parse($new_uri);
+ // don't redirect if the target host is the same as the
+ // starting host
+ if ($uri->host === $new_uri->host) return true;
+ $uri = $new_uri; // overwrite
+ return true;
+ }
+
+ protected function makeReplace($uri, $config, $context) {
+ $string = $uri->toString();
+ // always available
+ $this->replace['%s'] = $string;
+ $this->replace['%r'] = $context->get('EmbeddedURI', true);
+ $token = $context->get('CurrentToken', true);
+ $this->replace['%n'] = $token ? $token->name : null;
+ $this->replace['%m'] = $context->get('CurrentAttr', true);
+ $this->replace['%p'] = $context->get('CurrentCSSProperty', true);
+ // not always available
+ if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIParser.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIParser.php
new file mode 100644
index 0000000..374b4f2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIParser.php
@@ -0,0 +1,70 @@
+<?php
+
+/**
+ * Parses a URI into the components and fragment identifier as specified
+ * by RFC 3986.
+ */
+class HTMLPurifier_URIParser
+{
+
+ /**
+ * Instance of HTMLPurifier_PercentEncoder to do normalization with.
+ */
+ protected $percentEncoder;
+
+ public function __construct() {
+ $this->percentEncoder = new HTMLPurifier_PercentEncoder();
+ }
+
+ /**
+ * Parses a URI.
+ * @param $uri string URI to parse
+ * @return HTMLPurifier_URI representation of URI. This representation has
+ * not been validated yet and may not conform to RFC.
+ */
+ public function parse($uri) {
+
+ $uri = $this->percentEncoder->normalize($uri);
+
+ // Regexp is as per Appendix B.
+ // Note that ["<>] are an addition to the RFC's recommended
+ // characters, because they represent external delimeters.
+ $r_URI = '!'.
+ '(([^:/?#"<>]+):)?'. // 2. Scheme
+ '(//([^/?#"<>]*))?'. // 4. Authority
+ '([^?#"<>]*)'. // 5. Path
+ '(\?([^#"<>]*))?'. // 7. Query
+ '(#([^"<>]*))?'. // 8. Fragment
+ '!';
+
+ $matches = array();
+ $result = preg_match($r_URI, $uri, $matches);
+
+ if (!$result) return false; // *really* invalid URI
+
+ // seperate out parts
+ $scheme = !empty($matches[1]) ? $matches[2] : null;
+ $authority = !empty($matches[3]) ? $matches[4] : null;
+ $path = $matches[5]; // always present, can be empty
+ $query = !empty($matches[6]) ? $matches[7] : null;
+ $fragment = !empty($matches[8]) ? $matches[9] : null;
+
+ // further parse authority
+ if ($authority !== null) {
+ $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/";
+ $matches = array();
+ preg_match($r_authority, $authority, $matches);
+ $userinfo = !empty($matches[1]) ? $matches[2] : null;
+ $host = !empty($matches[3]) ? $matches[3] : '';
+ $port = !empty($matches[4]) ? (int) $matches[5] : null;
+ } else {
+ $port = $host = $userinfo = null;
+ }
+
+ return new HTMLPurifier_URI(
+ $scheme, $userinfo, $host, $port, $path, $query, $fragment);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme.php
new file mode 100644
index 0000000..78dd9f6
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme.php
@@ -0,0 +1,89 @@
+<?php
+
+/**
+ * Validator for the components of a URI for a specific scheme
+ */
+abstract class HTMLPurifier_URIScheme
+{
+
+ /**
+ * Scheme's default port (integer). If an explicit port number is
+ * specified that coincides with the default port, it will be
+ * elided.
+ */
+ public $default_port = null;
+
+ /**
+ * Whether or not URIs of this schem are locatable by a browser
+ * http and ftp are accessible, while mailto and news are not.
+ */
+ public $browsable = false;
+
+ /**
+ * Whether or not the URI always uses <hier_part>, resolves edge cases
+ * with making relative URIs absolute
+ */
+ public $hierarchical = false;
+
+ /**
+ * Whether or not the URI may omit a hostname when the scheme is
+ * explicitly specified, ala file:///path/to/file. As of writing,
+ * 'file' is the only scheme that browsers support his properly.
+ */
+ public $may_omit_host = false;
+
+ /**
+ * Validates the components of a URI for a specific scheme.
+ * @param $uri Reference to a HTMLPurifier_URI object
+ * @param $config HTMLPurifier_Config object
+ * @param $context HTMLPurifier_Context object
+ * @return Bool success or failure
+ */
+ public abstract function doValidate(&$uri, $config, $context);
+
+ /**
+ * Public interface for validating components of a URI. Performs a
+ * bunch of default actions. Don't overload this method.
+ * @param $uri Reference to a HTMLPurifier_URI object
+ * @param $config HTMLPurifier_Config object
+ * @param $context HTMLPurifier_Context object
+ * @return Bool success or failure
+ */
+ public function validate(&$uri, $config, $context) {
+ if ($this->default_port == $uri->port) $uri->port = null;
+ // kludge: browsers do funny things when the scheme but not the
+ // authority is set
+ if (!$this->may_omit_host &&
+ // if the scheme is present, a missing host is always in error
+ (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) ||
+ // if the scheme is not present, a *blank* host is in error,
+ // since this translates into '///path' which most browsers
+ // interpret as being 'http://path'.
+ (is_null($uri->scheme) && $uri->host === '')
+ ) {
+ do {
+ if (is_null($uri->scheme)) {
+ if (substr($uri->path, 0, 2) != '//') {
+ $uri->host = null;
+ break;
+ }
+ // URI is '////path', so we cannot nullify the
+ // host to preserve semantics. Try expanding the
+ // hostname instead (fall through)
+ }
+ // first see if we can manually insert a hostname
+ $host = $config->get('URI.Host');
+ if (!is_null($host)) {
+ $uri->host = $host;
+ } else {
+ // we can't do anything sensible, reject the URL.
+ return false;
+ }
+ } while (false);
+ }
+ return $this->doValidate($uri, $config, $context);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/data.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/data.php
new file mode 100644
index 0000000..22f16c2
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/data.php
@@ -0,0 +1,96 @@
+<?php
+
+/**
+ * Implements data: URI for base64 encoded images supported by GD.
+ */
+class HTMLPurifier_URIScheme_data extends HTMLPurifier_URIScheme {
+
+ public $browsable = true;
+ public $allowed_types = array(
+ // you better write validation code for other types if you
+ // decide to allow them
+ 'image/jpeg' => true,
+ 'image/gif' => true,
+ 'image/png' => true,
+ );
+ // this is actually irrelevant since we only write out the path
+ // component
+ public $may_omit_host = true;
+
+ public function doValidate(&$uri, $config, $context) {
+ $result = explode(',', $uri->path, 2);
+ $is_base64 = false;
+ $charset = null;
+ $content_type = null;
+ if (count($result) == 2) {
+ list($metadata, $data) = $result;
+ // do some legwork on the metadata
+ $metas = explode(';', $metadata);
+ while(!empty($metas)) {
+ $cur = array_shift($metas);
+ if ($cur == 'base64') {
+ $is_base64 = true;
+ break;
+ }
+ if (substr($cur, 0, 8) == 'charset=') {
+ // doesn't match if there are arbitrary spaces, but
+ // whatever dude
+ if ($charset !== null) continue; // garbage
+ $charset = substr($cur, 8); // not used
+ } else {
+ if ($content_type !== null) continue; // garbage
+ $content_type = $cur;
+ }
+ }
+ } else {
+ $data = $result[0];
+ }
+ if ($content_type !== null && empty($this->allowed_types[$content_type])) {
+ return false;
+ }
+ if ($charset !== null) {
+ // error; we don't allow plaintext stuff
+ $charset = null;
+ }
+ $data = rawurldecode($data);
+ if ($is_base64) {
+ $raw_data = base64_decode($data);
+ } else {
+ $raw_data = $data;
+ }
+ // XXX probably want to refactor this into a general mechanism
+ // for filtering arbitrary content types
+ $file = tempnam("/tmp", "");
+ file_put_contents($file, $raw_data);
+ if (function_exists('exif_imagetype')) {
+ $image_code = exif_imagetype($file);
+ } elseif (function_exists('getimagesize')) {
+ set_error_handler(array($this, 'muteErrorHandler'));
+ $info = getimagesize($file);
+ restore_error_handler();
+ if ($info == false) return false;
+ $image_code = $info[2];
+ } else {
+ trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR);
+ }
+ $real_content_type = image_type_to_mime_type($image_code);
+ if ($real_content_type != $content_type) {
+ // we're nice guys; if the content type is something else we
+ // support, change it over
+ if (empty($this->allowed_types[$real_content_type])) return false;
+ $content_type = $real_content_type;
+ }
+ // ok, it's kosher, rewrite what we need
+ $uri->userinfo = null;
+ $uri->host = null;
+ $uri->port = null;
+ $uri->fragment = null;
+ $uri->query = null;
+ $uri->path = "$content_type;base64," . base64_encode($raw_data);
+ return true;
+ }
+
+ public function muteErrorHandler($errno, $errstr) {}
+
+}
+
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/file.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/file.php
new file mode 100644
index 0000000..c55391e
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/file.php
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * Validates file as defined by RFC 1630 and RFC 1738.
+ */
+class HTMLPurifier_URIScheme_file extends HTMLPurifier_URIScheme {
+
+ // Generally file:// URLs are not accessible from most
+ // machines, so placing them as an img src is incorrect.
+ public $browsable = false;
+
+ // Basically the *only* URI scheme for which this is true, since
+ // accessing files on the local machine is very common. In fact,
+ // browsers on some operating systems don't understand the
+ // authority, though I hear it is used on Windows to refer to
+ // network shares.
+ public $may_omit_host = true;
+
+ public function doValidate(&$uri, $config, $context) {
+ // Authentication method is not supported
+ $uri->userinfo = null;
+ // file:// makes no provisions for accessing the resource
+ $uri->port = null;
+ // While it seems to work on Firefox, the querystring has
+ // no possible effect and is thus stripped.
+ $uri->query = null;
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/ftp.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/ftp.php
new file mode 100644
index 0000000..ebe183c
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/ftp.php
@@ -0,0 +1,42 @@
+<?php
+
+/**
+ * Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738.
+ */
+class HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme {
+
+ public $default_port = 21;
+ public $browsable = true; // usually
+ public $hierarchical = true;
+
+ public function doValidate(&$uri, $config, $context) {
+ $uri->query = null;
+
+ // typecode check
+ $semicolon_pos = strrpos($uri->path, ';'); // reverse
+ if ($semicolon_pos !== false) {
+ $type = substr($uri->path, $semicolon_pos + 1); // no semicolon
+ $uri->path = substr($uri->path, 0, $semicolon_pos);
+ $type_ret = '';
+ if (strpos($type, '=') !== false) {
+ // figure out whether or not the declaration is correct
+ list($key, $typecode) = explode('=', $type, 2);
+ if ($key !== 'type') {
+ // invalid key, tack it back on encoded
+ $uri->path .= '%3B' . $type;
+ } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') {
+ $type_ret = ";type=$typecode";
+ }
+ } else {
+ $uri->path .= '%3B' . $type;
+ }
+ $uri->path = str_replace(';', '%3B', $uri->path);
+ $uri->path .= $type_ret;
+ }
+
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/http.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/http.php
new file mode 100644
index 0000000..ea3cb2f
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/http.php
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * Validates http (HyperText Transfer Protocol) as defined by RFC 2616
+ */
+class HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme {
+
+ public $default_port = 80;
+ public $browsable = true;
+ public $hierarchical = true;
+
+ public function doValidate(&$uri, $config, $context) {
+ $uri->userinfo = null;
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/https.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/https.php
new file mode 100644
index 0000000..9745c21
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/https.php
@@ -0,0 +1,12 @@
+<?php
+
+/**
+ * Validates https (Secure HTTP) according to http scheme.
+ */
+class HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http {
+
+ public $default_port = 443;
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/mailto.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/mailto.php
new file mode 100644
index 0000000..5869da9
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/mailto.php
@@ -0,0 +1,27 @@
+<?php
+
+// VERY RELAXED! Shouldn't cause problems, not even Firefox checks if the
+// email is valid, but be careful!
+
+/**
+ * Validates mailto (for E-mail) according to RFC 2368
+ * @todo Validate the email address
+ * @todo Filter allowed query parameters
+ */
+
+class HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme {
+
+ public $browsable = false;
+ public $may_omit_host = true;
+
+ public function doValidate(&$uri, $config, $context) {
+ $uri->userinfo = null;
+ $uri->host = null;
+ $uri->port = null;
+ // we need to validate path against RFC 2368's addr-spec
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/news.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/news.php
new file mode 100644
index 0000000..28bce54
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/news.php
@@ -0,0 +1,22 @@
+<?php
+
+/**
+ * Validates news (Usenet) as defined by generic RFC 1738
+ */
+class HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme {
+
+ public $browsable = false;
+ public $may_omit_host = true;
+
+ public function doValidate(&$uri, $config, $context) {
+ $uri->userinfo = null;
+ $uri->host = null;
+ $uri->port = null;
+ $uri->query = null;
+ // typecode check needed on path
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/nntp.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/nntp.php
new file mode 100644
index 0000000..ca80262
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URIScheme/nntp.php
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738
+ */
+class HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme {
+
+ public $default_port = 119;
+ public $browsable = false;
+
+ public function doValidate(&$uri, $config, $context) {
+ $uri->userinfo = null;
+ $uri->query = null;
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URISchemeRegistry.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URISchemeRegistry.php
new file mode 100644
index 0000000..067ba91
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/URISchemeRegistry.php
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * Registry for retrieving specific URI scheme validator objects.
+ */
+class HTMLPurifier_URISchemeRegistry
+{
+
+ /**
+ * Retrieve sole instance of the registry.
+ * @param $prototype Optional prototype to overload sole instance with,
+ * or bool true to reset to default registry.
+ * @note Pass a registry object $prototype with a compatible interface and
+ * the function will copy it and return it all further times.
+ */
+ public static function instance($prototype = null) {
+ static $instance = null;
+ if ($prototype !== null) {
+ $instance = $prototype;
+ } elseif ($instance === null || $prototype == true) {
+ $instance = new HTMLPurifier_URISchemeRegistry();
+ }
+ return $instance;
+ }
+
+ /**
+ * Cache of retrieved schemes.
+ */
+ protected $schemes = array();
+
+ /**
+ * Retrieves a scheme validator object
+ * @param $scheme String scheme name like http or mailto
+ * @param $config HTMLPurifier_Config object
+ * @param $config HTMLPurifier_Context object
+ */
+ public function getScheme($scheme, $config, $context) {
+ if (!$config) $config = HTMLPurifier_Config::createDefault();
+
+ // important, otherwise attacker could include arbitrary file
+ $allowed_schemes = $config->get('URI.AllowedSchemes');
+ if (!$config->get('URI.OverrideAllowedSchemes') &&
+ !isset($allowed_schemes[$scheme])
+ ) {
+ return;
+ }
+
+ if (isset($this->schemes[$scheme])) return $this->schemes[$scheme];
+ if (!isset($allowed_schemes[$scheme])) return;
+
+ $class = 'HTMLPurifier_URIScheme_' . $scheme;
+ if (!class_exists($class)) return;
+ $this->schemes[$scheme] = new $class();
+ return $this->schemes[$scheme];
+ }
+
+ /**
+ * Registers a custom scheme to the cache, bypassing reflection.
+ * @param $scheme Scheme name
+ * @param $scheme_obj HTMLPurifier_URIScheme object
+ */
+ public function register($scheme, $scheme_obj) {
+ $this->schemes[$scheme] = $scheme_obj;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/UnitConverter.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/UnitConverter.php
new file mode 100644
index 0000000..2e9db5a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/UnitConverter.php
@@ -0,0 +1,254 @@
+<?php
+
+/**
+ * Class for converting between different unit-lengths as specified by
+ * CSS.
+ */
+class HTMLPurifier_UnitConverter
+{
+
+ const ENGLISH = 1;
+ const METRIC = 2;
+ const DIGITAL = 3;
+
+ /**
+ * Units information array. Units are grouped into measuring systems
+ * (English, Metric), and are assigned an integer representing
+ * the conversion factor between that unit and the smallest unit in
+ * the system. Numeric indexes are actually magical constants that
+ * encode conversion data from one system to the next, with a O(n^2)
+ * constraint on memory (this is generally not a problem, since
+ * the number of measuring systems is small.)
+ */
+ protected static $units = array(
+ self::ENGLISH => array(
+ 'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary
+ 'pt' => 4,
+ 'pc' => 48,
+ 'in' => 288,
+ self::METRIC => array('pt', '0.352777778', 'mm'),
+ ),
+ self::METRIC => array(
+ 'mm' => 1,
+ 'cm' => 10,
+ self::ENGLISH => array('mm', '2.83464567', 'pt'),
+ ),
+ );
+
+ /**
+ * Minimum bcmath precision for output.
+ */
+ protected $outputPrecision;
+
+ /**
+ * Bcmath precision for internal calculations.
+ */
+ protected $internalPrecision;
+
+ /**
+ * Whether or not BCMath is available
+ */
+ private $bcmath;
+
+ public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false) {
+ $this->outputPrecision = $output_precision;
+ $this->internalPrecision = $internal_precision;
+ $this->bcmath = !$force_no_bcmath && function_exists('bcmul');
+ }
+
+ /**
+ * Converts a length object of one unit into another unit.
+ * @param HTMLPurifier_Length $length
+ * Instance of HTMLPurifier_Length to convert. You must validate()
+ * it before passing it here!
+ * @param string $to_unit
+ * Unit to convert to.
+ * @note
+ * About precision: This conversion function pays very special
+ * attention to the incoming precision of values and attempts
+ * to maintain a number of significant figure. Results are
+ * fairly accurate up to nine digits. Some caveats:
+ * - If a number is zero-padded as a result of this significant
+ * figure tracking, the zeroes will be eliminated.
+ * - If a number contains less than four sigfigs ($outputPrecision)
+ * and this causes some decimals to be excluded, those
+ * decimals will be added on.
+ */
+ public function convert($length, $to_unit) {
+
+ if (!$length->isValid()) return false;
+
+ $n = $length->getN();
+ $unit = $length->getUnit();
+
+ if ($n === '0' || $unit === false) {
+ return new HTMLPurifier_Length('0', false);
+ }
+
+ $state = $dest_state = false;
+ foreach (self::$units as $k => $x) {
+ if (isset($x[$unit])) $state = $k;
+ if (isset($x[$to_unit])) $dest_state = $k;
+ }
+ if (!$state || !$dest_state) return false;
+
+ // Some calculations about the initial precision of the number;
+ // this will be useful when we need to do final rounding.
+ $sigfigs = $this->getSigFigs($n);
+ if ($sigfigs < $this->outputPrecision) $sigfigs = $this->outputPrecision;
+
+ // BCMath's internal precision deals only with decimals. Use
+ // our default if the initial number has no decimals, or increase
+ // it by how ever many decimals, thus, the number of guard digits
+ // will always be greater than or equal to internalPrecision.
+ $log = (int) floor(log(abs($n), 10));
+ $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision
+
+ for ($i = 0; $i < 2; $i++) {
+
+ // Determine what unit IN THIS SYSTEM we need to convert to
+ if ($dest_state === $state) {
+ // Simple conversion
+ $dest_unit = $to_unit;
+ } else {
+ // Convert to the smallest unit, pending a system shift
+ $dest_unit = self::$units[$state][$dest_state][0];
+ }
+
+ // Do the conversion if necessary
+ if ($dest_unit !== $unit) {
+ $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);
+ $n = $this->mul($n, $factor, $cp);
+ $unit = $dest_unit;
+ }
+
+ // Output was zero, so bail out early. Shouldn't ever happen.
+ if ($n === '') {
+ $n = '0';
+ $unit = $to_unit;
+ break;
+ }
+
+ // It was a simple conversion, so bail out
+ if ($dest_state === $state) {
+ break;
+ }
+
+ if ($i !== 0) {
+ // Conversion failed! Apparently, the system we forwarded
+ // to didn't have this unit. This should never happen!
+ return false;
+ }
+
+ // Pre-condition: $i == 0
+
+ // Perform conversion to next system of units
+ $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);
+ $unit = self::$units[$state][$dest_state][2];
+ $state = $dest_state;
+
+ // One more loop around to convert the unit in the new system.
+
+ }
+
+ // Post-condition: $unit == $to_unit
+ if ($unit !== $to_unit) return false;
+
+ // Useful for debugging:
+ //echo "<pre>n";
+ //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";
+
+ $n = $this->round($n, $sigfigs);
+ if (strpos($n, '.') !== false) $n = rtrim($n, '0');
+ $n = rtrim($n, '.');
+
+ return new HTMLPurifier_Length($n, $unit);
+ }
+
+ /**
+ * Returns the number of significant figures in a string number.
+ * @param string $n Decimal number
+ * @return int number of sigfigs
+ */
+ public function getSigFigs($n) {
+ $n = ltrim($n, '0+-');
+ $dp = strpos($n, '.'); // decimal position
+ if ($dp === false) {
+ $sigfigs = strlen(rtrim($n, '0'));
+ } else {
+ $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character
+ if ($dp !== 0) $sigfigs--;
+ }
+ return $sigfigs;
+ }
+
+ /**
+ * Adds two numbers, using arbitrary precision when available.
+ */
+ private function add($s1, $s2, $scale) {
+ if ($this->bcmath) return bcadd($s1, $s2, $scale);
+ else return $this->scale($s1 + $s2, $scale);
+ }
+
+ /**
+ * Multiples two numbers, using arbitrary precision when available.
+ */
+ private function mul($s1, $s2, $scale) {
+ if ($this->bcmath) return bcmul($s1, $s2, $scale);
+ else return $this->scale($s1 * $s2, $scale);
+ }
+
+ /**
+ * Divides two numbers, using arbitrary precision when available.
+ */
+ private function div($s1, $s2, $scale) {
+ if ($this->bcmath) return bcdiv($s1, $s2, $scale);
+ else return $this->scale($s1 / $s2, $scale);
+ }
+
+ /**
+ * Rounds a number according to the number of sigfigs it should have,
+ * using arbitrary precision when available.
+ */
+ private function round($n, $sigfigs) {
+ $new_log = (int) floor(log(abs($n), 10)); // Number of digits left of decimal - 1
+ $rp = $sigfigs - $new_log - 1; // Number of decimal places needed
+ $neg = $n < 0 ? '-' : ''; // Negative sign
+ if ($this->bcmath) {
+ if ($rp >= 0) {
+ $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);
+ $n = bcdiv($n, '1', $rp);
+ } else {
+ // This algorithm partially depends on the standardized
+ // form of numbers that comes out of bcmath.
+ $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);
+ $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);
+ }
+ return $n;
+ } else {
+ return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);
+ }
+ }
+
+ /**
+ * Scales a float to $scale digits right of decimal point, like BCMath.
+ */
+ private function scale($r, $scale) {
+ if ($scale < 0) {
+ // The f sprintf type doesn't support negative numbers, so we
+ // need to cludge things manually. First get the string.
+ $r = sprintf('%.0f', (float) $r);
+ // Due to floating point precision loss, $r will more than likely
+ // look something like 4652999999999.9234. We grab one more digit
+ // than we need to precise from $r and then use that to round
+ // appropriately.
+ $precise = (string) round(substr($r, 0, strlen($r) + $scale), -1);
+ // Now we return it, truncating the zero that was rounded off.
+ return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);
+ }
+ return sprintf('%.' . $scale . 'f', (float) $r);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser.php
new file mode 100644
index 0000000..bfd812a
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser.php
@@ -0,0 +1,154 @@
+<?php
+
+/**
+ * Parses string representations into their corresponding native PHP
+ * variable type. The base implementation does a simple type-check.
+ */
+class HTMLPurifier_VarParser
+{
+
+ const STRING = 1;
+ const ISTRING = 2;
+ const TEXT = 3;
+ const ITEXT = 4;
+ const INT = 5;
+ const FLOAT = 6;
+ const BOOL = 7;
+ const LOOKUP = 8;
+ const ALIST = 9;
+ const HASH = 10;
+ const MIXED = 11;
+
+ /**
+ * Lookup table of allowed types. Mainly for backwards compatibility, but
+ * also convenient for transforming string type names to the integer constants.
+ */
+ static public $types = array(
+ 'string' => self::STRING,
+ 'istring' => self::ISTRING,
+ 'text' => self::TEXT,
+ 'itext' => self::ITEXT,
+ 'int' => self::INT,
+ 'float' => self::FLOAT,
+ 'bool' => self::BOOL,
+ 'lookup' => self::LOOKUP,
+ 'list' => self::ALIST,
+ 'hash' => self::HASH,
+ 'mixed' => self::MIXED
+ );
+
+ /**
+ * Lookup table of types that are string, and can have aliases or
+ * allowed value lists.
+ */
+ static public $stringTypes = array(
+ self::STRING => true,
+ self::ISTRING => true,
+ self::TEXT => true,
+ self::ITEXT => true,
+ );
+
+ /**
+ * Validate a variable according to type. Throws
+ * HTMLPurifier_VarParserException if invalid.
+ * It may return NULL as a valid type if $allow_null is true.
+ *
+ * @param $var Variable to validate
+ * @param $type Type of variable, see HTMLPurifier_VarParser->types
+ * @param $allow_null Whether or not to permit null as a value
+ * @return Validated and type-coerced variable
+ */
+ final public function parse($var, $type, $allow_null = false) {
+ if (is_string($type)) {
+ if (!isset(HTMLPurifier_VarParser::$types[$type])) {
+ throw new HTMLPurifier_VarParserException("Invalid type '$type'");
+ } else {
+ $type = HTMLPurifier_VarParser::$types[$type];
+ }
+ }
+ $var = $this->parseImplementation($var, $type, $allow_null);
+ if ($allow_null && $var === null) return null;
+ // These are basic checks, to make sure nothing horribly wrong
+ // happened in our implementations.
+ switch ($type) {
+ case (self::STRING):
+ case (self::ISTRING):
+ case (self::TEXT):
+ case (self::ITEXT):
+ if (!is_string($var)) break;
+ if ($type == self::ISTRING || $type == self::ITEXT) $var = strtolower($var);
+ return $var;
+ case (self::INT):
+ if (!is_int($var)) break;
+ return $var;
+ case (self::FLOAT):
+ if (!is_float($var)) break;
+ return $var;
+ case (self::BOOL):
+ if (!is_bool($var)) break;
+ return $var;
+ case (self::LOOKUP):
+ case (self::ALIST):
+ case (self::HASH):
+ if (!is_array($var)) break;
+ if ($type === self::LOOKUP) {
+ foreach ($var as $k) if ($k !== true) $this->error('Lookup table contains value other than true');
+ } elseif ($type === self::ALIST) {
+ $keys = array_keys($var);
+ if (array_keys($keys) !== $keys) $this->error('Indices for list are not uniform');
+ }
+ return $var;
+ case (self::MIXED):
+ return $var;
+ default:
+ $this->errorInconsistent(get_class($this), $type);
+ }
+ $this->errorGeneric($var, $type);
+ }
+
+ /**
+ * Actually implements the parsing. Base implementation is to not
+ * do anything to $var. Subclasses should overload this!
+ */
+ protected function parseImplementation($var, $type, $allow_null) {
+ return $var;
+ }
+
+ /**
+ * Throws an exception.
+ */
+ protected function error($msg) {
+ throw new HTMLPurifier_VarParserException($msg);
+ }
+
+ /**
+ * Throws an inconsistency exception.
+ * @note This should not ever be called. It would be called if we
+ * extend the allowed values of HTMLPurifier_VarParser without
+ * updating subclasses.
+ */
+ protected function errorInconsistent($class, $type) {
+ throw new HTMLPurifier_Exception("Inconsistency in $class: ".HTMLPurifier_VarParser::getTypeName($type)." not implemented");
+ }
+
+ /**
+ * Generic error for if a type didn't work.
+ */
+ protected function errorGeneric($var, $type) {
+ $vtype = gettype($var);
+ $this->error("Expected type ".HTMLPurifier_VarParser::getTypeName($type).", got $vtype");
+ }
+
+ static public function getTypeName($type) {
+ static $lookup;
+ if (!$lookup) {
+ // Lazy load the alternative lookup table
+ $lookup = array_flip(HTMLPurifier_VarParser::$types);
+ }
+ if (!isset($lookup[$type])) return 'unknown';
+ return $lookup[$type];
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Flexible.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Flexible.php
new file mode 100644
index 0000000..a424edb
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Flexible.php
@@ -0,0 +1,103 @@
+<?php
+
+/**
+ * Performs safe variable parsing based on types which can be used by
+ * users. This may not be able to represent all possible data inputs,
+ * however.
+ */
+class HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser
+{
+
+ protected function parseImplementation($var, $type, $allow_null) {
+ if ($allow_null && $var === null) return null;
+ switch ($type) {
+ // Note: if code "breaks" from the switch, it triggers a generic
+ // exception to be thrown. Specific errors can be specifically
+ // done here.
+ case self::MIXED :
+ case self::ISTRING :
+ case self::STRING :
+ case self::TEXT :
+ case self::ITEXT :
+ return $var;
+ case self::INT :
+ if (is_string($var) && ctype_digit($var)) $var = (int) $var;
+ return $var;
+ case self::FLOAT :
+ if ((is_string($var) && is_numeric($var)) || is_int($var)) $var = (float) $var;
+ return $var;
+ case self::BOOL :
+ if (is_int($var) && ($var === 0 || $var === 1)) {
+ $var = (bool) $var;
+ } elseif (is_string($var)) {
+ if ($var == 'on' || $var == 'true' || $var == '1') {
+ $var = true;
+ } elseif ($var == 'off' || $var == 'false' || $var == '0') {
+ $var = false;
+ } else {
+ throw new HTMLPurifier_VarParserException("Unrecognized value '$var' for $type");
+ }
+ }
+ return $var;
+ case self::ALIST :
+ case self::HASH :
+ case self::LOOKUP :
+ if (is_string($var)) {
+ // special case: technically, this is an array with
+ // a single empty string item, but having an empty
+ // array is more intuitive
+ if ($var == '') return array();
+ if (strpos($var, "\n") === false && strpos($var, "\r") === false) {
+ // simplistic string to array method that only works
+ // for simple lists of tag names or alphanumeric characters
+ $var = explode(',',$var);
+ } else {
+ $var = preg_split('/(,|[\n\r]+)/', $var);
+ }
+ // remove spaces
+ foreach ($var as $i => $j) $var[$i] = trim($j);
+ if ($type === self::HASH) {
+ // key:value,key2:value2
+ $nvar = array();
+ foreach ($var as $keypair) {
+ $c = explode(':', $keypair, 2);
+ if (!isset($c[1])) continue;
+ $nvar[trim($c[0])] = trim($c[1]);
+ }
+ $var = $nvar;
+ }
+ }
+ if (!is_array($var)) break;
+ $keys = array_keys($var);
+ if ($keys === array_keys($keys)) {
+ if ($type == self::ALIST) return $var;
+ elseif ($type == self::LOOKUP) {
+ $new = array();
+ foreach ($var as $key) {
+ $new[$key] = true;
+ }
+ return $new;
+ } else break;
+ }
+ if ($type === self::ALIST) {
+ trigger_error("Array list did not have consecutive integer indexes", E_USER_WARNING);
+ return array_values($var);
+ }
+ if ($type === self::LOOKUP) {
+ foreach ($var as $key => $value) {
+ if ($value !== true) {
+ trigger_error("Lookup array has non-true value at key '$key'; maybe your input array was not indexed numerically", E_USER_WARNING);
+ }
+ $var[$key] = true;
+ }
+ }
+ return $var;
+ default:
+ $this->errorInconsistent(__CLASS__, $type);
+ }
+ $this->errorGeneric($var, $type);
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Native.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Native.php
new file mode 100644
index 0000000..55c4aea
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParser/Native.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * This variable parser uses PHP's internal code engine. Because it does
+ * this, it can represent all inputs; however, it is dangerous and cannot
+ * be used by users.
+ */
+class HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser
+{
+
+ protected function parseImplementation($var, $type, $allow_null) {
+ return $this->evalExpression($var);
+ }
+
+ protected function evalExpression($expr) {
+ $var = null;
+ $result = eval("\$var = $expr;");
+ if ($result === false) {
+ throw new HTMLPurifier_VarParserException("Fatal error in evaluated code");
+ }
+ return $var;
+ }
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParserException.php b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParserException.php
new file mode 100644
index 0000000..82e465d
--- /dev/null
+++ b/admin/survey/classes/htmlpurifier-4.3.0/library/HTMLPurifier/VarParserException.php
@@ -0,0 +1,11 @@
+<?php
+
+/**
+ * Exception type for HTMLPurifier_VarParser
+ */
+class HTMLPurifier_VarParserException extends HTMLPurifier_Exception
+{
+
+}
+
+// vim: et sw=4 sts=4
diff --git a/admin/survey/classes/log/class.SurveyLog.php b/admin/survey/classes/log/class.SurveyLog.php
new file mode 100644
index 0000000..3b37bb7
--- /dev/null
+++ b/admin/survey/classes/log/class.SurveyLog.php
@@ -0,0 +1,98 @@
+<?php
+
+/**
+ *
+ * Logiranje v 1ki
+ *
+ * Logi se nahajajo v direktoriju logs/
+ * Spororcila se zapisujejo v datoteko Y-m-d.log
+ *
+ */
+
+class SurveyLog {
+
+
+ // Log message types
+ const ERROR = 'ERROR';
+ const DEBUG = 'DEBUG';
+ const INFO = 'INFO';
+ const MAILER = 'MAILER';
+ const IZVOZ = 'IZVOZ';
+ const PAYMENT = 'PLACILO';
+
+
+ private $messages = array();
+
+
+ public function __construct(){
+ global $site_path;
+
+ define('LOG_FOLDER', $site_path.'logs/');
+
+ if (!is_dir(LOG_FOLDER) OR !is_writable(LOG_FOLDER)){
+ throw new Exception('Directory '.LOG_FOLDER.' must be writable');
+ }
+ }
+
+
+
+ // Dodamo sporocilo (vrstico), ki se zapise v log
+ public function addMessage($type, $message){
+
+ // Display the time in the current locale timezone
+ $time = date('Y-m-d H:i:s');
+
+ // Popravimo, da nimamo čšž-jev
+ $message = str_replace("č", "c", $message);
+ $message = str_replace("š", "s", $message);
+ $message = str_replace("ž", "z", $message);
+ $message = str_replace("Č", "C", $message);
+ $message = str_replace("Š", "S", $message);
+ $message = str_replace("Ž", "Z", $message);
+
+ $this->messages[] = array(
+ 'time' => $time,
+ 'type' => $type,
+ 'body' => $message,
+ );
+ }
+
+
+ // Zapisemo sporocila v log file
+ public function write(){
+
+ // Nimamo sporocil - ne naredimo nicesar
+ if (empty($this->messages)){
+ return;
+ }
+
+
+ // Ime loga
+ $filename = LOG_FOLDER.date('Y-m-d').'.log';
+
+ // Ce dnevni log file se ne obstaja ga ustvarimo in nastavimo pravice
+ if (!file_exists($filename)){
+
+ // Create the log file
+ file_put_contents($filename, 'Loging by class.SurveyLog.php'.PHP_EOL);
+
+ // Allow anyone to write to log files
+ //chmod($filename, 0666);
+ }
+
+ // Set the log line format
+ $format = 'time --- type: body';
+
+
+ // Loop cez vsa sporocila in zapis v file
+ foreach ($this->messages as $message){
+
+ file_put_contents($filename, PHP_EOL.strtr($format, $message), FILE_APPEND);
+ }
+
+
+ // Resetiramo array s sporocili
+ $this->messages = array();
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/mobile/class.MobileSurveyAdmin.php b/admin/survey/classes/mobile/class.MobileSurveyAdmin.php
new file mode 100644
index 0000000..3193246
--- /dev/null
+++ b/admin/survey/classes/mobile/class.MobileSurveyAdmin.php
@@ -0,0 +1,746 @@
+<?php
+
+/*
+ * Class, ki skrbi za mobile izris admin vmesnika
+ *
+ */
+
+
+
+class MobileSurveyAdmin{
+
+
+ var $surveyAdminClass;
+
+
+ function __construct($surveyAdminClass){
+ global $site_url;
+
+ $this->surveyAdminClass = $surveyAdminClass;
+ }
+
+
+ // Izris glave z menijem - znotraj ankete
+ public function displayHeaderMobile(){
+
+ echo '<div class="mobile_header '.($this->surveyAdminClass->anketa > 0 ? 'survey_edit' : 'survey_list').'">';
+
+ // Ikona za meni
+ $this->displayMenuIcon();
+
+ // Meni
+ $this->displayMenu();
+
+ // Naslov ankete
+ if($this->surveyAdminClass->anketa > 0){
+ $this->displaySurveyTitle();
+ }
+ // Logo - enak kot na desktopu
+ else{
+ $this->displayLogo();
+ }
+
+ // Se inicializiramo zeynep jquery mobile menu
+ echo '<script> mobile_init(); </script>';
+
+ echo '</div>';
+ }
+
+
+ // Prikazemo mobile logo
+ private function displayLogo(){
+ global $lang;
+ global $site_url;
+
+ echo '<div class="mobile_logo">';
+
+ $logo_class = ($lang['id'] != "1") ? ' class="english"' : '';
+ $su = ($site_url == "https://www.1ka.si/" && $lang['id'] != "1") ? "https://www.1ka.si/d/en/" : $site_url;
+
+ echo '<a href="' . $su . '" title="' . $lang['srv_1cs'] . '" id="enka_logo" ' . $logo_class . '></a>';
+
+ echo '</div>';
+ }
+
+ private function displaySurveyTitle(){
+
+ SurveyInfo::getInstance()->SurveyInit($this->surveyAdminClass->anketa);
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ echo '<div class="mobile_survey_title">'.$row['naslov'].'</div>';
+ }
+
+ private function displayMenuIcon(){
+
+ echo '<div class="mobile_menu_icon mobile_menu_open">';
+ echo ' <span class="faicon bars"></span>';
+ echo '</div>';
+
+ echo '<div class="mobile_menu_icon mobile_menu_close">';
+ echo ' <span>✕</span>';
+ echo '</div>';
+ }
+
+
+ // Izris menija
+ private function displayMenu(){
+
+ echo '<div class="mobile_menu first" data-menu-name="first">';
+
+ // Izris uporabniških podatkov v dropdownu
+ $this->displayMenuUser();
+
+ // Meni znotraj ankete
+ if($this->surveyAdminClass->anketa > 0){
+
+ // Izris glavne navigacije v dropdownu
+ $this->displayMenuSurveyNavigation();
+
+ // Izris akcij za anketo (kopiraj, brisi...) v dropdownu
+ $this->displayMenuSurveyActions();
+ }
+ // Meni v mojih anketah
+ else{
+ $this->displayMenuMySurveysNavigation();
+ }
+
+ echo '</div>';
+
+ }
+
+ // Izris uporabniških podatkov v dropdownu
+ private function displayMenuUser(){
+ global $lang, $global_user_id, $site_url;
+
+
+ $sql = $this->surveyAdminClass->db_select_user($global_user_id);
+ $row = mysqli_fetch_array($sql);
+
+ $user_name = $row['name'] . ' ' . $row['surname'];
+ $user_name = (strlen($user_name) > 25) ? substr($user_name, 0, 25) . '...' : $user_name;
+
+ $user_email = '<br><span class="email">'.$row['email'].'</span>';
+
+
+ echo '<div class="mobile_menu_user">';
+
+ echo '<ul>';
+
+ echo ' <li class="has-submenu">';
+ echo ' <a href="#" data-submenu="submenu_user" title="'.$user_name.'"><span class="faicon arrow_back"></span>'.$user_name.$user_email.'</a>';
+ echo ' </li>';
+
+ // Podmeni
+ echo ' <div id="submenu_user" class="submenu">';
+
+
+ // Podmeni header
+ echo ' <div class="submenu-header" data-submenu-close="submenu_user">';
+ echo ' <a href="#"><span class="faicon arrow_back"></span></a>';
+ echo ' <label>'.$user_name.'</label>';
+ echo ' </div>';
+
+
+ // Podmeni vsebina
+ echo ' <div class="submenu_user_content">';
+
+ echo ' <div><a href="'.$site_url.'admin/survey/index.php?a=nastavitve&m=global_user_myProfile"><span class="faicon user"></span>' . $lang['edit_data'] . '</a></div>';
+
+ // Odjava na nov nacin preko frontend/api
+ echo ' <div><form name="odjava" id="form_odjava" method="post" action="'.$site_url.'frontend/api/api.php?action=logout">';
+ echo ' <span class="as_link" onClick="$(\'#form_odjava\').submit();"><span class="faicon logout"></span>' . $lang['logout'] . '</span>';
+ echo ' </form></div>';
+
+ echo ' </div>';
+
+
+ echo ' </div>';
+
+ echo '</ul>';
+
+ echo '</div>';
+ }
+
+ // Izris glavne navigacije v mojih anketah
+ private function displayMenuMySurveysNavigation(){
+ global $lang, $admin_type, $app_settings;
+
+
+ # naložimo razred z seznamom anket
+ $SL = new SurveyList();
+ $SLCount = $SL->countSurveys();
+ $SLCountPhone = $SL->countPhoneSurveys();
+
+
+ echo '<div class="mobile_menu_navigation">';
+
+ echo '<ul>';
+
+
+ // MOJE ANKETE
+ $this->displayMenuItem($lang['srv_pregledovanje'], $url='index.php?a=pregledovanje');
+
+
+ // TELEFONSKA ANKETA
+ if ($SLCountPhone > 0 && $admin_type != '0') {
+ $this->displayMenuItem($lang['srv_telephone_surveys'], $url='index.php?a=phoneSurveys');
+ }
+
+
+ // AKTIVNOST
+ if ($SLCount > 0 && $admin_type == 0) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_ankete'],
+ 'url' => 'index.php?a=diagnostics'
+ ),
+ array(
+ 'title' => $lang['srv_weekly_diagnostics'],
+ 'url' => 'index.php?a=diagnostics&t=time_span_daily'
+ ),
+ array(
+ 'title' => $lang['srv_monthly_diagnostics'],
+ 'url' => 'index.php?a=diagnostics&t=time_span_monthly'
+ ),
+ array(
+ 'title' => $lang['srv_yearly_diagnostics'],
+ 'url' => 'index.php?a=diagnostics&t=time_span_yearly'
+ ),
+ array(
+ 'title' => $lang['srv_all_diagnostics'],
+ 'url' => 'index.php?a=diagnostics&t=time_span&uvoz=0&ustrezni=1&delnoustrezni=1&neustrezni=0'
+ ),
+ array(
+ 'title' => $lang['srv_metapodatki'],
+ 'url' => 'index.php?a=diagnostics&t=paradata'
+ )
+ );
+
+ $this->displayMenuItemWithSubmenu($name='diagnostics', $lang['srv_diagnostics'], $submenu);
+ }
+
+
+ // UPORABNIKI
+ if ($admin_type <= 1) {
+
+ // Admini imajo pregled nad vsemi zavihki uporabnikov
+ if ($admin_type == 0) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['n_users_list'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki'
+ ),
+ array(
+ 'title' => $lang['n_users_list_all'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki&m=all'
+ ),
+ array(
+ 'title' => $lang['n_deleted_users'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki&m=izbrisani'
+ ),
+ array(
+ 'title' => $lang['n_unconfirmed_users'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki&m=nepotrjeni'
+ ),
+ array(
+ 'title' => $lang['n_unsigned_users'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki&m=odjavljeni'
+ ),
+ array(
+ 'title' => $lang['srv_hierarchy_users_access'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki&m=sa-modul'
+ ),
+ );
+ }
+
+ // Manegerji imajo samo osnovni pregled svojih uporabnikov
+ if ($admin_type == 1) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['n_users_list'],
+ 'url' => 'index.php?a=diagnostics&t=uporabniki'
+ )
+ );
+ }
+
+ $this->displayMenuItemWithSubmenu($name='uporabniki', $lang['hour_users'], $submenu);
+ }
+
+
+ // KNJIZNICA
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_javna_knjiznica'],
+ 'url' => 'index.php?a=knjiznica'
+ ),
+ array(
+ 'title' => $lang['srv_moja_knjiznica'],
+ 'url' => 'index.php?a=knjiznica&t=moje_ankete'
+ )
+ );
+
+ $this->displayMenuItemWithSubmenu($name='knjiznica', $lang['srv_library'], $submenu);
+
+
+ // NASTAVITVE
+ if ($admin_type == '0') {
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_settingsSystem'],
+ 'url' => 'index.php?a=nastavitve&m=system'
+ ),
+ array(
+ 'title' => $lang['srv_testiranje_predvidenicas'],
+ 'url' => 'index.php?a=nastavitve&m=predvidenicasi'
+ ),
+ array(
+ 'title' => $lang['srv_collectData'],
+ 'url' => 'index.php?a=nastavitve&m=collectData'
+ ),
+ array(
+ 'title' => $lang['srv_nice_url'],
+ 'url' => 'index.php?a=nastavitve&m=nice_links'
+ ),
+ array(
+ 'title' => $lang['srv_anketa_admin'],
+ 'url' => 'index.php?a=nastavitve&m=anketa_admin'
+ ),
+ array(
+ 'title' => $lang['srv_anketa_deleted'],
+ 'url' => 'index.php?a=nastavitve&m=anketa_deleted'
+ ),
+ array(
+ 'title' => $lang['srv_data_deleted'],
+ 'url' => 'index.php?a=nastavitve&m=data_deleted'
+ ),
+ array(
+ 'title' => $lang['srv_user_settings'],
+ 'url' => 'index.php?a=nastavitve&m=global_user_settings'
+ ),
+ array(
+ 'title' => $lang['edit_data'],
+ 'url' => 'index.php?a=nastavitve&m=global_user_myProfile'
+ ),
+ );
+ }
+ else{
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_user_settings'],
+ 'url' => 'index.php?a=nastavitve&m=global_user_settings'
+ ),
+ array(
+ 'title' => $lang['edit_data'],
+ 'url' => 'index.php?a=nastavitve&m=global_user_myProfile'
+ ),
+ );
+ }
+
+ $this->displayMenuItemWithSubmenu($name='nastavitve', $lang['settings'], $submenu);
+
+
+ // NAROCILA
+ if($app_settings['commercial_packages']){
+
+ // placila - samo admini
+ if ($admin_type == '0') {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_narocila_my'],
+ 'url' => 'index.php?a=narocila'
+ ),
+ array(
+ 'title' => $lang['srv_placila'],
+ 'url' => 'index.php?a=narocila&m=placila'
+ )
+ );
+
+ $this->displayMenuItemWithSubmenu($name='nastavitve', $lang['settings'], $submenu);
+ }
+ // moja narocila
+ else{
+ $this->displayMenuItem($lang['srv_narocila'], $url='index.php?a=narocila');
+ }
+ }
+
+
+ // GDPR
+ $request_counter = GDPR::countUserUnfinishedRequests();
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_gdpr_user_settings'],
+ 'url' => 'index.php?a=gdpr'
+ ),
+ array(
+ 'title' => $lang['srv_gdpr_survey_list'],
+ 'url' => 'index.php?a=gdpr&m=placila'
+ ),
+ array(
+ 'title' => $lang['srv_gdpr_dpa'],
+ 'url' => 'index.php?a=gdpr'
+ ),
+ array(
+ 'title' => $lang['srv_gdpr_requests'].' ('.$request_counter.')',
+ 'url' => 'index.php?a=gdpr&m=gdpr_requests'
+ )
+ );
+
+ // Vse zahteve za izbris - samo ADMINI
+ if($admin_type == '0'){
+ $submenu[] = array(
+ 'title' => $lang['srv_gdpr_requests_all'],
+ 'url' => 'index.php?a=gdpr&m=gdpr_requests_all'
+ );
+ }
+
+ $this->displayMenuItemWithSubmenu($name='gdpr', 'GDPR', $submenu);
+
+
+ echo '</ul>';
+
+ echo '</div>';
+ }
+
+ // Izris glavne navigacije v anketi
+ private function displayMenuSurveyNavigation(){
+ global $lang;
+
+
+ $hierarhija_type = (!empty($_SESSION['hierarhija'][$this->surveyAdminClass->anketa]['type']) ? $_SESSION['hierarhija'][$this->surveyAdminClass->anketa]['type'] : null);
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+ SurveyInfo:: getInstance()->SurveyInit($this->surveyAdminClass->anketa);
+
+ $modules = SurveyInfo::getSurveyModules();
+ $d = new Dostop();
+
+
+ echo '<div class="mobile_menu_navigation first" data-menu-name="first">';
+
+ echo '<ul>';
+
+
+ // MOJE ANKETE
+ echo '<li>';
+ echo '<a class="left-1ka" href="index.php?a=pregledovanje" title="' . $lang['srv_pregledovanje'] . ' (' . strtolower($lang['srv_create_survey']) . ', ' . strtolower($lang['srv_library']) . ')">' . $lang['srv_pregledovanje'] . '</a>';
+ echo '</li>';
+
+
+ // STATUS
+ if ($this->surveyAdminClass->skin == 0 && $this->surveyAdminClass->isAnketar == false && $d->checkDostopSub('dashboard')) {
+
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ $this->displayMenuItem($lang['srv_status_summary'], $url='index.php?anketa='.$this->anketa.'&a='.A_REPORTI);
+ }
+ else{
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_status_summary'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_REPORTI
+ ),
+ array(
+ 'title' => $lang['srv_metapodatki'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_PARA_GRAPH
+ )
+ );
+
+ $this->displayMenuItemWithSubmenu($name='dashboard', $lang['srv_navigation_status'], $submenu);
+ }
+ }
+
+
+ // UREJANJE
+ if ($d->checkDostopSub('edit') && $hierarhija_type < 5 && !$this->surveyAdminClass->isAnketar) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_editirajanketo2'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . ($this->surveyAdminClass->survey_type > 1 ? '&a=' . A_BRANCHING : '')
+ ),
+ array(
+ 'title' => $lang['srv_nastavitve_ankete'] ,
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_SETTINGS
+ ),
+ array(
+ 'title' => $lang['srv_themes'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_TEMA
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiv'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_ARHIVI
+ ),
+ );
+
+ $this->displayMenuItemWithSubmenu($name='edit', $lang['srv_vprasalnik'], $submenu);
+ }
+
+
+ # TESTIRANJE - ne prikazemo v glasovanju
+ if ($this->surveyAdminClass->survey_type != 0 && $this->surveyAdminClass->survey_type != 1 && $d->checkDostopSub('test')) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_testiranje_diagnostika'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_TESTIRANJE . '&m=' . M_TESTIRANJE_DIAGNOSTIKA
+ ),
+ array(
+ 'title' => $lang['srv_testiranje_komentarji'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_KOMENTARJI
+ ),
+ array(
+ 'title' => $lang['srv_testiranje_vnosi'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_TESTIRANJE . '&m=' . M_TESTIRANJE_VNOSI
+ ),
+ );
+
+ $this->displayMenuItemWithSubmenu($name='test', $lang['srv_testiranje'], $submenu);
+ }
+
+
+ // OBJAVA
+ if ($d->checkDostopSub('publish')) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_publication_base'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_VABILA . '&m=settings'
+ ),
+ array(
+ 'title' => $lang['srv_publication_url'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_VABILA . '&m=url'
+ ),
+ array(
+ 'title' => $lang['srv_inv_nav_invitations'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_INVITATIONS . '&m=settings'
+ ),
+ );
+
+ $this->displayMenuItemWithSubmenu($name='publish', $lang['srv_vabila'], $submenu);
+ }
+
+
+ // PODATKI - ne prikazemo v glasovanju
+ if ($this->surveyAdminClass->survey_type != 0 && $d->checkDostopSub('data')) {
+
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_link_data_browse'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_COLLECT_DATA
+ ),
+ array(
+ 'title' => $lang['srv_data_navigation_calculate'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_COLLECT_DATA . '&m=calculation'
+ ),
+ array(
+ 'title' => $lang['srv_data_navigation_import'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_COLLECT_DATA . '&m=append'
+ )
+ );
+
+ if ($d->checkDostopSub('export')) {
+ $submenu[] = array(
+ 'title' => $lang['srv_export_tab'],
+ 'url' => 'index.php?anketa=' . $this->surveyAdminClass->anketa . '&a=' . A_COLLECT_DATA_EXPORT
+ );
+ }
+
+ $this->displayMenuItemWithSubmenu($name='data', $lang['srv_results'], $submenu);
+ }
+
+
+ // ANALIZA
+ if ($d->checkDostopSub('analyse')) {
+
+ // Hierarhija
+ if (SurveyInfo::getInstance()->checkSurveyModule('hierarhija')) {
+ $this->displayMenuItem($lang['srv_stat_analiza'], $url='index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_MEANS_HIERARHY);
+ }
+ // Navadne analize
+ else{
+ $submenu = array(
+ array(
+ 'title' => $lang['srv_stat_analiza'],
+ 'name' => 'analyse_submenu',
+ 'submenu' => array(
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_0'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_SUMMARY
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_1'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_DESCRIPTOR
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_2'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_FREQUENCY
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_3'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_CROSSTAB
+ ),
+ array(
+ 'title' => $lang['srv_multicrosstabs'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_MULTICROSSTABS
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_4'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_MEANS
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_5'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_TTEST
+ ),
+ array(
+ 'title' => $lang['srv_analiza_arhiviraj_type_6'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_BREAK
+ )
+ )
+ ),
+ array(
+ 'title' => $lang['srv_analiza_charts'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_CHARTS
+ ),
+ array(
+ 'title' => $lang['srv_reporti'],
+ 'url' => 'index.php?anketa='.$this->surveyAdminClass->anketa.'&a='.A_ANALYSIS.'&m='.M_ANALYSIS_LINKS
+ ),
+ );
+
+ $this->displayMenuItemWithSubmenu($name='analyse', $lang['srv_analiza'], $submenu);
+ }
+ }
+
+
+ echo '</ul>';
+
+ echo '</div>';
+ }
+
+ // Izris akcij za anketo (kopiraj, brisi...) v dropdownu
+ private function displayMenuSurveyActions(){
+ global $lang;
+
+ echo '<div class="mobile_menu_actions">';
+
+ # kopiranje
+ echo ' <a href="#" onclick="anketa_copy_top(\'' . $this->surveyAdminClass->anketa . '\'); return false;" title="'.$lang['srv_anketacopy'].'" class="srv_ico">';
+ echo ' <span class="faicon anketa_copy"></span> '.$lang['srv_anketacopy'];
+ echo ' </a>';
+
+ # brisanje
+ echo ' <a href="#" onclick="anketa_delete(\'' . $this->surveyAdminClass->anketa . '\', \'' . $lang['srv_anketadeleteconfirm'] . '\'); return false;" title="' . $lang['srv_anketadelete'] . '" class="srv_ico">';
+ echo ' <span class="faicon anketa_delete" title="'.$lang['srv_anketadelete'].'"></span> '.$lang['srv_anketadelete'];
+ echo ' </a>';
+
+ echo '</div>';
+ }
+
+
+
+ private function displayMenuItemWithSubmenu($name, $title, $submenu){
+ global $lang;
+
+ echo '<li class="has-submenu">';
+ echo ' <a href="#" data-submenu="submenu_'.$name.'" title="'.$title.'">'.$title.'<span class="faicon arrow_back"></span></a>';
+ echo '</li>';
+
+ // Podmeni
+ echo '<div id="submenu_'.$name.'" class="submenu">';
+
+
+ // Podmeni header
+ echo '<div class="submenu-header" data-submenu-close="submenu_'.$name.'">';
+
+ // Nazaj
+ echo ' <a href="#"><span class="faicon arrow_back"></span></a>';
+
+ // Label
+ echo '<label>'.$title.'</label>';
+
+ echo '</div>';
+
+
+ // Vsebina podmenija
+ echo '<ul>';
+ foreach($submenu as $submenu_item){
+
+ // Dodaten podmeni
+ if(isset($submenu_item['name'])){
+ //$this->displaySubmenuItem($submenu_item['name'], $submenu_item['title'], $submenu_item['submenu']);
+ $this->displayMenuItemWithSubmenu($submenu_item['name'], $submenu_item['title'], $submenu_item['submenu']);
+ }
+ else{
+ $this->displayMenuItem($submenu_item['title'], $submenu_item['url']);
+ }
+ }
+ echo '</ul>';
+
+ echo '</div>';
+ }
+
+ private function displayMenuItem($title, $url){
+
+ echo '<li>';
+ echo '<a href="'.$url.'" title="'.$title.'">'.$title.'</a>';
+ echo '</li>';
+ }
+
+
+ // Gumb za dodajanje vprasanja
+ public static function displayAddQuestion($ank_id){
+ global $lang;
+
+ echo '<div class="mobile_add_question bottom">';
+ echo ' <span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="mobile_add_question_popup(); return false;">';
+ echo ' <span class="plus">+</span> ';
+ echo ' <span>'.$lang['srv_mobile_add_question'].'</span>';
+ echo ' </a></span>';
+ echo '</div>';
+
+
+ // Popup za dodajanje vprašanja
+ echo '<div class="mobile_add_question_popup">';
+
+ echo ' <div class="mobile_add_question_item" onClick="mobile_add_question(\'1\');"><span class="faicon radio_32"></span> <span class="item_text">'.$lang['srv_vprasanje_tip_1'].'</span></div>';
+ echo ' <div class="mobile_add_question_item" onClick="mobile_add_question(\'2\');"><span class="faicon check_32"></span> <span class="item_text">'.$lang['srv_vprasanje_tip_2'].'</span></div>';
+ echo ' <div class="mobile_add_question_item" onClick="mobile_add_question(\'21\');"><span class="faicon abc_32"></span> <span class="item_text">'.$lang['srv_vprasanje_tip_21'].'</span></div>';
+ echo ' <div class="mobile_add_question_item" onClick="mobile_add_question(\'7\');"><span class="faicon number_32"></span> <span class="item_text">'.$lang['srv_vprasanje_tip_7'].'</span></div>';
+ echo ' <div class="mobile_add_question_item" onClick="mobile_add_question(\'5\');"><span class="faicon nagovor"></span> <span class="item_text">'.$lang['srv_vprasanje_tip_5'].'</span></div>';
+ echo ' <div class="mobile_add_question_item" onClick="mobile_add_question(\'6\');"><span class="faicon matrix_32"></span> <span class="item_text">'.$lang['srv_vprasanje_tip_6'].'</span></div>';
+
+ echo ' <span class="buttonwrapper mobile_add_question_button">';
+ echo ' <a class="ovalbutton ovalbutton_orange" href="#" onclick="mobile_add_question_popup_close(); return false;"><span>Zapri</span></a>';
+ echo ' </span>';
+
+ echo '</div>';
+ }
+
+ // Div ko se nimamo nobenega vprasanja v anketi
+ public static function displayNoQuestions($ank_id){
+ global $lang;
+
+ // Skrijemo spodnji gumb
+ echo '<style>.mobile_add_question.bottom{display: none;}</style>';
+
+ echo '<div class="mobile_add_question center">';
+ echo ' <span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="mobile_add_question_popup(); return false;">';
+ echo ' <span class="plus">+</span> ';
+ echo ' <span>'.$lang['srv_mobile_add_question'].'</span>';
+ echo ' </a></span>';
+ echo '</div>';
+ }
+
+ // Div za dodajanje kategorije v vprasanje
+ public static function displayAddQuestionCategory($ank_id, $spr_id, $tip){
+ global $lang;
+
+ echo '<div class="add-variable-mobile">';
+ echo ' <a href="#" onclick="vrednost_new_mobile(\''.$spr_id.'\', \''.$tip.'\'); return false;" title="'.$lang['srv_novavrednost'].'"><span class="faicon add small"></span> '.$lang['srv_novavrednost'].'</a>';
+ echo '</div>';
+ }
+}
diff --git a/admin/survey/classes/objects/obj.MailAdapter.php b/admin/survey/classes/objects/obj.MailAdapter.php
new file mode 100644
index 0000000..1f13c87
--- /dev/null
+++ b/admin/survey/classes/objects/obj.MailAdapter.php
@@ -0,0 +1,945 @@
+<?php
+
+/**
+ *
+ * Class skrbi za pošiljanje mailov
+ * @author Peter Hrvatin
+ * 22.8.2019
+ *
+ */
+
+class MailAdapter{
+
+ private $ank_id = null;
+
+ private $settings = array();
+ private $mailModes = array(0=>'1ka', 1=>'google', 2=>'smtp');
+ private $mailMode = '1ka'; // 1ka, google, smtp
+ private $recipients = array();
+
+ /** Tip posiljanja
+ * "invitation" - email vabilo
+ * "alert" - email obvescanje (aktivacija ankete, zakljucena anketa, arhiv ankete...)
+ * "admin" - email povezan z administracijo (alerti za admine)
+ * "account" - email povezan z upravljanjem racuna (dodan dostop do anket...)
+ * "payments" - email povezan s placili paketov (posiljanje racunov, predracunov...)
+ */
+ private $type = '';
+
+ private $password_hash_key = '#&_ww.9$.1ka#"%o';
+
+ private $phpMailerClass;
+
+ /** Debugging
+ * 0 = off (for production use)
+ * 1 = client messages
+ * 2 = client and server messages
+ */
+ private $phpMailerDebug = 0;
+
+
+ public function __construct($anketa=null, $type=''){
+ global $admin_type;
+ global $mysql_database_name;
+
+ // Nastavimo tip posiljanja
+ $this->type = $type;
+
+ // Inicializiramo phpMailer razred
+ $this->prepareMailer();
+
+
+ // Posiljanje iz ankete
+ if ((int)$anketa > 0){
+
+ $this->ank_id = $anketa;
+
+ // Pripravimo nastavitve za posiljanje ankete
+ $this->prepareSurveySettings();
+ }
+ // Splosno posiljanje (brez id-ja ankete)
+ else{
+
+ // Pripravimo splosne nastavitve aplikacije za posiljanje
+ $this->prepareGeneralSettings();
+ }
+ }
+
+
+
+ // Pripravimo nastavitve posiljanja za doloceno anketo
+ private function prepareSurveySettings(){
+ global $admin_type;
+ global $mysql_database_name;
+ global $email_server_settings;
+ global $email_server_fromSurvey;
+
+
+ // Polovimo nastavitve ce obstajajo v bazi
+ SurveySetting::getInstance()->Init($this->ank_id);
+ $mail1kaSavedConfig = unserialize(SurveySetting::getInstance()->getSurveyMiscSetting('send_mail_config'));
+ $this->settings = is_array($mail1kaSavedConfig) ? $mail1kaSavedConfig : array();
+
+
+ // Nastavitve imamo ze shranjene v bazi - samo nastavimo ustrezen "mode"
+ if(!empty($this->settings)){
+
+ // Nastavimo "mode" posiljanja (1ka, gmail ali smtp)
+ $mailMode = (int)$this->settings['SMTPMailMode'];
+
+ if ($mailMode === 2){
+ $this->mailMode = 'smtp';
+ }
+ else if ($mailMode === 1){
+ $this->mailMode = 'google';
+ }
+ else{
+ $this->mailMode = '1ka';
+ }
+
+
+ // Password dekodiramo
+ if (isset($this->settings['1ka']['SMTPPassword'])){
+ $this->settings['1ka']['SMTPPassword'] = $this->decryptPassword($this->settings['1ka']['SMTPPassword']);
+ }
+ if (isset($this->settings['google']['SMTPPassword'])){
+ $this->settings['google']['SMTPPassword'] = $this->decryptPassword($this->settings['google']['SMTPPassword']);
+ }
+ if (isset($this->settings['smtp']['SMTPPassword'])){
+ $this->settings['smtp']['SMTPPassword'] = $this->decryptPassword($this->settings['smtp']['SMTPPassword']);
+ }
+
+
+ // Pri 1ka nastavitvah lahko nastavljamo samo reply to, vse ostalo je veedno default
+ if($this->settings['1ka']['SMTPReplyTo'] == '')
+ $this->settings['1ka']['SMTPReplyTo'] = $email_server_settings['SMTPReplyTo'];
+
+ $this->settings['1ka']['SMTPFrom'] = $email_server_settings['SMTPFrom'];
+ $this->settings['1ka']['SMTPFromNice'] = $email_server_settings['SMTPFromNice'];
+ $this->settings['1ka']['SMTPHost'] = $email_server_settings['SMTPHost'];
+ $this->settings['1ka']['SMTPPort'] = $email_server_settings['SMTPPort'];
+
+ if(isset($email_server_settings['SMTPAuth']) && $email_server_settings['SMTPAuth'] == 1){
+ $this->settings['1ka']['SMTPAuth'] = $email_server_settings['SMTPAuth'];
+ $this->settings['1ka']['SMTPUsername'] = $email_server_settings['SMTPUsername'];
+ $this->settings['1ka']['SMTPPassword'] = $email_server_settings['SMTPPassword'];
+ }
+
+ if(isset($email_server_settings['SMTPSecure']))
+ $this->settings['1ka']['SMTPSecure'] = $email_server_settings['SMTPSecure'];
+
+ // Pri google smtp je username vedno email
+ if($this->mailMode == 'google')
+ $this->settings['google']['SMTPUsername'] = $this->settings['google']['SMTPFrom'];
+
+ // ce posiljamo mail vabila in smo na www.1ka.si oz. virutalkah in smo admin - posiljamo preko sekundarnega maila (raziskave@1ka.si)
+ if($this->type == 'invitation' && $admin_type == 0 && isset($email_server_settings['secondary_mail'])){
+ $this->settings['1ka']['SMTPFrom'] = $email_server_settings['secondary_mail']['SMTPFrom'];
+ $this->settings['1ka']['SMTPFromNice'] = $email_server_settings['secondary_mail']['SMTPFromNice'];
+ $this->settings['1ka']['SMTPReplyTo'] = $email_server_settings['secondary_mail']['SMTPReplyTo'];
+ $this->settings['1ka']['SMTPUsername'] = $email_server_settings['secondary_mail']['SMTPUsername'];
+ $this->settings['1ka']['SMTPPassword'] = $email_server_settings['secondary_mail']['SMTPPassword'];
+ }
+
+ // Nastavimo default delay
+ if(!isset($this->settings['1ka']['SMTPDelay']) || $this->settings['1ka']['SMTPDelay'] == '' || $this->settings['1ka']['SMTPDelay'] == '0')
+ $this->settings['1ka']['SMTPDelay'] = 500000;
+ }
+ // Nimamo se nicesar v bazi - nastavimo default nastavitve
+ else{
+
+ // Nastavimo 1ka smtp
+ $this->settings['1ka']['SMTPFrom'] = $email_server_settings['SMTPFrom'];
+ $this->settings['1ka']['SMTPFromNice'] = $email_server_settings['SMTPFromNice'];
+ $this->settings['1ka']['SMTPReplyTo'] = $email_server_settings['SMTPReplyTo'];
+ $this->settings['1ka']['SMTPHost'] = $email_server_settings['SMTPHost'];
+ $this->settings['1ka']['SMTPPort'] = $email_server_settings['SMTPPort'];
+
+ if(isset($email_server_settings['SMTPAuth']) && $email_server_settings['SMTPAuth'] == 1){
+ $this->settings['1ka']['SMTPAuth'] = $email_server_settings['SMTPAuth'];
+ $this->settings['1ka']['SMTPUsername'] = $email_server_settings['SMTPUsername'];
+ $this->settings['1ka']['SMTPPassword'] = $email_server_settings['SMTPPassword'];
+ }
+
+ if(isset($email_server_settings['SMTPSecure']))
+ $this->settings['1ka']['SMTPSecure'] = $email_server_settings['SMTPSecure'];
+
+ // Nastavimo default delay
+ $this->settings['1ka']['SMTPDelay'] = 500000;
+
+ // Nastavimo gmail smtp
+ $this->settings['google']['SMTPHost'] = 'smtp.gmail.com';
+ $this->settings['google']['SMTPPort'] = '587';
+ $this->settings['google']['SMTPSecure'] = 'tls';
+ $this->settings['google']['SMTPAuth'] = 1;
+
+ // Nastavimo default delay
+ $this->settings['google']['SMTPDelay'] = 500000;
+
+
+ // Ce imamo nastavljeno, da se za posiljanje iz ankete uporabi isti smtp streznik kot za generalno posiljanje
+ if($email_server_fromSurvey){
+ $this->prepareGeneralSettings();
+ }
+ else{
+
+ // ce posiljamo mail vabila (default razlicno za admine in ostale)
+ if($this->type == 'invitation'){
+
+ // Pri vabilih je default 1ka streznik samo na www.1ka.si in to samo za admine
+ if($admin_type == 0 && isset($email_server_settings['secondary_mail'])){
+ $this->mailMode = '1ka';
+ $this->settings['1ka']['SMTPFrom'] = $email_server_settings['secondary_mail']['SMTPFrom'];
+ $this->settings['1ka']['SMTPFromNice'] = $email_server_settings['secondary_mail']['SMTPFromNice'];
+ $this->settings['1ka']['SMTPReplyTo'] = $email_server_settings['secondary_mail']['SMTPReplyTo'];
+ $this->settings['1ka']['SMTPUsername'] = $email_server_settings['secondary_mail']['SMTPUsername'];
+ $this->settings['1ka']['SMTPPassword'] = $email_server_settings['secondary_mail']['SMTPPassword'];
+ }
+ // Drugace je potrebno nastaviti smtp
+ else{
+ $this->mailMode = 'smtp';
+ }
+ }
+ // Ce ne gre za vabila se uporabi kar 1ka streznik
+ else{
+ //$this->prepareGeneralSettings();
+ $this->mailMode = '1ka';
+ }
+ }
+ }
+ }
+
+ // Pripravimo nastavitve splosnega posiljanja v aplikaciji glede na nastavitve v settings_optional.php
+ private function prepareGeneralSettings(){
+ global $email_server_settings;
+ global $mysql_database_name;
+
+ $this->mailMode = 'smtp';
+ $this->settings['SMTPMailMode'] = 2;
+
+ $this->settings['smtp'] = array(
+ 'SMTPFrom' => $email_server_settings['SMTPFrom'],
+ 'SMTPFromNice' => $email_server_settings['SMTPFromNice'],
+ 'SMTPReplyTo' => $email_server_settings['SMTPReplyTo'],
+
+ 'SMTPHost' => $email_server_settings['SMTPHost'],
+ 'SMTPPort' => $email_server_settings['SMTPPort']
+ );
+
+ if(isset($email_server_settings['SMTPAuth']) && $email_server_settings['SMTPAuth'] == 1){
+ $this->settings['smtp']['SMTPAuth'] = $email_server_settings['SMTPAuth'];
+ $this->settings['smtp']['SMTPUsername'] = $email_server_settings['SMTPUsername'];
+ $this->settings['smtp']['SMTPPassword'] = $email_server_settings['SMTPPassword'];
+ }
+
+ if(isset($email_server_settings['SMTPSecure']))
+ $this->settings['smtp']['SMTPSecure'] = $email_server_settings['SMTPSecure'];
+
+ // ce posiljamo v povezavi s placili (racuni, predracuni...) - posiljamo preko tretjega maila (invoice@1ka.si)
+ if($this->type == 'payments' && isset($email_server_settings['payments_mail']) && $mysql_database_name == 'real1kasi'){
+ $this->settings['smtp']['SMTPFrom'] = $email_server_settings['payments_mail']['SMTPFrom'];
+ $this->settings['smtp']['SMTPFromNice'] = $email_server_settings['payments_mail']['SMTPFromNice'];
+ $this->settings['smtp']['SMTPReplyTo'] = $email_server_settings['payments_mail']['SMTPReplyTo'];
+ $this->settings['smtp']['SMTPUsername'] = $email_server_settings['payments_mail']['SMTPUsername'];
+ $this->settings['smtp']['SMTPPassword'] = $email_server_settings['payments_mail']['SMTPPassword'];
+ }
+
+ // Nastavimo default delay
+ $this->settings['smtp']['SMTPDelay'] = 500000;
+ }
+
+
+
+ public function is1KA () {
+ return $this->mailMode == '1ka';
+ }
+ public function isGoogle () {
+ return $this->mailMode == 'google';
+ }
+ public function isSMTP () {
+ return $this->mailMode == 'smtp';
+ }
+
+ // Vrnemo nastavitve posiljanja za dolocen mode
+ public function getSettings($mailModeString = null){
+
+ // Pogledamo za kateri "mode" pridobivamo nastavitve
+ if ($mailModeString == null){
+ $mailModeString = $this->getMailMode($asString=true);
+ }
+ $result = $this->settings[$mailModeString];
+
+ if(isset($result) && is_array($result))
+ return $result;
+ else
+ return array();
+ }
+
+ // Vrnemo nastavitve posiljanja na podlagi requesta
+ public function getSettingsFromRequest($request){
+
+ $settings = array();
+
+ $mode = $request['SMTPMailMode'];
+
+ foreach ($request AS $pkey => $pvalue){
+
+ // if starts with SMTP && END WITH $_REQUEST['send_mail_mode']
+ if (!strncmp($pkey, "SMTP", strlen("SMTP")) && substr($pkey, -strlen($mode))===$mode){
+ $settings[rtrim($pkey, "{$mode}")] = $pvalue;
+ }
+ }
+ $settings['SMTPMailMode'] = $mode;
+
+ return $settings;
+ }
+
+ // Vrnemo nastavitev from (email)
+ public function getMailFrom(){
+ $s = $this->getSettings();
+ return $s['SMTPFrom'];
+ }
+
+ // Vrnemo nastavitev from (ime)
+ public function getMailFromNice(){
+ $s = $this->getSettings();
+ return $s['SMTPFromNice'];
+ }
+
+ // Vrnemo reply-to nastavitev
+ public function getMailReplyTo(){
+ $s = $this->getSettings();
+ return $s['SMTPReplyTo'];
+ }
+
+
+ // Vrnemo nastavitev mode-a posiljanja (1ka, google ali smtp)
+ public function getMailMode($asString=false){
+
+ if ($asString)
+ return $this->mailMode;
+ else
+ return (int)array_search($this->mailMode, $this->mailModes);
+ }
+
+
+ // Vrnemo nastavitve za dolocen mode
+ public function get1KASettings(){
+
+ $result = $this->settings['1ka'];
+
+ if(isset($result) && is_array($result))
+ return $result;
+ else
+ return array();
+ }
+
+ public function getGoogleSettings(){
+
+ $result = $this->settings['google'];
+
+ if(isset($result) && is_array($result))
+ return $result;
+ else
+ return array();
+ }
+
+ public function getSMTPSettings(){
+
+ $result = $this->settings['smtp'];
+
+ if(isset($result) && is_array($result))
+ return $result;
+ else
+ return array();
+ }
+
+
+
+ // Nastavimo nastavitve za dolocen "mode" in jih shranimo v bazo
+ public function setSettings($mode, $settings){
+
+ foreach ($settings AS $key => $value){
+
+ if ( $key == 'SMTPMailMode' ){
+ $this->settings[$key] = $value;
+ }
+
+ // geslo shranimo samo če ni null
+ else if ( $key != 'SMTPPassword' || ($key == 'SMTPPassword' && !empty($value)) ){
+
+ $this->settings[$this->mailModes[(int)$mode]][$key] = $value;
+ }
+ }
+
+ $this->saveSettings();
+ }
+
+ // Shranimo nastavitve v bazo
+ private function saveSettings(){
+
+ $settings = $this->settings;
+
+ // Passworde zakodiramo pred shranjevanjem v bazo
+ if (isset($settings['1ka']['SMTPPassword'])){
+ $settings['1ka']['SMTPPassword'] = $this->encryptPassword($settings['1ka']['SMTPPassword']);
+ }
+ if (isset($settings['google']['SMTPPassword'])){
+ $settings['google']['SMTPPassword'] = $this->encryptPassword($settings['google']['SMTPPassword']);
+ }
+ if (isset($settings['smtp']['SMTPPassword'])){
+ $settings['smtp']['SMTPPassword'] = $this->encryptPassword($settings['smtp']['SMTPPassword']);
+ }
+
+ $c = mysqli_real_escape_string($GLOBALS['connect_db'], serialize($settings));
+ $succ = SurveySetting::getInstance()->setSurveyMiscSetting('send_mail_config', $c);
+ }
+
+ // Nastavimo reply to mail
+ public function setMailReplyTo($reply_to){
+
+ if($this->validEmail($reply_to)){
+ $s = $this->getSettings();
+ $s['SMTPReplyTo'] = $reply_to;
+
+ $this->setSettings((int)$this->settings['SMTPMailMode'], $s);
+ }
+ }
+
+ // Nastavimo from ime
+ public function setMailFromNice($from_nice){
+
+ $s = $this->getSettings();
+ $s['SMTPFromNice'] = $from_nice;
+
+ $this->setSettings((int)$this->settings['SMTPMailMode'], $s);
+ }
+
+ // Nastavimo from email
+ public function setMailFrom($from){
+
+ if($this->validEmail($from)){
+ $s = $this->getSettings();
+ $s['SMTPFrom'] = $from;
+
+ $this->setSettings((int)$this->settings['SMTPMailMode'], $s);
+ }
+ }
+
+
+ // Dodamo respondenta emaila
+ public function addRecipients($recipient){
+
+ // Ce imamo vec prejemnikov
+ if(is_array($recipient)){
+
+ foreach($recipient as $email){
+ if ($this->validEmail($email))
+ $this->recipients[] = $email;
+ }
+ }
+ else{
+ if ($this->validEmail($recipient))
+ $this->recipients[] = $recipient;
+ }
+ }
+
+ // Dodamo attachment
+ public function addAttachment($file, $file_name){
+
+ $this->phpMailerClass->addStringAttachment($file, $file_name);
+ }
+
+
+
+ // Inicializiramo phpmailer razred in nastavimo splosne nastavitve
+ private function prepareMailer(){
+
+ // Inicializiramo razred
+ $this->phpMailerClass = new PHPMailer\PHPMailer\PHPMailer();
+
+ // Nastavimo se debugging
+ $this->phpMailerClass->SMTPDebug = $this->phpMailerDebug;
+
+
+ // UTF8 encoding
+ $this->phpMailerClass->CharSet = 'UTF-8';
+
+ // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
+ $this->phpMailerClass->Priority = 3;
+
+ // 8-bit encoding
+ //$this->phpMailerClass->Encoding = '8bit';
+
+ // RFC 2822 Compliant for Max 998 characters per line
+ $this->phpMailerClass->WordWrap = 900;
+
+ //$this->phpMailerClass->Helo = $settings["ServerHostname"];
+
+
+ // Vedno posiljamo preko smtp
+ $this->phpMailerClass->isSMTP();
+ }
+
+ // Posljemo mail
+ public function sendMail($email_msg, $email_subject){
+ global $mysql_database_name;
+
+ // Nastavimo ustrezen "mode"
+ $mailModeString = $this->mailMode;
+
+ // Dobimo nastavitve iz baze
+ $settings = $this->getSettings($mailModeString);
+
+
+ // Nastavimo mail server
+ $this->phpMailerClass->Host = $settings["SMTPHost"];
+
+ // Nastavimo SMTP port
+ $this->phpMailerClass->Port = $settings["SMTPPort"];
+
+ // Nastavimo ssl / tls
+ $this->phpMailerClass->SMTPSecure = $settings['SMTPSecure'];
+
+ // Nastavimo ce se uporablja SMTP avtentikacijo
+ if($settings["SMTPAuth"] == 1)
+ $this->phpMailerClass->SMTPAuth = true;
+
+ // Nastavimo username za SMTP avtentikacijo
+ $this->phpMailerClass->Username = $settings["SMTPUsername"];
+
+ // Nastavimo password za SMTP avtentikacijo
+ $this->phpMailerClass->Password = $settings["SMTPPassword"];
+
+
+ // Posebej vklopimo, ker drugace sisplet smtp ne deluje!
+ if($this->phpMailerClass->Host == 'mail.sisplet.org'){
+ $this->phpMailerClass->SMTPOptions = array(
+ 'ssl' => array(
+ 'verify_peer' => false
+ )
+ );
+ }
+
+
+ // Kdo posilja
+ if(isset($settings["SMTPFromNice"]) && $settings["SMTPFromNice"] != "") {
+ $this->phpMailerClass->SetFrom($settings["SMTPFrom"], $settings["SMTPFromNice"]);
+ }
+ else{
+ $this->phpMailerClass->SetFrom($settings["SMTPFrom"]);
+ }
+
+ // Reply-to naslov
+ $this->phpMailerClass->AddReplyTo($settings["SMTPReplyTo"]);
+
+ // Subject
+ $this->phpMailerClass->Subject = $email_subject;
+
+ // Vsebina maila
+ $this->prepareEmailDesign($email_msg);
+
+
+ // Loop cez prejemnike in posiljanje
+ if (!empty($this->recipients)){
+
+ // Loop cez vse prejemnike
+ foreach ($this->recipients AS $recipient){
+ $this->phpMailerClass->AddAddress($recipient);
+ }
+
+ // Posljemo mail
+ $success = $this->phpMailerClass->send();
+
+
+ // Logiramo posiljanje
+ $SL = new SurveyLog();
+
+ // Napaka
+ if (!$success) {
+
+ if((int)$this->ank_id > 0)
+ $SL->addMessage(SurveyLog::MAILER, "NAPAKA pri pošiljanju emaila iz ankete ".$this->ank_id." na naslove ".implode(",", $this->recipients)."! ".$this->phpMailerClass->ErrorInfo);
+ else
+ $SL->addMessage(SurveyLog::MAILER, "NAPAKA pri pošiljanju emaila na naslove ".implode(",", $this->recipients)."! ".$this->phpMailerClass->ErrorInfo);
+
+ if($this->phpMailerDebug > 0)
+ echo "<br />Mailer Error: " . $this->phpMailerClass->ErrorInfo.'<br /><br />';
+ }
+ // Uspesno posiljanje
+ else {
+
+ if((int)$this->ank_id > 0)
+ $SL->addMessage(SurveyLog::MAILER, "USPEŠNO pošiljanje emaila iz ankete ".$this->ank_id." na naslove ".implode(",", $this->recipients));
+ else
+ $SL->addMessage(SurveyLog::MAILER, "USPEŠNO pošiljanje emaila na naslove ".implode(",", $this->recipients));
+
+ if($this->phpMailerDebug > 0)
+ echo "Message sent!<br /><br />";
+ }
+
+ $SL->write();
+
+
+ // Dodamo pavzo po pošiljanju ce je nastavljena - default je vedno 2 / sekundo
+ $delay = (isset($settings['SMTPDelay']) && intval($settings['SMTPDelay']) > 0) ? $settings['SMTPDelay'] : 500000;
+ if($delay > 0){
+ usleep ($delay);
+ }
+
+ return $success;
+ }
+ }
+
+ // Posljemo testni mail pri testiranju nastavitev streznika
+ public function sendMailTest($email_msg, $email_subject, $mailMode=null, $settings=null){
+ global $mysql_database_name;
+
+ // Nastavimo ustrezen "mode"
+ $mailModeString = $this->mailModes[$mailMode];
+
+
+ // Ce gre za gmail ali 1ka napolnimo default podatke
+ if(!isset($settings["SMTPHost"]))
+ $settings["SMTPHost"] = $this->settings[$mailModeString]["SMTPHost"];
+ if(!isset($settings["SMTPPort"]))
+ $settings["SMTPPort"] = $this->settings[$mailModeString]["SMTPPort"];
+ if(!isset($settings["SMTPSecure"]))
+ $settings["SMTPSecure"] = $this->settings[$mailModeString]["SMTPSecure"];
+ if(!isset($settings["SMTPAuth"]))
+ $settings["SMTPAuth"] = $this->settings[$mailModeString]["SMTPAuth"];
+
+ if(!isset($settings["SMTPUsername"]))
+ $settings["SMTPUsername"] = $this->settings[$mailModeString]["SMTPUsername"];
+ if(!isset($settings["SMTPPassword"]))
+ $settings["SMTPPassword"] = $this->settings[$mailModeString]["SMTPPassword"];
+
+ // Pri google smtp je username vedno email
+ if($mailModeString == 'google')
+ $settings['SMTPUsername'] = $settings['SMTPFrom'];
+
+
+ // Nastavimo mail server
+ $this->phpMailerClass->Host = $settings["SMTPHost"];
+
+ // Nastavimo SMTP port
+ $this->phpMailerClass->Port = $settings["SMTPPort"];
+
+ // Nastavimo ssl / tls
+ $this->phpMailerClass->SMTPSecure = $settings['SMTPSecure'];
+
+ // Nastavimo ce se uporablja SMTP avtentikacijo
+ if($settings["SMTPAuth"] == 1)
+ $this->phpMailerClass->SMTPAuth = true;
+
+ // Nastavimo username za SMTP avtentikacijo
+ $this->phpMailerClass->Username = $settings["SMTPUsername"];
+
+ // Nastavimo password za SMTP avtentikacijo
+ $this->phpMailerClass->Password = $settings["SMTPPassword"];
+
+
+ // Posebej vklopimo, ker drugace sisplet smtp ne deluje!
+ if($this->phpMailerClass->Host == 'mail.sisplet.org'){
+ $this->phpMailerClass->SMTPOptions = array(
+ 'ssl' => array(
+ 'verify_peer' => false
+ )
+ );
+ }
+
+
+ // Kdo posilja
+ if(isset($settings["SMTPFromNice"]) && $settings["SMTPFromNice"] != "") {
+ $this->phpMailerClass->SetFrom($settings["SMTPFrom"], $settings["SMTPFromNice"]);
+ }
+ else{
+ $this->phpMailerClass->SetFrom($settings["SMTPFrom"]);
+ }
+
+ // Reply-to naslov
+ $this->phpMailerClass->AddReplyTo($settings["SMTPReplyTo"]);
+
+ // Subject
+ $this->phpMailerClass->Subject = $email_subject;
+
+ // Vsebina maila
+ $this->prepareEmailDesign($email_msg);
+
+
+ // Loop cez prejemnike in posiljanje
+ if (!empty($this->recipients)){
+
+ // Loop cez vse prejemnike
+ foreach ($this->recipients AS $recipient){
+ $this->phpMailerClass->AddAddress($recipient);
+ }
+
+ // Posljemo mail
+ $success = $this->phpMailerClass->send();
+
+
+ // Logiramo posiljanje
+ $SL = new SurveyLog();
+
+ // Napaka
+ if (!$success) {
+
+ if((int)$this->ank_id > 0)
+ $SL->addMessage(SurveyLog::MAILER, "NAPAKA pri pošiljanju pošiljanje testnega emaila na naslov ".implode(",", $this->recipients)."! ".$this->phpMailerClass->ErrorInfo);
+
+ //if($this->phpMailerDebug > 0)
+ echo "<br />Mailer Error: " . $this->phpMailerClass->ErrorInfo.'<br /><br />';
+ }
+ // Uspesno posiljanje
+ else {
+
+ $SL->addMessage(SurveyLog::MAILER, "USPEŠNO pošiljanje testnega emaila na naslov ".implode(",", $this->recipients));
+
+ if($this->phpMailerDebug > 0)
+ echo "Message sent!<br /><br />";
+ }
+
+ $SL->write();
+
+
+ return $success;
+ }
+ }
+
+ // Pripravimo design emaila
+ private function prepareEmailDesign($content, $heading='', $image='', $button=''){
+ global $lang, $app_settings, $site_domain;
+
+ // V nekaterih primerih ne designeramo maila
+ if(!in_array($this->type, array('account', 'payments')) || !in_array($site_domain, array('localhost', 'www.1ka.si', 'test.1ka.si', 'test2.1ka.si'))){
+ $this->phpMailerClass->msgHTML($content);
+ return;
+ }
+
+ // Najprej pocistimo signature
+ $signature = Common::getEmailSignature();
+ $content = str_replace($signature, "", $content);
+
+ // Logo
+ $logo_src = ($lang['id'] == '1') ? 'https://www.1ka.si/public/img/logo/1ka_slo.png' : 'https://www.1ka.si/public/img/logo/1ka_eng.png';
+
+ // Naslov
+ //$heading = 'Naslovček';
+ $heading_html = ($heading != '') ? '<tr><td style="color: #153643; font-family: Montserrat,sans-serif;"><h1 style="font-size: 24px; margin: 0;">'.$heading.'</h1></td></tr>' : '';
+
+ // Vsebina
+ $text = $content;
+ $text_html = ($text != '') ? '<tr><td style="color: #153643; font-family: Montserrat,sans-serif; font-size: 16px; line-height: 24px; padding: 20px 0 30px 0;"><p style="margin: 0;">'.$text.'</p></td></tr>' : '';
+
+ // Slika
+ //$image = '<img src="https://www.go-tel.si/upload/relevantna-slika.png" style="display: block;" />';
+ $image_html = ($image != '') ? '<tr><td align="center"><img src="'.$image.'" style="display: block;" /></td></tr>' : '';
+
+ // Gumb
+ //$button = array('url'=>'https://1ka.si', 'text'=>'Gumbek');
+ $button_html = ($button != '') ? '<tr><td align="center"><a href="'.$button['url'].'" style="text-decoration:none"><p style="font-family: Montserrat,sans-serif; font-size: 18px; padding: 20px 0 20px 0;text-align:center;background-color:#1e88e5;color:white;">'.$button['text'].'</p></a></td></tr>' : '';
+
+
+ $designed_content = '
+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+ <html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB">
+
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <title>1ka sporočilo</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
+
+ <style type="text/css">
+ a[x-apple-data-detectors] {color: inherit !important;}
+
+ a{
+ color:#1e88e5;
+ text-decoration:none;
+ transition:0.2s;
+ }
+ a:hover{
+ color: #4ca0ea;
+ }
+
+ @media only screen and (max-width: 600px){
+ table.white_holder{
+ border-collapse:collapse;
+ width:100%;
+ }
+ .content img{
+ width:100%;
+ }
+ }
+ </style>
+ </head>
+
+ <body style="margin: 0; padding: 0;">
+ <table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color:#1e88e5;" bgcolor="#1e88e5"><tr><td>
+ <table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
+ <tr>
+ <td style="padding: 30px 15px 30px 15px;">
+ <table align="center" border="0" cellpadding="0" cellspacing="0" width="570" class="white_holder">
+ <tr>
+ <td align="center" bgcolor="white" style="padding: 30px 0 30px 0;">
+ <img src="'.$logo_src.'" alt="header" width="100" style="display: block;" />
+ </td>
+ </tr>
+ <tr>
+ <td bgcolor="#ffffff" style="padding: 20px 30px 40px 30px;">
+ <table border="0" cellpadding="0" cellspacing="0" width="100%" class="content">
+
+ <!-- NASLOV -->
+ '.$heading_html.'
+
+ <!-- SLIKA -->
+ '.$image_html.'
+
+ <!-- VSEBINA -->
+ '.$text_html.'
+
+ <!-- GUMB -->
+ '.$button_html.'
+
+ <!-- PODPIS -->
+ <tr>
+ <td style="color: #153643; font-family: Montserrat,sans-serif; font-size: 16px; line-height: 24px; padding: 20px 0 0 0;">
+ <p style="margin: 0;">'.$lang['srv_1ka_mail_signature_bye'].'</p>
+ </td>
+ </tr>
+
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td bgcolor="#f7f7f7" style="padding: 30px 30px;color:#ababab;">
+ <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">
+ <tr>
+ <td style="color: #828282; font-family: Montserrat,sans-serif; font-size: 13px; line-height: 24px;">
+ <p style="margin: 0 0 25px 0;">'.$lang['email_template_footer'].'</p>
+ </td>
+ </tr>
+ <tr>
+ <td align="center">
+ <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;">
+ <tr>
+ <td style="width:40px;" width="40">
+ <a href="https://www.facebook.com/1KAenklikanketa/" target="_blank">
+ <img src="https://www.1ka.si/public/img/social/fb_blue.png" alt="Facebook" height="35" style="display: block;" border="0" />
+ </a>
+ </td>
+ <td style="background-color:#f7f7f7;width:20px;" width="20">&nbsp;</td>
+ <td style="width:40px;" width="40">
+ <a href="https://www.youtube.com/channel/UCWhsQe9qIjGpbD0-TCdPg7Q" target="_blank">
+ <img src="https://www.1ka.si/public/img/social/yt.png" alt="Youtube" height="35" style="display: block;" border="0" />
+ </a>
+ </td>
+ <td style="background-color:#f7f7f7;width:20px;" width="20" >&nbsp;</td>
+ <td style="width:40px;" width="40">
+ <a href="https://twitter.com/enklikanketa" target="_blank">
+ <img src="https://www.1ka.si/public/img/social/twitter_blue.png" alt="Twitter" height="35" style="display: block;" border="0" />
+ </a>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table> <!-- &reg; 1KA -->
+ <p style="color: #efefef; font-family: Montserrat,sans-serif; font-size: 12px; line-height: 24px; padding: 5px 0 30px 0;text-align:center">
+ '.$lang['email_template_footer2_recipient'].' <a href="mailto:'.$this->recipients[0].'" style="color: #efefef;">'.$this->recipients[0].'</a>.
+ <br>
+ '.$lang['email_template_footer2_unsubscribe'].'
+ </p>
+ </td>
+ </tr>
+ </table>
+ </td></tr></table>
+ </body>
+
+ </html>
+ ';
+
+
+ /*echo $designed_content;
+ die();*/
+
+ $this->phpMailerClass->msgHTML($designed_content);
+ }
+
+
+
+ // Preveri ce je mail veljaven
+ private function validEmail($email = null){
+ return Common::getInstance()->validEmail($email);
+ }
+
+ // Enkripcija gesla za mail streznik
+ private function encryptPassword($password){
+
+ // Kateri php modul uporabljamo (mcrypt ali openssl) - kasneje se bo vse preneslo na openssl
+ $php_encrypt_module = 'openssl';
+
+ // Star modul mcrypt, ki ni vec kompatibilen s php7.3
+ if($php_encrypt_module == 'mcrypt'){
+
+ $iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_ECB);
+ $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
+ $encryptedPassword = mcrypt_encrypt(MCRYPT_CAST_256, $this->password_hash_key , $password, MCRYPT_MODE_ECB, $iv);
+
+ return $encryptedPassword;
+ }
+ // Prehod iz mcrypt na openssl - NI KOMPATIBILNO ZA NAZAJ! - DODATNO SE BASE_ENCODE
+ else{
+
+
+ $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
+ $encryptedPassword = openssl_encrypt($password, 'AES-256-CBC', $this->password_hash_key, 0, $iv);
+
+ return base64_encode($encryptedPassword . '::' . $iv);
+
+ // Prehod iz mcrypt na openssl - NI KOMPATIBILNO ZA NAZAJ! - star openssl za gorenje
+ /*$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
+ $encryptedPassword = openssl_encrypt($password, 'AES-256-CBC', $this->password_hash_key, 0, $iv);
+
+ return $encryptedPassword . '::' . $iv;*/
+ }
+ }
+
+ // Dekripcija gesla za mail streznik
+ private function decryptPassword($encryptedPassword){
+
+ // Kateri php modul uporabljamo (mcrypt ali openssl) - kasneje se bo vse preneslo na openssl
+ $php_encrypt_module = 'openssl';
+
+ // Star modul mcrypt, ki ni vec kompatibilen s php7.3
+ if($php_encrypt_module == 'mcrypt'){
+
+ $iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_ECB);
+ $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
+ $decryptedPassword = mcrypt_decrypt(MCRYPT_CAST_256, $this->password_hash_key , $encryptedPassword, MCRYPT_MODE_ECB, $iv);
+
+ return $decryptedPassword;
+ }
+ // Prehod iz mcrypt na openssl - NI KOMPATIBILNO ZA NAZAJ! - DODATNO SE BASE_ENCODE
+ else{
+
+ // Prehod iz mcrypt na openssl - NI KOMPATIBILNO ZA NAZAJ! - DODATNO SE BASE_DECODE
+ $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
+ list($encrypted_data, $iv) = explode('::', base64_decode($encryptedPassword), 2);
+ $decryptedPassword = openssl_decrypt($encrypted_data, 'AES-256-CBC', $this->password_hash_key, 0, $iv);
+
+ return $decryptedPassword;
+
+ // Prehod iz mcrypt na openssl - NI KOMPATIBILNO ZA NAZAJ! - star openssl za gorenje
+ /*$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
+ list($encrypted_data, $iv) = explode('::', $encryptedPassword, 2);
+ $decryptedPassword = openssl_decrypt($encrypted_data, 'AES-256-CBC', $this->password_hash_key, 0, $iv);
+
+ return $decryptedPassword;*/
+ }
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/objects/obj.PopUp.php b/admin/survey/classes/objects/obj.PopUp.php
new file mode 100644
index 0000000..836cc8e
--- /dev/null
+++ b/admin/survey/classes/objects/obj.PopUp.php
@@ -0,0 +1,150 @@
+<?php
+/**
+ *
+ * @author veselicg
+ *
+ * Večina funkcij vrača sam klass da omogočamo chaining
+ *
+ * Primer uporabe:
+ *
+ * $popUp = new PopUp();
+ *
+ * # določimo naslovno vrstico popupa. če ni podano je ne prikazuje
+ * $popUp -> setHeaderText('Moj PopUp:')
+ *
+ * # določimo id diva (..<div id="nek_id_diva"...)
+ * -> setId('nek_id_diva')
+ *
+ * # po potrebi dodamo css je (..<div class="css1 css2"...)
+ * -> addCss('css1')
+ * -> addCss('css2')
+ *
+ * #dodamo vsebino (osrednji del) popupa
+ * -> setContent($content);
+ *
+ * # dodamo gumb Prekliči - je standarden gumb
+ * $popUp->addButton(new PopUpCancelButton());
+ *
+ *
+ * #dodamo gumb izberi profil
+ * $button = new PopUpButton($lang['srv_save_profile']);
+ * $button -> setFloat('right')
+ * -> setButtonColor('orange')
+ * -> addAction('onClick','changeColectDataStatus(); return false;');
+ * $popUp->addButton($button);
+ *
+ * # izrišemo div
+ * echo $popUp; # lahko tudi $popUp->display();
+ *
+ */
+class PopUp
+{
+ private $_id = null;
+ private $_css = array('divPopUp');
+
+ private $_headerText = null;
+ private $_content = null;
+ private $_buttons = array();
+
+ protected $_displayed = false;
+
+ public function setId($id)
+ {
+ $this->_id = $id;
+ return $this;
+ }
+
+ public function addCss($css)
+ {
+ $this->_css[] = $css;
+ return $this;
+ }
+
+ public function setHeaderText($headerText)
+ {
+ $this->_headerText = $headerText;
+ return $this;
+ }
+
+ public function setContent($content)
+ {
+ $this->_content = $content;
+ return $this;
+ }
+
+ public function addContent($content)
+ {
+ $this->_content .= $content;
+ return $this;
+ }
+
+
+ public function addButton(PopUpButton $button)
+ {
+ $this->_buttons[] = $button;
+ return $this;
+ }
+
+ public function display()
+ {
+ $this->_displayed = true;
+
+ #začnemo osnovni div
+ echo '<div';
+ if ($this->_id != null)
+ {
+ echo ' id="'.$this->_id.'"';
+ }
+ if (count($this->_css) > 0)
+ {
+ echo ' class="'. implode(' ',$this->_css).'"';
+ }
+ echo '>';
+
+ #dodamo header
+ if ($this->_headerText != null)
+ {
+ echo '<div class="divPopUp_top">';
+ echo $this->_headerText;
+ echo '</div>'; #PM_top
+ }
+
+ #dodamo vsebino - content
+ echo '<div class="divPopUp_content">';
+ echo $this->_content;
+ echo '</div>'; # class="divPopUp_content"
+
+ # začnemo div z gumbi
+ echo '<div class="divPopUp_btm">';
+
+ # izrišemo gumbe
+ if (count($this->_buttons) > 0) {
+ foreach ($this->_buttons AS $button)
+ {
+ echo $button;
+ }
+ }
+
+ #zaključimo div z gumbi
+ echo '</div>'; #class="inv_FS_btm clr"
+
+ #zaključimo div z gumbi
+ echo '</div>';
+ return $this;
+ }
+
+ public function __toString() {
+ ob_start();
+ $this->display();
+ $content = ob_get_clean();
+ return $content;
+ }
+
+ public function __destruct() {
+ if ($this->_displayed == false)
+ {
+ $this->display();
+ }
+ return $this;
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/objects/obj.PopUpButton.php b/admin/survey/classes/objects/obj.PopUpButton.php
new file mode 100644
index 0000000..5131c17
--- /dev/null
+++ b/admin/survey/classes/objects/obj.PopUpButton.php
@@ -0,0 +1,133 @@
+<?php
+/**
+ *
+ * @author veselicg
+ *
+ * Večina funkcij vrača sam klass da omogočamo chaining
+ *
+ * Primer uporabe:
+ *
+ * $popUp = new PopUp();
+ *
+ * # določimo naslovno vrstico popupa. če ni podano je ne prikazuje
+ * $popUp -> setHeaderText('Moj PopUp:')
+ *
+ * # določimo id diva (..<div id="nek_id_diva"...)
+ * -> setId('nek_id_diva')
+ *
+ * # po potrebi dodamo css je (..<div class="css1 css2"...)
+ * -> addCss('css1')
+ * -> addCss('css2')
+ *
+ * #dodamo vsebino (osrednji del) popupa
+ * -> setContent($content);
+ *
+ * # dodamo gumb Prekliči - je standarden gumb
+ * $popUp->addButton(new PopUpCancelButton());
+ *
+ *
+ * #dodamo gumb izberi profil
+ * $button = new PopUpButton($lang['srv_save_profile']);
+ * $button -> setFloat('right')
+ * -> setButtonColor('orange')
+ * -> addAction('onClick','changeColectDataStatus(); return false;');
+ * $popUp->addButton($button);
+ *
+ * # izrišemo div
+ * echo $popUp; # lahko tudi $popUp->display();
+ *
+ */
+
+/** Gumbi
+ *
+ *
+ */
+class PopUpButton
+{
+ # tekst gumba
+ private $_caption = null;
+ #mouse over title gumba, privzeto je enak caption
+ private $_title = null;
+ private $_float = 'floatLeft';
+ private $_space = 'spaceLeft';
+
+ private $_buttonColor = 'gray';
+ private $_actions = array();
+
+ public function __construct($caption = null)
+ {
+ $this->setCaption($caption);
+
+ # for chaining
+ return $this;
+ }
+
+ public function setCaption($caption)
+ {
+ $this->_caption = $caption;
+ # če title ni nastavljen ga nastavimo enako kot caption
+ if ($this->_title === null)
+ {
+ $this->setTitle($caption);
+ }
+
+ # for chaining
+ return $this;
+
+ }
+
+ public function setTitle($title)
+ {
+ $this->_title = $title;
+
+ # for chaining
+ return $this;
+
+ }
+
+ public function setFloat($float = 'Left')
+ {
+ $this->_float = 'float'.ucfirst($float);
+ $this->_space = 'space'.ucfirst($float);
+
+ # for chaining
+ return $this;
+
+ }
+
+ public function setButtonColor($buttonColor)
+ {
+ switch ($buttonColor) {
+ case 'orange':
+ $this->_buttonColor = 'orange';
+ break;
+
+ default:
+ $this->_buttonColor = 'gray';
+ break;
+ }
+
+
+ # for chaining
+ return $this;
+ }
+
+ public function addAction($actionTriger, $action)
+ {
+ $this->_actions[] = $actionTriger.'="'.$action.'"';
+
+ # for chaining
+ return $this;
+ }
+
+ public function __toString() {
+ $str = '<div class="'.$this->_float.' '.$this->_space.'">';
+ $str .= '<div class="buttonwrapper" title="'.$this->_title.'">';
+ $str .= '<a class="ovalbutton ovalbutton_'.$this->_buttonColor.'" href="#" '.implode(' ', $this->_actions).'>';
+ $str .= '<span>'.$this->_caption.'</span>';
+ $str .= '</a>';
+ $str .= '</div>';
+ $str .= '</div>';
+ return $str;
+ }
+}
diff --git a/admin/survey/classes/objects/obj.PopUpCancelButton.php b/admin/survey/classes/objects/obj.PopUpCancelButton.php
new file mode 100644
index 0000000..6a0a27e
--- /dev/null
+++ b/admin/survey/classes/objects/obj.PopUpCancelButton.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ *
+ * @author veselicg
+ *
+ * Večina funkcij vrača sam klass da omogočamo chaining
+ *
+ * Primer uporabe:
+ *
+ * $popUp = new PopUp();
+ *
+ * # določimo naslovno vrstico popupa. če ni podano je ne prikazuje
+ * $popUp -> setHeaderText('Moj PopUp:')
+ *
+ * # določimo id diva (..<div id="nek_id_diva"...)
+ * -> setId('nek_id_diva')
+ *
+ * # po potrebi dodamo css je (..<div class="css1 css2"...)
+ * -> addCss('css1')
+ * -> addCss('css2')
+ *
+ * #dodamo vsebino (osrednji del) popupa
+ * -> setContent($content);
+ *
+ * # dodamo gumb Prekliči - je standarden gumb
+ * $popUp->addButton(new PopUpCancelButton());
+ *
+ *
+ * #dodamo gumb izberi profil
+ * $button = new PopUpButton($lang['srv_save_profile']);
+ * $button -> setFloat('right')
+ * -> setButtonColor('orange')
+ * -> addAction('onClick','changeColectDataStatus(); return false;');
+ * $popUp->addButton($button);
+ *
+ * # izrišemo div
+ * echo $popUp; # lahko tudi $popUp->display();
+ *
+ */
+
+/** Gumbi
+ *
+ *
+ */
+
+/** Sistemski gumb za skritje popupa
+ */
+class PopUpCancelButton extends PopUpButton
+{
+ public function __construct()
+ {
+ // call Parent's (PopUpButton) constructor
+ global $lang;
+ parent::__construct($lang['srv_cancel']);
+ $this -> addAction('onClick',"$('#fade').fadeOut('slow');$('#fullscreen').fadeOut('slow').html(''); return false;");
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/objects/obj.SpremenljivkaSkala.php b/admin/survey/classes/objects/obj.SpremenljivkaSkala.php
new file mode 100644
index 0000000..da020ad
--- /dev/null
+++ b/admin/survey/classes/objects/obj.SpremenljivkaSkala.php
@@ -0,0 +1,195 @@
+<?php
+/*
+ *
+ * skala - 0 Ordinalna
+ * skala - 1 Nominalna
+ * skala - 2 Razmernostna
+ *
+ * Radio grupe so privzeto ordinalne, vendar jih v primeru kadar imamo samo dve kategoriji
+ * in ni drugače uporabniško določeno označimo kot nominalne
+ *
+ *
+ * Spremenljivka je nominalna: Kategorij odgovorov ni mogoče primerjati niti ni mogoče računati povprečij. Npr. spol, barva, regija, država.
+ * Spremenlijvka je ordinialna: Kategorije odgovorov je mogoče primerjati; računamo lahko tudi povprečje. Npr. lestvice na skalah (strinjanje, zadovoljstvo,…)
+ *
+ */
+class SpremenljivkaSkala {
+
+ // set a constant
+ const ORD = 0;
+ const NOM = 1;
+ const RAZ = 2;
+
+ private $spr_id; #id spremenljivke
+ private $spr_data; #podatkispremenljivke (cache)
+ private $skala = -1; #skala spremenljivke
+
+ /** SpremenljivkaSkala
+ *
+ * @param Intiger $spr_id
+ */
+ function __construct($spr_id) {
+ $this->spr_id = (int)$spr_id;
+ $this->spr_data = Cache::srv_spremenljivka($this->spr_id);
+
+ #polovimo nastavitev iz baze
+ $tmpSkala = (int)$this->spr_data['skala'];
+ $this->skala = $this->getSpremenljivkaRealSkala($tmpSkala);
+ }
+
+
+ /** Vrene pravo skalo spremenljivke, glede na št. kategorij, ipd..., če ni uporabniško določena
+ * Lahko vrne tudi NULL za nagovor ali za tipe nove tipe kateri niso dodani
+ *
+ * @param (int) $skala
+ *
+ * @return SpremenljivkaSkala::ORD = 0
+ * @return SpremenljivkaSkala::NOM = 1
+ * @return SpremenljivkaSkala::RAZ = 2
+ * @return NULL
+ */
+ function getSpremenljivkaRealSkala($skala) {
+ # če je skala večja ali enaka 0 je uporabniško določena
+ if ((int)$skala >= 0) {
+ return $skala;
+ } else {
+ # če ne pa je vse odvisno od vrste spremenljivke in drugih zadev (in od vasjinega razpoloženja)
+ switch ((int)$this->spr_data['tip']) {
+ #radio
+ case 1:
+ #dropdown
+ case 3:
+ $sql = sisplet_query("SELECT count(*) FROM srv_vrednost WHERE spr_id = '$this->spr_id'");
+ list($cnt) = mysqli_fetch_row($sql);
+ # če imamo samo dve kategoriji jo razglasimo za nominalno
+ if ((int)$cnt == 2) {
+ return SpremenljivkaSkala::NOM;
+ } else {
+ return SpremenljivkaSkala::ORD;
+ }
+ break;
+ #checkbox
+ case 2:
+ return SpremenljivkaSkala::NOM;
+ break;
+ #tekst old
+ case 4:
+ return SpremenljivkaSkala::NOM;
+ break;
+ #6 multigrid
+ case 6:
+ $sql = sisplet_query("SELECT count(*) FROM srv_grid WHERE spr_id = '$this->spr_id'");
+ list($cnt) = mysqli_fetch_row($sql);
+ # če imamo samo dve kategoriji jo razglasimo za nominalno
+ if ((int)$cnt == 2) {
+ return SpremenljivkaSkala::NOM;
+ } else {
+ return SpremenljivkaSkala::ORD;
+ }
+ break;
+ #number
+ case 7:
+ return SpremenljivkaSkala::RAZ;
+ break;
+ #datum
+ case 8:
+ return SpremenljivkaSkala::ORD;
+ break;
+ #multi checkbox
+ case 16 : // mcheckbox
+ return SpremenljivkaSkala::NOM;
+ break;
+ #razvrščanje
+ case 17:
+ return SpremenljivkaSkala::ORD;
+ break;
+ #vsota
+ case 18:
+ return SpremenljivkaSkala::RAZ;
+ break;
+ #multi tekst
+ case 19:
+ return SpremenljivkaSkala::NOM;
+ break;
+ #multi num
+ case 20:
+ return SpremenljivkaSkala::RAZ;
+ break;
+ #tekst *
+ case 21:
+ return SpremenljivkaSkala::NOM;
+ break;
+ #kalkulacija
+ case 22:
+ return SpremenljivkaSkala::NOM;
+ break;
+ }
+ }
+ return NULL;
+ }
+
+ /** vrne skalo spremenljivke kot numerično vrednost
+ *
+ * @return (Intiger) $this->skala
+ */
+ function getSkala() {
+ if ((int)$skala >= 0) {
+ return $this->skala;
+ }
+ return NULL;
+ }
+
+ /** vrne skalo spremenljivke kot tekstovno vrednost
+ *
+ * @return (text) $this->skala
+ */
+ function getSkalaAsText() {
+ global $lang;
+ switch ($this->skala) {
+ case SpremenljivkaSkala::ORD:
+ return $lang['srv_analiza_oblika_ordi'];
+ break;
+ case SpremenljivkaSkala::NOM:
+ return $lang['srv_analiza_oblika_nomi'];
+ break;
+ case SpremenljivkaSkala::RAZ:
+ return $lang['srv_analiza_oblika_razm'];
+ break;
+ }
+ return NULL;
+ }
+
+ /** Ali lahko za tip spremenljivke spremenimo skalo
+ *
+ * skalo lahko spremninjamo pri
+ * -radio
+ * -dropdown
+ * -multi radio
+ *
+ * @return boolean
+ */
+ function canChangeSkala() {
+ switch ((int)$this->spr_data['tip']) {
+ case 1:
+ case 3:
+ case 6:
+ return true;
+ break;
+ }
+ return false;
+ }
+
+ /** Ali je trenutna skala enaka pogoju
+ *
+ * @param const(ORD|NOM|RAZ) $what
+ * @return boolean
+ */
+ function is($what) {
+ return ($this->getSkala() == $what) ? TRUE : FALSE;
+ }
+
+ function __toString() {
+ return (String)$this->getSkala();
+ }
+}
+
diff --git a/admin/survey/classes/phpqrcode/CHANGELOG b/admin/survey/classes/phpqrcode/CHANGELOG
new file mode 100644
index 0000000..1088530
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/CHANGELOG
@@ -0,0 +1,38 @@
+* 1.0.0 build 2010031920
+
+ - first public release
+ - help in readme, install
+ - cleanup ans separation of QRtools and QRspec
+ - now TCPDF binding requires minimal changes in TCPDF, having most of job
+ done in QRtools tcpdfBarcodeArray
+ - nicer QRtools::timeBenchmark output
+ - license and copyright notices in files
+ - indent cleanup - from tab to 4spc, keep it that way please :)
+ - sf project, repository, wiki
+ - simple code generator in index.php
+
+* 1.1.0 build 2010032113
+
+ - added merge tool wich generate merged version of code
+ located in phpqrcode.php
+ - splited qrconst.php from qrlib.php
+
+* 1.1.1 build 2010032405
+
+ - patch by Rick Seymour allowing saving PNG and displaying it at the same time
+ - added version info in VERSION file
+ - modified merge tool to include version info into generated file
+ - fixed e-mail in almost all head comments
+
+* 1.1.2 build 2010032722
+
+ - full integration with TCPDF thanks to Nicola Asuni, it's author
+ - fixed bug with alphanumeric encoding detection
+
+* 1.1.3 build 2010081807
+
+ - short opening tags replaced with standard ones
+
+* 1.1.4 build 2010100721
+
+ - added missing static keyword QRinput::check (found by Luke Brookhart, Onjax LLC)
diff --git a/admin/survey/classes/phpqrcode/INSTALL b/admin/survey/classes/phpqrcode/INSTALL
new file mode 100644
index 0000000..eac6b07
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/INSTALL
@@ -0,0 +1,67 @@
+== REQUIREMENTS ==
+
+ * PHP5
+ * PHP GD2 extension with JPEG and PNG support
+
+== INSTALLATION ==
+
+If you want to recreate cache by yourself make sure cache directory is
+writable and you have permisions to write into it. Also make sure you are
+able to read files in it if you have cache option enabled
+
+== CONFIGURATION ==
+
+Feel free to modify config constants in qrconfig.php file. Read about it in
+provided comments and project wiki page (links in README file)
+
+== QUICK START ==
+
+Notice: probably you should'nt use all of this in same script :)
+
+<?phpb
+
+//include only that one, rest required files will be included from it
+include "qrlib.php"
+
+//write code into file, Error corection lecer is lowest, L (one form: L,M,Q,H)
+//each code square will be 4x4 pixels (4x zoom)
+//code will have 2 code squares white boundary around
+
+QRcode::png('PHP QR Code :)', 'test.png', 'L', 4, 2);
+
+//same as above but outputs file directly into browser (with appr. header etc.)
+//all other settings are default
+//WARNING! it should be FIRST and ONLY output generated by script, otherwise
+//rest of output will land inside PNG binary, breaking it for sure
+QRcode::png('PHP QR Code :)');
+
+//show benchmark
+QRtools::timeBenchmark();
+
+//rebuild cache
+QRtools::buildCache();
+
+//code generated in text mode - as a binary table
+//then displayed out as HTML using Unicode block building chars :)
+$tab = $qr->encode('PHP QR Code :)');
+QRspec::debug($tab, true);
+
+== TCPDF INTEGRATION ==
+
+Inside bindings/tcpdf you will find slightly modified 2dbarcodes.php.
+Instal phpqrcode liblaty inside tcpdf folder, then overwrite (or merge)
+2dbarcodes.php
+
+Then use similar as example #50 from TCPDF examples:
+
+<?php
+
+$style = array(
+ 'border' => true,
+ 'padding' => 4,
+ 'fgcolor' => array(0,0,0),
+ 'bgcolor' => false, //array(255,255,255)
+);
+
+//code name: QR, specify error correction level after semicolon (L,M,Q,H)
+$pdf->write2DBarcode('PHP QR Code :)', 'QR,L', '', '', 30, 30, $style, 'N');
diff --git a/admin/survey/classes/phpqrcode/LICENSE b/admin/survey/classes/phpqrcode/LICENSE
new file mode 100644
index 0000000..1883303
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/admin/survey/classes/phpqrcode/README b/admin/survey/classes/phpqrcode/README
new file mode 100644
index 0000000..a022fb5
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/README
@@ -0,0 +1,45 @@
+This is PHP implementation of QR Code 2-D barcode generator. It is pure-php
+LGPL-licensed implementation based on C libqrencode by Kentaro Fukuchi.
+
+== LICENSING ==
+
+Copyright (C) 2010 by Dominik Dzienia
+
+This library is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free
+Software Foundation; either version 3 of the License, or any later version.
+
+This library is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+PARTICULAR PURPOSE. See the GNU Lesser General Public License (LICENSE file)
+for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this library; if not, write to the Free Software Foundation, Inc., 51
+Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+== INSTALATION AND USAGE ==
+
+ * INSTALL file
+ * http://sourceforge.net/apps/mediawiki/phpqrcode/index.php?title=Main_Page
+
+== CONTACT ==
+
+Fell free to contact me via e-mail (deltalab at poczta dot fm) or using
+folowing project pages:
+
+ * http://sourceforge.net/projects/phpqrcode/
+ * http://phpqrcode.sourceforge.net/
+
+== ACKNOWLEDGMENTS ==
+
+Based on C libqrencode library (ver. 3.1.1)
+Copyright (C) 2006-2010 by Kentaro Fukuchi
+http://megaui.net/fukuchi/works/qrencode/index.en.html
+
+QR Code is registered trademarks of DENSO WAVE INCORPORATED in JAPAN and other
+countries.
+
+Reed-Solomon code encoder is written by Phil Karn, KA9Q.
+Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/VERSION b/admin/survey/classes/phpqrcode/VERSION
new file mode 100644
index 0000000..9f99279
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/VERSION
@@ -0,0 +1,2 @@
+1.1.4
+2010100721 \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/bindings/tcpdf/qrcode.php b/admin/survey/classes/phpqrcode/bindings/tcpdf/qrcode.php
new file mode 100644
index 0000000..4cb1389
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/bindings/tcpdf/qrcode.php
@@ -0,0 +1,2875 @@
+<?php
+//============================================================+
+// File name : qrcode.php
+// Begin : 2010-03-22
+// Last Update : 2010-03-29
+// Version : 1.0.002
+// License : GNU LGPL v.3 (http://www.gnu.org/copyleft/lesser.html)
+// ----------------------------------------------------------------------------
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 3 of the License, or any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+// or browse http://www.gnu.org/copyleft/lesser.html
+//
+// ----------------------------------------------------------------------------
+//
+// DESCRIPTION :
+//
+// Class to create QR-code arrays for TCPDF class.
+// QR Code symbol is a 2D barcode that can be scanned by
+// handy terminals such as a mobile phone with CCD.
+// The capacity of QR Code is up to 7000 digits or 4000
+// characters, and has high robustness.
+// This class supports QR Code model 2, described in
+// JIS (Japanese Industrial Standards) X0510:2004
+// or ISO/IEC 18004.
+// Currently the following features are not supported:
+// ECI and FNC1 mode, Micro QR Code, QR Code model 1,
+// Structured mode.
+//
+// This class is derived from the following projects:
+// ---------------------------------------------------------
+// "PHP QR Code encoder"
+// License: GNU-LGPLv3
+// Copyright (C) 2010 by Dominik Dzienia <deltalab at poczta dot fm>
+// http://phpqrcode.sourceforge.net/
+// https://sourceforge.net/projects/phpqrcode/
+//
+// The "PHP QR Code encoder" is based on
+// "C libqrencode library" (ver. 3.1.1)
+// License: GNU-LGPL 2.1
+// Copyright (C) 2006-2010 by Kentaro Fukuchi
+// http://megaui.net/fukuchi/works/qrencode/index.en.html
+//
+// Reed-Solomon code encoder is written by Phil Karn, KA9Q.
+// Copyright (C) 2002-2006 Phil Karn, KA9Q
+//
+// QR Code is registered trademark of DENSO WAVE INCORPORATED
+// http://www.denso-wave.com/qrcode/index-e.html
+// ---------------------------------------------------------
+//
+// Author: Nicola Asuni
+//
+// (c) Copyright 2010:
+// Nicola Asuni
+// Tecnick.com S.r.l.
+// Via della Pace, 11
+// 09044 Quartucciu (CA)
+// ITALY
+// www.tecnick.com
+// info@tecnick.com
+//============================================================+
+
+/**
+ * Class to create QR-code arrays for TCPDF class.
+ * QR Code symbol is a 2D barcode that can be scanned by handy terminals such as a mobile phone with CCD.
+ * The capacity of QR Code is up to 7000 digits or 4000 characters, and has high robustness.
+ * This class supports QR Code model 2, described in JIS (Japanese Industrial Standards) X0510:2004 or ISO/IEC 18004.
+ * Currently the following features are not supported: ECI and FNC1 mode, Micro QR Code, QR Code model 1, Structured mode.
+ *
+ * This class is derived from "PHP QR Code encoder" by Dominik Dzienia (http://phpqrcode.sourceforge.net/) based on "libqrencode C library 3.1.1." by Kentaro Fukuchi (http://megaui.net/fukuchi/works/qrencode/index.en.html), contains Reed-Solomon code written by Phil Karn, KA9Q. QR Code is registered trademark of DENSO WAVE INCORPORATED (http://www.denso-wave.com/qrcode/index-e.html).
+ * Please read comments on this class source file for full copyright and license information.
+ *
+ * @package com.tecnick.tcpdf
+ * @abstract Class for generating QR-code array for TCPDF.
+ * @author Nicola Asuni
+ * @copyright 2010 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
+ * @link http://www.tcpdf.org
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL
+ * @version 1.0.002
+ */
+
+// definitions
+if (!defined('QRCODEDEFS')) {
+
+ /**
+ * Indicate that definitions for this class are set
+ */
+ define('QRCODEDEFS', true);
+
+ // -----------------------------------------------------
+
+ // Encoding modes (characters which can be encoded in QRcode)
+
+ /**
+ * Encoding mode
+ */
+ define('QR_MODE_NL', -1);
+
+ /**
+ * Encoding mode numeric (0-9). 3 characters are encoded to 10bit length. In theory, 7089 characters or less can be stored in a QRcode.
+ */
+ define('QR_MODE_NM', 0);
+
+ /**
+ * Encoding mode alphanumeric (0-9A-Z $%*+-./:) 45characters. 2 characters are encoded to 11bit length. In theory, 4296 characters or less can be stored in a QRcode.
+ */
+ define('QR_MODE_AN', 1);
+
+ /**
+ * Encoding mode 8bit byte data. In theory, 2953 characters or less can be stored in a QRcode.
+ */
+ define('QR_MODE_8B', 2);
+
+ /**
+ * Encoding mode KANJI. A KANJI character (multibyte character) is encoded to 13bit length. In theory, 1817 characters or less can be stored in a QRcode.
+ */
+ define('QR_MODE_KJ', 3);
+
+ /**
+ * Encoding mode STRUCTURED (currently unsupported)
+ */
+ define('QR_MODE_ST', 4);
+
+ // -----------------------------------------------------
+
+ // Levels of error correction.
+ // QRcode has a function of an error correcting for miss reading that white is black.
+ // Error correcting is defined in 4 level as below.
+
+ /**
+ * Error correction level L : About 7% or less errors can be corrected.
+ */
+ define('QR_ECLEVEL_L', 0);
+
+ /**
+ * Error correction level M : About 15% or less errors can be corrected.
+ */
+ define('QR_ECLEVEL_M', 1);
+
+ /**
+ * Error correction level Q : About 25% or less errors can be corrected.
+ */
+ define('QR_ECLEVEL_Q', 2);
+
+ /**
+ * Error correction level H : About 30% or less errors can be corrected.
+ */
+ define('QR_ECLEVEL_H', 3);
+
+ // -----------------------------------------------------
+
+ // Version. Size of QRcode is defined as version.
+ // Version is from 1 to 40.
+ // Version 1 is 21*21 matrix. And 4 modules increases whenever 1 version increases.
+ // So version 40 is 177*177 matrix.
+
+ /**
+ * Maximum QR Code version.
+ */
+ define('QRSPEC_VERSION_MAX', 40);
+
+ /**
+ * Maximum matrix size for maximum version (version 40 is 177*177 matrix).
+ */
+ define('QRSPEC_WIDTH_MAX', 177);
+
+ // -----------------------------------------------------
+
+ /**
+ * Matrix index to get width from $capacity array.
+ */
+ define('QRCAP_WIDTH', 0);
+
+ /**
+ * Matrix index to get number of words from $capacity array.
+ */
+ define('QRCAP_WORDS', 1);
+
+ /**
+ * Matrix index to get remainder from $capacity array.
+ */
+ define('QRCAP_REMINDER', 2);
+
+ /**
+ * Matrix index to get error correction level from $capacity array.
+ */
+ define('QRCAP_EC', 3);
+
+ // -----------------------------------------------------
+
+ // Structure (currently usupported)
+
+ /**
+ * Number of header bits for structured mode
+ */
+ define('STRUCTURE_HEADER_BITS', 20);
+
+ /**
+ * Max number of symbols for structured mode
+ */
+ define('MAX_STRUCTURED_SYMBOLS', 16);
+
+ // -----------------------------------------------------
+
+ // Masks
+
+ /**
+ * Down point base value for case 1 mask pattern (concatenation of same color in a line or a column)
+ */
+ define('N1', 3);
+
+ /**
+ * Down point base value for case 2 mask pattern (module block of same color)
+ */
+ define('N2', 3);
+
+ /**
+ * Down point base value for case 3 mask pattern (1:1:3:1:1(dark:bright:dark:bright:dark)pattern in a line or a column)
+ */
+ define('N3', 40);
+
+ /**
+ * Down point base value for case 4 mask pattern (ration of dark modules in whole)
+ */
+ define('N4', 10);
+
+ // -----------------------------------------------------
+
+ // Optimization settings
+
+ /**
+ * if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
+ */
+ define('QR_FIND_BEST_MASK', true);
+
+ /**
+ * if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
+ */
+ define('QR_FIND_FROM_RANDOM', 2);
+
+ /**
+ * when QR_FIND_BEST_MASK === false
+ */
+ define('QR_DEFAULT_MASK', 2);
+
+ // -----------------------------------------------------
+
+} // end of definitions
+
+// #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#
+
+if (!class_exists('QRcode', false)) {
+
+ // for compaibility with PHP4
+ if (!function_exists('str_split')) {
+ /**
+ * Convert a string to an array (needed for PHP4 compatibility)
+ * @param string $string The input string.
+ * @param int $split_length Maximum length of the chunk.
+ * @return If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length. FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string , the entire string is returned as the first (and only) array element.
+ */
+ function str_split($string, $split_length=1) {
+ if ((strlen($string) > $split_length) OR (!$split_length)) {
+ do {
+ $c = strlen($string);
+ $parts[] = substr($string, 0, $split_length);
+ $string = substr($string, $split_length);
+ } while ($string !== false);
+ } else {
+ $parts = array($string);
+ }
+ return $parts;
+ }
+ }
+
+ // #####################################################
+
+ /**
+ * Class to create QR-code arrays for TCPDF class.
+ * QR Code symbol is a 2D barcode that can be scanned by handy terminals such as a mobile phone with CCD.
+ * The capacity of QR Code is up to 7000 digits or 4000 characters, and has high robustness.
+ * This class supports QR Code model 2, described in JIS (Japanese Industrial Standards) X0510:2004 or ISO/IEC 18004.
+ * Currently the following features are not supported: ECI and FNC1 mode, Micro QR Code, QR Code model 1, Structured mode.
+ *
+ * This class is derived from "PHP QR Code encoder" by Dominik Dzienia (http://phpqrcode.sourceforge.net/) based on "libqrencode C library 3.1.1." by Kentaro Fukuchi (http://megaui.net/fukuchi/works/qrencode/index.en.html), contains Reed-Solomon code written by Phil Karn, KA9Q. QR Code is registered trademark of DENSO WAVE INCORPORATED (http://www.denso-wave.com/qrcode/index-e.html).
+ * Please read comments on this class source file for full copyright and license information.
+ *
+ * @name QRcode
+ * @package com.tecnick.tcpdf
+ * @abstract Class for generating QR-code array for TCPDF.
+ * @author Nicola Asuni
+ * @copyright 2010 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
+ * @link http://www.tcpdf.org
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL
+ * @version 1.0.002
+ */
+ class QRcode {
+
+ /**
+ * @var barcode array to be returned which is readable by TCPDF
+ * @access protected
+ */
+ protected $barcode_array = array();
+
+ /**
+ * @var QR code version. Size of QRcode is defined as version. Version is from 1 to 40. Version 1 is 21*21 matrix. And 4 modules increases whenever 1 version increases. So version 40 is 177*177 matrix.
+ * @access protected
+ */
+ protected $version = 0;
+
+ /**
+ * @var Levels of error correction. See definitions for possible values.
+ * @access protected
+ */
+ protected $level = QR_ECLEVEL_L;
+
+ /**
+ * @var Encoding mode
+ * @access protected
+ */
+ protected $hint = QR_MODE_8B;
+
+ /**
+ * @var if true the input string will be converted to uppercase
+ * @access protected
+ */
+ protected $casesensitive = true;
+
+ /**
+ * @var structured QR code (not supported yet)
+ * @access protected
+ */
+ protected $structured = 0;
+
+ /**
+ * @var mask data
+ * @access protected
+ */
+ protected $data;
+
+ // FrameFiller
+
+ /**
+ * @var width
+ * @access protected
+ */
+ protected $width;
+
+ /**
+ * @var frame
+ * @access protected
+ */
+ protected $frame;
+
+ /**
+ * @var X position of bit
+ * @access protected
+ */
+ protected $x;
+
+ /**
+ * @var Y position of bit
+ * @access protected
+ */
+ protected $y;
+
+ /**
+ * @var direction
+ * @access protected
+ */
+ protected $dir;
+
+ /**
+ * @var single bit
+ * @access protected
+ */
+ protected $bit;
+
+ // ---- QRrawcode ----
+
+ /**
+ * @var data code
+ * @access protected
+ */
+ protected $datacode = array();
+
+ /**
+ * @var error correction code
+ * @access protected
+ */
+ protected $ecccode = array();
+
+ /**
+ * @var blocks
+ * @access protected
+ */
+ protected $blocks;
+
+ /**
+ * @var Reed-Solomon blocks
+ * @access protected
+ */
+ protected $rsblocks = array(); //of RSblock
+
+ /**
+ * @var counter
+ * @access protected
+ */
+ protected $count;
+
+ /**
+ * @var data length
+ * @access protected
+ */
+ protected $dataLength;
+
+ /**
+ * @var error correction length
+ * @access protected
+ */
+ protected $eccLength;
+
+ /**
+ * @var b1
+ * @access protected
+ */
+ protected $b1;
+
+ // ---- QRmask ----
+
+ /**
+ * @var run length
+ * @access protected
+ */
+ protected $runLength = array();
+
+ // ---- QRsplit ----
+
+ /**
+ * @var input data string
+ * @access protected
+ */
+ protected $dataStr = '';
+
+ /**
+ * @var input items
+ * @access protected
+ */
+ protected $items;
+
+ // Reed-Solomon items
+
+ /**
+ * @var Reed-Solomon items
+ * @access protected
+ */
+ protected $rsitems = array();
+
+ /**
+ * @var array of frames
+ * @access protected
+ */
+ protected $frames = array();
+
+ /**
+ * @var alphabet-numeric convesion table
+ * @access protected
+ */
+ protected $anTable = array(
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //
+ 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, //
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, //
+ -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, //
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, //
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 //
+ );
+
+ /**
+ * @var array Table of the capacity of symbols
+ * See Table 1 (pp.13) and Table 12-16 (pp.30-36), JIS X0510:2004.
+ * @access protected
+ */
+ protected $capacity = array(
+ array( 0, 0, 0, array( 0, 0, 0, 0)), //
+ array( 21, 26, 0, array( 7, 10, 13, 17)), // 1
+ array( 25, 44, 7, array( 10, 16, 22, 28)), //
+ array( 29, 70, 7, array( 15, 26, 36, 44)), //
+ array( 33, 100, 7, array( 20, 36, 52, 64)), //
+ array( 37, 134, 7, array( 26, 48, 72, 88)), // 5
+ array( 41, 172, 7, array( 36, 64, 96, 112)), //
+ array( 45, 196, 0, array( 40, 72, 108, 130)), //
+ array( 49, 242, 0, array( 48, 88, 132, 156)), //
+ array( 53, 292, 0, array( 60, 110, 160, 192)), //
+ array( 57, 346, 0, array( 72, 130, 192, 224)), // 10
+ array( 61, 404, 0, array( 80, 150, 224, 264)), //
+ array( 65, 466, 0, array( 96, 176, 260, 308)), //
+ array( 69, 532, 0, array( 104, 198, 288, 352)), //
+ array( 73, 581, 3, array( 120, 216, 320, 384)), //
+ array( 77, 655, 3, array( 132, 240, 360, 432)), // 15
+ array( 81, 733, 3, array( 144, 280, 408, 480)), //
+ array( 85, 815, 3, array( 168, 308, 448, 532)), //
+ array( 89, 901, 3, array( 180, 338, 504, 588)), //
+ array( 93, 991, 3, array( 196, 364, 546, 650)), //
+ array( 97, 1085, 3, array( 224, 416, 600, 700)), // 20
+ array(101, 1156, 4, array( 224, 442, 644, 750)), //
+ array(105, 1258, 4, array( 252, 476, 690, 816)), //
+ array(109, 1364, 4, array( 270, 504, 750, 900)), //
+ array(113, 1474, 4, array( 300, 560, 810, 960)), //
+ array(117, 1588, 4, array( 312, 588, 870, 1050)), // 25
+ array(121, 1706, 4, array( 336, 644, 952, 1110)), //
+ array(125, 1828, 4, array( 360, 700, 1020, 1200)), //
+ array(129, 1921, 3, array( 390, 728, 1050, 1260)), //
+ array(133, 2051, 3, array( 420, 784, 1140, 1350)), //
+ array(137, 2185, 3, array( 450, 812, 1200, 1440)), // 30
+ array(141, 2323, 3, array( 480, 868, 1290, 1530)), //
+ array(145, 2465, 3, array( 510, 924, 1350, 1620)), //
+ array(149, 2611, 3, array( 540, 980, 1440, 1710)), //
+ array(153, 2761, 3, array( 570, 1036, 1530, 1800)), //
+ array(157, 2876, 0, array( 570, 1064, 1590, 1890)), // 35
+ array(161, 3034, 0, array( 600, 1120, 1680, 1980)), //
+ array(165, 3196, 0, array( 630, 1204, 1770, 2100)), //
+ array(169, 3362, 0, array( 660, 1260, 1860, 2220)), //
+ array(173, 3532, 0, array( 720, 1316, 1950, 2310)), //
+ array(177, 3706, 0, array( 750, 1372, 2040, 2430)) // 40
+ );
+
+ /**
+ * @var array Length indicator
+ * @access protected
+ */
+ protected $lengthTableBits = array(
+ array(10, 12, 14),
+ array( 9, 11, 13),
+ array( 8, 16, 16),
+ array( 8, 10, 12)
+ );
+
+ /**
+ * @var array Table of the error correction code (Reed-Solomon block)
+ * See Table 12-16 (pp.30-36), JIS X0510:2004.
+ * @access protected
+ */
+ protected $eccTable = array(
+ array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), //
+ array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1
+ array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), //
+ array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), //
+ array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), //
+ array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5
+ array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), //
+ array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), //
+ array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), //
+ array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), //
+ array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), // 10
+ array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), //
+ array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), //
+ array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), //
+ array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), //
+ array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), // 15
+ array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), //
+ array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), //
+ array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), //
+ array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), //
+ array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), // 20
+ array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), //
+ array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), //
+ array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), //
+ array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), //
+ array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), // 25
+ array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), //
+ array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), //
+ array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), //
+ array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), //
+ array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), // 30
+ array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), //
+ array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), //
+ array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), //
+ array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), //
+ array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), // 35
+ array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), //
+ array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), //
+ array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), //
+ array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), //
+ array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)) // 40
+ );
+
+ /**
+ * @var array Positions of alignment patterns.
+ * This array includes only the second and the third position of the alignment patterns. Rest of them can be calculated from the distance between them.
+ * See Table 1 in Appendix E (pp.71) of JIS X0510:2004.
+ * @access protected
+ */
+ protected $alignmentPattern = array(
+ array( 0, 0),
+ array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5
+ array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10
+ array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), // 11-15
+ array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), // 16-20
+ array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), // 21-25
+ array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), // 26-30
+ array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), // 31-35
+ array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58) // 35-40
+ );
+
+ /**
+ * @var array Version information pattern (BCH coded).
+ * See Table 1 in Appendix D (pp.68) of JIS X0510:2004.
+ * size: [QRSPEC_VERSION_MAX - 6]
+ * @access protected
+ */
+ protected $versionPattern = array(
+ 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, //
+ 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, //
+ 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, //
+ 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, //
+ 0x27541, 0x28c69
+ );
+
+ /**
+ * @var array Format information
+ * @access protected
+ */
+ protected $formatInfo = array(
+ array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), //
+ array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), //
+ array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), //
+ array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) //
+ );
+
+
+ // -------------------------------------------------
+ // -------------------------------------------------
+
+
+ /**
+ * This is the class constructor.
+ * Creates a QRcode object
+ * @param string $code code to represent using QRcode
+ * @param string $eclevel error level: <ul><li>L : About 7% or less errors can be corrected.</li><li>M : About 15% or less errors can be corrected.</li><li>Q : About 25% or less errors can be corrected.</li><li>H : About 30% or less errors can be corrected.</li></ul>
+ * @access public
+ * @since 1.0.000
+ */
+ public function __construct($code, $eclevel = 'L') {
+ $barcode_array = array();
+ if ((is_null($code)) OR ($code == '\0') OR ($code == '')) {
+ return false;
+ }
+ // set error correction level
+ $this->level = array_search($eclevel, array('L', 'M', 'Q', 'H'));
+ if ($this->level === false) {
+ $this->level = QR_ECLEVEL_L;
+ }
+ if (($this->hint != QR_MODE_8B) AND ($this->hint != QR_MODE_KJ)) {
+ return false;
+ }
+ if (($this->version < 0) OR ($this->version > QRSPEC_VERSION_MAX)) {
+ return false;
+ }
+ $this->items = array();
+ $this->encodeString($code);
+ $qrTab = $this->binarize($this->data);
+ $size = count($qrTab);
+ $barcode_array['num_rows'] = $size;
+ $barcode_array['num_cols'] = $size;
+ $barcode_array['bcode'] = array();
+ foreach ($qrTab as $line) {
+ $arrAdd = array();
+ foreach (str_split($line) as $char) {
+ $arrAdd[] = ($char=='1')?1:0;
+ }
+ $barcode_array['bcode'][] = $arrAdd;
+ }
+ $this->barcode_array = $barcode_array;
+ }
+
+ /**
+ * Returns a barcode array which is readable by TCPDF
+ * @return array barcode array readable by TCPDF;
+ * @access public
+ */
+ public function getBarcodeArray() {
+ return $this->barcode_array;
+ }
+
+ /**
+ * Convert the frame in binary form
+ * @param array $frame array to binarize
+ * @return array frame in binary form
+ */
+ protected function binarize($frame) {
+ $len = count($frame);
+ // the frame is square (width = height)
+ foreach ($frame as &$frameLine) {
+ for ($i=0; $i<$len; $i++) {
+ $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';
+ }
+ }
+ return $frame;
+ }
+
+ /**
+ * Encode the input string to QR code
+ * @param string $string input string to encode
+ */
+ protected function encodeString($string) {
+ $this->dataStr = $string;
+ if (!$this->casesensitive) {
+ $this->toUpper();
+ }
+ $ret = $this->splitString();
+ if ($ret < 0) {
+ return NULL;
+ }
+ $this->encodeMask(-1);
+ }
+
+ /**
+ * Encode mask
+ * @param int $mask masking mode
+ */
+ protected function encodeMask($mask) {
+ $spec = array(0, 0, 0, 0, 0);
+ $this->datacode = $this->getByteStream($this->items);
+ if (is_null($this->datacode)) {
+ return NULL;
+ }
+ $spec = $this->getEccSpec($this->version, $this->level, $spec);
+ $this->b1 = $this->rsBlockNum1($spec);
+ $this->dataLength = $this->rsDataLength($spec);
+ $this->eccLength = $this->rsEccLength($spec);
+ $this->ecccode = array_fill(0, $this->eccLength, 0);
+ $this->blocks = $this->rsBlockNum($spec);
+ $ret = $this->init($spec);
+ if ($ret < 0) {
+ return NULL;
+ }
+ $this->count = 0;
+ $this->width = $this->getWidth($this->version);
+ $this->frame = $this->newFrame($this->version);
+ $this->x = $this->width - 1;
+ $this->y = $this->width - 1;
+ $this->dir = -1;
+ $this->bit = -1;
+ // inteleaved data and ecc codes
+ for ($i=0; $i < ($this->dataLength + $this->eccLength); $i++) {
+ $code = $this->getCode();
+ $bit = 0x80;
+ for ($j=0; $j<8; $j++) {
+ $addr = $this->getNextPosition();
+ $this->setFrameAt($addr, 0x02 | (($bit & $code) != 0));
+ $bit = $bit >> 1;
+ }
+ }
+ // remainder bits
+ $j = $this->getRemainder($this->version);
+ for ($i=0; $i<$j; $i++) {
+ $addr = $this->getNextPosition();
+ $this->setFrameAt($addr, 0x02);
+ }
+ // masking
+ $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0);
+ if ($mask < 0) {
+ if (QR_FIND_BEST_MASK) {
+ $masked = $this->mask($this->width, $this->frame, $this->level);
+ } else {
+ $masked = $this->makeMask($this->width, $this->frame, (intval(QR_DEFAULT_MASK) % 8), $this->level);
+ }
+ } else {
+ $masked = $this->makeMask($this->width, $this->frame, $mask, $this->level);
+ }
+ if ($masked == NULL) {
+ return NULL;
+ }
+ $this->data = $masked;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // FrameFiller
+
+ /**
+ * Set frame value at specified position
+ * @param array $at x,y position
+ * @param int $val value of the character to set
+ */
+ protected function setFrameAt($at, $val) {
+ $this->frame[$at['y']][$at['x']] = chr($val);
+ }
+
+ /**
+ * Get frame value at specified position
+ * @param array $at x,y position
+ * @return value at specified position
+ */
+ protected function getFrameAt($at) {
+ return ord($this->frame[$at['y']][$at['x']]);
+ }
+
+ /**
+ * Return the next frame position
+ * @return array of x,y coordinates
+ */
+ protected function getNextPosition() {
+ do {
+ if ($this->bit == -1) {
+ $this->bit = 0;
+ return array('x'=>$this->x, 'y'=>$this->y);
+ }
+ $x = $this->x;
+ $y = $this->y;
+ $w = $this->width;
+ if ($this->bit == 0) {
+ $x--;
+ $this->bit++;
+ } else {
+ $x++;
+ $y += $this->dir;
+ $this->bit--;
+ }
+ if ($this->dir < 0) {
+ if ($y < 0) {
+ $y = 0;
+ $x -= 2;
+ $this->dir = 1;
+ if ($x == 6) {
+ $x--;
+ $y = 9;
+ }
+ }
+ } else {
+ if ($y == $w) {
+ $y = $w - 1;
+ $x -= 2;
+ $this->dir = -1;
+ if ($x == 6) {
+ $x--;
+ $y -= 8;
+ }
+ }
+ }
+ if (($x < 0) OR ($y < 0)) {
+ return NULL;
+ }
+ $this->x = $x;
+ $this->y = $y;
+ } while(ord($this->frame[$y][$x]) & 0x80);
+ return array('x'=>$x, 'y'=>$y);
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRrawcode
+
+ /**
+ * Initialize code.
+ * @param array $spec array of ECC specification
+ * @return 0 in case of success, -1 in case of error
+ */
+ protected function init($spec) {
+ $dl = $this->rsDataCodes1($spec);
+ $el = $this->rsEccCodes1($spec);
+ $rs = $this->init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+ $blockNo = 0;
+ $dataPos = 0;
+ $eccPos = 0;
+ $endfor = $this->rsBlockNum1($spec);
+ for ($i=0; $i < $endfor; ++$i) {
+ $ecc = array_slice($this->ecccode, $eccPos);
+ $this->rsblocks[$blockNo] = array();
+ $this->rsblocks[$blockNo]['dataLength'] = $dl;
+ $this->rsblocks[$blockNo]['data'] = array_slice($this->datacode, $dataPos);
+ $this->rsblocks[$blockNo]['eccLength'] = $el;
+ $ecc = $this->encode_rs_char($rs, $this->rsblocks[$blockNo]['data'], $ecc);
+ $this->rsblocks[$blockNo]['ecc'] = $ecc;
+ $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
+ $dataPos += $dl;
+ $eccPos += $el;
+ $blockNo++;
+ }
+ if ($this->rsBlockNum2($spec) == 0) {
+ return 0;
+ }
+ $dl = $this->rsDataCodes2($spec);
+ $el = $this->rsEccCodes2($spec);
+ $rs = $this->init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+ if ($rs == NULL) {
+ return -1;
+ }
+ $endfor = $this->rsBlockNum2($spec);
+ for ($i=0; $i < $endfor; ++$i) {
+ $ecc = array_slice($this->ecccode, $eccPos);
+ $this->rsblocks[$blockNo] = array();
+ $this->rsblocks[$blockNo]['dataLength'] = $dl;
+ $this->rsblocks[$blockNo]['data'] = array_slice($this->datacode, $dataPos);
+ $this->rsblocks[$blockNo]['eccLength'] = $el;
+ $ecc = $this->encode_rs_char($rs, $this->rsblocks[$blockNo]['data'], $ecc);
+ $this->rsblocks[$blockNo]['ecc'] = $ecc;
+ $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc);
+ $dataPos += $dl;
+ $eccPos += $el;
+ $blockNo++;
+ }
+ return 0;
+ }
+
+ /**
+ * Return Reed-Solomon block code.
+ * @return array rsblocks
+ */
+ protected function getCode() {
+ if ($this->count < $this->dataLength) {
+ $row = $this->count % $this->blocks;
+ $col = $this->count / $this->blocks;
+ if ($col >= $this->rsblocks[0]['dataLength']) {
+ $row += $this->b1;
+ }
+ $ret = $this->rsblocks[$row]['data'][$col];
+ } elseif ($this->count < $this->dataLength + $this->eccLength) {
+ $row = ($this->count - $this->dataLength) % $this->blocks;
+ $col = ($this->count - $this->dataLength) / $this->blocks;
+ $ret = $this->rsblocks[$row]['ecc'][$col];
+ } else {
+ return 0;
+ }
+ $this->count++;
+ return $ret;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRmask
+
+ /**
+ * Write Format Information on frame and returns the number of black bits
+ * @param int $width frame width
+ * @param array $frame frame
+ * @param array $mask masking mode
+ * @param int $level error correction level
+ * @return int blacks
+ */
+ protected function writeFormatInformation($width, &$frame, $mask, $level) {
+ $blacks = 0;
+ $format = $this->getFormatInfo($mask, $level);
+ for ($i=0; $i<8; ++$i) {
+ if ($format & 1) {
+ $blacks += 2;
+ $v = 0x85;
+ } else {
+ $v = 0x84;
+ }
+ $frame[8][$width - 1 - $i] = chr($v);
+ if ($i < 6) {
+ $frame[$i][8] = chr($v);
+ } else {
+ $frame[$i + 1][8] = chr($v);
+ }
+ $format = $format >> 1;
+ }
+ for ($i=0; $i<7; ++$i) {
+ if ($format & 1) {
+ $blacks += 2;
+ $v = 0x85;
+ } else {
+ $v = 0x84;
+ }
+ $frame[$width - 7 + $i][8] = chr($v);
+ if ($i == 0) {
+ $frame[8][7] = chr($v);
+ } else {
+ $frame[8][6 - $i] = chr($v);
+ }
+ $format = $format >> 1;
+ }
+ return $blacks;
+ }
+
+ /**
+ * mask0
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask0($x, $y) {
+ return ($x + $y) & 1;
+ }
+
+ /**
+ * mask1
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask1($x, $y) {
+ return ($y & 1);
+ }
+
+ /**
+ * mask2
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask2($x, $y) {
+ return ($x % 3);
+ }
+
+ /**
+ * mask3
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask3($x, $y) {
+ return ($x + $y) % 3;
+ }
+
+ /**
+ * mask4
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask4($x, $y) {
+ return (((int)($y / 2)) + ((int)($x / 3))) & 1;
+ }
+
+ /**
+ * mask5
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask5($x, $y) {
+ return (($x * $y) & 1) + ($x * $y) % 3;
+ }
+
+ /**
+ * mask6
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask6($x, $y) {
+ return ((($x * $y) & 1) + ($x * $y) % 3) & 1;
+ }
+
+ /**
+ * mask7
+ * @param int $x X position
+ * @param int $y Y position
+ * @return int mask
+ */
+ protected function mask7($x, $y) {
+ return ((($x * $y) % 3) + (($x + $y) & 1)) & 1;
+ }
+
+ /**
+ * Return bitmask
+ * @param int $maskNo mask number
+ * @param int $width width
+ * @param array $frame frame
+ * @return array bitmask
+ */
+ protected function generateMaskNo($maskNo, $width, $frame) {
+ $bitMask = array_fill(0, $width, array_fill(0, $width, 0));
+ for ($y=0; $y<$width; ++$y) {
+ for ($x=0; $x<$width; ++$x) {
+ if (ord($frame[$y][$x]) & 0x80) {
+ $bitMask[$y][$x] = 0;
+ } else {
+ $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y);
+ $bitMask[$y][$x] = ($maskFunc == 0)?1:0;
+ }
+ }
+ }
+ return $bitMask;
+ }
+
+ /**
+ * makeMaskNo
+ * @param int $maskNo
+ * @param int $width
+ * @param int $s
+ * @param int $d
+ * @param boolean $maskGenOnly
+ * @return int b
+ */
+ protected function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly=false) {
+ $b = 0;
+ $bitMask = array();
+ $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
+ if ($maskGenOnly) {
+ return;
+ }
+ $d = $s;
+ for ($y=0; $y<$width; ++$y) {
+ for ($x=0; $x<$width; ++$x) {
+ if ($bitMask[$y][$x] == 1) {
+ $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]);
+ }
+ $b += (int)(ord($d[$y][$x]) & 1);
+ }
+ }
+ return $b;
+ }
+
+ /**
+ * makeMask
+ * @param int $width
+ * @param array $frame
+ * @param int $maskNo
+ * @param int $level
+ * @return array mask
+ */
+ protected function makeMask($width, $frame, $maskNo, $level) {
+ $masked = array_fill(0, $width, str_repeat("\0", $width));
+ $this->makeMaskNo($maskNo, $width, $frame, $masked);
+ $this->writeFormatInformation($width, $masked, $maskNo, $level);
+ return $masked;
+ }
+
+ /**
+ * calcN1N3
+ * @param int $length
+ * @return int demerit
+ */
+ protected function calcN1N3($length) {
+ $demerit = 0;
+ for ($i=0; $i<$length; ++$i) {
+ if ($this->runLength[$i] >= 5) {
+ $demerit += (N1 + ($this->runLength[$i] - 5));
+ }
+ if ($i & 1) {
+ if (($i >= 3) AND ($i < ($length-2)) AND ($this->runLength[$i] % 3 == 0)) {
+ $fact = (int)($this->runLength[$i] / 3);
+ if (($this->runLength[$i-2] == $fact)
+ AND ($this->runLength[$i-1] == $fact)
+ AND ($this->runLength[$i+1] == $fact)
+ AND ($this->runLength[$i+2] == $fact)) {
+ if (($this->runLength[$i-3] < 0) OR ($this->runLength[$i-3] >= (4 * $fact))) {
+ $demerit += N3;
+ } elseif ((($i+3) >= $length) OR ($this->runLength[$i+3] >= (4 * $fact))) {
+ $demerit += N3;
+ }
+ }
+ }
+ }
+ }
+ return $demerit;
+ }
+
+ /**
+ * evaluateSymbol
+ * @param int $width
+ * @param array $frame
+ * @return int demerit
+ */
+ protected function evaluateSymbol($width, $frame) {
+ $head = 0;
+ $demerit = 0;
+ for ($y=0; $y<$width; ++$y) {
+ $head = 0;
+ $this->runLength[0] = 1;
+ $frameY = $frame[$y];
+ if ($y > 0) {
+ $frameYM = $frame[$y-1];
+ }
+ for ($x=0; $x<$width; ++$x) {
+ if (($x > 0) AND ($y > 0)) {
+ $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]);
+ $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]);
+ if (($b22 | ($w22 ^ 1)) & 1) {
+ $demerit += N2;
+ }
+ }
+ if (($x == 0) AND (ord($frameY[$x]) & 1)) {
+ $this->runLength[0] = -1;
+ $head = 1;
+ $this->runLength[$head] = 1;
+ } elseif ($x > 0) {
+ if ((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) {
+ $head++;
+ $this->runLength[$head] = 1;
+ } else {
+ $this->runLength[$head]++;
+ }
+ }
+ }
+ $demerit += $this->calcN1N3($head+1);
+ }
+ for ($x=0; $x<$width; ++$x) {
+ $head = 0;
+ $this->runLength[0] = 1;
+ for ($y=0; $y<$width; ++$y) {
+ if (($y == 0) AND (ord($frame[$y][$x]) & 1)) {
+ $this->runLength[0] = -1;
+ $head = 1;
+ $this->runLength[$head] = 1;
+ } elseif ($y > 0) {
+ if ((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) {
+ $head++;
+ $this->runLength[$head] = 1;
+ } else {
+ $this->runLength[$head]++;
+ }
+ }
+ }
+ $demerit += $this->calcN1N3($head+1);
+ }
+ return $demerit;
+ }
+
+ /**
+ * mask
+ * @param int $width
+ * @param array $frame
+ * @param int $level
+ * @return array best mask
+ */
+ protected function mask($width, $frame, $level) {
+ $minDemerit = PHP_INT_MAX;
+ $bestMaskNum = 0;
+ $bestMask = array();
+ $checked_masks = array(0, 1, 2, 3, 4, 5, 6, 7);
+ if (QR_FIND_FROM_RANDOM !== false) {
+ $howManuOut = 8 - (QR_FIND_FROM_RANDOM % 9);
+ for ($i = 0; $i < $howManuOut; ++$i) {
+ $remPos = rand (0, count($checked_masks)-1);
+ unset($checked_masks[$remPos]);
+ $checked_masks = array_values($checked_masks);
+ }
+ }
+ $bestMask = $frame;
+ foreach ($checked_masks as $i) {
+ $mask = array_fill(0, $width, str_repeat("\0", $width));
+ $demerit = 0;
+ $blacks = 0;
+ $blacks = $this->makeMaskNo($i, $width, $frame, $mask);
+ $blacks += $this->writeFormatInformation($width, $mask, $i, $level);
+ $blacks = (int)(100 * $blacks / ($width * $width));
+ $demerit = (int)((int)(abs($blacks - 50) / 5) * N4);
+ $demerit += $this->evaluateSymbol($width, $mask);
+ if ($demerit < $minDemerit) {
+ $minDemerit = $demerit;
+ $bestMask = $mask;
+ $bestMaskNum = $i;
+ }
+ }
+ return $bestMask;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRsplit
+
+ /**
+ * Return true if the character at specified position is a number
+ * @param string $str string
+ * @param int $pos characted position
+ * @return boolean true of false
+ */
+ protected function isdigitat($str, $pos) {
+ if ($pos >= strlen($str)) {
+ return false;
+ }
+ return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9')));
+ }
+
+ /**
+ * Return true if the character at specified position is an alphanumeric character
+ * @param string $str string
+ * @param int $pos characted position
+ * @return boolean true of false
+ */
+ protected function isalnumat($str, $pos) {
+ if ($pos >= strlen($str)) {
+ return false;
+ }
+ return ($this->lookAnTable(ord($str[$pos])) >= 0);
+ }
+
+ /**
+ * identifyMode
+ * @param int $pos
+ * @return int mode
+ */
+ protected function identifyMode($pos) {
+ if ($pos >= strlen($this->dataStr)) {
+ return QR_MODE_NL;
+ }
+ $c = $this->dataStr[$pos];
+ if ($this->isdigitat($this->dataStr, $pos)) {
+ return QR_MODE_NM;
+ } elseif ($this->isalnumat($this->dataStr, $pos)) {
+ return QR_MODE_AN;
+ } elseif ($this->hint == QR_MODE_KJ) {
+ if ($pos+1 < strlen($this->dataStr)) {
+ $d = $this->dataStr[$pos+1];
+ $word = (ord($c) << 8) | ord($d);
+ if (($word >= 0x8140 && $word <= 0x9ffc) OR ($word >= 0xe040 && $word <= 0xebbf)) {
+ return QR_MODE_KJ;
+ }
+ }
+ }
+ return QR_MODE_8B;
+ }
+
+ /**
+ * eatNum
+ * @return int run
+ */
+ protected function eatNum() {
+ $ln = $this->lengthIndicator(QR_MODE_NM, $this->version);
+ $p = 0;
+ while($this->isdigitat($this->dataStr, $p)) {
+ $p++;
+ }
+ $run = $p;
+ $mode = $this->identifyMode($p);
+ if ($mode == QR_MODE_8B) {
+ $dif = $this->estimateBitsModeNum($run) + 4 + $ln
+ + $this->estimateBitsMode8(1) // + 4 + l8
+ - $this->estimateBitsMode8($run + 1); // - 4 - l8
+ if ($dif > 0) {
+ return $this->eat8();
+ }
+ }
+ if ($mode == QR_MODE_AN) {
+ $dif = $this->estimateBitsModeNum($run) + 4 + $ln
+ + $this->estimateBitsModeAn(1) // + 4 + la
+ - $this->estimateBitsModeAn($run + 1);// - 4 - la
+ if ($dif > 0) {
+ return $this->eatAn();
+ }
+ }
+ $this->items = $this->appendNewInputItem($this->items, QR_MODE_NM, $run, str_split($this->dataStr));
+ return $run;
+ }
+
+ /**
+ * eatAn
+ * @return int run
+ */
+ protected function eatAn() {
+ $la = $this->lengthIndicator(QR_MODE_AN, $this->version);
+ $ln = $this->lengthIndicator(QR_MODE_NM, $this->version);
+ $p = 0;
+ while($this->isalnumat($this->dataStr, $p)) {
+ if ($this->isdigitat($this->dataStr, $p)) {
+ $q = $p;
+ while($this->isdigitat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = $this->estimateBitsModeAn($p) // + 4 + la
+ + $this->estimateBitsModeNum($q - $p) + 4 + $ln
+ - $this->estimateBitsModeAn($q); // - 4 - la
+ if ($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else {
+ $p++;
+ }
+ }
+ $run = $p;
+ if (!$this->isalnumat($this->dataStr, $p)) {
+ $dif = $this->estimateBitsModeAn($run) + 4 + $la
+ + $this->estimateBitsMode8(1) // + 4 + l8
+ - $this->estimateBitsMode8($run + 1); // - 4 - l8
+ if ($dif > 0) {
+ return $this->eat8();
+ }
+ }
+ $this->items = $this->appendNewInputItem($this->items, QR_MODE_AN, $run, str_split($this->dataStr));
+ return $run;
+ }
+
+ /**
+ * eatKanji
+ * @return int run
+ */
+ protected function eatKanji() {
+ $p = 0;
+ while($this->identifyMode($p) == QR_MODE_KJ) {
+ $p += 2;
+ }
+ $this->items = $this->appendNewInputItem($this->items, QR_MODE_KJ, $p, str_split($this->dataStr));
+ return $run;
+ }
+
+ /**
+ * eat8
+ * @return int run
+ */
+ protected function eat8() {
+ $la = $this->lengthIndicator(QR_MODE_AN, $this->version);
+ $ln = $this->lengthIndicator(QR_MODE_NM, $this->version);
+ $p = 1;
+ $dataStrLen = strlen($this->dataStr);
+ while($p < $dataStrLen) {
+ $mode = $this->identifyMode($p);
+ if ($mode == QR_MODE_KJ) {
+ break;
+ }
+ if ($mode == QR_MODE_NM) {
+ $q = $p;
+ while($this->isdigitat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = $this->estimateBitsMode8($p) // + 4 + l8
+ + $this->estimateBitsModeNum($q - $p) + 4 + $ln
+ - $this->estimateBitsMode8($q); // - 4 - l8
+ if ($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } elseif ($mode == QR_MODE_AN) {
+ $q = $p;
+ while($this->isalnumat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = $this->estimateBitsMode8($p) // + 4 + l8
+ + $this->estimateBitsModeAn($q - $p) + 4 + $la
+ - $this->estimateBitsMode8($q); // - 4 - l8
+ if ($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else {
+ $p++;
+ }
+ }
+ $run = $p;
+ $this->items = $this->appendNewInputItem($this->items, QR_MODE_8B, $run, str_split($this->dataStr));
+ return $run;
+ }
+
+ /**
+ * splitString
+ */
+ protected function splitString() {
+ while (strlen($this->dataStr) > 0) {
+ if ($this->dataStr == '') {
+ return 0;
+ }
+ $mode = $this->identifyMode(0);
+ switch ($mode) {
+ case QR_MODE_NM: {
+ $length = $this->eatNum();
+ break;
+ }
+ case QR_MODE_AN: {
+ $length = $this->eatAn();
+ break;
+ }
+ case QR_MODE_KJ: {
+ if ($hint == QR_MODE_KJ) {
+ $length = $this->eatKanji();
+ } else {
+ $length = $this->eat8();
+ }
+ break;
+ }
+ default: {
+ $length = $this->eat8();
+ break;
+ }
+ }
+ if ($length == 0) {
+ return 0;
+ }
+ if ($length < 0) {
+ return -1;
+ }
+ $this->dataStr = substr($this->dataStr, $length);
+ }
+ }
+
+ /**
+ * toUpper
+ */
+ protected function toUpper() {
+ $stringLen = strlen($this->dataStr);
+ $p = 0;
+ while ($p < $stringLen) {
+ $mode = $this->identifyMode(substr($this->dataStr, $p), $this->hint);
+ if ($mode == QR_MODE_KJ) {
+ $p += 2;
+ } else {
+ if ((ord($this->dataStr[$p]) >= ord('a')) AND (ord($this->dataStr[$p]) <= ord('z'))) {
+ $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32);
+ }
+ $p++;
+ }
+ }
+ return $this->dataStr;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRinputItem
+
+ /**
+ * newInputItem
+ * @param int $mode
+ * @param int $size
+ * @param array $data
+ * @param array $bstream
+ * @return array input item
+ */
+ protected function newInputItem($mode, $size, $data, $bstream=null) {
+ $setData = array_slice($data, 0, $size);
+ if (count($setData) < $size) {
+ $setData = array_merge($setData, array_fill(0, ($size - count($setData)), 0));
+ }
+ if (!$this->check($mode, $size, $setData)) {
+ return NULL;
+ }
+ $inputitem = array();
+ $inputitem['mode'] = $mode;
+ $inputitem['size'] = $size;
+ $inputitem['data'] = $setData;
+ $inputitem['bstream'] = $bstream;
+ return $inputitem;
+ }
+
+ /**
+ * encodeModeNum
+ * @param array $inputitem
+ * @param int $version
+ * @return array input item
+ */
+ protected function encodeModeNum($inputitem, $version) {
+ $words = (int)($inputitem['size'] / 3);
+ $inputitem['bstream'] = array();
+ $val = 0x1;
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, $val);
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], $this->lengthIndicator(QR_MODE_NM, $version), $inputitem['size']);
+ for ($i=0; $i < $words; ++$i) {
+ $val = (ord($inputitem['data'][$i*3 ]) - ord('0')) * 100;
+ $val += (ord($inputitem['data'][$i*3+1]) - ord('0')) * 10;
+ $val += (ord($inputitem['data'][$i*3+2]) - ord('0'));
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 10, $val);
+ }
+ if ($inputitem['size'] - $words * 3 == 1) {
+ $val = ord($inputitem['data'][$words*3]) - ord('0');
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, $val);
+ } elseif (($inputitem['size'] - ($words * 3)) == 2) {
+ $val = (ord($inputitem['data'][$words*3 ]) - ord('0')) * 10;
+ $val += (ord($inputitem['data'][$words*3+1]) - ord('0'));
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 7, $val);
+ }
+ return $inputitem;
+ }
+
+ /**
+ * encodeModeAn
+ * @param array $inputitem
+ * @param int $version
+ * @return array input item
+ */
+ protected function encodeModeAn($inputitem, $version) {
+ $words = (int)($inputitem['size'] / 2);
+ $inputitem['bstream'] = array();
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x02);
+ $inputitem['bstream'] = $this->appendNum(v, $this->lengthIndicator(QR_MODE_AN, $version), $inputitem['size']);
+ for ($i=0; $i < $words; ++$i) {
+ $val = (int)$this->lookAnTable(ord($inputitem['data'][$i*2 ])) * 45;
+ $val += (int)$this->lookAnTable(ord($inputitem['data'][$i*2+1]));
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 11, $val);
+ }
+ if ($inputitem['size'] & 1) {
+ $val = $this->lookAnTable(ord($inputitem['data'][($words * 2)]));
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 6, $val);
+ }
+ return $inputitem;
+ }
+
+ /**
+ * encodeMode8
+ * @param array $inputitem
+ * @param int $version
+ * @return array input item
+ */
+ protected function encodeMode8($inputitem, $version) {
+ $inputitem['bstream'] = array();
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x4);
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], $this->lengthIndicator(QR_MODE_8B, $version), $inputitem['size']);
+ for ($i=0; $i < $inputitem['size']; ++$i) {
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 8, ord($inputitem['data'][$i]));
+ }
+ return $inputitem;
+ }
+
+ /**
+ * encodeModeKanji
+ * @param array $inputitem
+ * @param int $version
+ * @return array input item
+ */
+ protected function encodeModeKanji($inputitem, $version) {
+ $inputitem['bstream'] = array();
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x8);
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], $this->lengthIndicator(QR_MODE_KJ, $version), (int)($inputitem['size'] / 2));
+ for ($i=0; $i<$inputitem['size']; $i+=2) {
+ $val = (ord($inputitem['data'][$i]) << 8) | ord($inputitem['data'][$i+1]);
+ if ($val <= 0x9ffc) {
+ $val -= 0x8140;
+ } else {
+ $val -= 0xc140;
+ }
+ $h = ($val >> 8) * 0xc0;
+ $val = ($val & 0xff) + $h;
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 13, $val);
+ }
+ return $inputitem;
+ }
+
+ /**
+ * encodeModeStructure
+ * @param array $inputitem
+ * @return array input item
+ */
+ protected function encodeModeStructure($inputitem) {
+ $inputitem['bstream'] = array();
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x03);
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, ord($inputitem['data'][1]) - 1);
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, ord($inputitem['data'][0]) - 1);
+ $inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 8, ord($inputitem['data'][2]));
+ return $inputitem;
+ }
+
+ /**
+ * encodeBitStream
+ * @param array $inputitem
+ * @param int $version
+ * @return array input item
+ */
+ protected function encodeBitStream($inputitem, $version) {
+ $inputitem['bstream'] = array();
+ $words = $this->maximumWords($inputitem['mode'], $version);
+ if ($inputitem['size'] > $words) {
+ $st1 = $this->newInputItem($inputitem['mode'], $words, $inputitem['data']);
+ $st2 = $this->newInputItem($inputitem['mode'], $inputitem['size'] - $words, array_slice($inputitem['data'], $words));
+ $st1 = $this->encodeBitStream($st1, $version);
+ $st2 = $this->encodeBitStream($st2, $version);
+ $inputitem['bstream'] = array();
+ $inputitem['bstream'] = $this->appendBitstream($inputitem['bstream'], $st1['bstream']);
+ $inputitem['bstream'] = $this->appendBitstream($inputitem['bstream'], $st2['bstream']);
+ } else {
+ switch($inputitem['mode']) {
+ case QR_MODE_NM: {
+ $inputitem = $this->encodeModeNum($inputitem, $version);
+ break;
+ }
+ case QR_MODE_AN: {
+ $inputitem = $this->encodeModeAn($inputitem, $version);
+ break;
+ }
+ case QR_MODE_8B: {
+ $inputitem = $this->encodeMode8($inputitem, $version);
+ break;
+ }
+ case QR_MODE_KJ: {
+ $inputitem = $this->encodeModeKanji($inputitem, $version);
+ break;
+ }
+ case QR_MODE_ST: {
+ $inputitem = $this->encodeModeStructure($inputitem);
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ }
+ return $inputitem;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRinput
+
+ /**
+ * Append data to an input object.
+ * The data is copied and appended to the input object.
+ * @param array items input items
+ * @param int $mode encoding mode.
+ * @param int $size size of data (byte).
+ * @param array $data array of input data.
+ * @return items
+ *
+ */
+ protected function appendNewInputItem($items, $mode, $size, $data) {
+ $items[] = $this->newInputItem($mode, $size, $data);
+ return $items;
+ }
+
+ /**
+ * insertStructuredAppendHeader
+ * @param array $items
+ * @param int $size
+ * @param int $index
+ * @param int $parity
+ * @return array items
+ */
+ protected function insertStructuredAppendHeader($items, $size, $index, $parity) {
+ if ($size > MAX_STRUCTURED_SYMBOLS) {
+ return -1;
+ }
+ if (($index <= 0) OR ($index > MAX_STRUCTURED_SYMBOLS)) {
+ return -1;
+ }
+ $buf = array($size, $index, $parity);
+ $entry = $this->newInputItem(QR_MODE_ST, 3, buf);
+ array_unshift($items, $entry);
+ return $items;
+ }
+
+ /**
+ * calcParity
+ * @param array $items
+ * @return int parity
+ */
+ protected function calcParity($items) {
+ $parity = 0;
+ foreach ($items as $item) {
+ if ($item['mode'] != QR_MODE_ST) {
+ for ($i=$item['size']-1; $i>=0; --$i) {
+ $parity ^= $item['data'][$i];
+ }
+ }
+ }
+ return $parity;
+ }
+
+ /**
+ * checkModeNum
+ * @param int $size
+ * @param array $data
+ * @return boolean true or false
+ */
+ protected function checkModeNum($size, $data) {
+ for ($i=0; $i<$size; ++$i) {
+ if ((ord($data[$i]) < ord('0')) OR (ord($data[$i]) > ord('9'))){
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * estimateBitsModeNum
+ * @param int $size
+ * @return int number of bits
+ */
+ protected function estimateBitsModeNum($size) {
+ $w = (int)$size / 3;
+ $bits = $w * 10;
+ switch($size - $w * 3) {
+ case 1: {
+ $bits += 4;
+ break;
+ }
+ case 2: {
+ $bits += 7;
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ return $bits;
+ }
+
+ /**
+ * Look up the alphabet-numeric convesion table (see JIS X0510:2004, pp.19).
+ * @param int $c character value
+ * @return value
+ */
+ protected function lookAnTable($c) {
+ return (($c > 127)?-1:$this->anTable[$c]);
+ }
+
+ /**
+ * checkModeAn
+ * @param int $size
+ * @param array $data
+ * @return boolean true or false
+ */
+ protected function checkModeAn($size, $data) {
+ for ($i=0; $i<$size; ++$i) {
+ if ($this->lookAnTable(ord($data[$i])) == -1) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * estimateBitsModeAn
+ * @param int $size
+ * @return int number of bits
+ */
+ protected function estimateBitsModeAn($size) {
+ $w = (int)($size / 2);
+ $bits = $w * 11;
+ if ($size & 1) {
+ $bits += 6;
+ }
+ return $bits;
+ }
+
+ /**
+ * estimateBitsMode8
+ * @param int $size
+ * @return int number of bits
+ */
+ protected function estimateBitsMode8($size) {
+ return $size * 8;
+ }
+
+ /**
+ * estimateBitsModeKanji
+ * @param int $size
+ * @return int number of bits
+ */
+ protected function estimateBitsModeKanji($size) {
+ return (int)(($size / 2) * 13);
+ }
+
+ /**
+ * checkModeKanji
+ * @param int $size
+ * @param array $data
+ * @return boolean true or false
+ */
+ protected function checkModeKanji($size, $data) {
+ if ($size & 1) {
+ return false;
+ }
+ for ($i=0; $i<$size; $i+=2) {
+ $val = (ord($data[$i]) << 8) | ord($data[$i+1]);
+ if (($val < 0x8140) OR (($val > 0x9ffc) AND ($val < 0xe040)) OR ($val > 0xebbf)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Validate the input data.
+ * @param int $mode encoding mode.
+ * @param int $size size of data (byte).
+ * @param array data data to validate
+ * @return boolean true in case of valid data, false otherwise
+ */
+ protected function check($mode, $size, $data) {
+ if ($size <= 0) {
+ return false;
+ }
+ switch($mode) {
+ case QR_MODE_NM: {
+ return $this->checkModeNum($size, $data);
+ }
+ case QR_MODE_AN: {
+ return $this->checkModeAn($size, $data);
+ }
+ case QR_MODE_KJ: {
+ return $this->checkModeKanji($size, $data);
+ }
+ case QR_MODE_8B: {
+ return true;
+ }
+ case QR_MODE_ST: {
+ return true;
+ }
+ default: {
+ break;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * estimateBitStreamSize
+ * @param array $items
+ * @param int $version
+ * @return int bits
+ */
+ protected function estimateBitStreamSize($items, $version) {
+ $bits = 0;
+ if ($version == 0) {
+ $version = 1;
+ }
+ foreach ($items as $item) {
+ switch($item['mode']) {
+ case QR_MODE_NM: {
+ $bits = $this->estimateBitsModeNum($item['size']);
+ break;
+ }
+ case QR_MODE_AN: {
+ $bits = $this->estimateBitsModeAn($item['size']);
+ break;
+ }
+ case QR_MODE_8B: {
+ $bits = $this->estimateBitsMode8($item['size']);
+ break;
+ }
+ case QR_MODE_KJ: {
+ $bits = $this->estimateBitsModeKanji($item['size']);
+ break;
+ }
+ case QR_MODE_ST: {
+ return STRUCTURE_HEADER_BITS;
+ }
+ default: {
+ return 0;
+ }
+ }
+ $l = $this->lengthIndicator($item['mode'], $version);
+ $m = 1 << $l;
+ $num = (int)(($item['size'] + $m - 1) / $m);
+ $bits += $num * (4 + $l);
+ }
+ return $bits;
+ }
+
+ /**
+ * estimateVersion
+ * @param array $items
+ * @return int version
+ */
+ protected function estimateVersion($items) {
+ $version = 0;
+ $prev = 0;
+ do {
+ $prev = $version;
+ $bits = $this->estimateBitStreamSize($items, $prev);
+ $version = $this->getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+ if ($version < 0) {
+ return -1;
+ }
+ } while ($version > $prev);
+ return $version;
+ }
+
+ /**
+ * lengthOfCode
+ * @param int $mode
+ * @param int $version
+ * @param int $bits
+ * @return int size
+ */
+ protected function lengthOfCode($mode, $version, $bits) {
+ $payload = $bits - 4 - $this->lengthIndicator($mode, $version);
+ switch($mode) {
+ case QR_MODE_NM: {
+ $chunks = (int)($payload / 10);
+ $remain = $payload - $chunks * 10;
+ $size = $chunks * 3;
+ if ($remain >= 7) {
+ $size += 2;
+ } elseif ($remain >= 4) {
+ $size += 1;
+ }
+ break;
+ }
+ case QR_MODE_AN: {
+ $chunks = (int)($payload / 11);
+ $remain = $payload - $chunks * 11;
+ $size = $chunks * 2;
+ if ($remain >= 6) {
+ ++$size;
+ }
+ break;
+ }
+ case QR_MODE_8B: {
+ $size = (int)($payload / 8);
+ break;
+ }
+ case QR_MODE_KJ: {
+ $size = (int)(($payload / 13) * 2);
+ break;
+ }
+ case QR_MODE_ST: {
+ $size = (int)($payload / 8);
+ break;
+ }
+ default: {
+ $size = 0;
+ break;
+ }
+ }
+ $maxsize = $this->maximumWords($mode, $version);
+ if ($size < 0) {
+ $size = 0;
+ }
+ if ($size > $maxsize) {
+ $size = $maxsize;
+ }
+ return $size;
+ }
+
+ /**
+ * createBitStream
+ * @param array $items
+ * @return array of items and total bits
+ */
+ protected function createBitStream($items) {
+ $total = 0;
+ foreach ($items as $key => $item) {
+ $items[$key] = $this->encodeBitStream($item, $this->version);
+ $bits = count($items[$key]['bstream']);
+ $total += $bits;
+ }
+ return array($items, $total);
+ }
+
+ /**
+ * convertData
+ * @param array $items
+ * @return array items
+ */
+ protected function convertData($items) {
+ $ver = $this->estimateVersion($items);
+ if ($ver > $this->version) {
+ $this->version = $ver;
+ }
+ for (;;) {
+ $cbs = $this->createBitStream($items);
+ $items = $cbs[0];
+ $bits = $cbs[1];
+ if ($bits < 0) {
+ return -1;
+ }
+ $ver = $this->getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+ if ($ver < 0) {
+ return -1;
+ } elseif ($ver > $this->version) {
+ $this->version = $ver;
+ } else {
+ break;
+ }
+ }
+ return $items;
+ }
+
+ /**
+ * Append Padding Bit to bitstream
+ * @param array $bstream
+ * @return array bitstream
+ */
+ protected function appendPaddingBit($bstream) {
+ $bits = count($bstream);
+ $maxwords = $this->getDataLength($this->version, $this->level);
+ $maxbits = $maxwords * 8;
+ if ($maxbits == $bits) {
+ return 0;
+ }
+ if ($maxbits - $bits < 5) {
+ return $this->appendNum($bstream, $maxbits - $bits, 0);
+ }
+ $bits += 4;
+ $words = (int)(($bits + 7) / 8);
+ $padding = array();
+ $padding = $this->appendNum($padding, $words * 8 - $bits + 4, 0);
+ $padlen = $maxwords - $words;
+ if ($padlen > 0) {
+ $padbuf = array();
+ for ($i=0; $i<$padlen; ++$i) {
+ $padbuf[$i] = ($i&1)?0x11:0xec;
+ }
+ $padding = $this->appendBytes($padding, $padlen, $padbuf);
+ }
+ return $this->appendBitstream($bstream, $padding);
+ }
+
+ /**
+ * mergeBitStream
+ * @param array $bstream
+ * @return array bitstream
+ */
+ protected function mergeBitStream($items) {
+ $items = $this->convertData($items);
+ $bstream = array();
+ foreach ($items as $item) {
+ $bstream = $this->appendBitstream($bstream, $item['bstream']);
+ }
+ return $bstream;
+ }
+
+ /**
+ * Returns a stream of bits.
+ * @param int $items
+ * @return array padded merged byte stream
+ */
+ protected function getBitStream($items) {
+ $bstream = $this->mergeBitStream($items);
+ return $this->appendPaddingBit($bstream);
+ }
+
+ /**
+ * Pack all bit streams padding bits into a byte array.
+ * @param int $items
+ * @return array padded merged byte stream
+ */
+ protected function getByteStream($items) {
+ $bstream = $this->getBitStream($items);
+ return $this->bitstreamToByte($bstream);
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRbitstream
+
+ /**
+ * Return an array with zeros
+ * @param int $setLength array size
+ * @return array
+ */
+ protected function allocate($setLength) {
+ return array_fill(0, $setLength, 0);
+ }
+
+ /**
+ * Return new bitstream from number
+ * @param int $bits number of bits
+ * @param int $num number
+ * @return array bitstream
+ */
+ protected function newFromNum($bits, $num) {
+ $bstream = $this->allocate($bits);
+ $mask = 1 << ($bits - 1);
+ for ($i=0; $i<$bits; ++$i) {
+ if ($num & $mask) {
+ $bstream[$i] = 1;
+ } else {
+ $bstream[$i] = 0;
+ }
+ $mask = $mask >> 1;
+ }
+ return $bstream;
+ }
+
+ /**
+ * Return new bitstream from bytes
+ * @param int $size size
+ * @param array $data bytes
+ * @return array bitstream
+ */
+ protected function newFromBytes($size, $data) {
+ $bstream = $this->allocate($size * 8);
+ $p=0;
+ for ($i=0; $i<$size; ++$i) {
+ $mask = 0x80;
+ for ($j=0; $j<8; ++$j) {
+ if ($data[$i] & $mask) {
+ $bstream[$p] = 1;
+ } else {
+ $bstream[$p] = 0;
+ }
+ $p++;
+ $mask = $mask >> 1;
+ }
+ }
+ return $bstream;
+ }
+
+ /**
+ * Append one bitstream to another
+ * @param array $bitstream original bitstream
+ * @param array $append bitstream to append
+ * @return array bitstream
+ */
+ protected function appendBitstream($bitstream, $append) {
+ if ((!is_array($append)) OR (count($append) == 0)) {
+ return $bitstream;
+ }
+ if (count($bitstream) == 0) {
+ return $append;
+ }
+ return array_values(array_merge($bitstream, $append));
+ }
+
+ /**
+ * Append one bitstream created from number to another
+ * @param array $bitstream original bitstream
+ * @param int $bits number of bits
+ * @param int $num number
+ * @return array bitstream
+ */
+ protected function appendNum($bitstream, $bits, $num) {
+ if ($bits == 0) {
+ return 0;
+ }
+ $b = $this->newFromNum($bits, $num);
+ return $this->appendBitstream($bitstream, $b);
+ }
+
+ /**
+ * Append one bitstream created from bytes to another
+ * @param array $bitstream original bitstream
+ * @param int $size size
+ * @param array $data bytes
+ * @return array bitstream
+ */
+ protected function appendBytes($bitstream, $size, $data) {
+ if ($size == 0) {
+ return 0;
+ }
+ $b = $this->newFromBytes($size, $data);
+ return $this->appendBitstream($bitstream, $b);
+ }
+
+ /**
+ * Convert bitstream to bytes
+ * @param array $bitstream original bitstream
+ * @return array of bytes
+ */
+ protected function bitstreamToByte($bstream) {
+ $size = count($bstream);
+ if ($size == 0) {
+ return array();
+ }
+ $data = array_fill(0, (int)(($size + 7) / 8), 0);
+ $bytes = (int)($size / 8);
+ $p = 0;
+ for ($i=0; $i<$bytes; $i++) {
+ $v = 0;
+ for ($j=0; $j<8; $j++) {
+ $v = $v << 1;
+ $v |= $bstream[$p];
+ $p++;
+ }
+ $data[$i] = $v;
+ }
+ if ($size & 7) {
+ $v = 0;
+ for ($j=0; $j<($size & 7); $j++) {
+ $v = $v << 1;
+ $v |= $bstream[$p];
+ $p++;
+ }
+ $data[$bytes] = $v;
+ }
+ return $data;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRspec
+
+ /**
+ * Replace a value on the array at the specified position
+ * @param array $srctab
+ * @param int $x X position
+ * @param int $y Y position
+ * @param string $repl value to replace
+ * @param int $replLen length of the repl string
+ * @return array srctab
+ */
+ protected function qrstrset($srctab, $x, $y, $repl, $replLen=false) {
+ $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));
+ return $srctab;
+ }
+
+ /**
+ * Return maximum data code length (bytes) for the version.
+ * @param int $version version
+ * @param int $level error correction level
+ * @return int maximum size (bytes)
+ */
+ protected function getDataLength($version, $level) {
+ return $this->capacity[$version][QRCAP_WORDS] - $this->capacity[$version][QRCAP_EC][$level];
+ }
+
+ /**
+ * Return maximum error correction code length (bytes) for the version.
+ * @param int $version version
+ * @param int $level error correction level
+ * @return int ECC size (bytes)
+ */
+ protected function getECCLength($version, $level){
+ return $this->capacity[$version][QRCAP_EC][$level];
+ }
+
+ /**
+ * Return the width of the symbol for the version.
+ * @param int $version version
+ * @return int width
+ */
+ protected function getWidth($version) {
+ return $this->capacity[$version][QRCAP_WIDTH];
+ }
+
+ /**
+ * Return the numer of remainder bits.
+ * @param int $version version
+ * @return int number of remainder bits
+ */
+ protected function getRemainder($version) {
+ return $this->capacity[$version][QRCAP_REMINDER];
+ }
+
+ /**
+ * Return a version number that satisfies the input code length.
+ * @param int $size input code length (byte)
+ * @param int $level error correction level
+ * @return int version number
+ */
+ protected function getMinimumVersion($size, $level) {
+ for ($i=1; $i <= QRSPEC_VERSION_MAX; ++$i) {
+ $words = $this->capacity[$i][QRCAP_WORDS] - $this->capacity[$i][QRCAP_EC][$level];
+ if ($words >= $size) {
+ return $i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Return the size of length indicator for the mode and version.
+ * @param int $mode encoding mode
+ * @param int $version version
+ * @return int the size of the appropriate length indicator (bits).
+ */
+ protected function lengthIndicator($mode, $version) {
+ if ($mode == QR_MODE_ST) {
+ return 0;
+ }
+ if ($version <= 9) {
+ $l = 0;
+ } elseif ($version <= 26) {
+ $l = 1;
+ } else {
+ $l = 2;
+ }
+ return $this->lengthTableBits[$mode][$l];
+ }
+
+ /**
+ * Return the maximum length for the mode and version.
+ * @param int $mode encoding mode
+ * @param int $version version
+ * @return int the maximum length (bytes)
+ */
+ protected function maximumWords($mode, $version) {
+ if ($mode == QR_MODE_ST) {
+ return 3;
+ }
+ if ($version <= 9) {
+ $l = 0;
+ } else if ($version <= 26) {
+ $l = 1;
+ } else {
+ $l = 2;
+ }
+ $bits = $this->lengthTableBits[$mode][$l];
+ $words = (1 << $bits) - 1;
+ if ($mode == QR_MODE_KJ) {
+ $words *= 2; // the number of bytes is required
+ }
+ return $words;
+ }
+
+ /**
+ * Return an array of ECC specification.
+ * @param int $version version
+ * @param int $level error correction level
+ * @param array $spec an array of ECC specification contains as following: {# of type1 blocks, # of data code, # of ecc code, # of type2 blocks, # of data code}
+ * @return array spec
+ */
+ protected function getEccSpec($version, $level, $spec) {
+ if (count($spec) < 5) {
+ $spec = array(0, 0, 0, 0, 0);
+ }
+ $b1 = $this->eccTable[$version][$level][0];
+ $b2 = $this->eccTable[$version][$level][1];
+ $data = $this->getDataLength($version, $level);
+ $ecc = $this->getECCLength($version, $level);
+ if ($b2 == 0) {
+ $spec[0] = $b1;
+ $spec[1] = (int)($data / $b1);
+ $spec[2] = (int)($ecc / $b1);
+ $spec[3] = 0;
+ $spec[4] = 0;
+ } else {
+ $spec[0] = $b1;
+ $spec[1] = (int)($data / ($b1 + $b2));
+ $spec[2] = (int)($ecc / ($b1 + $b2));
+ $spec[3] = $b2;
+ $spec[4] = $spec[1] + 1;
+ }
+ return $spec;
+ }
+
+ /**
+ * Put an alignment marker.
+ * @param array $frame frame
+ * @param int $width width
+ * @param int $ox X center coordinate of the pattern
+ * @param int $oy Y center coordinate of the pattern
+ * @return array frame
+ */
+ protected function putAlignmentMarker($frame, $ox, $oy) {
+ $finder = array(
+ "\xa1\xa1\xa1\xa1\xa1",
+ "\xa1\xa0\xa0\xa0\xa1",
+ "\xa1\xa0\xa1\xa0\xa1",
+ "\xa1\xa0\xa0\xa0\xa1",
+ "\xa1\xa1\xa1\xa1\xa1"
+ );
+ $yStart = $oy - 2;
+ $xStart = $ox - 2;
+ for ($y=0; $y < 5; $y++) {
+ $frame = $this->qrstrset($frame, $xStart, $yStart+$y, $finder[$y]);
+ }
+ return $frame;
+ }
+
+ /**
+ * Put an alignment pattern.
+ * @param int $version version
+ * @param array $fram frame
+ * @param int $width width
+ * @return array frame
+ */
+ protected function putAlignmentPattern($version, $frame, $width) {
+ if ($version < 2) {
+ return $frame;
+ }
+ $d = $this->alignmentPattern[$version][1] - $this->alignmentPattern[$version][0];
+ if ($d < 0) {
+ $w = 2;
+ } else {
+ $w = (int)(($width - $this->alignmentPattern[$version][0]) / $d + 2);
+ }
+ if ($w * $w - 3 == 1) {
+ $x = $this->alignmentPattern[$version][0];
+ $y = $this->alignmentPattern[$version][0];
+ $frame = $this->putAlignmentMarker($frame, $x, $y);
+ return $frame;
+ }
+ $cx = $this->alignmentPattern[$version][0];
+ $wo = $w - 1;
+ for ($x=1; $x < $wo; ++$x) {
+ $frame = $this->putAlignmentMarker($frame, 6, $cx);
+ $frame = $this->putAlignmentMarker($frame, $cx, 6);
+ $cx += $d;
+ }
+ $cy = $this->alignmentPattern[$version][0];
+ for ($y=0; $y < $wo; ++$y) {
+ $cx = $this->alignmentPattern[$version][0];
+ for ($x=0; $x < $wo; ++$x) {
+ $frame = $this->putAlignmentMarker($frame, $cx, $cy);
+ $cx += $d;
+ }
+ $cy += $d;
+ }
+ return $frame;
+ }
+
+ /**
+ * Return BCH encoded version information pattern that is used for the symbol of version 7 or greater. Use lower 18 bits.
+ * @param int $version version
+ * @return BCH encoded version information pattern
+ */
+ protected function getVersionPattern($version) {
+ if (($version < 7) OR ($version > QRSPEC_VERSION_MAX)) {
+ return 0;
+ }
+ return $this->versionPattern[($version - 7)];
+ }
+
+ /**
+ * Return BCH encoded format information pattern.
+ * @param array $mask
+ * @param int $level error correction level
+ * @return BCH encoded format information pattern
+ */
+ protected function getFormatInfo($mask, $level) {
+ if (($mask < 0) OR ($mask > 7)) {
+ return 0;
+ }
+ if (($level < 0) OR ($level > 3)) {
+ return 0;
+ }
+ return $this->formatInfo[$level][$mask];
+ }
+
+ /**
+ * Put a finder pattern.
+ * @param array $frame frame
+ * @param int $width width
+ * @param int $ox X center coordinate of the pattern
+ * @param int $oy Y center coordinate of the pattern
+ * @return array frame
+ */
+ protected function putFinderPattern($frame, $ox, $oy) {
+ $finder = array(
+ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1",
+ "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1"
+ );
+ for ($y=0; $y < 7; $y++) {
+ $frame = $this->qrstrset($frame, $ox, ($oy + $y), $finder[$y]);
+ }
+ return $frame;
+ }
+
+ /**
+ * Return a copy of initialized frame.
+ * @param int $version version
+ * @return Array of unsigned char.
+ */
+ protected function createFrame($version) {
+ $width = $this->capacity[$version][QRCAP_WIDTH];
+ $frameLine = str_repeat ("\0", $width);
+ $frame = array_fill(0, $width, $frameLine);
+ // Finder pattern
+ $frame = $this->putFinderPattern($frame, 0, 0);
+ $frame = $this->putFinderPattern($frame, $width - 7, 0);
+ $frame = $this->putFinderPattern($frame, 0, $width - 7);
+ // Separator
+ $yOffset = $width - 7;
+ for ($y=0; $y < 7; ++$y) {
+ $frame[$y][7] = "\xc0";
+ $frame[$y][$width - 8] = "\xc0";
+ $frame[$yOffset][7] = "\xc0";
+ ++$yOffset;
+ }
+ $setPattern = str_repeat("\xc0", 8);
+ $frame = $this->qrstrset($frame, 0, 7, $setPattern);
+ $frame = $this->qrstrset($frame, $width-8, 7, $setPattern);
+ $frame = $this->qrstrset($frame, 0, $width - 8, $setPattern);
+ // Format info
+ $setPattern = str_repeat("\x84", 9);
+ $frame = $this->qrstrset($frame, 0, 8, $setPattern);
+ $frame = $this->qrstrset($frame, $width - 8, 8, $setPattern, 8);
+ $yOffset = $width - 8;
+ for ($y=0; $y < 8; ++$y,++$yOffset) {
+ $frame[$y][8] = "\x84";
+ $frame[$yOffset][8] = "\x84";
+ }
+ // Timing pattern
+ $wo = $width - 15;
+ for ($i=1; $i < $wo; ++$i) {
+ $frame[6][7+$i] = chr(0x90 | ($i & 1));
+ $frame[7+$i][6] = chr(0x90 | ($i & 1));
+ }
+ // Alignment pattern
+ $frame = $this->putAlignmentPattern($version, $frame, $width);
+ // Version information
+ if ($version >= 7) {
+ $vinf = $this->getVersionPattern($version);
+ $v = $vinf;
+ for ($x=0; $x<6; ++$x) {
+ for ($y=0; $y<3; ++$y) {
+ $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));
+ $v = $v >> 1;
+ }
+ }
+ $v = $vinf;
+ for ($y=0; $y<6; ++$y) {
+ for ($x=0; $x<3; ++$x) {
+ $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));
+ $v = $v >> 1;
+ }
+ }
+ }
+ // and a little bit...
+ $frame[$width - 8][8] = "\x81";
+ return $frame;
+ }
+
+ /**
+ * Set new frame for the specified version.
+ * @param int $version version
+ * @return Array of unsigned char.
+ */
+ protected function newFrame($version) {
+ if (($version < 1) OR ($version > QRSPEC_VERSION_MAX)) {
+ return NULL;
+ }
+ if (!isset($this->frames[$version])) {
+ $this->frames[$version] = $this->createFrame($version);
+ }
+ if (is_null($this->frames[$version])) {
+ return NULL;
+ }
+ return $this->frames[$version];
+ }
+
+ /**
+ * Return block number 0
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsBlockNum($spec) {
+ return ($spec[0] + $spec[3]);
+ }
+
+ /**
+ * Return block number 1
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsBlockNum1($spec) {
+ return $spec[0];
+ }
+
+ /**
+ * Return data codes 1
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsDataCodes1($spec) {
+ return $spec[1];
+ }
+
+ /**
+ * Return ecc codes 1
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsEccCodes1($spec) {
+ return $spec[2];
+ }
+
+ /**
+ * Return block number 2
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsBlockNum2($spec) {
+ return $spec[3];
+ }
+
+ /**
+ * Return data codes 2
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsDataCodes2($spec) {
+ return $spec[4];
+ }
+
+ /**
+ * Return ecc codes 2
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsEccCodes2($spec) {
+ return $spec[2];
+ }
+
+ /**
+ * Return data length
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsDataLength($spec) {
+ return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]);
+ }
+
+ /**
+ * Return ecc length
+ * @param array $spec
+ * @return int value
+ */
+ protected function rsEccLength($spec) {
+ return ($spec[0] + $spec[3]) * $spec[2];
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRrs
+
+ /**
+ * Initialize a Reed-Solomon codec and add it to existing rsitems
+ * @param int $symsize symbol size, bits
+ * @param int $gfpoly Field generator polynomial coefficients
+ * @param int $fcr first root of RS code generator polynomial, index form
+ * @param int $prim primitive element to generate polynomial roots
+ * @param int $nroots RS code generator polynomial degree (number of roots)
+ * @param int $pad padding bytes at front of shortened block
+ * @return array Array of RS values:<ul><li>mm = Bits per symbol;</li><li>nn = Symbols per block;</li><li>alpha_to = log lookup table array;</li><li>index_of = Antilog lookup table array;</li><li>genpoly = Generator polynomial array;</li><li>nroots = Number of generator;</li><li>roots = number of parity symbols;</li><li>fcr = First consecutive root, index form;</li><li>prim = Primitive element, index form;</li><li>iprim = prim-th root of 1, index form;</li><li>pad = Padding bytes in shortened block;</li><li>gfpoly</ul>.
+ */
+ protected function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) {
+ foreach ($this->rsitems as $rs) {
+ if (($rs['pad'] != $pad) OR ($rs['nroots'] != $nroots) OR ($rs['mm'] != $symsize)
+ OR ($rs['gfpoly'] != $gfpoly) OR ($rs['fcr'] != $fcr) OR ($rs['prim'] != $prim)) {
+ continue;
+ }
+ return $rs;
+ }
+ $rs = $this->init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad);
+ array_unshift($this->rsitems, $rs);
+ return $rs;
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - -
+
+ // QRrsItem
+
+ /**
+ * modnn
+ * @param array RS values
+ * @param int $x X position
+ * @return int X osition
+ */
+ protected function modnn($rs, $x) {
+ while ($x >= $rs['nn']) {
+ $x -= $rs['nn'];
+ $x = ($x >> $rs['mm']) + ($x & $rs['nn']);
+ }
+ return $x;
+ }
+
+ /**
+ * Initialize a Reed-Solomon codec and returns an array of values.
+ * @param int $symsize symbol size, bits
+ * @param int $gfpoly Field generator polynomial coefficients
+ * @param int $fcr first root of RS code generator polynomial, index form
+ * @param int $prim primitive element to generate polynomial roots
+ * @param int $nroots RS code generator polynomial degree (number of roots)
+ * @param int $pad padding bytes at front of shortened block
+ * @return array Array of RS values:<ul><li>mm = Bits per symbol;</li><li>nn = Symbols per block;</li><li>alpha_to = log lookup table array;</li><li>index_of = Antilog lookup table array;</li><li>genpoly = Generator polynomial array;</li><li>nroots = Number of generator;</li><li>roots = number of parity symbols;</li><li>fcr = First consecutive root, index form;</li><li>prim = Primitive element, index form;</li><li>iprim = prim-th root of 1, index form;</li><li>pad = Padding bytes in shortened block;</li><li>gfpoly</ul>.
+ */
+ protected function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) {
+ // Based on Reed solomon encoder by Phil Karn, KA9Q (GNU-LGPLv2)
+ $rs = null;
+ // Check parameter ranges
+ if (($symsize < 0) OR ($symsize > 8)) {
+ return $rs;
+ }
+ if (($fcr < 0) OR ($fcr >= (1<<$symsize))) {
+ return $rs;
+ }
+ if (($prim <= 0) OR ($prim >= (1<<$symsize))) {
+ return $rs;
+ }
+ if (($nroots < 0) OR ($nroots >= (1<<$symsize))) {
+ return $rs;
+ }
+ if (($pad < 0) OR ($pad >= ((1<<$symsize) -1 - $nroots))) {
+ return $rs;
+ }
+ $rs = array();
+ $rs['mm'] = $symsize;
+ $rs['nn'] = (1 << $symsize) - 1;
+ $rs['pad'] = $pad;
+ $rs['alpha_to'] = array_fill(0, ($rs['nn'] + 1), 0);
+ $rs['index_of'] = array_fill(0, ($rs['nn'] + 1), 0);
+ // PHP style macro replacement ;)
+ $NN =& $rs['nn'];
+ $A0 =& $NN;
+ // Generate Galois field lookup tables
+ $rs['index_of'][0] = $A0; // log(zero) = -inf
+ $rs['alpha_to'][$A0] = 0; // alpha**-inf = 0
+ $sr = 1;
+ for ($i=0; $i<$rs['nn']; ++$i) {
+ $rs['index_of'][$sr] = $i;
+ $rs['alpha_to'][$i] = $sr;
+ $sr <<= 1;
+ if ($sr & (1 << $symsize)) {
+ $sr ^= $gfpoly;
+ }
+ $sr &= $rs['nn'];
+ }
+ if ($sr != 1) {
+ // field generator polynomial is not primitive!
+ return NULL;
+ }
+ // Form RS code generator polynomial from its roots
+ $rs['genpoly'] = array_fill(0, ($nroots + 1), 0);
+ $rs['fcr'] = $fcr;
+ $rs['prim'] = $prim;
+ $rs['nroots'] = $nroots;
+ $rs['gfpoly'] = $gfpoly;
+ // Find prim-th root of 1, used in decoding
+ for ($iprim=1; ($iprim % $prim) != 0; $iprim += $rs['nn']) {
+ ; // intentional empty-body loop!
+ }
+ $rs['iprim'] = (int)($iprim / $prim);
+ $rs['genpoly'][0] = 1;
+
+
+ for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) {
+ $rs['genpoly'][$i+1] = 1;
+ // Multiply rs->genpoly[] by @**(root + x)
+ for ($j = $i; $j > 0; --$j) {
+ if ($rs['genpoly'][$j] != 0) {
+ $rs['genpoly'][$j] = $rs['genpoly'][$j-1] ^ $rs['alpha_to'][$this->modnn($rs, $rs['index_of'][$rs['genpoly'][$j]] + $root)];
+ } else {
+ $rs['genpoly'][$j] = $rs['genpoly'][$j-1];
+ }
+ }
+ // rs->genpoly[0] can never be zero
+ $rs['genpoly'][0] = $rs['alpha_to'][$this->modnn($rs, $rs['index_of'][$rs['genpoly'][0]] + $root)];
+ }
+ // convert rs->genpoly[] to index form for quicker encoding
+ for ($i = 0; $i <= $nroots; ++$i) {
+ $rs['genpoly'][$i] = $rs['index_of'][$rs['genpoly'][$i]];
+ }
+ return $rs;
+ }
+
+ /**
+ * Encode a Reed-Solomon codec and returns the parity array
+ * @param array $rs RS values
+ * @param array $data data
+ * @param array $parity parity
+ * @return parity array
+ */
+ protected function encode_rs_char($rs, $data, $parity) {
+ $MM =& $rs['mm']; // bits per symbol
+ $NN =& $rs['nn']; // the total number of symbols in a RS block
+ $ALPHA_TO =& $rs['alpha_to']; // the address of an array of NN elements to convert Galois field elements in index (log) form to polynomial form
+ $INDEX_OF =& $rs['index_of']; // the address of an array of NN elements to convert Galois field elements in polynomial form to index (log) form
+ $GENPOLY =& $rs['genpoly']; // an array of NROOTS+1 elements containing the generator polynomial in index form
+ $NROOTS =& $rs['nroots']; // the number of roots in the RS code generator polynomial, which is the same as the number of parity symbols in a block
+ $FCR =& $rs['fcr']; // first consecutive root, index form
+ $PRIM =& $rs['prim']; // primitive element, index form
+ $IPRIM =& $rs['iprim']; // prim-th root of 1, index form
+ $PAD =& $rs['pad']; // the number of pad symbols in a block
+ $A0 =& $NN;
+ $parity = array_fill(0, $NROOTS, 0);
+ for ($i=0; $i < ($NN - $NROOTS - $PAD); $i++) {
+ $feedback = $INDEX_OF[$data[$i] ^ $parity[0]];
+ if ($feedback != $A0) {
+ // feedback term is non-zero
+ // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must
+ // always be for the polynomials constructed by init_rs()
+ $feedback = $this->modnn($rs, $NN - $GENPOLY[$NROOTS] + $feedback);
+ for ($j=1; $j < $NROOTS; ++$j) {
+ $parity[$j] ^= $ALPHA_TO[$this->modnn($rs, $feedback + $GENPOLY[($NROOTS - $j)])];
+ }
+ }
+ // Shift
+ array_shift($parity);
+ if ($feedback != $A0) {
+ array_push($parity, $ALPHA_TO[$this->modnn($rs, $feedback + $GENPOLY[0])]);
+ } else {
+ array_push($parity, 0);
+ }
+ }
+ return $parity;
+ }
+
+ } // end QRcode class
+
+} // END OF "class_exists QRcode"
+?>
diff --git a/admin/survey/classes/phpqrcode/cache/frame_1.png b/admin/survey/classes/phpqrcode/cache/frame_1.png
new file mode 100644
index 0000000..86ce6e9
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_1.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_10.png b/admin/survey/classes/phpqrcode/cache/frame_10.png
new file mode 100644
index 0000000..dbfcd70
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_10.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_11.png b/admin/survey/classes/phpqrcode/cache/frame_11.png
new file mode 100644
index 0000000..c07c761
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_11.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_12.png b/admin/survey/classes/phpqrcode/cache/frame_12.png
new file mode 100644
index 0000000..8ba6782
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_12.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_13.png b/admin/survey/classes/phpqrcode/cache/frame_13.png
new file mode 100644
index 0000000..6e49d35
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_13.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_14.png b/admin/survey/classes/phpqrcode/cache/frame_14.png
new file mode 100644
index 0000000..efc36c0
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_14.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_15.png b/admin/survey/classes/phpqrcode/cache/frame_15.png
new file mode 100644
index 0000000..a9f416c
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_15.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_16.png b/admin/survey/classes/phpqrcode/cache/frame_16.png
new file mode 100644
index 0000000..6ac8fe8
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_16.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_17.png b/admin/survey/classes/phpqrcode/cache/frame_17.png
new file mode 100644
index 0000000..5b929ac
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_17.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_18.png b/admin/survey/classes/phpqrcode/cache/frame_18.png
new file mode 100644
index 0000000..ee0d6a3
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_18.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_19.png b/admin/survey/classes/phpqrcode/cache/frame_19.png
new file mode 100644
index 0000000..20fddd8
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_19.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_2.png b/admin/survey/classes/phpqrcode/cache/frame_2.png
new file mode 100644
index 0000000..9c150eb
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_2.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_20.png b/admin/survey/classes/phpqrcode/cache/frame_20.png
new file mode 100644
index 0000000..23a061d
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_20.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_21.png b/admin/survey/classes/phpqrcode/cache/frame_21.png
new file mode 100644
index 0000000..291598c
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_21.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_22.png b/admin/survey/classes/phpqrcode/cache/frame_22.png
new file mode 100644
index 0000000..bc97bd0
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_22.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_23.png b/admin/survey/classes/phpqrcode/cache/frame_23.png
new file mode 100644
index 0000000..b8f16ae
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_23.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_24.png b/admin/survey/classes/phpqrcode/cache/frame_24.png
new file mode 100644
index 0000000..397c64f
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_24.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_25.png b/admin/survey/classes/phpqrcode/cache/frame_25.png
new file mode 100644
index 0000000..25bc445
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_25.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_26.png b/admin/survey/classes/phpqrcode/cache/frame_26.png
new file mode 100644
index 0000000..f4a6b39
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_26.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_27.png b/admin/survey/classes/phpqrcode/cache/frame_27.png
new file mode 100644
index 0000000..8419ec2
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_27.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_28.png b/admin/survey/classes/phpqrcode/cache/frame_28.png
new file mode 100644
index 0000000..7609d8e
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_28.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_29.png b/admin/survey/classes/phpqrcode/cache/frame_29.png
new file mode 100644
index 0000000..ffe072c
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_29.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_3.png b/admin/survey/classes/phpqrcode/cache/frame_3.png
new file mode 100644
index 0000000..945ee7c
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_3.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_30.png b/admin/survey/classes/phpqrcode/cache/frame_30.png
new file mode 100644
index 0000000..75dbddd
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_30.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_31.png b/admin/survey/classes/phpqrcode/cache/frame_31.png
new file mode 100644
index 0000000..b14d1fa
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_31.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_32.png b/admin/survey/classes/phpqrcode/cache/frame_32.png
new file mode 100644
index 0000000..58d42db
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_32.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_33.png b/admin/survey/classes/phpqrcode/cache/frame_33.png
new file mode 100644
index 0000000..924c728
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_33.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_34.png b/admin/survey/classes/phpqrcode/cache/frame_34.png
new file mode 100644
index 0000000..a477042
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_34.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_35.png b/admin/survey/classes/phpqrcode/cache/frame_35.png
new file mode 100644
index 0000000..d29806c
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_35.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_36.png b/admin/survey/classes/phpqrcode/cache/frame_36.png
new file mode 100644
index 0000000..96ecb42
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_36.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_37.png b/admin/survey/classes/phpqrcode/cache/frame_37.png
new file mode 100644
index 0000000..fcc5162
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_37.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_38.png b/admin/survey/classes/phpqrcode/cache/frame_38.png
new file mode 100644
index 0000000..89238f3
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_38.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_39.png b/admin/survey/classes/phpqrcode/cache/frame_39.png
new file mode 100644
index 0000000..1dc9cd1
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_39.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_4.png b/admin/survey/classes/phpqrcode/cache/frame_4.png
new file mode 100644
index 0000000..b72f9e7
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_4.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_40.png b/admin/survey/classes/phpqrcode/cache/frame_40.png
new file mode 100644
index 0000000..8034d86
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_40.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_5.png b/admin/survey/classes/phpqrcode/cache/frame_5.png
new file mode 100644
index 0000000..96b6494
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_5.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_6.png b/admin/survey/classes/phpqrcode/cache/frame_6.png
new file mode 100644
index 0000000..05ca358
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_6.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_7.png b/admin/survey/classes/phpqrcode/cache/frame_7.png
new file mode 100644
index 0000000..7d2ff4f
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_7.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_8.png b/admin/survey/classes/phpqrcode/cache/frame_8.png
new file mode 100644
index 0000000..db1f187
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_8.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/cache/frame_9.png b/admin/survey/classes/phpqrcode/cache/frame_9.png
new file mode 100644
index 0000000..74ddf08
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/cache/frame_9.png
Binary files differ
diff --git a/admin/survey/classes/phpqrcode/imgs/.gitignore b/admin/survey/classes/phpqrcode/imgs/.gitignore
new file mode 100644
index 0000000..a3a0c8b
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/imgs/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/index.php b/admin/survey/classes/phpqrcode/index.php
new file mode 100644
index 0000000..ec6be6a
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/index.php
@@ -0,0 +1,94 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Exemplatory usage
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ echo "<h1>PHP QR Code</h1><hr/>";
+
+ //set it to writable location, a place for temp generated PNG files
+ $PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
+
+ //html PNG location prefix
+ $PNG_WEB_DIR = 'temp/';
+
+ include "qrlib.php";
+
+ //ofcourse we need rights to create temp dir
+ if (!file_exists($PNG_TEMP_DIR))
+ mkdir($PNG_TEMP_DIR);
+
+
+ $filename = $PNG_TEMP_DIR.'test.png';
+
+ //processing form input
+ //remember to sanitize user input in real-life solution !!!
+ $errorCorrectionLevel = 'L';
+ if (isset($_REQUEST['level']) && in_array($_REQUEST['level'], array('L','M','Q','H')))
+ $errorCorrectionLevel = $_REQUEST['level'];
+
+ $matrixPointSize = 4;
+ if (isset($_REQUEST['size']))
+ $matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
+
+
+ if (isset($_REQUEST['data'])) {
+
+ //it's very important!
+ if (trim($_REQUEST['data']) == '')
+ die('data cannot be empty! <a href="?">back</a>');
+
+ // user data
+ $filename = $PNG_TEMP_DIR.'test'.md5($_REQUEST['data'].'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
+ QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel, $matrixPointSize, 2);
+
+ } else {
+
+ //default data
+ echo 'You can provide data in GET parameter: <a href="?data=like_that">like that</a><hr/>';
+ QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
+
+ }
+
+ //display generated file
+ echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
+
+ //config form
+ echo '<form action="index.php" method="post">
+ Data:&nbsp;<input name="data" value="'.(isset($_REQUEST['data'])?htmlspecialchars($_REQUEST['data']):'PHP QR Code :)').'" />&nbsp;
+ ECC:&nbsp;<select name="level">
+ <option value="L"'.(($errorCorrectionLevel=='L')?' selected':'').'>L - smallest</option>
+ <option value="M"'.(($errorCorrectionLevel=='M')?' selected':'').'>M</option>
+ <option value="Q"'.(($errorCorrectionLevel=='Q')?' selected':'').'>Q</option>
+ <option value="H"'.(($errorCorrectionLevel=='H')?' selected':'').'>H - best</option>
+ </select>&nbsp;
+ Size:&nbsp;<select name="size">';
+
+ for($i=1;$i<=10;$i++)
+ echo '<option value="'.$i.'"'.(($matrixPointSize==$i)?' selected':'').'>'.$i.'</option>';
+
+ echo '</select>&nbsp;
+ <input type="submit" value="GENERATE"></form><hr/>';
+
+ // benchmark
+ QRtools::timeBenchmark();
+
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/phpqrcode.php b/admin/survey/classes/phpqrcode/phpqrcode.php
new file mode 100644
index 0000000..13307b6
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/phpqrcode.php
@@ -0,0 +1,3312 @@
+<?php
+
+/*
+ * PHP QR Code encoder
+ *
+ * This file contains MERGED version of PHP QR Code library.
+ * It was auto-generated from full version for your convenience.
+ *
+ * This merged version was configured to not requre any external files,
+ * with disabled cache, error loging and weker but faster mask matching.
+ * If you need tune it up please use non-merged version.
+ *
+ * For full version, documentation, examples of use please visit:
+ *
+ * http://phpqrcode.sourceforge.net/
+ * https://sourceforge.net/projects/phpqrcode/
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+
+/*
+ * Version: 1.1.4
+ * Build: 2010100721
+ */
+
+
+
+//---- qrconst.php -----------------------------
+
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Common constants
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ // Encoding modes
+
+ define('QR_MODE_NUL', -1);
+ define('QR_MODE_NUM', 0);
+ define('QR_MODE_AN', 1);
+ define('QR_MODE_8', 2);
+ define('QR_MODE_KANJI', 3);
+ define('QR_MODE_STRUCTURE', 4);
+
+ // Levels of error correction.
+
+ define('QR_ECLEVEL_L', 0);
+ define('QR_ECLEVEL_M', 1);
+ define('QR_ECLEVEL_Q', 2);
+ define('QR_ECLEVEL_H', 3);
+
+ // Supported output formats
+
+ define('QR_FORMAT_TEXT', 0);
+ define('QR_FORMAT_PNG', 1);
+
+ class qrstr {
+ public static function set(&$srctab, $x, $y, $repl, $replLen = false) {
+ $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));
+ }
+ }
+
+
+
+//---- merged_config.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Config file, tuned-up for merged verion
+ */
+
+ define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there
+ define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true
+ define('QR_LOG_DIR', false); // default error logs dir
+
+ define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
+ define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
+ define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false
+
+ define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images
+
+
+
+
+//---- qrtools.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Toolset, handy and debug utilites.
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRtools {
+
+ //----------------------------------------------------------------------
+ public static function binarize($frame)
+ {
+ $len = count($frame);
+ foreach ($frame as &$frameLine) {
+
+ for($i=0; $i<$len; $i++) {
+ $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';
+ }
+ }
+
+ return $frame;
+ }
+
+ //----------------------------------------------------------------------
+ public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037')
+ {
+ $barcode_array = array();
+
+ if (!is_array($mode))
+ $mode = explode(',', $mode);
+
+ $eccLevel = 'L';
+
+ if (count($mode) > 1) {
+ $eccLevel = $mode[1];
+ }
+
+ $qrTab = QRcode::text($code, false, $eccLevel);
+ $size = count($qrTab);
+
+ $barcode_array['num_rows'] = $size;
+ $barcode_array['num_cols'] = $size;
+ $barcode_array['bcode'] = array();
+
+ foreach ($qrTab as $line) {
+ $arrAdd = array();
+ foreach(str_split($line) as $char)
+ $arrAdd[] = ($char=='1')?1:0;
+ $barcode_array['bcode'][] = $arrAdd;
+ }
+
+ return $barcode_array;
+ }
+
+ //----------------------------------------------------------------------
+ public static function clearCache()
+ {
+ self::$frames = array();
+ }
+
+ //----------------------------------------------------------------------
+ public static function buildCache()
+ {
+ QRtools::markTime('before_build_cache');
+
+ $mask = new QRmask();
+ for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) {
+ $frame = QRspec::newFrame($a);
+ if (QR_IMAGE) {
+ $fileName = QR_CACHE_DIR.'frame_'.$a.'.png';
+ QRimage::png(self::binarize($frame), $fileName, 1, 0);
+ }
+
+ $width = count($frame);
+ $bitMask = array_fill(0, $width, array_fill(0, $width, 0));
+ for ($maskNo=0; $maskNo<8; $maskNo++)
+ $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true);
+ }
+
+ QRtools::markTime('after_build_cache');
+ }
+
+ //----------------------------------------------------------------------
+ public static function log($outfile, $err)
+ {
+ if (QR_LOG_DIR !== false) {
+ if ($err != '') {
+ if ($outfile !== false) {
+ file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
+ } else {
+ file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
+ }
+ }
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function dumpMask($frame)
+ {
+ $width = count($frame);
+ for($y=0;$y<$width;$y++) {
+ for($x=0;$x<$width;$x++) {
+ echo ord($frame[$y][$x]).',';
+ }
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function markTime($markerId)
+ {
+ list($usec, $sec) = explode(" ", microtime());
+ $time = ((float)$usec + (float)$sec);
+
+ if (!isset($GLOBALS['qr_time_bench']))
+ $GLOBALS['qr_time_bench'] = array();
+
+ $GLOBALS['qr_time_bench'][$markerId] = $time;
+ }
+
+ //----------------------------------------------------------------------
+ public static function timeBenchmark()
+ {
+ self::markTime('finish');
+
+ $lastTime = 0;
+ $startTime = 0;
+ $p = 0;
+
+ echo '<table cellpadding="3" cellspacing="1">
+ <thead><tr style="border-bottom:1px solid silver"><td colspan="2" style="text-align:center">BENCHMARK</td></tr></thead>
+ <tbody>';
+
+ foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) {
+ if ($p > 0) {
+ echo '<tr><th style="text-align:right">till '.$markerId.': </th><td>'.number_format($thisTime-$lastTime, 6).'s</td></tr>';
+ } else {
+ $startTime = $thisTime;
+ }
+
+ $p++;
+ $lastTime = $thisTime;
+ }
+
+ echo '</tbody><tfoot>
+ <tr style="border-top:2px solid black"><th style="text-align:right">TOTAL: </th><td>'.number_format($lastTime-$startTime, 6).'s</td></tr>
+ </tfoot>
+ </table>';
+ }
+
+ }
+
+ //##########################################################################
+
+ QRtools::markTime('start');
+
+
+
+
+//---- qrspec.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * QR Code specifications
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * The following data / specifications are taken from
+ * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
+ * or
+ * "Automatic identification and data capture techniques --
+ * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('QRSPEC_VERSION_MAX', 40);
+ define('QRSPEC_WIDTH_MAX', 177);
+
+ define('QRCAP_WIDTH', 0);
+ define('QRCAP_WORDS', 1);
+ define('QRCAP_REMINDER', 2);
+ define('QRCAP_EC', 3);
+
+ class QRspec {
+
+ public static $capacity = array(
+ array( 0, 0, 0, array( 0, 0, 0, 0)),
+ array( 21, 26, 0, array( 7, 10, 13, 17)), // 1
+ array( 25, 44, 7, array( 10, 16, 22, 28)),
+ array( 29, 70, 7, array( 15, 26, 36, 44)),
+ array( 33, 100, 7, array( 20, 36, 52, 64)),
+ array( 37, 134, 7, array( 26, 48, 72, 88)), // 5
+ array( 41, 172, 7, array( 36, 64, 96, 112)),
+ array( 45, 196, 0, array( 40, 72, 108, 130)),
+ array( 49, 242, 0, array( 48, 88, 132, 156)),
+ array( 53, 292, 0, array( 60, 110, 160, 192)),
+ array( 57, 346, 0, array( 72, 130, 192, 224)), //10
+ array( 61, 404, 0, array( 80, 150, 224, 264)),
+ array( 65, 466, 0, array( 96, 176, 260, 308)),
+ array( 69, 532, 0, array( 104, 198, 288, 352)),
+ array( 73, 581, 3, array( 120, 216, 320, 384)),
+ array( 77, 655, 3, array( 132, 240, 360, 432)), //15
+ array( 81, 733, 3, array( 144, 280, 408, 480)),
+ array( 85, 815, 3, array( 168, 308, 448, 532)),
+ array( 89, 901, 3, array( 180, 338, 504, 588)),
+ array( 93, 991, 3, array( 196, 364, 546, 650)),
+ array( 97, 1085, 3, array( 224, 416, 600, 700)), //20
+ array(101, 1156, 4, array( 224, 442, 644, 750)),
+ array(105, 1258, 4, array( 252, 476, 690, 816)),
+ array(109, 1364, 4, array( 270, 504, 750, 900)),
+ array(113, 1474, 4, array( 300, 560, 810, 960)),
+ array(117, 1588, 4, array( 312, 588, 870, 1050)), //25
+ array(121, 1706, 4, array( 336, 644, 952, 1110)),
+ array(125, 1828, 4, array( 360, 700, 1020, 1200)),
+ array(129, 1921, 3, array( 390, 728, 1050, 1260)),
+ array(133, 2051, 3, array( 420, 784, 1140, 1350)),
+ array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30
+ array(141, 2323, 3, array( 480, 868, 1290, 1530)),
+ array(145, 2465, 3, array( 510, 924, 1350, 1620)),
+ array(149, 2611, 3, array( 540, 980, 1440, 1710)),
+ array(153, 2761, 3, array( 570, 1036, 1530, 1800)),
+ array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35
+ array(161, 3034, 0, array( 600, 1120, 1680, 1980)),
+ array(165, 3196, 0, array( 630, 1204, 1770, 2100)),
+ array(169, 3362, 0, array( 660, 1260, 1860, 2220)),
+ array(173, 3532, 0, array( 720, 1316, 1950, 2310)),
+ array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40
+ );
+
+ //----------------------------------------------------------------------
+ public static function getDataLength($version, $level)
+ {
+ return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getECCLength($version, $level)
+ {
+ return self::$capacity[$version][QRCAP_EC][$level];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getWidth($version)
+ {
+ return self::$capacity[$version][QRCAP_WIDTH];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getRemainder($version)
+ {
+ return self::$capacity[$version][QRCAP_REMINDER];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getMinimumVersion($size, $level)
+ {
+
+ for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) {
+ $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level];
+ if($words >= $size)
+ return $i;
+ }
+
+ return -1;
+ }
+
+ //######################################################################
+
+ public static $lengthTableBits = array(
+ array(10, 12, 14),
+ array( 9, 11, 13),
+ array( 8, 16, 16),
+ array( 8, 10, 12)
+ );
+
+ //----------------------------------------------------------------------
+ public static function lengthIndicator($mode, $version)
+ {
+ if ($mode == QR_MODE_STRUCTURE)
+ return 0;
+
+ if ($version <= 9) {
+ $l = 0;
+ } else if ($version <= 26) {
+ $l = 1;
+ } else {
+ $l = 2;
+ }
+
+ return self::$lengthTableBits[$mode][$l];
+ }
+
+ //----------------------------------------------------------------------
+ public static function maximumWords($mode, $version)
+ {
+ if($mode == QR_MODE_STRUCTURE)
+ return 3;
+
+ if($version <= 9) {
+ $l = 0;
+ } else if($version <= 26) {
+ $l = 1;
+ } else {
+ $l = 2;
+ }
+
+ $bits = self::$lengthTableBits[$mode][$l];
+ $words = (1 << $bits) - 1;
+
+ if($mode == QR_MODE_KANJI) {
+ $words *= 2; // the number of bytes is required
+ }
+
+ return $words;
+ }
+
+ // Error correction code -----------------------------------------------
+ // Table of the error correction code (Reed-Solomon block)
+ // See Table 12-16 (pp.30-36), JIS X0510:2004.
+
+ public static $eccTable = array(
+ array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)),
+ array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1
+ array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)),
+ array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)),
+ array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)),
+ array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5
+ array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)),
+ array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)),
+ array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)),
+ array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)),
+ array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10
+ array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)),
+ array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)),
+ array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)),
+ array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)),
+ array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15
+ array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)),
+ array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)),
+ array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)),
+ array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)),
+ array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20
+ array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)),
+ array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)),
+ array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)),
+ array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)),
+ array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25
+ array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)),
+ array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)),
+ array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)),
+ array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)),
+ array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30
+ array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)),
+ array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)),
+ array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)),
+ array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)),
+ array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35
+ array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)),
+ array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)),
+ array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)),
+ array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)),
+ array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40
+ );
+
+ //----------------------------------------------------------------------
+ // CACHEABLE!!!
+
+ public static function getEccSpec($version, $level, array &$spec)
+ {
+ if (count($spec) < 5) {
+ $spec = array(0,0,0,0,0);
+ }
+
+ $b1 = self::$eccTable[$version][$level][0];
+ $b2 = self::$eccTable[$version][$level][1];
+ $data = self::getDataLength($version, $level);
+ $ecc = self::getECCLength($version, $level);
+
+ if($b2 == 0) {
+ $spec[0] = $b1;
+ $spec[1] = (int)($data / $b1);
+ $spec[2] = (int)($ecc / $b1);
+ $spec[3] = 0;
+ $spec[4] = 0;
+ } else {
+ $spec[0] = $b1;
+ $spec[1] = (int)($data / ($b1 + $b2));
+ $spec[2] = (int)($ecc / ($b1 + $b2));
+ $spec[3] = $b2;
+ $spec[4] = $spec[1] + 1;
+ }
+ }
+
+ // Alignment pattern ---------------------------------------------------
+
+ // Positions of alignment patterns.
+ // This array includes only the second and the third position of the
+ // alignment patterns. Rest of them can be calculated from the distance
+ // between them.
+
+ // See Table 1 in Appendix E (pp.71) of JIS X0510:2004.
+
+ public static $alignmentPattern = array(
+ array( 0, 0),
+ array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5
+ array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10
+ array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15
+ array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20
+ array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25
+ array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30
+ array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35
+ array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40
+ );
+
+
+ /** --------------------------------------------------------------------
+ * Put an alignment marker.
+ * @param frame
+ * @param width
+ * @param ox,oy center coordinate of the pattern
+ */
+ public static function putAlignmentMarker(array &$frame, $ox, $oy)
+ {
+ $finder = array(
+ "\xa1\xa1\xa1\xa1\xa1",
+ "\xa1\xa0\xa0\xa0\xa1",
+ "\xa1\xa0\xa1\xa0\xa1",
+ "\xa1\xa0\xa0\xa0\xa1",
+ "\xa1\xa1\xa1\xa1\xa1"
+ );
+
+ $yStart = $oy-2;
+ $xStart = $ox-2;
+
+ for($y=0; $y<5; $y++) {
+ QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function putAlignmentPattern($version, &$frame, $width)
+ {
+ if($version < 2)
+ return;
+
+ $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0];
+ if($d < 0) {
+ $w = 2;
+ } else {
+ $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2);
+ }
+
+ if($w * $w - 3 == 1) {
+ $x = self::$alignmentPattern[$version][0];
+ $y = self::$alignmentPattern[$version][0];
+ self::putAlignmentMarker($frame, $x, $y);
+ return;
+ }
+
+ $cx = self::$alignmentPattern[$version][0];
+ for($x=1; $x<$w - 1; $x++) {
+ self::putAlignmentMarker($frame, 6, $cx);
+ self::putAlignmentMarker($frame, $cx, 6);
+ $cx += $d;
+ }
+
+ $cy = self::$alignmentPattern[$version][0];
+ for($y=0; $y<$w-1; $y++) {
+ $cx = self::$alignmentPattern[$version][0];
+ for($x=0; $x<$w-1; $x++) {
+ self::putAlignmentMarker($frame, $cx, $cy);
+ $cx += $d;
+ }
+ $cy += $d;
+ }
+ }
+
+ // Version information pattern -----------------------------------------
+
+ // Version information pattern (BCH coded).
+ // See Table 1 in Appendix D (pp.68) of JIS X0510:2004.
+
+ // size: [QRSPEC_VERSION_MAX - 6]
+
+ public static $versionPattern = array(
+ 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d,
+ 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9,
+ 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75,
+ 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64,
+ 0x27541, 0x28c69
+ );
+
+ //----------------------------------------------------------------------
+ public static function getVersionPattern($version)
+ {
+ if($version < 7 || $version > QRSPEC_VERSION_MAX)
+ return 0;
+
+ return self::$versionPattern[$version -7];
+ }
+
+ // Format information --------------------------------------------------
+ // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib)
+
+ public static $formatInfo = array(
+ array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976),
+ array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0),
+ array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed),
+ array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b)
+ );
+
+ public static function getFormatInfo($mask, $level)
+ {
+ if($mask < 0 || $mask > 7)
+ return 0;
+
+ if($level < 0 || $level > 3)
+ return 0;
+
+ return self::$formatInfo[$level][$mask];
+ }
+
+ // Frame ---------------------------------------------------------------
+ // Cache of initial frames.
+
+ public static $frames = array();
+
+ /** --------------------------------------------------------------------
+ * Put a finder pattern.
+ * @param frame
+ * @param width
+ * @param ox,oy upper-left coordinate of the pattern
+ */
+ public static function putFinderPattern(&$frame, $ox, $oy)
+ {
+ $finder = array(
+ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1",
+ "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1"
+ );
+
+ for($y=0; $y<7; $y++) {
+ QRstr::set($frame, $ox, $oy+$y, $finder[$y]);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function createFrame($version)
+ {
+ $width = self::$capacity[$version][QRCAP_WIDTH];
+ $frameLine = str_repeat ("\0", $width);
+ $frame = array_fill(0, $width, $frameLine);
+
+ // Finder pattern
+ self::putFinderPattern($frame, 0, 0);
+ self::putFinderPattern($frame, $width - 7, 0);
+ self::putFinderPattern($frame, 0, $width - 7);
+
+ // Separator
+ $yOffset = $width - 7;
+
+ for($y=0; $y<7; $y++) {
+ $frame[$y][7] = "\xc0";
+ $frame[$y][$width - 8] = "\xc0";
+ $frame[$yOffset][7] = "\xc0";
+ $yOffset++;
+ }
+
+ $setPattern = str_repeat("\xc0", 8);
+
+ QRstr::set($frame, 0, 7, $setPattern);
+ QRstr::set($frame, $width-8, 7, $setPattern);
+ QRstr::set($frame, 0, $width - 8, $setPattern);
+
+ // Format info
+ $setPattern = str_repeat("\x84", 9);
+ QRstr::set($frame, 0, 8, $setPattern);
+ QRstr::set($frame, $width - 8, 8, $setPattern, 8);
+
+ $yOffset = $width - 8;
+
+ for($y=0; $y<8; $y++,$yOffset++) {
+ $frame[$y][8] = "\x84";
+ $frame[$yOffset][8] = "\x84";
+ }
+
+ // Timing pattern
+
+ for($i=1; $i<$width-15; $i++) {
+ $frame[6][7+$i] = chr(0x90 | ($i & 1));
+ $frame[7+$i][6] = chr(0x90 | ($i & 1));
+ }
+
+ // Alignment pattern
+ self::putAlignmentPattern($version, $frame, $width);
+
+ // Version information
+ if($version >= 7) {
+ $vinf = self::getVersionPattern($version);
+
+ $v = $vinf;
+
+ for($x=0; $x<6; $x++) {
+ for($y=0; $y<3; $y++) {
+ $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));
+ $v = $v >> 1;
+ }
+ }
+
+ $v = $vinf;
+ for($y=0; $y<6; $y++) {
+ for($x=0; $x<3; $x++) {
+ $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));
+ $v = $v >> 1;
+ }
+ }
+ }
+
+ // and a little bit...
+ $frame[$width - 8][8] = "\x81";
+
+ return $frame;
+ }
+
+ //----------------------------------------------------------------------
+ public static function debug($frame, $binary_mode = false)
+ {
+ if ($binary_mode) {
+
+ foreach ($frame as &$frameLine) {
+ $frameLine = join('<span class="m">&nbsp;&nbsp;</span>', explode('0', $frameLine));
+ $frameLine = join('&#9608;&#9608;', explode('1', $frameLine));
+ }
+
+ ?>
+ <style>
+ .m { background-color: white; }
+ </style>
+ <?php
+ echo '<pre><tt><br/ ><br/ ><br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+ echo join("<br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $frame);
+ echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >';
+
+ } else {
+
+ foreach ($frame as &$frameLine) {
+ $frameLine = join('<span class="m">&nbsp;</span>', explode("\xc0", $frameLine));
+ $frameLine = join('<span class="m">&#9618;</span>', explode("\xc1", $frameLine));
+ $frameLine = join('<span class="p">&nbsp;</span>', explode("\xa0", $frameLine));
+ $frameLine = join('<span class="p">&#9618;</span>', explode("\xa1", $frameLine));
+ $frameLine = join('<span class="s">&#9671;</span>', explode("\x84", $frameLine)); //format 0
+ $frameLine = join('<span class="s">&#9670;</span>', explode("\x85", $frameLine)); //format 1
+ $frameLine = join('<span class="x">&#9762;</span>', explode("\x81", $frameLine)); //special bit
+ $frameLine = join('<span class="c">&nbsp;</span>', explode("\x90", $frameLine)); //clock 0
+ $frameLine = join('<span class="c">&#9719;</span>', explode("\x91", $frameLine)); //clock 1
+ $frameLine = join('<span class="f">&nbsp;</span>', explode("\x88", $frameLine)); //version
+ $frameLine = join('<span class="f">&#9618;</span>', explode("\x89", $frameLine)); //version
+ $frameLine = join('&#9830;', explode("\x01", $frameLine));
+ $frameLine = join('&#8901;', explode("\0", $frameLine));
+ }
+
+ ?>
+ <style>
+ .p { background-color: yellow; }
+ .m { background-color: #00FF00; }
+ .s { background-color: #FF0000; }
+ .c { background-color: aqua; }
+ .x { background-color: pink; }
+ .f { background-color: gold; }
+ </style>
+ <?php
+ echo "<pre><tt>";
+ echo join("<br/ >", $frame);
+ echo "</tt></pre>";
+
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function serial($frame)
+ {
+ return gzcompress(join("\n", $frame), 9);
+ }
+
+ //----------------------------------------------------------------------
+ public static function unserial($code)
+ {
+ return explode("\n", gzuncompress($code));
+ }
+
+ //----------------------------------------------------------------------
+ public static function newFrame($version)
+ {
+ if($version < 1 || $version > QRSPEC_VERSION_MAX)
+ return null;
+
+ if(!isset(self::$frames[$version])) {
+
+ $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat';
+
+ if (QR_CACHEABLE) {
+ if (file_exists($fileName)) {
+ self::$frames[$version] = self::unserial(file_get_contents($fileName));
+ } else {
+ self::$frames[$version] = self::createFrame($version);
+ file_put_contents($fileName, self::serial(self::$frames[$version]));
+ }
+ } else {
+ self::$frames[$version] = self::createFrame($version);
+ }
+ }
+
+ if(is_null(self::$frames[$version]))
+ return null;
+
+ return self::$frames[$version];
+ }
+
+ //----------------------------------------------------------------------
+ public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; }
+ public static function rsBlockNum1($spec) { return $spec[0]; }
+ public static function rsDataCodes1($spec) { return $spec[1]; }
+ public static function rsEccCodes1($spec) { return $spec[2]; }
+ public static function rsBlockNum2($spec) { return $spec[3]; }
+ public static function rsDataCodes2($spec) { return $spec[4]; }
+ public static function rsEccCodes2($spec) { return $spec[2]; }
+ public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); }
+ public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; }
+
+ }
+
+
+
+//---- qrimage.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Image output of code using GD2
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('QR_IMAGE', true);
+
+ class QRimage {
+
+ //----------------------------------------------------------------------
+ public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)
+ {
+ $image = self::image($frame, $pixelPerPoint, $outerFrame);
+
+ if ($filename === false) {
+ Header("Content-type: image/png");
+ ImagePng($image);
+ } else {
+ if($saveandprint===TRUE){
+ ImagePng($image, $filename);
+ header("Content-type: image/png");
+ ImagePng($image);
+ }else{
+ ImagePng($image, $filename);
+ }
+ }
+
+ ImageDestroy($image);
+ }
+
+ //----------------------------------------------------------------------
+ public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85)
+ {
+ $image = self::image($frame, $pixelPerPoint, $outerFrame);
+
+ if ($filename === false) {
+ Header("Content-type: image/jpeg");
+ ImageJpeg($image, null, $q);
+ } else {
+ ImageJpeg($image, $filename, $q);
+ }
+
+ ImageDestroy($image);
+ }
+
+ //----------------------------------------------------------------------
+ private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4)
+ {
+ $h = count($frame);
+ $w = strlen($frame[0]);
+
+ $imgW = $w + 2*$outerFrame;
+ $imgH = $h + 2*$outerFrame;
+
+ $base_image =ImageCreate($imgW, $imgH);
+
+ $col[0] = ImageColorAllocate($base_image,255,255,255);
+ $col[1] = ImageColorAllocate($base_image,0,0,0);
+
+ imagefill($base_image, 0, 0, $col[0]);
+
+ for($y=0; $y<$h; $y++) {
+ for($x=0; $x<$w; $x++) {
+ if ($frame[$y][$x] == '1') {
+ ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]);
+ }
+ }
+ }
+
+ $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint);
+ ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH);
+ ImageDestroy($base_image);
+
+ return $target_image;
+ }
+ }
+
+
+
+//---- qrinput.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Input encoding class
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('STRUCTURE_HEADER_BITS', 20);
+ define('MAX_STRUCTURED_SYMBOLS', 16);
+
+ class QRinputItem {
+
+ public $mode;
+ public $size;
+ public $data;
+ public $bstream;
+
+ public function __construct($mode, $size, $data, $bstream = null)
+ {
+ $setData = array_slice($data, 0, $size);
+
+ if (count($setData) < $size) {
+ $setData = array_merge($setData, array_fill(0,$size-count($setData),0));
+ }
+
+ if(!QRinput::check($mode, $size, $setData)) {
+ throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData));
+ return null;
+ }
+
+ $this->mode = $mode;
+ $this->size = $size;
+ $this->data = $setData;
+ $this->bstream = $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeNum($version)
+ {
+ try {
+
+ $words = (int)($this->size / 3);
+ $bs = new QRbitstream();
+
+ $val = 0x1;
+ $bs->appendNum(4, $val);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size);
+
+ for($i=0; $i<$words; $i++) {
+ $val = (ord($this->data[$i*3 ]) - ord('0')) * 100;
+ $val += (ord($this->data[$i*3+1]) - ord('0')) * 10;
+ $val += (ord($this->data[$i*3+2]) - ord('0'));
+ $bs->appendNum(10, $val);
+ }
+
+ if($this->size - $words * 3 == 1) {
+ $val = ord($this->data[$words*3]) - ord('0');
+ $bs->appendNum(4, $val);
+ } else if($this->size - $words * 3 == 2) {
+ $val = (ord($this->data[$words*3 ]) - ord('0')) * 10;
+ $val += (ord($this->data[$words*3+1]) - ord('0'));
+ $bs->appendNum(7, $val);
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeAn($version)
+ {
+ try {
+ $words = (int)($this->size / 2);
+ $bs = new QRbitstream();
+
+ $bs->appendNum(4, 0x02);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size);
+
+ for($i=0; $i<$words; $i++) {
+ $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45;
+ $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1]));
+
+ $bs->appendNum(11, $val);
+ }
+
+ if($this->size & 1) {
+ $val = QRinput::lookAnTable(ord($this->data[$words * 2]));
+ $bs->appendNum(6, $val);
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeMode8($version)
+ {
+ try {
+ $bs = new QRbitstream();
+
+ $bs->appendNum(4, 0x4);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size);
+
+ for($i=0; $i<$this->size; $i++) {
+ $bs->appendNum(8, ord($this->data[$i]));
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeKanji($version)
+ {
+ try {
+
+ $bs = new QRbitrtream();
+
+ $bs->appendNum(4, 0x8);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2));
+
+ for($i=0; $i<$this->size; $i+=2) {
+ $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]);
+ if($val <= 0x9ffc) {
+ $val -= 0x8140;
+ } else {
+ $val -= 0xc140;
+ }
+
+ $h = ($val >> 8) * 0xc0;
+ $val = ($val & 0xff) + $h;
+
+ $bs->appendNum(13, $val);
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeStructure()
+ {
+ try {
+ $bs = new QRbitstream();
+
+ $bs->appendNum(4, 0x03);
+ $bs->appendNum(4, ord($this->data[1]) - 1);
+ $bs->appendNum(4, ord($this->data[0]) - 1);
+ $bs->appendNum(8, ord($this->data[2]));
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function estimateBitStreamSizeOfEntry($version)
+ {
+ $bits = 0;
+
+ if($version == 0)
+ $version = 1;
+
+ switch($this->mode) {
+ case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break;
+ case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break;
+ case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break;
+ case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break;
+ case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS;
+ default:
+ return 0;
+ }
+
+ $l = QRspec::lengthIndicator($this->mode, $version);
+ $m = 1 << $l;
+ $num = (int)(($this->size + $m - 1) / $m);
+
+ $bits += $num * (4 + $l);
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeBitStream($version)
+ {
+ try {
+
+ unset($this->bstream);
+ $words = QRspec::maximumWords($this->mode, $version);
+
+ if($this->size > $words) {
+
+ $st1 = new QRinputItem($this->mode, $words, $this->data);
+ $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words));
+
+ $st1->encodeBitStream($version);
+ $st2->encodeBitStream($version);
+
+ $this->bstream = new QRbitstream();
+ $this->bstream->append($st1->bstream);
+ $this->bstream->append($st2->bstream);
+
+ unset($st1);
+ unset($st2);
+
+ } else {
+
+ $ret = 0;
+
+ switch($this->mode) {
+ case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break;
+ case QR_MODE_AN: $ret = $this->encodeModeAn($version); break;
+ case QR_MODE_8: $ret = $this->encodeMode8($version); break;
+ case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break;
+ case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break;
+
+ default:
+ break;
+ }
+
+ if($ret < 0)
+ return -1;
+ }
+
+ return $this->bstream->size();
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+ };
+
+ //##########################################################################
+
+ class QRinput {
+
+ public $items;
+
+ private $version;
+ private $level;
+
+ //----------------------------------------------------------------------
+ public function __construct($version = 0, $level = QR_ECLEVEL_L)
+ {
+ if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) {
+ throw new Exception('Invalid version no');
+ return NULL;
+ }
+
+ $this->version = $version;
+ $this->level = $level;
+ }
+
+ //----------------------------------------------------------------------
+ public function getVersion()
+ {
+ return $this->version;
+ }
+
+ //----------------------------------------------------------------------
+ public function setVersion($version)
+ {
+ if($version < 0 || $version > QRSPEC_VERSION_MAX) {
+ throw new Exception('Invalid version no');
+ return -1;
+ }
+
+ $this->version = $version;
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function getErrorCorrectionLevel()
+ {
+ return $this->level;
+ }
+
+ //----------------------------------------------------------------------
+ public function setErrorCorrectionLevel($level)
+ {
+ if($level > QR_ECLEVEL_H) {
+ throw new Exception('Invalid ECLEVEL');
+ return -1;
+ }
+
+ $this->level = $level;
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendEntry(QRinputItem $entry)
+ {
+ $this->items[] = $entry;
+ }
+
+ //----------------------------------------------------------------------
+ public function append($mode, $size, $data)
+ {
+ try {
+ $entry = new QRinputItem($mode, $size, $data);
+ $this->items[] = $entry;
+ return 0;
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+
+ public function insertStructuredAppendHeader($size, $index, $parity)
+ {
+ if( $size > MAX_STRUCTURED_SYMBOLS ) {
+ throw new Exception('insertStructuredAppendHeader wrong size');
+ }
+
+ if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) {
+ throw new Exception('insertStructuredAppendHeader wrong index');
+ }
+
+ $buf = array($size, $index, $parity);
+
+ try {
+ $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf);
+ array_unshift($this->items, $entry);
+ return 0;
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function calcParity()
+ {
+ $parity = 0;
+
+ foreach($this->items as $item) {
+ if($item->mode != QR_MODE_STRUCTURE) {
+ for($i=$item->size-1; $i>=0; $i--) {
+ $parity ^= $item->data[$i];
+ }
+ }
+ }
+
+ return $parity;
+ }
+
+ //----------------------------------------------------------------------
+ public static function checkModeNum($size, $data)
+ {
+ for($i=0; $i<$size; $i++) {
+ if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ //----------------------------------------------------------------------
+ public static function estimateBitsModeNum($size)
+ {
+ $w = (int)$size / 3;
+ $bits = $w * 10;
+
+ switch($size - $w * 3) {
+ case 1:
+ $bits += 4;
+ break;
+ case 2:
+ $bits += 7;
+ break;
+ default:
+ break;
+ }
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public static $anTable = array(
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1,
+ -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
+ );
+
+ //----------------------------------------------------------------------
+ public static function lookAnTable($c)
+ {
+ return (($c > 127)?-1:self::$anTable[$c]);
+ }
+
+ //----------------------------------------------------------------------
+ public static function checkModeAn($size, $data)
+ {
+ for($i=0; $i<$size; $i++) {
+ if (self::lookAnTable(ord($data[$i])) == -1) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ //----------------------------------------------------------------------
+ public static function estimateBitsModeAn($size)
+ {
+ $w = (int)($size / 2);
+ $bits = $w * 11;
+
+ if($size & 1) {
+ $bits += 6;
+ }
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public static function estimateBitsMode8($size)
+ {
+ return $size * 8;
+ }
+
+ //----------------------------------------------------------------------
+ public function estimateBitsModeKanji($size)
+ {
+ return (int)(($size / 2) * 13);
+ }
+
+ //----------------------------------------------------------------------
+ public static function checkModeKanji($size, $data)
+ {
+ if($size & 1)
+ return false;
+
+ for($i=0; $i<$size; $i+=2) {
+ $val = (ord($data[$i]) << 8) | ord($data[$i+1]);
+ if( $val < 0x8140
+ || ($val > 0x9ffc && $val < 0xe040)
+ || $val > 0xebbf) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /***********************************************************************
+ * Validation
+ **********************************************************************/
+
+ public static function check($mode, $size, $data)
+ {
+ if($size <= 0)
+ return false;
+
+ switch($mode) {
+ case QR_MODE_NUM: return self::checkModeNum($size, $data); break;
+ case QR_MODE_AN: return self::checkModeAn($size, $data); break;
+ case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break;
+ case QR_MODE_8: return true; break;
+ case QR_MODE_STRUCTURE: return true; break;
+
+ default:
+ break;
+ }
+
+ return false;
+ }
+
+
+ //----------------------------------------------------------------------
+ public function estimateBitStreamSize($version)
+ {
+ $bits = 0;
+
+ foreach($this->items as $item) {
+ $bits += $item->estimateBitStreamSizeOfEntry($version);
+ }
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public function estimateVersion()
+ {
+ $version = 0;
+ $prev = 0;
+ do {
+ $prev = $version;
+ $bits = $this->estimateBitStreamSize($prev);
+ $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+ if ($version < 0) {
+ return -1;
+ }
+ } while ($version > $prev);
+
+ return $version;
+ }
+
+ //----------------------------------------------------------------------
+ public static function lengthOfCode($mode, $version, $bits)
+ {
+ $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version);
+ switch($mode) {
+ case QR_MODE_NUM:
+ $chunks = (int)($payload / 10);
+ $remain = $payload - $chunks * 10;
+ $size = $chunks * 3;
+ if($remain >= 7) {
+ $size += 2;
+ } else if($remain >= 4) {
+ $size += 1;
+ }
+ break;
+ case QR_MODE_AN:
+ $chunks = (int)($payload / 11);
+ $remain = $payload - $chunks * 11;
+ $size = $chunks * 2;
+ if($remain >= 6)
+ $size++;
+ break;
+ case QR_MODE_8:
+ $size = (int)($payload / 8);
+ break;
+ case QR_MODE_KANJI:
+ $size = (int)(($payload / 13) * 2);
+ break;
+ case QR_MODE_STRUCTURE:
+ $size = (int)($payload / 8);
+ break;
+ default:
+ $size = 0;
+ break;
+ }
+
+ $maxsize = QRspec::maximumWords($mode, $version);
+ if($size < 0) $size = 0;
+ if($size > $maxsize) $size = $maxsize;
+
+ return $size;
+ }
+
+ //----------------------------------------------------------------------
+ public function createBitStream()
+ {
+ $total = 0;
+
+ foreach($this->items as $item) {
+ $bits = $item->encodeBitStream($this->version);
+
+ if($bits < 0)
+ return -1;
+
+ $total += $bits;
+ }
+
+ return $total;
+ }
+
+ //----------------------------------------------------------------------
+ public function convertData()
+ {
+ $ver = $this->estimateVersion();
+ if($ver > $this->getVersion()) {
+ $this->setVersion($ver);
+ }
+
+ for(;;) {
+ $bits = $this->createBitStream();
+
+ if($bits < 0)
+ return -1;
+
+ $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+ if($ver < 0) {
+ throw new Exception('WRONG VERSION');
+ return -1;
+ } else if($ver > $this->getVersion()) {
+ $this->setVersion($ver);
+ } else {
+ break;
+ }
+ }
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendPaddingBit(&$bstream)
+ {
+ $bits = $bstream->size();
+ $maxwords = QRspec::getDataLength($this->version, $this->level);
+ $maxbits = $maxwords * 8;
+
+ if ($maxbits == $bits) {
+ return 0;
+ }
+
+ if ($maxbits - $bits < 5) {
+ return $bstream->appendNum($maxbits - $bits, 0);
+ }
+
+ $bits += 4;
+ $words = (int)(($bits + 7) / 8);
+
+ $padding = new QRbitstream();
+ $ret = $padding->appendNum($words * 8 - $bits + 4, 0);
+
+ if($ret < 0)
+ return $ret;
+
+ $padlen = $maxwords - $words;
+
+ if($padlen > 0) {
+
+ $padbuf = array();
+ for($i=0; $i<$padlen; $i++) {
+ $padbuf[$i] = ($i&1)?0x11:0xec;
+ }
+
+ $ret = $padding->appendBytes($padlen, $padbuf);
+
+ if($ret < 0)
+ return $ret;
+
+ }
+
+ $ret = $bstream->append($padding);
+
+ return $ret;
+ }
+
+ //----------------------------------------------------------------------
+ public function mergeBitStream()
+ {
+ if($this->convertData() < 0) {
+ return null;
+ }
+
+ $bstream = new QRbitstream();
+
+ foreach($this->items as $item) {
+ $ret = $bstream->append($item->bstream);
+ if($ret < 0) {
+ return null;
+ }
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function getBitStream()
+ {
+
+ $bstream = $this->mergeBitStream();
+
+ if($bstream == null) {
+ return null;
+ }
+
+ $ret = $this->appendPaddingBit($bstream);
+ if($ret < 0) {
+ return null;
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function getByteStream()
+ {
+ $bstream = $this->getBitStream();
+ if($bstream == null) {
+ return null;
+ }
+
+ return $bstream->toByte();
+ }
+ }
+
+
+
+
+
+
+//---- qrbitstream.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Bitstream class
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRbitstream {
+
+ public $data = array();
+
+ //----------------------------------------------------------------------
+ public function size()
+ {
+ return count($this->data);
+ }
+
+ //----------------------------------------------------------------------
+ public function allocate($setLength)
+ {
+ $this->data = array_fill(0, $setLength, 0);
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public static function newFromNum($bits, $num)
+ {
+ $bstream = new QRbitstream();
+ $bstream->allocate($bits);
+
+ $mask = 1 << ($bits - 1);
+ for($i=0; $i<$bits; $i++) {
+ if($num & $mask) {
+ $bstream->data[$i] = 1;
+ } else {
+ $bstream->data[$i] = 0;
+ }
+ $mask = $mask >> 1;
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public static function newFromBytes($size, $data)
+ {
+ $bstream = new QRbitstream();
+ $bstream->allocate($size * 8);
+ $p=0;
+
+ for($i=0; $i<$size; $i++) {
+ $mask = 0x80;
+ for($j=0; $j<8; $j++) {
+ if($data[$i] & $mask) {
+ $bstream->data[$p] = 1;
+ } else {
+ $bstream->data[$p] = 0;
+ }
+ $p++;
+ $mask = $mask >> 1;
+ }
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function append(QRbitstream $arg)
+ {
+ if (is_null($arg)) {
+ return -1;
+ }
+
+ if($arg->size() == 0) {
+ return 0;
+ }
+
+ if($this->size() == 0) {
+ $this->data = $arg->data;
+ return 0;
+ }
+
+ $this->data = array_values(array_merge($this->data, $arg->data));
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendNum($bits, $num)
+ {
+ if ($bits == 0)
+ return 0;
+
+ $b = QRbitstream::newFromNum($bits, $num);
+
+ if(is_null($b))
+ return -1;
+
+ $ret = $this->append($b);
+ unset($b);
+
+ return $ret;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendBytes($size, $data)
+ {
+ if ($size == 0)
+ return 0;
+
+ $b = QRbitstream::newFromBytes($size, $data);
+
+ if(is_null($b))
+ return -1;
+
+ $ret = $this->append($b);
+ unset($b);
+
+ return $ret;
+ }
+
+ //----------------------------------------------------------------------
+ public function toByte()
+ {
+
+ $size = $this->size();
+
+ if($size == 0) {
+ return array();
+ }
+
+ $data = array_fill(0, (int)(($size + 7) / 8), 0);
+ $bytes = (int)($size / 8);
+
+ $p = 0;
+
+ for($i=0; $i<$bytes; $i++) {
+ $v = 0;
+ for($j=0; $j<8; $j++) {
+ $v = $v << 1;
+ $v |= $this->data[$p];
+ $p++;
+ }
+ $data[$i] = $v;
+ }
+
+ if($size & 7) {
+ $v = 0;
+ for($j=0; $j<($size & 7); $j++) {
+ $v = $v << 1;
+ $v |= $this->data[$p];
+ $p++;
+ }
+ $data[$bytes] = $v;
+ }
+
+ return $data;
+ }
+
+ }
+
+
+
+
+//---- qrsplit.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Input splitting classes
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * The following data / specifications are taken from
+ * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
+ * or
+ * "Automatic identification and data capture techniques --
+ * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+ class QRsplit {
+
+ public $dataStr = '';
+ public $input;
+ public $modeHint;
+
+ //----------------------------------------------------------------------
+ public function __construct($dataStr, $input, $modeHint)
+ {
+ $this->dataStr = $dataStr;
+ $this->input = $input;
+ $this->modeHint = $modeHint;
+ }
+
+ //----------------------------------------------------------------------
+ public static function isdigitat($str, $pos)
+ {
+ if ($pos >= strlen($str))
+ return false;
+
+ return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9')));
+ }
+
+ //----------------------------------------------------------------------
+ public static function isalnumat($str, $pos)
+ {
+ if ($pos >= strlen($str))
+ return false;
+
+ return (QRinput::lookAnTable(ord($str[$pos])) >= 0);
+ }
+
+ //----------------------------------------------------------------------
+ public function identifyMode($pos)
+ {
+ if ($pos >= strlen($this->dataStr))
+ return QR_MODE_NUL;
+
+ $c = $this->dataStr[$pos];
+
+ if(self::isdigitat($this->dataStr, $pos)) {
+ return QR_MODE_NUM;
+ } else if(self::isalnumat($this->dataStr, $pos)) {
+ return QR_MODE_AN;
+ } else if($this->modeHint == QR_MODE_KANJI) {
+
+ if ($pos+1 < strlen($this->dataStr))
+ {
+ $d = $this->dataStr[$pos+1];
+ $word = (ord($c) << 8) | ord($d);
+ if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) {
+ return QR_MODE_KANJI;
+ }
+ }
+ }
+
+ return QR_MODE_8;
+ }
+
+ //----------------------------------------------------------------------
+ public function eatNum()
+ {
+ $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
+
+ $p = 0;
+ while(self::isdigitat($this->dataStr, $p)) {
+ $p++;
+ }
+
+ $run = $p;
+ $mode = $this->identifyMode($p);
+
+ if($mode == QR_MODE_8) {
+ $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln
+ + QRinput::estimateBitsMode8(1) // + 4 + l8
+ - QRinput::estimateBitsMode8($run + 1); // - 4 - l8
+ if($dif > 0) {
+ return $this->eat8();
+ }
+ }
+ if($mode == QR_MODE_AN) {
+ $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln
+ + QRinput::estimateBitsModeAn(1) // + 4 + la
+ - QRinput::estimateBitsModeAn($run + 1);// - 4 - la
+ if($dif > 0) {
+ return $this->eatAn();
+ }
+ }
+
+ $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr));
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function eatAn()
+ {
+ $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());
+ $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
+
+ $p = 0;
+
+ while(self::isalnumat($this->dataStr, $p)) {
+ if(self::isdigitat($this->dataStr, $p)) {
+ $q = $p;
+ while(self::isdigitat($this->dataStr, $q)) {
+ $q++;
+ }
+
+ $dif = QRinput::estimateBitsModeAn($p) // + 4 + la
+ + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln
+ - QRinput::estimateBitsModeAn($q); // - 4 - la
+
+ if($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else {
+ $p++;
+ }
+ }
+
+ $run = $p;
+
+ if(!self::isalnumat($this->dataStr, $p)) {
+ $dif = QRinput::estimateBitsModeAn($run) + 4 + $la
+ + QRinput::estimateBitsMode8(1) // + 4 + l8
+ - QRinput::estimateBitsMode8($run + 1); // - 4 - l8
+ if($dif > 0) {
+ return $this->eat8();
+ }
+ }
+
+ $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr));
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function eatKanji()
+ {
+ $p = 0;
+
+ while($this->identifyMode($p) == QR_MODE_KANJI) {
+ $p += 2;
+ }
+
+ $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr));
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function eat8()
+ {
+ $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());
+ $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
+
+ $p = 1;
+ $dataStrLen = strlen($this->dataStr);
+
+ while($p < $dataStrLen) {
+
+ $mode = $this->identifyMode($p);
+ if($mode == QR_MODE_KANJI) {
+ break;
+ }
+ if($mode == QR_MODE_NUM) {
+ $q = $p;
+ while(self::isdigitat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = QRinput::estimateBitsMode8($p) // + 4 + l8
+ + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln
+ - QRinput::estimateBitsMode8($q); // - 4 - l8
+ if($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else if($mode == QR_MODE_AN) {
+ $q = $p;
+ while(self::isalnumat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = QRinput::estimateBitsMode8($p) // + 4 + l8
+ + QRinput::estimateBitsModeAn($q - $p) + 4 + $la
+ - QRinput::estimateBitsMode8($q); // - 4 - l8
+ if($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else {
+ $p++;
+ }
+ }
+
+ $run = $p;
+ $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr));
+
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function splitString()
+ {
+ while (strlen($this->dataStr) > 0)
+ {
+ if($this->dataStr == '')
+ return 0;
+
+ $mode = $this->identifyMode(0);
+
+ switch ($mode) {
+ case QR_MODE_NUM: $length = $this->eatNum(); break;
+ case QR_MODE_AN: $length = $this->eatAn(); break;
+ case QR_MODE_KANJI:
+ if ($hint == QR_MODE_KANJI)
+ $length = $this->eatKanji();
+ else $length = $this->eat8();
+ break;
+ default: $length = $this->eat8(); break;
+
+ }
+
+ if($length == 0) return 0;
+ if($length < 0) return -1;
+
+ $this->dataStr = substr($this->dataStr, $length);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function toUpper()
+ {
+ $stringLen = strlen($this->dataStr);
+ $p = 0;
+
+ while ($p<$stringLen) {
+ $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint);
+ if($mode == QR_MODE_KANJI) {
+ $p += 2;
+ } else {
+ if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) {
+ $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32);
+ }
+ $p++;
+ }
+ }
+
+ return $this->dataStr;
+ }
+
+ //----------------------------------------------------------------------
+ public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true)
+ {
+ if(is_null($string) || $string == '\0' || $string == '') {
+ throw new Exception('empty string!!!');
+ }
+
+ $split = new QRsplit($string, $input, $modeHint);
+
+ if(!$casesensitive)
+ $split->toUpper();
+
+ return $split->splitString();
+ }
+ }
+
+
+
+//---- qrrscode.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Reed-Solomon error correction support
+ *
+ * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q
+ * (libfec is released under the GNU Lesser General Public License.)
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRrsItem {
+
+ public $mm; // Bits per symbol
+ public $nn; // Symbols per block (= (1<<mm)-1)
+ public $alpha_to = array(); // log lookup table
+ public $index_of = array(); // Antilog lookup table
+ public $genpoly = array(); // Generator polynomial
+ public $nroots; // Number of generator roots = number of parity symbols
+ public $fcr; // First consecutive root, index form
+ public $prim; // Primitive element, index form
+ public $iprim; // prim-th root of 1, index form
+ public $pad; // Padding bytes in shortened block
+ public $gfpoly;
+
+ //----------------------------------------------------------------------
+ public function modnn($x)
+ {
+ while ($x >= $this->nn) {
+ $x -= $this->nn;
+ $x = ($x >> $this->mm) + ($x & $this->nn);
+ }
+
+ return $x;
+ }
+
+ //----------------------------------------------------------------------
+ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)
+ {
+ // Common code for intializing a Reed-Solomon control block (char or int symbols)
+ // Copyright 2004 Phil Karn, KA9Q
+ // May be used under the terms of the GNU Lesser General Public License (LGPL)
+
+ $rs = null;
+
+ // Check parameter ranges
+ if($symsize < 0 || $symsize > 8) return $rs;
+ if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs;
+ if($prim <= 0 || $prim >= (1<<$symsize)) return $rs;
+ if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values!
+ if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding
+
+ $rs = new QRrsItem();
+ $rs->mm = $symsize;
+ $rs->nn = (1<<$symsize)-1;
+ $rs->pad = $pad;
+
+ $rs->alpha_to = array_fill(0, $rs->nn+1, 0);
+ $rs->index_of = array_fill(0, $rs->nn+1, 0);
+
+ // PHP style macro replacement ;)
+ $NN =& $rs->nn;
+ $A0 =& $NN;
+
+ // Generate Galois field lookup tables
+ $rs->index_of[0] = $A0; // log(zero) = -inf
+ $rs->alpha_to[$A0] = 0; // alpha**-inf = 0
+ $sr = 1;
+
+ for($i=0; $i<$rs->nn; $i++) {
+ $rs->index_of[$sr] = $i;
+ $rs->alpha_to[$i] = $sr;
+ $sr <<= 1;
+ if($sr & (1<<$symsize)) {
+ $sr ^= $gfpoly;
+ }
+ $sr &= $rs->nn;
+ }
+
+ if($sr != 1){
+ // field generator polynomial is not primitive!
+ $rs = NULL;
+ return $rs;
+ }
+
+ /* Form RS code generator polynomial from its roots */
+ $rs->genpoly = array_fill(0, $nroots+1, 0);
+
+ $rs->fcr = $fcr;
+ $rs->prim = $prim;
+ $rs->nroots = $nroots;
+ $rs->gfpoly = $gfpoly;
+
+ /* Find prim-th root of 1, used in decoding */
+ for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn)
+ ; // intentional empty-body loop!
+
+ $rs->iprim = (int)($iprim / $prim);
+ $rs->genpoly[0] = 1;
+
+ for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) {
+ $rs->genpoly[$i+1] = 1;
+
+ // Multiply rs->genpoly[] by @**(root + x)
+ for ($j = $i; $j > 0; $j--) {
+ if ($rs->genpoly[$j] != 0) {
+ $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)];
+ } else {
+ $rs->genpoly[$j] = $rs->genpoly[$j-1];
+ }
+ }
+ // rs->genpoly[0] can never be zero
+ $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)];
+ }
+
+ // convert rs->genpoly[] to index form for quicker encoding
+ for ($i = 0; $i <= $nroots; $i++)
+ $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]];
+
+ return $rs;
+ }
+
+ //----------------------------------------------------------------------
+ public function encode_rs_char($data, &$parity)
+ {
+ $MM =& $this->mm;
+ $NN =& $this->nn;
+ $ALPHA_TO =& $this->alpha_to;
+ $INDEX_OF =& $this->index_of;
+ $GENPOLY =& $this->genpoly;
+ $NROOTS =& $this->nroots;
+ $FCR =& $this->fcr;
+ $PRIM =& $this->prim;
+ $IPRIM =& $this->iprim;
+ $PAD =& $this->pad;
+ $A0 =& $NN;
+
+ $parity = array_fill(0, $NROOTS, 0);
+
+ for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) {
+
+ $feedback = $INDEX_OF[$data[$i] ^ $parity[0]];
+ if($feedback != $A0) {
+ // feedback term is non-zero
+
+ // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must
+ // always be for the polynomials constructed by init_rs()
+ $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback);
+
+ for($j=1;$j<$NROOTS;$j++) {
+ $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])];
+ }
+ }
+
+ // Shift
+ array_shift($parity);
+ if($feedback != $A0) {
+ array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]);
+ } else {
+ array_push($parity, 0);
+ }
+ }
+ }
+ }
+
+ //##########################################################################
+
+ class QRrs {
+
+ public static $items = array();
+
+ //----------------------------------------------------------------------
+ public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)
+ {
+ foreach(self::$items as $rs) {
+ if($rs->pad != $pad) continue;
+ if($rs->nroots != $nroots) continue;
+ if($rs->mm != $symsize) continue;
+ if($rs->gfpoly != $gfpoly) continue;
+ if($rs->fcr != $fcr) continue;
+ if($rs->prim != $prim) continue;
+
+ return $rs;
+ }
+
+ $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad);
+ array_unshift(self::$items, $rs);
+
+ return $rs;
+ }
+ }
+
+
+
+//---- qrmask.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Masking
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('N1', 3);
+ define('N2', 3);
+ define('N3', 40);
+ define('N4', 10);
+
+ class QRmask {
+
+ public $runLength = array();
+
+ //----------------------------------------------------------------------
+ public function __construct()
+ {
+ $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0);
+ }
+
+ //----------------------------------------------------------------------
+ public function writeFormatInformation($width, &$frame, $mask, $level)
+ {
+ $blacks = 0;
+ $format = QRspec::getFormatInfo($mask, $level);
+
+ for($i=0; $i<8; $i++) {
+ if($format & 1) {
+ $blacks += 2;
+ $v = 0x85;
+ } else {
+ $v = 0x84;
+ }
+
+ $frame[8][$width - 1 - $i] = chr($v);
+ if($i < 6) {
+ $frame[$i][8] = chr($v);
+ } else {
+ $frame[$i + 1][8] = chr($v);
+ }
+ $format = $format >> 1;
+ }
+
+ for($i=0; $i<7; $i++) {
+ if($format & 1) {
+ $blacks += 2;
+ $v = 0x85;
+ } else {
+ $v = 0x84;
+ }
+
+ $frame[$width - 7 + $i][8] = chr($v);
+ if($i == 0) {
+ $frame[8][7] = chr($v);
+ } else {
+ $frame[8][6 - $i] = chr($v);
+ }
+
+ $format = $format >> 1;
+ }
+
+ return $blacks;
+ }
+
+ //----------------------------------------------------------------------
+ public function mask0($x, $y) { return ($x+$y)&1; }
+ public function mask1($x, $y) { return ($y&1); }
+ public function mask2($x, $y) { return ($x%3); }
+ public function mask3($x, $y) { return ($x+$y)%3; }
+ public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; }
+ public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; }
+ public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; }
+ public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; }
+
+ //----------------------------------------------------------------------
+ private function generateMaskNo($maskNo, $width, $frame)
+ {
+ $bitMask = array_fill(0, $width, array_fill(0, $width, 0));
+
+ for($y=0; $y<$width; $y++) {
+ for($x=0; $x<$width; $x++) {
+ if(ord($frame[$y][$x]) & 0x80) {
+ $bitMask[$y][$x] = 0;
+ } else {
+ $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y);
+ $bitMask[$y][$x] = ($maskFunc == 0)?1:0;
+ }
+
+ }
+ }
+
+ return $bitMask;
+ }
+
+ //----------------------------------------------------------------------
+ public static function serial($bitFrame)
+ {
+ $codeArr = array();
+
+ foreach ($bitFrame as $line)
+ $codeArr[] = join('', $line);
+
+ return gzcompress(join("\n", $codeArr), 9);
+ }
+
+ //----------------------------------------------------------------------
+ public static function unserial($code)
+ {
+ $codeArr = array();
+
+ $codeLines = explode("\n", gzuncompress($code));
+ foreach ($codeLines as $line)
+ $codeArr[] = str_split($line);
+
+ return $codeArr;
+ }
+
+ //----------------------------------------------------------------------
+ public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false)
+ {
+ $b = 0;
+ $bitMask = array();
+
+ $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat';
+
+ if (QR_CACHEABLE) {
+ if (file_exists($fileName)) {
+ $bitMask = self::unserial(file_get_contents($fileName));
+ } else {
+ $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
+ if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo))
+ mkdir(QR_CACHE_DIR.'mask_'.$maskNo);
+ file_put_contents($fileName, self::serial($bitMask));
+ }
+ } else {
+ $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
+ }
+
+ if ($maskGenOnly)
+ return;
+
+ $d = $s;
+
+ for($y=0; $y<$width; $y++) {
+ for($x=0; $x<$width; $x++) {
+ if($bitMask[$y][$x] == 1) {
+ $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]);
+ }
+ $b += (int)(ord($d[$y][$x]) & 1);
+ }
+ }
+
+ return $b;
+ }
+
+ //----------------------------------------------------------------------
+ public function makeMask($width, $frame, $maskNo, $level)
+ {
+ $masked = array_fill(0, $width, str_repeat("\0", $width));
+ $this->makeMaskNo($maskNo, $width, $frame, $masked);
+ $this->writeFormatInformation($width, $masked, $maskNo, $level);
+
+ return $masked;
+ }
+
+ //----------------------------------------------------------------------
+ public function calcN1N3($length)
+ {
+ $demerit = 0;
+
+ for($i=0; $i<$length; $i++) {
+
+ if($this->runLength[$i] >= 5) {
+ $demerit += (N1 + ($this->runLength[$i] - 5));
+ }
+ if($i & 1) {
+ if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) {
+ $fact = (int)($this->runLength[$i] / 3);
+ if(($this->runLength[$i-2] == $fact) &&
+ ($this->runLength[$i-1] == $fact) &&
+ ($this->runLength[$i+1] == $fact) &&
+ ($this->runLength[$i+2] == $fact)) {
+ if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) {
+ $demerit += N3;
+ } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) {
+ $demerit += N3;
+ }
+ }
+ }
+ }
+ }
+ return $demerit;
+ }
+
+ //----------------------------------------------------------------------
+ public function evaluateSymbol($width, $frame)
+ {
+ $head = 0;
+ $demerit = 0;
+
+ for($y=0; $y<$width; $y++) {
+ $head = 0;
+ $this->runLength[0] = 1;
+
+ $frameY = $frame[$y];
+
+ if ($y>0)
+ $frameYM = $frame[$y-1];
+
+ for($x=0; $x<$width; $x++) {
+ if(($x > 0) && ($y > 0)) {
+ $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]);
+ $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]);
+
+ if(($b22 | ($w22 ^ 1))&1) {
+ $demerit += N2;
+ }
+ }
+ if(($x == 0) && (ord($frameY[$x]) & 1)) {
+ $this->runLength[0] = -1;
+ $head = 1;
+ $this->runLength[$head] = 1;
+ } else if($x > 0) {
+ if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) {
+ $head++;
+ $this->runLength[$head] = 1;
+ } else {
+ $this->runLength[$head]++;
+ }
+ }
+ }
+
+ $demerit += $this->calcN1N3($head+1);
+ }
+
+ for($x=0; $x<$width; $x++) {
+ $head = 0;
+ $this->runLength[0] = 1;
+
+ for($y=0; $y<$width; $y++) {
+ if($y == 0 && (ord($frame[$y][$x]) & 1)) {
+ $this->runLength[0] = -1;
+ $head = 1;
+ $this->runLength[$head] = 1;
+ } else if($y > 0) {
+ if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) {
+ $head++;
+ $this->runLength[$head] = 1;
+ } else {
+ $this->runLength[$head]++;
+ }
+ }
+ }
+
+ $demerit += $this->calcN1N3($head+1);
+ }
+
+ return $demerit;
+ }
+
+
+ //----------------------------------------------------------------------
+ public function mask($width, $frame, $level)
+ {
+ $minDemerit = PHP_INT_MAX;
+ $bestMaskNum = 0;
+ $bestMask = array();
+
+ $checked_masks = array(0,1,2,3,4,5,6,7);
+
+ if (QR_FIND_FROM_RANDOM !== false) {
+
+ $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9);
+ for ($i = 0; $i < $howManuOut; $i++) {
+ $remPos = rand (0, count($checked_masks)-1);
+ unset($checked_masks[$remPos]);
+ $checked_masks = array_values($checked_masks);
+ }
+
+ }
+
+ $bestMask = $frame;
+
+ foreach($checked_masks as $i) {
+ $mask = array_fill(0, $width, str_repeat("\0", $width));
+
+ $demerit = 0;
+ $blacks = 0;
+ $blacks = $this->makeMaskNo($i, $width, $frame, $mask);
+ $blacks += $this->writeFormatInformation($width, $mask, $i, $level);
+ $blacks = (int)(100 * $blacks / ($width * $width));
+ $demerit = (int)((int)(abs($blacks - 50) / 5) * N4);
+ $demerit += $this->evaluateSymbol($width, $mask);
+
+ if($demerit < $minDemerit) {
+ $minDemerit = $demerit;
+ $bestMask = $mask;
+ $bestMaskNum = $i;
+ }
+ }
+
+ return $bestMask;
+ }
+
+ //----------------------------------------------------------------------
+ }
+
+
+
+
+//---- qrencode.php -----------------------------
+
+
+
+
+/*
+ * PHP QR Code encoder
+ *
+ * Main encoder classes.
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRrsblock {
+ public $dataLength;
+ public $data = array();
+ public $eccLength;
+ public $ecc = array();
+
+ public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs)
+ {
+ $rs->encode_rs_char($data, $ecc);
+
+ $this->dataLength = $dl;
+ $this->data = $data;
+ $this->eccLength = $el;
+ $this->ecc = $ecc;
+ }
+ };
+
+ //##########################################################################
+
+ class QRrawcode {
+ public $version;
+ public $datacode = array();
+ public $ecccode = array();
+ public $blocks;
+ public $rsblocks = array(); //of RSblock
+ public $count;
+ public $dataLength;
+ public $eccLength;
+ public $b1;
+
+ //----------------------------------------------------------------------
+ public function __construct(QRinput $input)
+ {
+ $spec = array(0,0,0,0,0);
+
+ $this->datacode = $input->getByteStream();
+ if(is_null($this->datacode)) {
+ throw new Exception('null imput string');
+ }
+
+ QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec);
+
+ $this->version = $input->getVersion();
+ $this->b1 = QRspec::rsBlockNum1($spec);
+ $this->dataLength = QRspec::rsDataLength($spec);
+ $this->eccLength = QRspec::rsEccLength($spec);
+ $this->ecccode = array_fill(0, $this->eccLength, 0);
+ $this->blocks = QRspec::rsBlockNum($spec);
+
+ $ret = $this->init($spec);
+ if($ret < 0) {
+ throw new Exception('block alloc error');
+ return null;
+ }
+
+ $this->count = 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function init(array $spec)
+ {
+ $dl = QRspec::rsDataCodes1($spec);
+ $el = QRspec::rsEccCodes1($spec);
+ $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+
+
+ $blockNo = 0;
+ $dataPos = 0;
+ $eccPos = 0;
+ for($i=0; $i<QRspec::rsBlockNum1($spec); $i++) {
+ $ecc = array_slice($this->ecccode,$eccPos);
+ $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);
+ $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
+
+ $dataPos += $dl;
+ $eccPos += $el;
+ $blockNo++;
+ }
+
+ if(QRspec::rsBlockNum2($spec) == 0)
+ return 0;
+
+ $dl = QRspec::rsDataCodes2($spec);
+ $el = QRspec::rsEccCodes2($spec);
+ $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+
+ if($rs == NULL) return -1;
+
+ for($i=0; $i<QRspec::rsBlockNum2($spec); $i++) {
+ $ecc = array_slice($this->ecccode,$eccPos);
+ $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);
+ $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
+
+ $dataPos += $dl;
+ $eccPos += $el;
+ $blockNo++;
+ }
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function getCode()
+ {
+ $ret;
+
+ if($this->count < $this->dataLength) {
+ $row = $this->count % $this->blocks;
+ $col = $this->count / $this->blocks;
+ if($col >= $this->rsblocks[0]->dataLength) {
+ $row += $this->b1;
+ }
+ $ret = $this->rsblocks[$row]->data[$col];
+ } else if($this->count < $this->dataLength + $this->eccLength) {
+ $row = ($this->count - $this->dataLength) % $this->blocks;
+ $col = ($this->count - $this->dataLength) / $this->blocks;
+ $ret = $this->rsblocks[$row]->ecc[$col];
+ } else {
+ return 0;
+ }
+ $this->count++;
+
+ return $ret;
+ }
+ }
+
+ //##########################################################################
+
+ class QRcode {
+
+ public $version;
+ public $width;
+ public $data;
+
+ //----------------------------------------------------------------------
+ public function encodeMask(QRinput $input, $mask)
+ {
+ if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) {
+ throw new Exception('wrong version');
+ }
+ if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) {
+ throw new Exception('wrong level');
+ }
+
+ $raw = new QRrawcode($input);
+
+ QRtools::markTime('after_raw');
+
+ $version = $raw->version;
+ $width = QRspec::getWidth($version);
+ $frame = QRspec::newFrame($version);
+
+ $filler = new FrameFiller($width, $frame);
+ if(is_null($filler)) {
+ return NULL;
+ }
+
+ // inteleaved data and ecc codes
+ for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) {
+ $code = $raw->getCode();
+ $bit = 0x80;
+ for($j=0; $j<8; $j++) {
+ $addr = $filler->next();
+ $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0));
+ $bit = $bit >> 1;
+ }
+ }
+
+ QRtools::markTime('after_filler');
+
+ unset($raw);
+
+ // remainder bits
+ $j = QRspec::getRemainder($version);
+ for($i=0; $i<$j; $i++) {
+ $addr = $filler->next();
+ $filler->setFrameAt($addr, 0x02);
+ }
+
+ $frame = $filler->frame;
+ unset($filler);
+
+
+ // masking
+ $maskObj = new QRmask();
+ if($mask < 0) {
+
+ if (QR_FIND_BEST_MASK) {
+ $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel());
+ } else {
+ $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel());
+ }
+ } else {
+ $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel());
+ }
+
+ if($masked == NULL) {
+ return NULL;
+ }
+
+ QRtools::markTime('after_mask');
+
+ $this->version = $version;
+ $this->width = $width;
+ $this->data = $masked;
+
+ return $this;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeInput(QRinput $input)
+ {
+ return $this->encodeMask($input, -1);
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeString8bit($string, $version, $level)
+ {
+ if(string == NULL) {
+ throw new Exception('empty string!');
+ return NULL;
+ }
+
+ $input = new QRinput($version, $level);
+ if($input == NULL) return NULL;
+
+ $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string));
+ if($ret < 0) {
+ unset($input);
+ return NULL;
+ }
+ return $this->encodeInput($input);
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeString($string, $version, $level, $hint, $casesensitive)
+ {
+
+ if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) {
+ throw new Exception('bad hint');
+ return NULL;
+ }
+
+ $input = new QRinput($version, $level);
+ if($input == NULL) return NULL;
+
+ $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive);
+ if($ret < 0) {
+ return NULL;
+ }
+
+ return $this->encodeInput($input);
+ }
+
+ //----------------------------------------------------------------------
+ public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
+ {
+ $enc = QRencode::factory($level, $size, $margin);
+ return $enc->encodePNG($text, $outfile, $saveandprint=false);
+ }
+
+ //----------------------------------------------------------------------
+ public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)
+ {
+ $enc = QRencode::factory($level, $size, $margin);
+ return $enc->encode($text, $outfile);
+ }
+
+ //----------------------------------------------------------------------
+ public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)
+ {
+ $enc = QRencode::factory($level, $size, $margin);
+ return $enc->encodeRAW($text, $outfile);
+ }
+ }
+
+ //##########################################################################
+
+ class FrameFiller {
+
+ public $width;
+ public $frame;
+ public $x;
+ public $y;
+ public $dir;
+ public $bit;
+
+ //----------------------------------------------------------------------
+ public function __construct($width, &$frame)
+ {
+ $this->width = $width;
+ $this->frame = $frame;
+ $this->x = $width - 1;
+ $this->y = $width - 1;
+ $this->dir = -1;
+ $this->bit = -1;
+ }
+
+ //----------------------------------------------------------------------
+ public function setFrameAt($at, $val)
+ {
+ $this->frame[$at['y']][$at['x']] = chr($val);
+ }
+
+ //----------------------------------------------------------------------
+ public function getFrameAt($at)
+ {
+ return ord($this->frame[$at['y']][$at['x']]);
+ }
+
+ //----------------------------------------------------------------------
+ public function next()
+ {
+ do {
+
+ if($this->bit == -1) {
+ $this->bit = 0;
+ return array('x'=>$this->x, 'y'=>$this->y);
+ }
+
+ $x = $this->x;
+ $y = $this->y;
+ $w = $this->width;
+
+ if($this->bit == 0) {
+ $x--;
+ $this->bit++;
+ } else {
+ $x++;
+ $y += $this->dir;
+ $this->bit--;
+ }
+
+ if($this->dir < 0) {
+ if($y < 0) {
+ $y = 0;
+ $x -= 2;
+ $this->dir = 1;
+ if($x == 6) {
+ $x--;
+ $y = 9;
+ }
+ }
+ } else {
+ if($y == $w) {
+ $y = $w - 1;
+ $x -= 2;
+ $this->dir = -1;
+ if($x == 6) {
+ $x--;
+ $y -= 8;
+ }
+ }
+ }
+ if($x < 0 || $y < 0) return null;
+
+ $this->x = $x;
+ $this->y = $y;
+
+ } while(ord($this->frame[$y][$x]) & 0x80);
+
+ return array('x'=>$x, 'y'=>$y);
+ }
+
+ } ;
+
+ //##########################################################################
+
+ class QRencode {
+
+ public $casesensitive = true;
+ public $eightbit = false;
+
+ public $version = 0;
+ public $size = 3;
+ public $margin = 4;
+
+ public $structured = 0; // not supported yet
+
+ public $level = QR_ECLEVEL_L;
+ public $hint = QR_MODE_8;
+
+ //----------------------------------------------------------------------
+ public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4)
+ {
+ $enc = new QRencode();
+ $enc->size = $size;
+ $enc->margin = $margin;
+
+ switch ($level.'') {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ $enc->level = $level;
+ break;
+ case 'l':
+ case 'L':
+ $enc->level = QR_ECLEVEL_L;
+ break;
+ case 'm':
+ case 'M':
+ $enc->level = QR_ECLEVEL_M;
+ break;
+ case 'q':
+ case 'Q':
+ $enc->level = QR_ECLEVEL_Q;
+ break;
+ case 'h':
+ case 'H':
+ $enc->level = QR_ECLEVEL_H;
+ break;
+ }
+
+ return $enc;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeRAW($intext, $outfile = false)
+ {
+ $code = new QRcode();
+
+ if($this->eightbit) {
+ $code->encodeString8bit($intext, $this->version, $this->level);
+ } else {
+ $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
+ }
+
+ return $code->data;
+ }
+
+ //----------------------------------------------------------------------
+ public function encode($intext, $outfile = false)
+ {
+ $code = new QRcode();
+
+ if($this->eightbit) {
+ $code->encodeString8bit($intext, $this->version, $this->level);
+ } else {
+ $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
+ }
+
+ QRtools::markTime('after_encode');
+
+ if ($outfile!== false) {
+ file_put_contents($outfile, join("\n", QRtools::binarize($code->data)));
+ } else {
+ return QRtools::binarize($code->data);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodePNG($intext, $outfile = false,$saveandprint=false)
+ {
+ try {
+
+ ob_start();
+ $tab = $this->encode($intext);
+ $err = ob_get_contents();
+ ob_end_clean();
+
+ if ($err != '')
+ QRtools::log($outfile, $err);
+
+ $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));
+
+ QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);
+
+ } catch (Exception $e) {
+
+ QRtools::log($outfile, $e->getMessage());
+
+ }
+ }
+ }
+
+
diff --git a/admin/survey/classes/phpqrcode/qrbitstream.php b/admin/survey/classes/phpqrcode/qrbitstream.php
new file mode 100644
index 0000000..7d4ec4a
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrbitstream.php
@@ -0,0 +1,180 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Bitstream class
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRbitstream {
+
+ public $data = array();
+
+ //----------------------------------------------------------------------
+ public function size()
+ {
+ return count($this->data);
+ }
+
+ //----------------------------------------------------------------------
+ public function allocate($setLength)
+ {
+ $this->data = array_fill(0, $setLength, 0);
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public static function newFromNum($bits, $num)
+ {
+ $bstream = new QRbitstream();
+ $bstream->allocate($bits);
+
+ $mask = 1 << ($bits - 1);
+ for($i=0; $i<$bits; $i++) {
+ if($num & $mask) {
+ $bstream->data[$i] = 1;
+ } else {
+ $bstream->data[$i] = 0;
+ }
+ $mask = $mask >> 1;
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public static function newFromBytes($size, $data)
+ {
+ $bstream = new QRbitstream();
+ $bstream->allocate($size * 8);
+ $p=0;
+
+ for($i=0; $i<$size; $i++) {
+ $mask = 0x80;
+ for($j=0; $j<8; $j++) {
+ if($data[$i] & $mask) {
+ $bstream->data[$p] = 1;
+ } else {
+ $bstream->data[$p] = 0;
+ }
+ $p++;
+ $mask = $mask >> 1;
+ }
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function append(QRbitstream $arg)
+ {
+ if (is_null($arg)) {
+ return -1;
+ }
+
+ if($arg->size() == 0) {
+ return 0;
+ }
+
+ if($this->size() == 0) {
+ $this->data = $arg->data;
+ return 0;
+ }
+
+ $this->data = array_values(array_merge($this->data, $arg->data));
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendNum($bits, $num)
+ {
+ if ($bits == 0)
+ return 0;
+
+ $b = QRbitstream::newFromNum($bits, $num);
+
+ if(is_null($b))
+ return -1;
+
+ $ret = $this->append($b);
+ unset($b);
+
+ return $ret;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendBytes($size, $data)
+ {
+ if ($size == 0)
+ return 0;
+
+ $b = QRbitstream::newFromBytes($size, $data);
+
+ if(is_null($b))
+ return -1;
+
+ $ret = $this->append($b);
+ unset($b);
+
+ return $ret;
+ }
+
+ //----------------------------------------------------------------------
+ public function toByte()
+ {
+
+ $size = $this->size();
+
+ if($size == 0) {
+ return array();
+ }
+
+ $data = array_fill(0, (int)(($size + 7) / 8), 0);
+ $bytes = (int)($size / 8);
+
+ $p = 0;
+
+ for($i=0; $i<$bytes; $i++) {
+ $v = 0;
+ for($j=0; $j<8; $j++) {
+ $v = $v << 1;
+ $v |= $this->data[$p];
+ $p++;
+ }
+ $data[$i] = $v;
+ }
+
+ if($size & 7) {
+ $v = 0;
+ for($j=0; $j<($size & 7); $j++) {
+ $v = $v << 1;
+ $v |= $this->data[$p];
+ $p++;
+ }
+ $data[$bytes] = $v;
+ }
+
+ return $data;
+ }
+
+ }
diff --git a/admin/survey/classes/phpqrcode/qrconfig.php b/admin/survey/classes/phpqrcode/qrconfig.php
new file mode 100644
index 0000000..e53dff8
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrconfig.php
@@ -0,0 +1,17 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Config file, feel free to modify
+ */
+
+ define('QR_CACHEABLE', true); // use cache - more disk reads but less CPU power, masks and format templates are stored there
+ define('QR_CACHE_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR); // used when QR_CACHEABLE === true
+ define('QR_LOG_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR); // default error logs dir
+
+ define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
+ define('QR_FIND_FROM_RANDOM', false); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
+ define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false
+
+ define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrconst.php b/admin/survey/classes/phpqrcode/qrconst.php
new file mode 100644
index 0000000..9fac9fd
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrconst.php
@@ -0,0 +1,54 @@
+<?php
+
+/*
+ * PHP QR Code encoder
+ *
+ * Common constants
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ // Encoding modes
+
+ define('QR_MODE_NUL', -1);
+ define('QR_MODE_NUM', 0);
+ define('QR_MODE_AN', 1);
+ define('QR_MODE_8', 2);
+ define('QR_MODE_KANJI', 3);
+ define('QR_MODE_STRUCTURE', 4);
+
+ // Levels of error correction.
+
+ define('QR_ECLEVEL_L', 0);
+ define('QR_ECLEVEL_M', 1);
+ define('QR_ECLEVEL_Q', 2);
+ define('QR_ECLEVEL_H', 3);
+
+ // Supported output formats
+
+ define('QR_FORMAT_TEXT', 0);
+ define('QR_FORMAT_PNG', 1);
+
+ class qrstr {
+ public static function set(&$srctab, $x, $y, $repl, $replLen = false) {
+ $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));
+ }
+ } \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrencode.php b/admin/survey/classes/phpqrcode/qrencode.php
new file mode 100644
index 0000000..4b77a5b
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrencode.php
@@ -0,0 +1,502 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Main encoder classes.
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRrsblock {
+ public $dataLength;
+ public $data = array();
+ public $eccLength;
+ public $ecc = array();
+
+ public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs)
+ {
+ $rs->encode_rs_char($data, $ecc);
+
+ $this->dataLength = $dl;
+ $this->data = $data;
+ $this->eccLength = $el;
+ $this->ecc = $ecc;
+ }
+ };
+
+ //##########################################################################
+
+ class QRrawcode {
+ public $version;
+ public $datacode = array();
+ public $ecccode = array();
+ public $blocks;
+ public $rsblocks = array(); //of RSblock
+ public $count;
+ public $dataLength;
+ public $eccLength;
+ public $b1;
+
+ //----------------------------------------------------------------------
+ public function __construct(QRinput $input)
+ {
+ $spec = array(0,0,0,0,0);
+
+ $this->datacode = $input->getByteStream();
+ if(is_null($this->datacode)) {
+ throw new Exception('null imput string');
+ }
+
+ QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec);
+
+ $this->version = $input->getVersion();
+ $this->b1 = QRspec::rsBlockNum1($spec);
+ $this->dataLength = QRspec::rsDataLength($spec);
+ $this->eccLength = QRspec::rsEccLength($spec);
+ $this->ecccode = array_fill(0, $this->eccLength, 0);
+ $this->blocks = QRspec::rsBlockNum($spec);
+
+ $ret = $this->init($spec);
+ if($ret < 0) {
+ throw new Exception('block alloc error');
+ return null;
+ }
+
+ $this->count = 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function init(array $spec)
+ {
+ $dl = QRspec::rsDataCodes1($spec);
+ $el = QRspec::rsEccCodes1($spec);
+ $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+
+
+ $blockNo = 0;
+ $dataPos = 0;
+ $eccPos = 0;
+ for($i=0; $i<QRspec::rsBlockNum1($spec); $i++) {
+ $ecc = array_slice($this->ecccode,$eccPos);
+ $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);
+ $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
+
+ $dataPos += $dl;
+ $eccPos += $el;
+ $blockNo++;
+ }
+
+ if(QRspec::rsBlockNum2($spec) == 0)
+ return 0;
+
+ $dl = QRspec::rsDataCodes2($spec);
+ $el = QRspec::rsEccCodes2($spec);
+ $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+
+ if($rs == NULL) return -1;
+
+ for($i=0; $i<QRspec::rsBlockNum2($spec); $i++) {
+ $ecc = array_slice($this->ecccode,$eccPos);
+ $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);
+ $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
+
+ $dataPos += $dl;
+ $eccPos += $el;
+ $blockNo++;
+ }
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function getCode()
+ {
+ $ret;
+
+ if($this->count < $this->dataLength) {
+ $row = $this->count % $this->blocks;
+ $col = $this->count / $this->blocks;
+ if($col >= $this->rsblocks[0]->dataLength) {
+ $row += $this->b1;
+ }
+ $ret = $this->rsblocks[$row]->data[$col];
+ } else if($this->count < $this->dataLength + $this->eccLength) {
+ $row = ($this->count - $this->dataLength) % $this->blocks;
+ $col = ($this->count - $this->dataLength) / $this->blocks;
+ $ret = $this->rsblocks[$row]->ecc[$col];
+ } else {
+ return 0;
+ }
+ $this->count++;
+
+ return $ret;
+ }
+ }
+
+ //##########################################################################
+
+ class QRcode {
+
+ public $version;
+ public $width;
+ public $data;
+
+ //----------------------------------------------------------------------
+ public function encodeMask(QRinput $input, $mask)
+ {
+ if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) {
+ throw new Exception('wrong version');
+ }
+ if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) {
+ throw new Exception('wrong level');
+ }
+
+ $raw = new QRrawcode($input);
+
+ QRtools::markTime('after_raw');
+
+ $version = $raw->version;
+ $width = QRspec::getWidth($version);
+ $frame = QRspec::newFrame($version);
+
+ $filler = new FrameFiller($width, $frame);
+ if(is_null($filler)) {
+ return NULL;
+ }
+
+ // inteleaved data and ecc codes
+ for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) {
+ $code = $raw->getCode();
+ $bit = 0x80;
+ for($j=0; $j<8; $j++) {
+ $addr = $filler->next();
+ $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0));
+ $bit = $bit >> 1;
+ }
+ }
+
+ QRtools::markTime('after_filler');
+
+ unset($raw);
+
+ // remainder bits
+ $j = QRspec::getRemainder($version);
+ for($i=0; $i<$j; $i++) {
+ $addr = $filler->next();
+ $filler->setFrameAt($addr, 0x02);
+ }
+
+ $frame = $filler->frame;
+ unset($filler);
+
+
+ // masking
+ $maskObj = new QRmask();
+ if($mask < 0) {
+
+ if (QR_FIND_BEST_MASK) {
+ $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel());
+ } else {
+ $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel());
+ }
+ } else {
+ $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel());
+ }
+
+ if($masked == NULL) {
+ return NULL;
+ }
+
+ QRtools::markTime('after_mask');
+
+ $this->version = $version;
+ $this->width = $width;
+ $this->data = $masked;
+
+ return $this;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeInput(QRinput $input)
+ {
+ return $this->encodeMask($input, -1);
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeString8bit($string, $version, $level)
+ {
+ if(string == NULL) {
+ throw new Exception('empty string!');
+ return NULL;
+ }
+
+ $input = new QRinput($version, $level);
+ if($input == NULL) return NULL;
+
+ $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string));
+ if($ret < 0) {
+ unset($input);
+ return NULL;
+ }
+ return $this->encodeInput($input);
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeString($string, $version, $level, $hint, $casesensitive)
+ {
+
+ if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) {
+ throw new Exception('bad hint');
+ return NULL;
+ }
+
+ $input = new QRinput($version, $level);
+ if($input == NULL) return NULL;
+
+ $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive);
+ if($ret < 0) {
+ return NULL;
+ }
+
+ return $this->encodeInput($input);
+ }
+
+ //----------------------------------------------------------------------
+ public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
+ {
+ $enc = QRencode::factory($level, $size, $margin);
+ return $enc->encodePNG($text, $outfile, $saveandprint=false);
+ }
+
+ //----------------------------------------------------------------------
+ public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)
+ {
+ $enc = QRencode::factory($level, $size, $margin);
+ return $enc->encode($text, $outfile);
+ }
+
+ //----------------------------------------------------------------------
+ public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)
+ {
+ $enc = QRencode::factory($level, $size, $margin);
+ return $enc->encodeRAW($text, $outfile);
+ }
+ }
+
+ //##########################################################################
+
+ class FrameFiller {
+
+ public $width;
+ public $frame;
+ public $x;
+ public $y;
+ public $dir;
+ public $bit;
+
+ //----------------------------------------------------------------------
+ public function __construct($width, &$frame)
+ {
+ $this->width = $width;
+ $this->frame = $frame;
+ $this->x = $width - 1;
+ $this->y = $width - 1;
+ $this->dir = -1;
+ $this->bit = -1;
+ }
+
+ //----------------------------------------------------------------------
+ public function setFrameAt($at, $val)
+ {
+ $this->frame[$at['y']][$at['x']] = chr($val);
+ }
+
+ //----------------------------------------------------------------------
+ public function getFrameAt($at)
+ {
+ return ord($this->frame[$at['y']][$at['x']]);
+ }
+
+ //----------------------------------------------------------------------
+ public function next()
+ {
+ do {
+
+ if($this->bit == -1) {
+ $this->bit = 0;
+ return array('x'=>$this->x, 'y'=>$this->y);
+ }
+
+ $x = $this->x;
+ $y = $this->y;
+ $w = $this->width;
+
+ if($this->bit == 0) {
+ $x--;
+ $this->bit++;
+ } else {
+ $x++;
+ $y += $this->dir;
+ $this->bit--;
+ }
+
+ if($this->dir < 0) {
+ if($y < 0) {
+ $y = 0;
+ $x -= 2;
+ $this->dir = 1;
+ if($x == 6) {
+ $x--;
+ $y = 9;
+ }
+ }
+ } else {
+ if($y == $w) {
+ $y = $w - 1;
+ $x -= 2;
+ $this->dir = -1;
+ if($x == 6) {
+ $x--;
+ $y -= 8;
+ }
+ }
+ }
+ if($x < 0 || $y < 0) return null;
+
+ $this->x = $x;
+ $this->y = $y;
+
+ } while(ord($this->frame[$y][$x]) & 0x80);
+
+ return array('x'=>$x, 'y'=>$y);
+ }
+
+ } ;
+
+ //##########################################################################
+
+ class QRencode {
+
+ public $casesensitive = true;
+ public $eightbit = false;
+
+ public $version = 0;
+ public $size = 3;
+ public $margin = 4;
+
+ public $structured = 0; // not supported yet
+
+ public $level = QR_ECLEVEL_L;
+ public $hint = QR_MODE_8;
+
+ //----------------------------------------------------------------------
+ public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4)
+ {
+ $enc = new QRencode();
+ $enc->size = $size;
+ $enc->margin = $margin;
+
+ switch ($level.'') {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ $enc->level = $level;
+ break;
+ case 'l':
+ case 'L':
+ $enc->level = QR_ECLEVEL_L;
+ break;
+ case 'm':
+ case 'M':
+ $enc->level = QR_ECLEVEL_M;
+ break;
+ case 'q':
+ case 'Q':
+ $enc->level = QR_ECLEVEL_Q;
+ break;
+ case 'h':
+ case 'H':
+ $enc->level = QR_ECLEVEL_H;
+ break;
+ }
+
+ return $enc;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeRAW($intext, $outfile = false)
+ {
+ $code = new QRcode();
+
+ if($this->eightbit) {
+ $code->encodeString8bit($intext, $this->version, $this->level);
+ } else {
+ $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
+ }
+
+ return $code->data;
+ }
+
+ //----------------------------------------------------------------------
+ public function encode($intext, $outfile = false)
+ {
+ $code = new QRcode();
+
+ if($this->eightbit) {
+ $code->encodeString8bit($intext, $this->version, $this->level);
+ } else {
+ $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
+ }
+
+ QRtools::markTime('after_encode');
+
+ if ($outfile!== false) {
+ file_put_contents($outfile, join("\n", QRtools::binarize($code->data)));
+ } else {
+ return QRtools::binarize($code->data);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodePNG($intext, $outfile = false,$saveandprint=false)
+ {
+ try {
+
+ ob_start();
+ $tab = $this->encode($intext);
+ $err = ob_get_contents();
+ ob_end_clean();
+
+ if ($err != '')
+ QRtools::log($outfile, $err);
+
+ $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));
+
+ QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);
+
+ } catch (Exception $e) {
+
+ QRtools::log($outfile, $e->getMessage());
+
+ }
+ }
+ }
diff --git a/admin/survey/classes/phpqrcode/qrimage.php b/admin/survey/classes/phpqrcode/qrimage.php
new file mode 100644
index 0000000..10b0a6e
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrimage.php
@@ -0,0 +1,95 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Image output of code using GD2
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('QR_IMAGE', true);
+
+ class QRimage {
+
+ //----------------------------------------------------------------------
+ public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)
+ {
+ $image = self::image($frame, $pixelPerPoint, $outerFrame);
+
+ if ($filename === false) {
+ Header("Content-type: image/png");
+ ImagePng($image);
+ } else {
+ if($saveandprint===TRUE){
+ ImagePng($image, $filename);
+ header("Content-type: image/png");
+ ImagePng($image);
+ }else{
+ ImagePng($image, $filename);
+ }
+ }
+
+ ImageDestroy($image);
+ }
+
+ //----------------------------------------------------------------------
+ public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85)
+ {
+ $image = self::image($frame, $pixelPerPoint, $outerFrame);
+
+ if ($filename === false) {
+ Header("Content-type: image/jpeg");
+ ImageJpeg($image, null, $q);
+ } else {
+ ImageJpeg($image, $filename, $q);
+ }
+
+ ImageDestroy($image);
+ }
+
+ //----------------------------------------------------------------------
+ private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4)
+ {
+ $h = count($frame);
+ $w = strlen($frame[0]);
+
+ $imgW = $w + 2*$outerFrame;
+ $imgH = $h + 2*$outerFrame;
+
+ $base_image =ImageCreate($imgW, $imgH);
+
+ $col[0] = ImageColorAllocate($base_image,255,255,255);
+ $col[1] = ImageColorAllocate($base_image,0,0,0);
+
+ imagefill($base_image, 0, 0, $col[0]);
+
+ for($y=0; $y<$h; $y++) {
+ for($x=0; $x<$w; $x++) {
+ if ($frame[$y][$x] == '1') {
+ ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]);
+ }
+ }
+ }
+
+ $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint);
+ ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH);
+ ImageDestroy($base_image);
+
+ return $target_image;
+ }
+ } \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrinput.php b/admin/survey/classes/phpqrcode/qrinput.php
new file mode 100644
index 0000000..0f6d7f9
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrinput.php
@@ -0,0 +1,729 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Input encoding class
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('STRUCTURE_HEADER_BITS', 20);
+ define('MAX_STRUCTURED_SYMBOLS', 16);
+
+ class QRinputItem {
+
+ public $mode;
+ public $size;
+ public $data;
+ public $bstream;
+
+ public function __construct($mode, $size, $data, $bstream = null)
+ {
+ $setData = array_slice($data, 0, $size);
+
+ if (count($setData) < $size) {
+ $setData = array_merge($setData, array_fill(0,$size-count($setData),0));
+ }
+
+ if(!QRinput::check($mode, $size, $setData)) {
+ throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData));
+ return null;
+ }
+
+ $this->mode = $mode;
+ $this->size = $size;
+ $this->data = $setData;
+ $this->bstream = $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeNum($version)
+ {
+ try {
+
+ $words = (int)($this->size / 3);
+ $bs = new QRbitstream();
+
+ $val = 0x1;
+ $bs->appendNum(4, $val);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size);
+
+ for($i=0; $i<$words; $i++) {
+ $val = (ord($this->data[$i*3 ]) - ord('0')) * 100;
+ $val += (ord($this->data[$i*3+1]) - ord('0')) * 10;
+ $val += (ord($this->data[$i*3+2]) - ord('0'));
+ $bs->appendNum(10, $val);
+ }
+
+ if($this->size - $words * 3 == 1) {
+ $val = ord($this->data[$words*3]) - ord('0');
+ $bs->appendNum(4, $val);
+ } else if($this->size - $words * 3 == 2) {
+ $val = (ord($this->data[$words*3 ]) - ord('0')) * 10;
+ $val += (ord($this->data[$words*3+1]) - ord('0'));
+ $bs->appendNum(7, $val);
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeAn($version)
+ {
+ try {
+ $words = (int)($this->size / 2);
+ $bs = new QRbitstream();
+
+ $bs->appendNum(4, 0x02);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size);
+
+ for($i=0; $i<$words; $i++) {
+ $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45;
+ $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1]));
+
+ $bs->appendNum(11, $val);
+ }
+
+ if($this->size & 1) {
+ $val = QRinput::lookAnTable(ord($this->data[$words * 2]));
+ $bs->appendNum(6, $val);
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeMode8($version)
+ {
+ try {
+ $bs = new QRbitstream();
+
+ $bs->appendNum(4, 0x4);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size);
+
+ for($i=0; $i<$this->size; $i++) {
+ $bs->appendNum(8, ord($this->data[$i]));
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeKanji($version)
+ {
+ try {
+
+ $bs = new QRbitrtream();
+
+ $bs->appendNum(4, 0x8);
+ $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2));
+
+ for($i=0; $i<$this->size; $i+=2) {
+ $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]);
+ if($val <= 0x9ffc) {
+ $val -= 0x8140;
+ } else {
+ $val -= 0xc140;
+ }
+
+ $h = ($val >> 8) * 0xc0;
+ $val = ($val & 0xff) + $h;
+
+ $bs->appendNum(13, $val);
+ }
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeModeStructure()
+ {
+ try {
+ $bs = new QRbitstream();
+
+ $bs->appendNum(4, 0x03);
+ $bs->appendNum(4, ord($this->data[1]) - 1);
+ $bs->appendNum(4, ord($this->data[0]) - 1);
+ $bs->appendNum(8, ord($this->data[2]));
+
+ $this->bstream = $bs;
+ return 0;
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function estimateBitStreamSizeOfEntry($version)
+ {
+ $bits = 0;
+
+ if($version == 0)
+ $version = 1;
+
+ switch($this->mode) {
+ case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break;
+ case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break;
+ case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break;
+ case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break;
+ case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS;
+ default:
+ return 0;
+ }
+
+ $l = QRspec::lengthIndicator($this->mode, $version);
+ $m = 1 << $l;
+ $num = (int)(($this->size + $m - 1) / $m);
+
+ $bits += $num * (4 + $l);
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public function encodeBitStream($version)
+ {
+ try {
+
+ unset($this->bstream);
+ $words = QRspec::maximumWords($this->mode, $version);
+
+ if($this->size > $words) {
+
+ $st1 = new QRinputItem($this->mode, $words, $this->data);
+ $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words));
+
+ $st1->encodeBitStream($version);
+ $st2->encodeBitStream($version);
+
+ $this->bstream = new QRbitstream();
+ $this->bstream->append($st1->bstream);
+ $this->bstream->append($st2->bstream);
+
+ unset($st1);
+ unset($st2);
+
+ } else {
+
+ $ret = 0;
+
+ switch($this->mode) {
+ case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break;
+ case QR_MODE_AN: $ret = $this->encodeModeAn($version); break;
+ case QR_MODE_8: $ret = $this->encodeMode8($version); break;
+ case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break;
+ case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break;
+
+ default:
+ break;
+ }
+
+ if($ret < 0)
+ return -1;
+ }
+
+ return $this->bstream->size();
+
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+ };
+
+ //##########################################################################
+
+ class QRinput {
+
+ public $items;
+
+ private $version;
+ private $level;
+
+ //----------------------------------------------------------------------
+ public function __construct($version = 0, $level = QR_ECLEVEL_L)
+ {
+ if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) {
+ throw new Exception('Invalid version no');
+ return NULL;
+ }
+
+ $this->version = $version;
+ $this->level = $level;
+ }
+
+ //----------------------------------------------------------------------
+ public function getVersion()
+ {
+ return $this->version;
+ }
+
+ //----------------------------------------------------------------------
+ public function setVersion($version)
+ {
+ if($version < 0 || $version > QRSPEC_VERSION_MAX) {
+ throw new Exception('Invalid version no');
+ return -1;
+ }
+
+ $this->version = $version;
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function getErrorCorrectionLevel()
+ {
+ return $this->level;
+ }
+
+ //----------------------------------------------------------------------
+ public function setErrorCorrectionLevel($level)
+ {
+ if($level > QR_ECLEVEL_H) {
+ throw new Exception('Invalid ECLEVEL');
+ return -1;
+ }
+
+ $this->level = $level;
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendEntry(QRinputItem $entry)
+ {
+ $this->items[] = $entry;
+ }
+
+ //----------------------------------------------------------------------
+ public function append($mode, $size, $data)
+ {
+ try {
+ $entry = new QRinputItem($mode, $size, $data);
+ $this->items[] = $entry;
+ return 0;
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+
+ public function insertStructuredAppendHeader($size, $index, $parity)
+ {
+ if( $size > MAX_STRUCTURED_SYMBOLS ) {
+ throw new Exception('insertStructuredAppendHeader wrong size');
+ }
+
+ if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) {
+ throw new Exception('insertStructuredAppendHeader wrong index');
+ }
+
+ $buf = array($size, $index, $parity);
+
+ try {
+ $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf);
+ array_unshift($this->items, $entry);
+ return 0;
+ } catch (Exception $e) {
+ return -1;
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function calcParity()
+ {
+ $parity = 0;
+
+ foreach($this->items as $item) {
+ if($item->mode != QR_MODE_STRUCTURE) {
+ for($i=$item->size-1; $i>=0; $i--) {
+ $parity ^= $item->data[$i];
+ }
+ }
+ }
+
+ return $parity;
+ }
+
+ //----------------------------------------------------------------------
+ public static function checkModeNum($size, $data)
+ {
+ for($i=0; $i<$size; $i++) {
+ if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ //----------------------------------------------------------------------
+ public static function estimateBitsModeNum($size)
+ {
+ $w = (int)$size / 3;
+ $bits = $w * 10;
+
+ switch($size - $w * 3) {
+ case 1:
+ $bits += 4;
+ break;
+ case 2:
+ $bits += 7;
+ break;
+ default:
+ break;
+ }
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public static $anTable = array(
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1,
+ -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
+ );
+
+ //----------------------------------------------------------------------
+ public static function lookAnTable($c)
+ {
+ return (($c > 127)?-1:self::$anTable[$c]);
+ }
+
+ //----------------------------------------------------------------------
+ public static function checkModeAn($size, $data)
+ {
+ for($i=0; $i<$size; $i++) {
+ if (self::lookAnTable(ord($data[$i])) == -1) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ //----------------------------------------------------------------------
+ public static function estimateBitsModeAn($size)
+ {
+ $w = (int)($size / 2);
+ $bits = $w * 11;
+
+ if($size & 1) {
+ $bits += 6;
+ }
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public static function estimateBitsMode8($size)
+ {
+ return $size * 8;
+ }
+
+ //----------------------------------------------------------------------
+ public function estimateBitsModeKanji($size)
+ {
+ return (int)(($size / 2) * 13);
+ }
+
+ //----------------------------------------------------------------------
+ public static function checkModeKanji($size, $data)
+ {
+ if($size & 1)
+ return false;
+
+ for($i=0; $i<$size; $i+=2) {
+ $val = (ord($data[$i]) << 8) | ord($data[$i+1]);
+ if( $val < 0x8140
+ || ($val > 0x9ffc && $val < 0xe040)
+ || $val > 0xebbf) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /***********************************************************************
+ * Validation
+ **********************************************************************/
+
+ public static function check($mode, $size, $data)
+ {
+ if($size <= 0)
+ return false;
+
+ switch($mode) {
+ case QR_MODE_NUM: return self::checkModeNum($size, $data); break;
+ case QR_MODE_AN: return self::checkModeAn($size, $data); break;
+ case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break;
+ case QR_MODE_8: return true; break;
+ case QR_MODE_STRUCTURE: return true; break;
+
+ default:
+ break;
+ }
+
+ return false;
+ }
+
+
+ //----------------------------------------------------------------------
+ public function estimateBitStreamSize($version)
+ {
+ $bits = 0;
+
+ foreach($this->items as $item) {
+ $bits += $item->estimateBitStreamSizeOfEntry($version);
+ }
+
+ return $bits;
+ }
+
+ //----------------------------------------------------------------------
+ public function estimateVersion()
+ {
+ $version = 0;
+ $prev = 0;
+ do {
+ $prev = $version;
+ $bits = $this->estimateBitStreamSize($prev);
+ $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+ if ($version < 0) {
+ return -1;
+ }
+ } while ($version > $prev);
+
+ return $version;
+ }
+
+ //----------------------------------------------------------------------
+ public static function lengthOfCode($mode, $version, $bits)
+ {
+ $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version);
+ switch($mode) {
+ case QR_MODE_NUM:
+ $chunks = (int)($payload / 10);
+ $remain = $payload - $chunks * 10;
+ $size = $chunks * 3;
+ if($remain >= 7) {
+ $size += 2;
+ } else if($remain >= 4) {
+ $size += 1;
+ }
+ break;
+ case QR_MODE_AN:
+ $chunks = (int)($payload / 11);
+ $remain = $payload - $chunks * 11;
+ $size = $chunks * 2;
+ if($remain >= 6)
+ $size++;
+ break;
+ case QR_MODE_8:
+ $size = (int)($payload / 8);
+ break;
+ case QR_MODE_KANJI:
+ $size = (int)(($payload / 13) * 2);
+ break;
+ case QR_MODE_STRUCTURE:
+ $size = (int)($payload / 8);
+ break;
+ default:
+ $size = 0;
+ break;
+ }
+
+ $maxsize = QRspec::maximumWords($mode, $version);
+ if($size < 0) $size = 0;
+ if($size > $maxsize) $size = $maxsize;
+
+ return $size;
+ }
+
+ //----------------------------------------------------------------------
+ public function createBitStream()
+ {
+ $total = 0;
+
+ foreach($this->items as $item) {
+ $bits = $item->encodeBitStream($this->version);
+
+ if($bits < 0)
+ return -1;
+
+ $total += $bits;
+ }
+
+ return $total;
+ }
+
+ //----------------------------------------------------------------------
+ public function convertData()
+ {
+ $ver = $this->estimateVersion();
+ if($ver > $this->getVersion()) {
+ $this->setVersion($ver);
+ }
+
+ for(;;) {
+ $bits = $this->createBitStream();
+
+ if($bits < 0)
+ return -1;
+
+ $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+ if($ver < 0) {
+ throw new Exception('WRONG VERSION');
+ return -1;
+ } else if($ver > $this->getVersion()) {
+ $this->setVersion($ver);
+ } else {
+ break;
+ }
+ }
+
+ return 0;
+ }
+
+ //----------------------------------------------------------------------
+ public function appendPaddingBit(&$bstream)
+ {
+ $bits = $bstream->size();
+ $maxwords = QRspec::getDataLength($this->version, $this->level);
+ $maxbits = $maxwords * 8;
+
+ if ($maxbits == $bits) {
+ return 0;
+ }
+
+ if ($maxbits - $bits < 5) {
+ return $bstream->appendNum($maxbits - $bits, 0);
+ }
+
+ $bits += 4;
+ $words = (int)(($bits + 7) / 8);
+
+ $padding = new QRbitstream();
+ $ret = $padding->appendNum($words * 8 - $bits + 4, 0);
+
+ if($ret < 0)
+ return $ret;
+
+ $padlen = $maxwords - $words;
+
+ if($padlen > 0) {
+
+ $padbuf = array();
+ for($i=0; $i<$padlen; $i++) {
+ $padbuf[$i] = ($i&1)?0x11:0xec;
+ }
+
+ $ret = $padding->appendBytes($padlen, $padbuf);
+
+ if($ret < 0)
+ return $ret;
+
+ }
+
+ $ret = $bstream->append($padding);
+
+ return $ret;
+ }
+
+ //----------------------------------------------------------------------
+ public function mergeBitStream()
+ {
+ if($this->convertData() < 0) {
+ return null;
+ }
+
+ $bstream = new QRbitstream();
+
+ foreach($this->items as $item) {
+ $ret = $bstream->append($item->bstream);
+ if($ret < 0) {
+ return null;
+ }
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function getBitStream()
+ {
+
+ $bstream = $this->mergeBitStream();
+
+ if($bstream == null) {
+ return null;
+ }
+
+ $ret = $this->appendPaddingBit($bstream);
+ if($ret < 0) {
+ return null;
+ }
+
+ return $bstream;
+ }
+
+ //----------------------------------------------------------------------
+ public function getByteStream()
+ {
+ $bstream = $this->getBitStream();
+ if($bstream == null) {
+ return null;
+ }
+
+ return $bstream->toByte();
+ }
+ }
+
+
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrlib.php b/admin/survey/classes/phpqrcode/qrlib.php
new file mode 100644
index 0000000..d55c4af
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrlib.php
@@ -0,0 +1,43 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Root library file, prepares environment and includes dependencies
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ $QR_BASEDIR = dirname(__FILE__).DIRECTORY_SEPARATOR;
+
+ // Required libs
+
+ include $QR_BASEDIR."qrconst.php";
+ include $QR_BASEDIR."qrconfig.php";
+ include $QR_BASEDIR."qrtools.php";
+ include $QR_BASEDIR."qrspec.php";
+ include $QR_BASEDIR."qrimage.php";
+ include $QR_BASEDIR."qrinput.php";
+ include $QR_BASEDIR."qrbitstream.php";
+ include $QR_BASEDIR."qrsplit.php";
+ include $QR_BASEDIR."qrrscode.php";
+ include $QR_BASEDIR."qrmask.php";
+ include $QR_BASEDIR."qrencode.php";
+
diff --git a/admin/survey/classes/phpqrcode/qrmask.php b/admin/survey/classes/phpqrcode/qrmask.php
new file mode 100644
index 0000000..b14d7ae
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrmask.php
@@ -0,0 +1,328 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Masking
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('N1', 3);
+ define('N2', 3);
+ define('N3', 40);
+ define('N4', 10);
+
+ class QRmask {
+
+ public $runLength = array();
+
+ //----------------------------------------------------------------------
+ public function __construct()
+ {
+ $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0);
+ }
+
+ //----------------------------------------------------------------------
+ public function writeFormatInformation($width, &$frame, $mask, $level)
+ {
+ $blacks = 0;
+ $format = QRspec::getFormatInfo($mask, $level);
+
+ for($i=0; $i<8; $i++) {
+ if($format & 1) {
+ $blacks += 2;
+ $v = 0x85;
+ } else {
+ $v = 0x84;
+ }
+
+ $frame[8][$width - 1 - $i] = chr($v);
+ if($i < 6) {
+ $frame[$i][8] = chr($v);
+ } else {
+ $frame[$i + 1][8] = chr($v);
+ }
+ $format = $format >> 1;
+ }
+
+ for($i=0; $i<7; $i++) {
+ if($format & 1) {
+ $blacks += 2;
+ $v = 0x85;
+ } else {
+ $v = 0x84;
+ }
+
+ $frame[$width - 7 + $i][8] = chr($v);
+ if($i == 0) {
+ $frame[8][7] = chr($v);
+ } else {
+ $frame[8][6 - $i] = chr($v);
+ }
+
+ $format = $format >> 1;
+ }
+
+ return $blacks;
+ }
+
+ //----------------------------------------------------------------------
+ public function mask0($x, $y) { return ($x+$y)&1; }
+ public function mask1($x, $y) { return ($y&1); }
+ public function mask2($x, $y) { return ($x%3); }
+ public function mask3($x, $y) { return ($x+$y)%3; }
+ public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; }
+ public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; }
+ public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; }
+ public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; }
+
+ //----------------------------------------------------------------------
+ private function generateMaskNo($maskNo, $width, $frame)
+ {
+ $bitMask = array_fill(0, $width, array_fill(0, $width, 0));
+
+ for($y=0; $y<$width; $y++) {
+ for($x=0; $x<$width; $x++) {
+ if(ord($frame[$y][$x]) & 0x80) {
+ $bitMask[$y][$x] = 0;
+ } else {
+ $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y);
+ $bitMask[$y][$x] = ($maskFunc == 0)?1:0;
+ }
+
+ }
+ }
+
+ return $bitMask;
+ }
+
+ //----------------------------------------------------------------------
+ public static function serial($bitFrame)
+ {
+ $codeArr = array();
+
+ foreach ($bitFrame as $line)
+ $codeArr[] = join('', $line);
+
+ return gzcompress(join("\n", $codeArr), 9);
+ }
+
+ //----------------------------------------------------------------------
+ public static function unserial($code)
+ {
+ $codeArr = array();
+
+ $codeLines = explode("\n", gzuncompress($code));
+ foreach ($codeLines as $line)
+ $codeArr[] = str_split($line);
+
+ return $codeArr;
+ }
+
+ //----------------------------------------------------------------------
+ public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false)
+ {
+ $b = 0;
+ $bitMask = array();
+
+ $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat';
+
+ if (QR_CACHEABLE) {
+ if (file_exists($fileName)) {
+ $bitMask = self::unserial(file_get_contents($fileName));
+ } else {
+ $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
+ if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo))
+ mkdir(QR_CACHE_DIR.'mask_'.$maskNo);
+ file_put_contents($fileName, self::serial($bitMask));
+ }
+ } else {
+ $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
+ }
+
+ if ($maskGenOnly)
+ return;
+
+ $d = $s;
+
+ for($y=0; $y<$width; $y++) {
+ for($x=0; $x<$width; $x++) {
+ if($bitMask[$y][$x] == 1) {
+ $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]);
+ }
+ $b += (int)(ord($d[$y][$x]) & 1);
+ }
+ }
+
+ return $b;
+ }
+
+ //----------------------------------------------------------------------
+ public function makeMask($width, $frame, $maskNo, $level)
+ {
+ $masked = array_fill(0, $width, str_repeat("\0", $width));
+ $this->makeMaskNo($maskNo, $width, $frame, $masked);
+ $this->writeFormatInformation($width, $masked, $maskNo, $level);
+
+ return $masked;
+ }
+
+ //----------------------------------------------------------------------
+ public function calcN1N3($length)
+ {
+ $demerit = 0;
+
+ for($i=0; $i<$length; $i++) {
+
+ if($this->runLength[$i] >= 5) {
+ $demerit += (N1 + ($this->runLength[$i] - 5));
+ }
+ if($i & 1) {
+ if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) {
+ $fact = (int)($this->runLength[$i] / 3);
+ if(($this->runLength[$i-2] == $fact) &&
+ ($this->runLength[$i-1] == $fact) &&
+ ($this->runLength[$i+1] == $fact) &&
+ ($this->runLength[$i+2] == $fact)) {
+ if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) {
+ $demerit += N3;
+ } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) {
+ $demerit += N3;
+ }
+ }
+ }
+ }
+ }
+ return $demerit;
+ }
+
+ //----------------------------------------------------------------------
+ public function evaluateSymbol($width, $frame)
+ {
+ $head = 0;
+ $demerit = 0;
+
+ for($y=0; $y<$width; $y++) {
+ $head = 0;
+ $this->runLength[0] = 1;
+
+ $frameY = $frame[$y];
+
+ if ($y>0)
+ $frameYM = $frame[$y-1];
+
+ for($x=0; $x<$width; $x++) {
+ if(($x > 0) && ($y > 0)) {
+ $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]);
+ $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]);
+
+ if(($b22 | ($w22 ^ 1))&1) {
+ $demerit += N2;
+ }
+ }
+ if(($x == 0) && (ord($frameY[$x]) & 1)) {
+ $this->runLength[0] = -1;
+ $head = 1;
+ $this->runLength[$head] = 1;
+ } else if($x > 0) {
+ if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) {
+ $head++;
+ $this->runLength[$head] = 1;
+ } else {
+ $this->runLength[$head]++;
+ }
+ }
+ }
+
+ $demerit += $this->calcN1N3($head+1);
+ }
+
+ for($x=0; $x<$width; $x++) {
+ $head = 0;
+ $this->runLength[0] = 1;
+
+ for($y=0; $y<$width; $y++) {
+ if($y == 0 && (ord($frame[$y][$x]) & 1)) {
+ $this->runLength[0] = -1;
+ $head = 1;
+ $this->runLength[$head] = 1;
+ } else if($y > 0) {
+ if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) {
+ $head++;
+ $this->runLength[$head] = 1;
+ } else {
+ $this->runLength[$head]++;
+ }
+ }
+ }
+
+ $demerit += $this->calcN1N3($head+1);
+ }
+
+ return $demerit;
+ }
+
+
+ //----------------------------------------------------------------------
+ public function mask($width, $frame, $level)
+ {
+ $minDemerit = PHP_INT_MAX;
+ $bestMaskNum = 0;
+ $bestMask = array();
+
+ $checked_masks = array(0,1,2,3,4,5,6,7);
+
+ if (QR_FIND_FROM_RANDOM !== false) {
+
+ $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9);
+ for ($i = 0; $i < $howManuOut; $i++) {
+ $remPos = rand (0, count($checked_masks)-1);
+ unset($checked_masks[$remPos]);
+ $checked_masks = array_values($checked_masks);
+ }
+
+ }
+
+ $bestMask = $frame;
+
+ foreach($checked_masks as $i) {
+ $mask = array_fill(0, $width, str_repeat("\0", $width));
+
+ $demerit = 0;
+ $blacks = 0;
+ $blacks = $this->makeMaskNo($i, $width, $frame, $mask);
+ $blacks += $this->writeFormatInformation($width, $mask, $i, $level);
+ $blacks = (int)(100 * $blacks / ($width * $width));
+ $demerit = (int)((int)(abs($blacks - 50) / 5) * N4);
+ $demerit += $this->evaluateSymbol($width, $mask);
+
+ if($demerit < $minDemerit) {
+ $minDemerit = $demerit;
+ $bestMask = $mask;
+ $bestMaskNum = $i;
+ }
+ }
+
+ return $bestMask;
+ }
+
+ //----------------------------------------------------------------------
+ }
diff --git a/admin/survey/classes/phpqrcode/qrrscode.php b/admin/survey/classes/phpqrcode/qrrscode.php
new file mode 100644
index 0000000..591129a
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrrscode.php
@@ -0,0 +1,210 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Reed-Solomon error correction support
+ *
+ * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q
+ * (libfec is released under the GNU Lesser General Public License.)
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRrsItem {
+
+ public $mm; // Bits per symbol
+ public $nn; // Symbols per block (= (1<<mm)-1)
+ public $alpha_to = array(); // log lookup table
+ public $index_of = array(); // Antilog lookup table
+ public $genpoly = array(); // Generator polynomial
+ public $nroots; // Number of generator roots = number of parity symbols
+ public $fcr; // First consecutive root, index form
+ public $prim; // Primitive element, index form
+ public $iprim; // prim-th root of 1, index form
+ public $pad; // Padding bytes in shortened block
+ public $gfpoly;
+
+ //----------------------------------------------------------------------
+ public function modnn($x)
+ {
+ while ($x >= $this->nn) {
+ $x -= $this->nn;
+ $x = ($x >> $this->mm) + ($x & $this->nn);
+ }
+
+ return $x;
+ }
+
+ //----------------------------------------------------------------------
+ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)
+ {
+ // Common code for intializing a Reed-Solomon control block (char or int symbols)
+ // Copyright 2004 Phil Karn, KA9Q
+ // May be used under the terms of the GNU Lesser General Public License (LGPL)
+
+ $rs = null;
+
+ // Check parameter ranges
+ if($symsize < 0 || $symsize > 8) return $rs;
+ if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs;
+ if($prim <= 0 || $prim >= (1<<$symsize)) return $rs;
+ if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values!
+ if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding
+
+ $rs = new QRrsItem();
+ $rs->mm = $symsize;
+ $rs->nn = (1<<$symsize)-1;
+ $rs->pad = $pad;
+
+ $rs->alpha_to = array_fill(0, $rs->nn+1, 0);
+ $rs->index_of = array_fill(0, $rs->nn+1, 0);
+
+ // PHP style macro replacement ;)
+ $NN =& $rs->nn;
+ $A0 =& $NN;
+
+ // Generate Galois field lookup tables
+ $rs->index_of[0] = $A0; // log(zero) = -inf
+ $rs->alpha_to[$A0] = 0; // alpha**-inf = 0
+ $sr = 1;
+
+ for($i=0; $i<$rs->nn; $i++) {
+ $rs->index_of[$sr] = $i;
+ $rs->alpha_to[$i] = $sr;
+ $sr <<= 1;
+ if($sr & (1<<$symsize)) {
+ $sr ^= $gfpoly;
+ }
+ $sr &= $rs->nn;
+ }
+
+ if($sr != 1){
+ // field generator polynomial is not primitive!
+ $rs = NULL;
+ return $rs;
+ }
+
+ /* Form RS code generator polynomial from its roots */
+ $rs->genpoly = array_fill(0, $nroots+1, 0);
+
+ $rs->fcr = $fcr;
+ $rs->prim = $prim;
+ $rs->nroots = $nroots;
+ $rs->gfpoly = $gfpoly;
+
+ /* Find prim-th root of 1, used in decoding */
+ for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn)
+ ; // intentional empty-body loop!
+
+ $rs->iprim = (int)($iprim / $prim);
+ $rs->genpoly[0] = 1;
+
+ for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) {
+ $rs->genpoly[$i+1] = 1;
+
+ // Multiply rs->genpoly[] by @**(root + x)
+ for ($j = $i; $j > 0; $j--) {
+ if ($rs->genpoly[$j] != 0) {
+ $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)];
+ } else {
+ $rs->genpoly[$j] = $rs->genpoly[$j-1];
+ }
+ }
+ // rs->genpoly[0] can never be zero
+ $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)];
+ }
+
+ // convert rs->genpoly[] to index form for quicker encoding
+ for ($i = 0; $i <= $nroots; $i++)
+ $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]];
+
+ return $rs;
+ }
+
+ //----------------------------------------------------------------------
+ public function encode_rs_char($data, &$parity)
+ {
+ $MM =& $this->mm;
+ $NN =& $this->nn;
+ $ALPHA_TO =& $this->alpha_to;
+ $INDEX_OF =& $this->index_of;
+ $GENPOLY =& $this->genpoly;
+ $NROOTS =& $this->nroots;
+ $FCR =& $this->fcr;
+ $PRIM =& $this->prim;
+ $IPRIM =& $this->iprim;
+ $PAD =& $this->pad;
+ $A0 =& $NN;
+
+ $parity = array_fill(0, $NROOTS, 0);
+
+ for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) {
+
+ $feedback = $INDEX_OF[$data[$i] ^ $parity[0]];
+ if($feedback != $A0) {
+ // feedback term is non-zero
+
+ // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must
+ // always be for the polynomials constructed by init_rs()
+ $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback);
+
+ for($j=1;$j<$NROOTS;$j++) {
+ $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])];
+ }
+ }
+
+ // Shift
+ array_shift($parity);
+ if($feedback != $A0) {
+ array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]);
+ } else {
+ array_push($parity, 0);
+ }
+ }
+ }
+ }
+
+ //##########################################################################
+
+ class QRrs {
+
+ public static $items = array();
+
+ //----------------------------------------------------------------------
+ public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)
+ {
+ foreach(self::$items as $rs) {
+ if($rs->pad != $pad) continue;
+ if($rs->nroots != $nroots) continue;
+ if($rs->mm != $symsize) continue;
+ if($rs->gfpoly != $gfpoly) continue;
+ if($rs->fcr != $fcr) continue;
+ if($rs->prim != $prim) continue;
+
+ return $rs;
+ }
+
+ $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad);
+ array_unshift(self::$items, $rs);
+
+ return $rs;
+ }
+ } \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrspec.php b/admin/survey/classes/phpqrcode/qrspec.php
new file mode 100644
index 0000000..92aea0c
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrspec.php
@@ -0,0 +1,592 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * QR Code specifications
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * The following data / specifications are taken from
+ * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
+ * or
+ * "Automatic identification and data capture techniques --
+ * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ define('QRSPEC_VERSION_MAX', 40);
+ define('QRSPEC_WIDTH_MAX', 177);
+
+ define('QRCAP_WIDTH', 0);
+ define('QRCAP_WORDS', 1);
+ define('QRCAP_REMINDER', 2);
+ define('QRCAP_EC', 3);
+
+ class QRspec {
+
+ public static $capacity = array(
+ array( 0, 0, 0, array( 0, 0, 0, 0)),
+ array( 21, 26, 0, array( 7, 10, 13, 17)), // 1
+ array( 25, 44, 7, array( 10, 16, 22, 28)),
+ array( 29, 70, 7, array( 15, 26, 36, 44)),
+ array( 33, 100, 7, array( 20, 36, 52, 64)),
+ array( 37, 134, 7, array( 26, 48, 72, 88)), // 5
+ array( 41, 172, 7, array( 36, 64, 96, 112)),
+ array( 45, 196, 0, array( 40, 72, 108, 130)),
+ array( 49, 242, 0, array( 48, 88, 132, 156)),
+ array( 53, 292, 0, array( 60, 110, 160, 192)),
+ array( 57, 346, 0, array( 72, 130, 192, 224)), //10
+ array( 61, 404, 0, array( 80, 150, 224, 264)),
+ array( 65, 466, 0, array( 96, 176, 260, 308)),
+ array( 69, 532, 0, array( 104, 198, 288, 352)),
+ array( 73, 581, 3, array( 120, 216, 320, 384)),
+ array( 77, 655, 3, array( 132, 240, 360, 432)), //15
+ array( 81, 733, 3, array( 144, 280, 408, 480)),
+ array( 85, 815, 3, array( 168, 308, 448, 532)),
+ array( 89, 901, 3, array( 180, 338, 504, 588)),
+ array( 93, 991, 3, array( 196, 364, 546, 650)),
+ array( 97, 1085, 3, array( 224, 416, 600, 700)), //20
+ array(101, 1156, 4, array( 224, 442, 644, 750)),
+ array(105, 1258, 4, array( 252, 476, 690, 816)),
+ array(109, 1364, 4, array( 270, 504, 750, 900)),
+ array(113, 1474, 4, array( 300, 560, 810, 960)),
+ array(117, 1588, 4, array( 312, 588, 870, 1050)), //25
+ array(121, 1706, 4, array( 336, 644, 952, 1110)),
+ array(125, 1828, 4, array( 360, 700, 1020, 1200)),
+ array(129, 1921, 3, array( 390, 728, 1050, 1260)),
+ array(133, 2051, 3, array( 420, 784, 1140, 1350)),
+ array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30
+ array(141, 2323, 3, array( 480, 868, 1290, 1530)),
+ array(145, 2465, 3, array( 510, 924, 1350, 1620)),
+ array(149, 2611, 3, array( 540, 980, 1440, 1710)),
+ array(153, 2761, 3, array( 570, 1036, 1530, 1800)),
+ array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35
+ array(161, 3034, 0, array( 600, 1120, 1680, 1980)),
+ array(165, 3196, 0, array( 630, 1204, 1770, 2100)),
+ array(169, 3362, 0, array( 660, 1260, 1860, 2220)),
+ array(173, 3532, 0, array( 720, 1316, 1950, 2310)),
+ array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40
+ );
+
+ //----------------------------------------------------------------------
+ public static function getDataLength($version, $level)
+ {
+ return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getECCLength($version, $level)
+ {
+ return self::$capacity[$version][QRCAP_EC][$level];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getWidth($version)
+ {
+ return self::$capacity[$version][QRCAP_WIDTH];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getRemainder($version)
+ {
+ return self::$capacity[$version][QRCAP_REMINDER];
+ }
+
+ //----------------------------------------------------------------------
+ public static function getMinimumVersion($size, $level)
+ {
+
+ for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) {
+ $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level];
+ if($words >= $size)
+ return $i;
+ }
+
+ return -1;
+ }
+
+ //######################################################################
+
+ public static $lengthTableBits = array(
+ array(10, 12, 14),
+ array( 9, 11, 13),
+ array( 8, 16, 16),
+ array( 8, 10, 12)
+ );
+
+ //----------------------------------------------------------------------
+ public static function lengthIndicator($mode, $version)
+ {
+ if ($mode == QR_MODE_STRUCTURE)
+ return 0;
+
+ if ($version <= 9) {
+ $l = 0;
+ } else if ($version <= 26) {
+ $l = 1;
+ } else {
+ $l = 2;
+ }
+
+ return self::$lengthTableBits[$mode][$l];
+ }
+
+ //----------------------------------------------------------------------
+ public static function maximumWords($mode, $version)
+ {
+ if($mode == QR_MODE_STRUCTURE)
+ return 3;
+
+ if($version <= 9) {
+ $l = 0;
+ } else if($version <= 26) {
+ $l = 1;
+ } else {
+ $l = 2;
+ }
+
+ $bits = self::$lengthTableBits[$mode][$l];
+ $words = (1 << $bits) - 1;
+
+ if($mode == QR_MODE_KANJI) {
+ $words *= 2; // the number of bytes is required
+ }
+
+ return $words;
+ }
+
+ // Error correction code -----------------------------------------------
+ // Table of the error correction code (Reed-Solomon block)
+ // See Table 12-16 (pp.30-36), JIS X0510:2004.
+
+ public static $eccTable = array(
+ array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)),
+ array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1
+ array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)),
+ array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)),
+ array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)),
+ array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5
+ array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)),
+ array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)),
+ array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)),
+ array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)),
+ array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10
+ array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)),
+ array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)),
+ array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)),
+ array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)),
+ array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15
+ array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)),
+ array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)),
+ array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)),
+ array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)),
+ array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20
+ array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)),
+ array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)),
+ array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)),
+ array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)),
+ array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25
+ array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)),
+ array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)),
+ array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)),
+ array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)),
+ array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30
+ array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)),
+ array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)),
+ array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)),
+ array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)),
+ array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35
+ array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)),
+ array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)),
+ array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)),
+ array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)),
+ array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40
+ );
+
+ //----------------------------------------------------------------------
+ // CACHEABLE!!!
+
+ public static function getEccSpec($version, $level, array &$spec)
+ {
+ if (count($spec) < 5) {
+ $spec = array(0,0,0,0,0);
+ }
+
+ $b1 = self::$eccTable[$version][$level][0];
+ $b2 = self::$eccTable[$version][$level][1];
+ $data = self::getDataLength($version, $level);
+ $ecc = self::getECCLength($version, $level);
+
+ if($b2 == 0) {
+ $spec[0] = $b1;
+ $spec[1] = (int)($data / $b1);
+ $spec[2] = (int)($ecc / $b1);
+ $spec[3] = 0;
+ $spec[4] = 0;
+ } else {
+ $spec[0] = $b1;
+ $spec[1] = (int)($data / ($b1 + $b2));
+ $spec[2] = (int)($ecc / ($b1 + $b2));
+ $spec[3] = $b2;
+ $spec[4] = $spec[1] + 1;
+ }
+ }
+
+ // Alignment pattern ---------------------------------------------------
+
+ // Positions of alignment patterns.
+ // This array includes only the second and the third position of the
+ // alignment patterns. Rest of them can be calculated from the distance
+ // between them.
+
+ // See Table 1 in Appendix E (pp.71) of JIS X0510:2004.
+
+ public static $alignmentPattern = array(
+ array( 0, 0),
+ array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5
+ array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10
+ array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15
+ array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20
+ array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25
+ array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30
+ array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35
+ array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40
+ );
+
+
+ /** --------------------------------------------------------------------
+ * Put an alignment marker.
+ * @param frame
+ * @param width
+ * @param ox,oy center coordinate of the pattern
+ */
+ public static function putAlignmentMarker(array &$frame, $ox, $oy)
+ {
+ $finder = array(
+ "\xa1\xa1\xa1\xa1\xa1",
+ "\xa1\xa0\xa0\xa0\xa1",
+ "\xa1\xa0\xa1\xa0\xa1",
+ "\xa1\xa0\xa0\xa0\xa1",
+ "\xa1\xa1\xa1\xa1\xa1"
+ );
+
+ $yStart = $oy-2;
+ $xStart = $ox-2;
+
+ for($y=0; $y<5; $y++) {
+ QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function putAlignmentPattern($version, &$frame, $width)
+ {
+ if($version < 2)
+ return;
+
+ $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0];
+ if($d < 0) {
+ $w = 2;
+ } else {
+ $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2);
+ }
+
+ if($w * $w - 3 == 1) {
+ $x = self::$alignmentPattern[$version][0];
+ $y = self::$alignmentPattern[$version][0];
+ self::putAlignmentMarker($frame, $x, $y);
+ return;
+ }
+
+ $cx = self::$alignmentPattern[$version][0];
+ for($x=1; $x<$w - 1; $x++) {
+ self::putAlignmentMarker($frame, 6, $cx);
+ self::putAlignmentMarker($frame, $cx, 6);
+ $cx += $d;
+ }
+
+ $cy = self::$alignmentPattern[$version][0];
+ for($y=0; $y<$w-1; $y++) {
+ $cx = self::$alignmentPattern[$version][0];
+ for($x=0; $x<$w-1; $x++) {
+ self::putAlignmentMarker($frame, $cx, $cy);
+ $cx += $d;
+ }
+ $cy += $d;
+ }
+ }
+
+ // Version information pattern -----------------------------------------
+
+ // Version information pattern (BCH coded).
+ // See Table 1 in Appendix D (pp.68) of JIS X0510:2004.
+
+ // size: [QRSPEC_VERSION_MAX - 6]
+
+ public static $versionPattern = array(
+ 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d,
+ 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9,
+ 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75,
+ 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64,
+ 0x27541, 0x28c69
+ );
+
+ //----------------------------------------------------------------------
+ public static function getVersionPattern($version)
+ {
+ if($version < 7 || $version > QRSPEC_VERSION_MAX)
+ return 0;
+
+ return self::$versionPattern[$version -7];
+ }
+
+ // Format information --------------------------------------------------
+ // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib)
+
+ public static $formatInfo = array(
+ array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976),
+ array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0),
+ array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed),
+ array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b)
+ );
+
+ public static function getFormatInfo($mask, $level)
+ {
+ if($mask < 0 || $mask > 7)
+ return 0;
+
+ if($level < 0 || $level > 3)
+ return 0;
+
+ return self::$formatInfo[$level][$mask];
+ }
+
+ // Frame ---------------------------------------------------------------
+ // Cache of initial frames.
+
+ public static $frames = array();
+
+ /** --------------------------------------------------------------------
+ * Put a finder pattern.
+ * @param frame
+ * @param width
+ * @param ox,oy upper-left coordinate of the pattern
+ */
+ public static function putFinderPattern(&$frame, $ox, $oy)
+ {
+ $finder = array(
+ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1",
+ "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+ "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1"
+ );
+
+ for($y=0; $y<7; $y++) {
+ QRstr::set($frame, $ox, $oy+$y, $finder[$y]);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function createFrame($version)
+ {
+ $width = self::$capacity[$version][QRCAP_WIDTH];
+ $frameLine = str_repeat ("\0", $width);
+ $frame = array_fill(0, $width, $frameLine);
+
+ // Finder pattern
+ self::putFinderPattern($frame, 0, 0);
+ self::putFinderPattern($frame, $width - 7, 0);
+ self::putFinderPattern($frame, 0, $width - 7);
+
+ // Separator
+ $yOffset = $width - 7;
+
+ for($y=0; $y<7; $y++) {
+ $frame[$y][7] = "\xc0";
+ $frame[$y][$width - 8] = "\xc0";
+ $frame[$yOffset][7] = "\xc0";
+ $yOffset++;
+ }
+
+ $setPattern = str_repeat("\xc0", 8);
+
+ QRstr::set($frame, 0, 7, $setPattern);
+ QRstr::set($frame, $width-8, 7, $setPattern);
+ QRstr::set($frame, 0, $width - 8, $setPattern);
+
+ // Format info
+ $setPattern = str_repeat("\x84", 9);
+ QRstr::set($frame, 0, 8, $setPattern);
+ QRstr::set($frame, $width - 8, 8, $setPattern, 8);
+
+ $yOffset = $width - 8;
+
+ for($y=0; $y<8; $y++,$yOffset++) {
+ $frame[$y][8] = "\x84";
+ $frame[$yOffset][8] = "\x84";
+ }
+
+ // Timing pattern
+
+ for($i=1; $i<$width-15; $i++) {
+ $frame[6][7+$i] = chr(0x90 | ($i & 1));
+ $frame[7+$i][6] = chr(0x90 | ($i & 1));
+ }
+
+ // Alignment pattern
+ self::putAlignmentPattern($version, $frame, $width);
+
+ // Version information
+ if($version >= 7) {
+ $vinf = self::getVersionPattern($version);
+
+ $v = $vinf;
+
+ for($x=0; $x<6; $x++) {
+ for($y=0; $y<3; $y++) {
+ $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));
+ $v = $v >> 1;
+ }
+ }
+
+ $v = $vinf;
+ for($y=0; $y<6; $y++) {
+ for($x=0; $x<3; $x++) {
+ $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));
+ $v = $v >> 1;
+ }
+ }
+ }
+
+ // and a little bit...
+ $frame[$width - 8][8] = "\x81";
+
+ return $frame;
+ }
+
+ //----------------------------------------------------------------------
+ public static function debug($frame, $binary_mode = false)
+ {
+ if ($binary_mode) {
+
+ foreach ($frame as &$frameLine) {
+ $frameLine = join('<span class="m">&nbsp;&nbsp;</span>', explode('0', $frameLine));
+ $frameLine = join('&#9608;&#9608;', explode('1', $frameLine));
+ }
+
+ ?>
+ <style>
+ .m { background-color: white; }
+ </style>
+ <?php
+ echo '<pre><tt><br/ ><br/ ><br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+ echo join("<br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $frame);
+ echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >';
+
+ } else {
+
+ foreach ($frame as &$frameLine) {
+ $frameLine = join('<span class="m">&nbsp;</span>', explode("\xc0", $frameLine));
+ $frameLine = join('<span class="m">&#9618;</span>', explode("\xc1", $frameLine));
+ $frameLine = join('<span class="p">&nbsp;</span>', explode("\xa0", $frameLine));
+ $frameLine = join('<span class="p">&#9618;</span>', explode("\xa1", $frameLine));
+ $frameLine = join('<span class="s">&#9671;</span>', explode("\x84", $frameLine)); //format 0
+ $frameLine = join('<span class="s">&#9670;</span>', explode("\x85", $frameLine)); //format 1
+ $frameLine = join('<span class="x">&#9762;</span>', explode("\x81", $frameLine)); //special bit
+ $frameLine = join('<span class="c">&nbsp;</span>', explode("\x90", $frameLine)); //clock 0
+ $frameLine = join('<span class="c">&#9719;</span>', explode("\x91", $frameLine)); //clock 1
+ $frameLine = join('<span class="f">&nbsp;</span>', explode("\x88", $frameLine)); //version
+ $frameLine = join('<span class="f">&#9618;</span>', explode("\x89", $frameLine)); //version
+ $frameLine = join('&#9830;', explode("\x01", $frameLine));
+ $frameLine = join('&#8901;', explode("\0", $frameLine));
+ }
+
+ ?>
+ <style>
+ .p { background-color: yellow; }
+ .m { background-color: #00FF00; }
+ .s { background-color: #FF0000; }
+ .c { background-color: aqua; }
+ .x { background-color: pink; }
+ .f { background-color: gold; }
+ </style>
+ <?php
+ echo "<pre><tt>";
+ echo join("<br/ >", $frame);
+ echo "</tt></pre>";
+
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function serial($frame)
+ {
+ return gzcompress(join("\n", $frame), 9);
+ }
+
+ //----------------------------------------------------------------------
+ public static function unserial($code)
+ {
+ return explode("\n", gzuncompress($code));
+ }
+
+ //----------------------------------------------------------------------
+ public static function newFrame($version)
+ {
+ if($version < 1 || $version > QRSPEC_VERSION_MAX)
+ return null;
+
+ if(!isset(self::$frames[$version])) {
+
+ $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat';
+
+ if (QR_CACHEABLE) {
+ if (file_exists($fileName)) {
+ self::$frames[$version] = self::unserial(file_get_contents($fileName));
+ } else {
+ self::$frames[$version] = self::createFrame($version);
+ file_put_contents($fileName, self::serial(self::$frames[$version]));
+ }
+ } else {
+ self::$frames[$version] = self::createFrame($version);
+ }
+ }
+
+ if(is_null(self::$frames[$version]))
+ return null;
+
+ return self::$frames[$version];
+ }
+
+ //----------------------------------------------------------------------
+ public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; }
+ public static function rsBlockNum1($spec) { return $spec[0]; }
+ public static function rsDataCodes1($spec) { return $spec[1]; }
+ public static function rsEccCodes1($spec) { return $spec[2]; }
+ public static function rsBlockNum2($spec) { return $spec[3]; }
+ public static function rsDataCodes2($spec) { return $spec[4]; }
+ public static function rsEccCodes2($spec) { return $spec[2]; }
+ public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); }
+ public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; }
+
+ } \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrsplit.php b/admin/survey/classes/phpqrcode/qrsplit.php
new file mode 100644
index 0000000..d75b827
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrsplit.php
@@ -0,0 +1,311 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Input splitting classes
+ *
+ * Based on libqrencode C library distributed under LGPL 2.1
+ * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * The following data / specifications are taken from
+ * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
+ * or
+ * "Automatic identification and data capture techniques --
+ * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+ class QRsplit {
+
+ public $dataStr = '';
+ public $input;
+ public $modeHint;
+
+ //----------------------------------------------------------------------
+ public function __construct($dataStr, $input, $modeHint)
+ {
+ $this->dataStr = $dataStr;
+ $this->input = $input;
+ $this->modeHint = $modeHint;
+ }
+
+ //----------------------------------------------------------------------
+ public static function isdigitat($str, $pos)
+ {
+ if ($pos >= strlen($str))
+ return false;
+
+ return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9')));
+ }
+
+ //----------------------------------------------------------------------
+ public static function isalnumat($str, $pos)
+ {
+ if ($pos >= strlen($str))
+ return false;
+
+ return (QRinput::lookAnTable(ord($str[$pos])) >= 0);
+ }
+
+ //----------------------------------------------------------------------
+ public function identifyMode($pos)
+ {
+ if ($pos >= strlen($this->dataStr))
+ return QR_MODE_NUL;
+
+ $c = $this->dataStr[$pos];
+
+ if(self::isdigitat($this->dataStr, $pos)) {
+ return QR_MODE_NUM;
+ } else if(self::isalnumat($this->dataStr, $pos)) {
+ return QR_MODE_AN;
+ } else if($this->modeHint == QR_MODE_KANJI) {
+
+ if ($pos+1 < strlen($this->dataStr))
+ {
+ $d = $this->dataStr[$pos+1];
+ $word = (ord($c) << 8) | ord($d);
+ if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) {
+ return QR_MODE_KANJI;
+ }
+ }
+ }
+
+ return QR_MODE_8;
+ }
+
+ //----------------------------------------------------------------------
+ public function eatNum()
+ {
+ $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
+
+ $p = 0;
+ while(self::isdigitat($this->dataStr, $p)) {
+ $p++;
+ }
+
+ $run = $p;
+ $mode = $this->identifyMode($p);
+
+ if($mode == QR_MODE_8) {
+ $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln
+ + QRinput::estimateBitsMode8(1) // + 4 + l8
+ - QRinput::estimateBitsMode8($run + 1); // - 4 - l8
+ if($dif > 0) {
+ return $this->eat8();
+ }
+ }
+ if($mode == QR_MODE_AN) {
+ $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln
+ + QRinput::estimateBitsModeAn(1) // + 4 + la
+ - QRinput::estimateBitsModeAn($run + 1);// - 4 - la
+ if($dif > 0) {
+ return $this->eatAn();
+ }
+ }
+
+ $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr));
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function eatAn()
+ {
+ $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());
+ $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
+
+ $p = 0;
+
+ while(self::isalnumat($this->dataStr, $p)) {
+ if(self::isdigitat($this->dataStr, $p)) {
+ $q = $p;
+ while(self::isdigitat($this->dataStr, $q)) {
+ $q++;
+ }
+
+ $dif = QRinput::estimateBitsModeAn($p) // + 4 + la
+ + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln
+ - QRinput::estimateBitsModeAn($q); // - 4 - la
+
+ if($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else {
+ $p++;
+ }
+ }
+
+ $run = $p;
+
+ if(!self::isalnumat($this->dataStr, $p)) {
+ $dif = QRinput::estimateBitsModeAn($run) + 4 + $la
+ + QRinput::estimateBitsMode8(1) // + 4 + l8
+ - QRinput::estimateBitsMode8($run + 1); // - 4 - l8
+ if($dif > 0) {
+ return $this->eat8();
+ }
+ }
+
+ $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr));
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function eatKanji()
+ {
+ $p = 0;
+
+ while($this->identifyMode($p) == QR_MODE_KANJI) {
+ $p += 2;
+ }
+
+ $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr));
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function eat8()
+ {
+ $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());
+ $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
+
+ $p = 1;
+ $dataStrLen = strlen($this->dataStr);
+
+ while($p < $dataStrLen) {
+
+ $mode = $this->identifyMode($p);
+ if($mode == QR_MODE_KANJI) {
+ break;
+ }
+ if($mode == QR_MODE_NUM) {
+ $q = $p;
+ while(self::isdigitat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = QRinput::estimateBitsMode8($p) // + 4 + l8
+ + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln
+ - QRinput::estimateBitsMode8($q); // - 4 - l8
+ if($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else if($mode == QR_MODE_AN) {
+ $q = $p;
+ while(self::isalnumat($this->dataStr, $q)) {
+ $q++;
+ }
+ $dif = QRinput::estimateBitsMode8($p) // + 4 + l8
+ + QRinput::estimateBitsModeAn($q - $p) + 4 + $la
+ - QRinput::estimateBitsMode8($q); // - 4 - l8
+ if($dif < 0) {
+ break;
+ } else {
+ $p = $q;
+ }
+ } else {
+ $p++;
+ }
+ }
+
+ $run = $p;
+ $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr));
+
+ if($ret < 0)
+ return -1;
+
+ return $run;
+ }
+
+ //----------------------------------------------------------------------
+ public function splitString()
+ {
+ while (strlen($this->dataStr) > 0)
+ {
+ if($this->dataStr == '')
+ return 0;
+
+ $mode = $this->identifyMode(0);
+
+ switch ($mode) {
+ case QR_MODE_NUM: $length = $this->eatNum(); break;
+ case QR_MODE_AN: $length = $this->eatAn(); break;
+ case QR_MODE_KANJI:
+ if ($hint == QR_MODE_KANJI)
+ $length = $this->eatKanji();
+ else $length = $this->eat8();
+ break;
+ default: $length = $this->eat8(); break;
+
+ }
+
+ if($length == 0) return 0;
+ if($length < 0) return -1;
+
+ $this->dataStr = substr($this->dataStr, $length);
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public function toUpper()
+ {
+ $stringLen = strlen($this->dataStr);
+ $p = 0;
+
+ while ($p<$stringLen) {
+ $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint);
+ if($mode == QR_MODE_KANJI) {
+ $p += 2;
+ } else {
+ if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) {
+ $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32);
+ }
+ $p++;
+ }
+ }
+
+ return $this->dataStr;
+ }
+
+ //----------------------------------------------------------------------
+ public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true)
+ {
+ if(is_null($string) || $string == '\0' || $string == '') {
+ throw new Exception('empty string!!!');
+ }
+
+ $split = new QRsplit($string, $input, $modeHint);
+
+ if(!$casesensitive)
+ $split->toUpper();
+
+ return $split->splitString();
+ }
+ } \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/qrtools.php b/admin/survey/classes/phpqrcode/qrtools.php
new file mode 100644
index 0000000..3012db4
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/qrtools.php
@@ -0,0 +1,172 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Toolset, handy and debug utilites.
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ class QRtools {
+
+ //----------------------------------------------------------------------
+ public static function binarize($frame)
+ {
+ $len = count($frame);
+ foreach ($frame as &$frameLine) {
+
+ for($i=0; $i<$len; $i++) {
+ $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';
+ }
+ }
+
+ return $frame;
+ }
+
+ //----------------------------------------------------------------------
+ public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037')
+ {
+ $barcode_array = array();
+
+ if (!is_array($mode))
+ $mode = explode(',', $mode);
+
+ $eccLevel = 'L';
+
+ if (count($mode) > 1) {
+ $eccLevel = $mode[1];
+ }
+
+ $qrTab = QRcode::text($code, false, $eccLevel);
+ $size = count($qrTab);
+
+ $barcode_array['num_rows'] = $size;
+ $barcode_array['num_cols'] = $size;
+ $barcode_array['bcode'] = array();
+
+ foreach ($qrTab as $line) {
+ $arrAdd = array();
+ foreach(str_split($line) as $char)
+ $arrAdd[] = ($char=='1')?1:0;
+ $barcode_array['bcode'][] = $arrAdd;
+ }
+
+ return $barcode_array;
+ }
+
+ //----------------------------------------------------------------------
+ public static function clearCache()
+ {
+ self::$frames = array();
+ }
+
+ //----------------------------------------------------------------------
+ public static function buildCache()
+ {
+ QRtools::markTime('before_build_cache');
+
+ $mask = new QRmask();
+ for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) {
+ $frame = QRspec::newFrame($a);
+ if (QR_IMAGE) {
+ $fileName = QR_CACHE_DIR.'frame_'.$a.'.png';
+ QRimage::png(self::binarize($frame), $fileName, 1, 0);
+ }
+
+ $width = count($frame);
+ $bitMask = array_fill(0, $width, array_fill(0, $width, 0));
+ for ($maskNo=0; $maskNo<8; $maskNo++)
+ $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true);
+ }
+
+ QRtools::markTime('after_build_cache');
+ }
+
+ //----------------------------------------------------------------------
+ public static function log($outfile, $err)
+ {
+ if (QR_LOG_DIR !== false) {
+ if ($err != '') {
+ if ($outfile !== false) {
+ file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
+ } else {
+ file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
+ }
+ }
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function dumpMask($frame)
+ {
+ $width = count($frame);
+ for($y=0;$y<$width;$y++) {
+ for($x=0;$x<$width;$x++) {
+ echo ord($frame[$y][$x]).',';
+ }
+ }
+ }
+
+ //----------------------------------------------------------------------
+ public static function markTime($markerId)
+ {
+ list($usec, $sec) = explode(" ", microtime());
+ $time = ((float)$usec + (float)$sec);
+
+ if (!isset($GLOBALS['qr_time_bench']))
+ $GLOBALS['qr_time_bench'] = array();
+
+ $GLOBALS['qr_time_bench'][$markerId] = $time;
+ }
+
+ //----------------------------------------------------------------------
+ public static function timeBenchmark()
+ {
+ self::markTime('finish');
+
+ $lastTime = 0;
+ $startTime = 0;
+ $p = 0;
+
+ echo '<table cellpadding="3" cellspacing="1">
+ <thead><tr style="border-bottom:1px solid silver"><td colspan="2" style="text-align:center">BENCHMARK</td></tr></thead>
+ <tbody>';
+
+ foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) {
+ if ($p > 0) {
+ echo '<tr><th style="text-align:right">till '.$markerId.': </th><td>'.number_format($thisTime-$lastTime, 6).'s</td></tr>';
+ } else {
+ $startTime = $thisTime;
+ }
+
+ $p++;
+ $lastTime = $thisTime;
+ }
+
+ echo '</tbody><tfoot>
+ <tr style="border-top:2px solid black"><th style="text-align:right">TOTAL: </th><td>'.number_format($lastTime-$startTime, 6).'s</td></tr>
+ </tfoot>
+ </table>';
+ }
+
+ }
+
+ //##########################################################################
+
+ QRtools::markTime('start');
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/tools/merge.bat b/admin/survey/classes/phpqrcode/tools/merge.bat
new file mode 100644
index 0000000..b60a485
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/tools/merge.bat
@@ -0,0 +1,2 @@
+php ./merge.php
+pause \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/tools/merge.php b/admin/survey/classes/phpqrcode/tools/merge.php
new file mode 100644
index 0000000..19d338b
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/tools/merge.php
@@ -0,0 +1,70 @@
+<?php
+
+/*
+ * PHP QR Code encoder
+ *
+ * Tool for merging all library files into one, simpler to incorporate.
+ *
+ * MAKE SURE THAT RESULTING PHPQRCode.php (and its dir) ARE WRITABLE!
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ $QR_BASEDIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR;
+ $QR_TOOLSDIR = dirname(__FILE__).DIRECTORY_SEPARATOR;
+
+ $outputFile = $QR_BASEDIR.'phpqrcode.php';
+
+ // Required libs
+
+ $fileList = array(
+ $QR_BASEDIR.'qrconst.php',
+ $QR_TOOLSDIR.'merged_config.php',
+ $QR_BASEDIR.'qrtools.php',
+ $QR_BASEDIR.'qrspec.php',
+ $QR_BASEDIR.'qrimage.php',
+ $QR_BASEDIR.'qrinput.php',
+ $QR_BASEDIR.'qrbitstream.php',
+ $QR_BASEDIR.'qrsplit.php',
+ $QR_BASEDIR.'qrrscode.php',
+ $QR_BASEDIR.'qrmask.php',
+ $QR_BASEDIR.'qrencode.php'
+ );
+
+ $headerFile = $QR_TOOLSDIR.'merged_header.php';
+ $versionFile = $QR_BASEDIR.'VERSION';
+
+ $outputCode = '';
+
+ foreach($fileList as $fileName) {
+ $outputCode .= "\n\n".'//---- '.basename($fileName).' -----------------------------'."\n\n";
+ $anotherCode = file_get_contents($fileName);
+ $anotherCode = preg_replace ('/^<\?php/', '', $anotherCode);
+ $anotherCode = preg_replace ('/\?>\*$/', '', $anotherCode);
+ $outputCode .= "\n\n".$anotherCode."\n\n";
+ }
+
+ $versionDataEx = explode("\n", file_get_contents($versionFile));
+
+ $outputContents = file_get_contents($headerFile);
+ $outputContents .= "\n\n/*\n * Version: ".trim($versionDataEx[0])."\n * Build: ".trim($versionDataEx[1])."\n */\n\n";
+ $outputContents .= $outputCode;
+
+ file_put_contents($outputFile, $outputContents);
+
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/tools/merge.sh b/admin/survey/classes/phpqrcode/tools/merge.sh
new file mode 100644
index 0000000..e4c2fbc
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/tools/merge.sh
@@ -0,0 +1,2 @@
+#!/bin/sh
+php ./merge.php \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/tools/merged_config.php b/admin/survey/classes/phpqrcode/tools/merged_config.php
new file mode 100644
index 0000000..55ddb45
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/tools/merged_config.php
@@ -0,0 +1,17 @@
+<?php
+/*
+ * PHP QR Code encoder
+ *
+ * Config file, tuned-up for merged verion
+ */
+
+ define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there
+ define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true
+ define('QR_LOG_DIR', false); // default error logs dir
+
+ define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
+ define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
+ define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false
+
+ define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images
+ \ No newline at end of file
diff --git a/admin/survey/classes/phpqrcode/tools/merged_header.php b/admin/survey/classes/phpqrcode/tools/merged_header.php
new file mode 100644
index 0000000..25805e5
--- /dev/null
+++ b/admin/survey/classes/phpqrcode/tools/merged_header.php
@@ -0,0 +1,36 @@
+<?php
+
+/*
+ * PHP QR Code encoder
+ *
+ * This file contains MERGED version of PHP QR Code library.
+ * It was auto-generated from full version for your convenience.
+ *
+ * This merged version was configured to not requre any external files,
+ * with disabled cache, error loging and weker but faster mask matching.
+ * If you need tune it up please use non-merged version.
+ *
+ * For full version, documentation, examples of use please visit:
+ *
+ * http://phpqrcode.sourceforge.net/
+ * https://sourceforge.net/projects/phpqrcode/
+ *
+ * PHP QR Code is distributed under LGPL 3
+ * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+ \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.html b/admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.html
new file mode 100644
index 0000000..02d8688
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.html
@@ -0,0 +1,363 @@
+ <table class="anl_tbl anl_bt anl_br tbl_clps">
+ <tbody>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span
+ class="anl_variabla"><a href="#"
+ </td>
+ <td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="5"><span
+ class="anl_variabla_label">Spol</span></td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span
+ class="taCenter printHide iconHide"><a href="#"><span
+ class="sprites analysis_sums_gray"
+ title="Sumarne frekvence (print, pdf, word, excel)"></span></a><a
+ href="#"><span
+ class="sprites analysis_sums_new_gray"
+ title="Dopolnjene frekvence (print, pdf, word, excel)"></span></a><a
+ href="#" ><span
+ class="sprites analysis_statistic_gray"
+ title="Opisne statistike (print, pdf, word, excel)"></span></a><a
+ href="#" ><span
+ class="sprites analysis_frequencys"
+ title="Osnovne frekvence (print, pdf, word, excel)"></span></a></span></td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div>
+ (Moški)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">3</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">33.3%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div>
+ (Ženski)</td>
+ <td class="anl_ac anl_br anl_bck_0_1">6</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">100.0%</td>
+ </tr>
+ <tr class="anl_bb">
+ <td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span
+ class="gray" value="0">&nbsp;(<span
+ class="sprites plus_orange folder_plusminus"
+ style="width: 12px; height: 12px"></span>)
+ </span><span
+ class="gray displayNone">&nbsp;(<span
+ class="sprites minus_orange folder_plusminus"
+ style="width: 12px; height: 12px"></span>)
+ </span></td>
+ <td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td>
+ <td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td>
+ </tr>
+ <tr class="anl_dash_red_bb displayNone">
+ <td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td>
+ <td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span
+ class="printHide anl_ita anl_detail_percent">&nbsp;&nbsp;<a
+ href="#single_missing_6" > <span
+ class="sprites plus_orange folder_plusminus"
+ style="width: 12px; height: 12px"></span>
+ </a></span><span
+ class="printHide anl_ita anl_detail_percent displayNone">&nbsp;&nbsp;<a
+ href="#single_missing_6" > <span
+ class="sprites minus_orange folder_plusminus"
+ style="width: 12px; height: 12px"></span>
+ </a></span>
+ <div
+ class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div>
+ <div
+ class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"></div>
+ </td>
+ <td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span
+ class="">&nbsp;</span></td>
+ <td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td>
+ </tr>
+ <tr class="displayNone">
+ <td
+ class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td>
+ <td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td>
+ <td
+ class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td>
+ <td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <br>
+ <table class="anl_tbl anl_bt anl_br tbl_clps">
+ <tbody>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span
+ class="anl_variabla"><a
+ href="#">Q2</a></span></td>
+ <td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span
+ class="anl_variabla_label">Dohodek</span></td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span
+ class="taCenter printHide iconHide"><a
+ href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a
+ href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic_gray"></span></a><a
+ href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys"></span></a></span></td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">900</div></td>
+ <td class="anl_ac anl_br anl_bck_0_0">1</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">11.1%</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">1000</div></td>
+ <td class="anl_ac anl_br anl_bck_0_1">1</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">22.2%</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1300</div></td>
+ <td class="anl_ac anl_br anl_bck_0_0">3</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">55.6%</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">1500</div></td>
+ <td class="anl_ac anl_br anl_bck_0_1">1</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">66.7%</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1600</div></td>
+ <td class="anl_ac anl_br anl_bck_0_0">1</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">77.8%</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">1700</div></td>
+ <td class="anl_ac anl_br anl_bck_0_1">1</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">88.9%</td>
+ </tr>
+ <tr
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">2000</div></td>
+ <td class="anl_ac anl_br anl_bck_0_0">1</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">100.0%</td>
+ </tr>
+ <tr class="anl_bb">
+ <td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span
+ value="0" class="gray" >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>)
+ </span><span class="anl_gray displayNone"
+ >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>)
+ </span></td>
+ <td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td>
+ <td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td>
+ </tr>
+ <tr class="anl_dash_red_bb displayNone" >
+ <td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td>
+ <td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span
+ class="printHide anl_ita anl_detail_percent"
+ >&nbsp;&nbsp;<a
+ href="#single_missing_7"> <span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>
+ </a></span><span class="printHide anl_ita anl_detail_percent displayNone"
+ >&nbsp;&nbsp;<a
+ href="#single_missing_7"> <span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>
+ </a></span>
+ <div
+ class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone"
+ >100.0%</div>
+ <div
+ class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"
+ ></div>
+ </td>
+ <td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td>
+ <td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td>
+ </tr>
+ <tr class="displayNone" >
+ <td
+ class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td>
+ <td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td>
+ <td
+ class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td>
+ <td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td>
+ </tr>
+ </tbody>
+ </table>
+ <br>
+ <table class="anl_tbl anl_bt anl_br tbl_clps">
+ <tbody>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span
+ class="anl_variabla"><a
+ href="#">Q3</a></span></td>
+ <td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span
+ class="anl_variabla_label">Država</span></td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span
+ class="taCenter printHide iconHide"><a
+ href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a
+ href="#"><span
+ title="Dopolnjene frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_new_gray"></span></a><a
+ href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic_gray"></span></a><a
+ href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys"></span></a></span></td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div>
+ (Slovenija)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">2</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">22.2%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div>
+ (Hrvaška)</td>
+ <td class="anl_ac anl_br anl_bck_0_1">2</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">44.4%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">3</div>
+ (Avstrija)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">2</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">66.7%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">4</div>
+ (Italija)</td>
+ <td class="anl_ac anl_br anl_bck_0_1">1</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">77.8%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">5</div>
+ (Madžarska)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">2</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">100.0%</td>
+ </tr>
+ <tr class="anl_bb" >
+ <td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span
+ value="0" class="gray" >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>)
+ </span><span class="anl_gray displayNone"
+ >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>)
+ </span></td>
+ <td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td>
+ <td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td>
+ </tr>
+ <tr class="anl_dash_red_bb displayNone" >
+ <td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td>
+ <td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span
+ class="printHide anl_ita anl_detail_percent"
+ >&nbsp;&nbsp;<a
+ href="#single_missing_8"> <span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>
+ </a></span><span class="printHide anl_ita anl_detail_percent displayNone"
+ >&nbsp;&nbsp;<a
+ href="#single_missing_8"> <span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>
+ </a></span>
+ <div
+ class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone"
+ >100.0%</div>
+ <div
+ class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"
+ ></div>
+ </td>
+ <td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span
+ >&nbsp;</span></td>
+ <td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td>
+ </tr>
+ <tr class="displayNone" >
+ <td
+ class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td>
+ <td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td>
+ <td
+ class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td>
+ <td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td>
+ </tr>
+ </tbody>
+ </table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.min.html
new file mode 100644
index 0000000..0ebaca2
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledFrekvence.min.html
@@ -0,0 +1,2 @@
+
+<table class="anl_tbl anl_bt anl_br tbl_clps"><tbody><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span class="anl_variabla"><a href="#" </td><td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="5"><span class="anl_variabla_label">Spol</span></td></tr><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span class="taCenter printHide iconHide"><a href="#"><span class="sprites analysis_sums_gray" title="Sumarne frekvence (print, pdf, word, excel)"></span></a><a href="#"><span class="sprites analysis_sums_new_gray" title="Dopolnjene frekvence (print, pdf, word, excel)"></span></a><a href="#"><span class="sprites analysis_statistic_gray" title="Opisne statistike (print, pdf, word, excel)"></span></a><a href="#"><span class="sprites analysis_frequencys" title="Osnovne frekvence (print, pdf, word, excel)"></span></a></span></td><td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div> (Moški)</td><td class="anl_ac anl_br anl_bck_0_0">3</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td><td class="anl_ar anl_bck_0_0 anl_pr10">33.3%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div> (Ženski)</td><td class="anl_ac anl_br anl_bck_0_1">6</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td><td class="anl_ar anl_bck_0_1 anl_pr10">100.0%</td></tr><tr class="anl_bb"><td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span class="gray" value="0">&nbsp;(<span class="sprites plus_orange folder_plusminus" style="width: 12px; height: 12px"></span>) </span><span class="gray displayNone">&nbsp;(<span class="sprites minus_orange folder_plusminus" style="width: 12px; height: 12px"></span>) </span></td><td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td><td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td></tr><tr class="anl_dash_red_bb displayNone"><td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td><td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span class="printHide anl_ita anl_detail_percent">&nbsp;&nbsp;<a href="#single_missing_6"><span class="sprites plus_orange folder_plusminus" style="width: 12px; height: 12px"></span></a></span><span class="printHide anl_ita anl_detail_percent displayNone">&nbsp;&nbsp;<a href="#single_missing_6"><span class="sprites minus_orange folder_plusminus" style="width: 12px; height: 12px"></span></a></span><div class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div><div class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"></div></td><td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span class="">&nbsp;</span></td><td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td></tr><tr class="displayNone"><td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td><td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td><td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td><td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td></tr></tbody></table><br><table class="anl_tbl anl_bt anl_br tbl_clps"><tbody><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span class="anl_variabla"><a href="#">Q2</a></span></td><td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span class="anl_variabla_label">Dohodek</span></td></tr><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic_gray"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys"></span></a></span></td><td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">900</div></td><td class="anl_ac anl_br anl_bck_0_0">1</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_0 anl_pr10">11.1%</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">1000</div></td><td class="anl_ac anl_br anl_bck_0_1">1</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_1 anl_pr10">22.2%</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1300</div></td><td class="anl_ac anl_br anl_bck_0_0">3</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td><td class="anl_ar anl_bck_0_0 anl_pr10">55.6%</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">1500</div></td><td class="anl_ac anl_br anl_bck_0_1">1</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_1 anl_pr10">66.7%</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1600</div></td><td class="anl_ac anl_br anl_bck_0_0">1</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_0 anl_pr10">77.8%</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">1700</div></td><td class="anl_ac anl_br anl_bck_0_1">1</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_1 anl_pr10">88.9%</td></tr><tr <td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">2000</div></td><td class="anl_ac anl_br anl_bck_0_0">1</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_0 anl_pr10">100.0%</td></tr><tr class="anl_bb"><td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span value="0" class="gray">&nbsp;(<span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span>) </span><span class="anl_gray displayNone">&nbsp;(<span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span>) </span></td><td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td><td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td></tr><tr class="anl_dash_red_bb displayNone"><td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td><td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span class="printHide anl_ita anl_detail_percent">&nbsp;&nbsp;<a href="#single_missing_7"><span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span></a></span><span class="printHide anl_ita anl_detail_percent displayNone">&nbsp;&nbsp;<a href="#single_missing_7"><span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span></a></span><div class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div><div class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"></div></td><td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td><td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td></tr><tr class="displayNone"><td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td><td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td><td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td><td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td></tr></tbody></table><br><table class="anl_tbl anl_bt anl_br tbl_clps"><tbody><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span class="anl_variabla"><a href="#">Q3</a></span></td><td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span class="anl_variabla_label">Država</span></td></tr><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Dopolnjene frekvence (print, pdf, word, excel)" class="sprites analysis_sums_new_gray"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic_gray"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys"></span></a></span></td><td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div> (Slovenija)</td><td class="anl_ac anl_br anl_bck_0_0">2</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_0 anl_pr10">22.2%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div> (Hrvaška)</td><td class="anl_ac anl_br anl_bck_0_1">2</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_1 anl_pr10">44.4%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">3</div> (Avstrija)</td><td class="anl_ac anl_br anl_bck_0_0">2</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_0 anl_pr10">66.7%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">4</div> (Italija)</td><td class="anl_ac anl_br anl_bck_0_1">1</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_1 anl_pr10">77.8%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">5</div> (Madžarska)</td><td class="anl_ac anl_br anl_bck_0_0">2</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_0 anl_pr10">100.0%</td></tr><tr class="anl_bb"><td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span value="0" class="gray">&nbsp;(<span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span>) </span><span class="anl_gray displayNone">&nbsp;(<span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span>) </span></td><td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td><td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td></tr><tr class="anl_dash_red_bb displayNone"><td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td><td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span class="printHide anl_ita anl_detail_percent">&nbsp;&nbsp;<a href="#single_missing_8"><span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span></a></span><span class="printHide anl_ita anl_detail_percent displayNone">&nbsp;&nbsp;<a href="#single_missing_8"><span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span></a></span><div class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div><div class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"></div></td><td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span>&nbsp;</span></td><td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td></tr><tr class="displayNone"><td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td><td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td><td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td><td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.html b/admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.html
new file mode 100644
index 0000000..ed1252c
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.html
@@ -0,0 +1,330 @@
+<!-- <br>Χ<sup>2</sup> = 4.500--><table gd2="undefined" sp2="149_0" sq2="6" gd1="undefined" sp1="153_0"
+ sq1="8" style="padding: 0px; margin: 0px; margin-top: 10px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <colgroup>
+ <col style="width: auto; min-width: 100px;">
+ <col style="width: auto; min-width: 100px;">
+ <col style="width: 12%;">
+ <col style="width: 12%;">
+ <col style="width: 12%;">
+ <col style="width: 12%;">
+ <col style="width: 12%;">
+ <col style="width: 12%;">
+ </colgroup>
+ <tbody>
+ <tr>
+ <td rowspan="2" colspan="2">&nbsp;</td>
+ <td colspan="6" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a title="Predogled vprašanja" href="/">Spol&nbsp;(Q2)</a></span>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="3" class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Moški<br>
+ ( 1 )
+ </td>
+ <td colspan="3" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_variable1 ctbCll">Ženska<br>
+ ( 2 )
+ </td>
+ </tr>
+ <tr>
+ <td rowspan="2" colspan="2">&nbsp;</td>
+ <td colspan="3" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a title="Predogled vprašanja" href="/">Starost&nbsp;(Q3)</a></span>
+ </td>
+ <td colspan="3" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a title="Predogled vprašanja" href="/">Starost&nbsp;(Q3)</a></span>
+ </td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">pod 20<br>
+ ( 1 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">20 - 40<br>
+ ( 2 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">nad 40<br>
+ ( 3 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">pod 20<br>
+ ( 1 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">20 - 40<br>
+ ( 2 )
+ </td>
+ <td class="anl_bt anl_bl anl_br anl_ac rsdl_bck_variable1 ctbCll">nad 40<br>
+ ( 3 )
+ </td>
+ </tr>
+
+
+ <tr>
+ <td rowspan="5" class="anl_bt anl_bb anl_bl anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a title="Predogled vprašanja" href="/">Država&nbsp;(Q1)</a></span>
+ </td>
+
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Slovenija<br>
+ ( 1 )
+ </td>
+ <td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell anl_br"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Hrvaška<br>
+ ( 2 )
+ </td>
+ <td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">4</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell anl_br"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Avstrija<br>
+ ( 3 )
+ </td>
+ <td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell anl_br"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">3</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Italija<br>
+ ( 4 )
+ </td>
+ <td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell anl_br"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Madžarska<br>
+ ( 5 )
+ </td>
+ <td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1"
+ class="ct_in_cell anl_bb"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2"
+ class="ct_in_cell anl_bb"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3"
+ class="ct_in_cell anl_bb"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4"
+ class="ct_in_cell anl_bb"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell anl_bb"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell anl_br anl_bb"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ </tbody>
+ </table>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.min.html
new file mode 100644
index 0000000..801bc2c
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledMultitabele.min.html
@@ -0,0 +1,2 @@
+
+<table gd2="undefined" sp2="149_0" sq2="6" gd1="undefined" sp1="153_0" sq1="8" style="padding: 0px; margin: 0px; margin-top: 10px;" class="anl_tbl_crosstab fullWidth fullHeight"><colgroup><col style="width: auto; min-width: 100px;"><col style="width: auto; min-width: 100px;"><col style="width: 12%;"><col style="width: 12%;"><col style="width: 12%;"><col style="width: 12%;"><col style="width: 12%;"><col style="width: 12%;"></colgroup><tbody><tr><td rowspan="2" colspan="2">&nbsp;</td><td colspan="6" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Spol&nbsp;(Q2)</a></span></td></tr><tr><td colspan="3" class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Moški<br> ( 1 ) </td><td colspan="3" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_variable1 ctbCll">Ženska<br> ( 2 ) </td></tr><tr><td rowspan="2" colspan="2">&nbsp;</td><td colspan="3" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Starost&nbsp;(Q3)</a></span></td><td colspan="3" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Starost&nbsp;(Q3)</a></span></td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">pod 20<br> ( 1 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">20 - 40<br> ( 2 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">nad 40<br> ( 3 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">pod 20<br> ( 1 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">20 - 40<br> ( 2 ) </td><td class="anl_bt anl_bl anl_br anl_ac rsdl_bck_variable1 ctbCll">nad 40<br> ( 3 ) </td></tr><tr><td rowspan="5" class="anl_bt anl_bb anl_bl anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Država&nbsp;(Q1)</a></span></td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Slovenija<br> ( 1 ) </td><td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell anl_br"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Hrvaška<br> ( 2 ) </td><td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">4</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">2</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell anl_br"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Avstrija<br> ( 3 ) </td><td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">2</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell anl_br"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">3</td></tr></tbody></table></td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Italija<br> ( 4 ) </td><td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell anl_br"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Madžarska<br> ( 5 ) </td><td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1" class="ct_in_cell anl_bb"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2" class="ct_in_cell anl_bb"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">2</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3" class="ct_in_cell anl_bb"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4" class="ct_in_cell anl_bb"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell anl_bb"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell anl_br anl_bb"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">0</td></tr></tbody></table></td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.html b/admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.html
new file mode 100644
index 0000000..bb3736a
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.html
@@ -0,0 +1,108 @@
+ <table class="anl_tbl anl_ba">
+ <tbody>
+ <tr>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w70">Variabla<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Vprašanje<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Veljavni<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-1 (Ni odgovoril)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-2 (Preskok (if))<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-3 (Prekinjeno)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-4 (Naknadno vprasanje)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-5 (Prazna enota)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-97 (Neustrezno)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-98 (Zavrnil)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-99 (Ne vem)<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Ustrezni<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Vse enote<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">NS<span></span></td>
+ </tr>
+
+
+ <tr>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q1</a></span></td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_bt">Spol</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">10</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">34</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">44</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">53</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.8</td>
+ </tr>
+ <tr>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">23%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">77%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ </tr>
+
+
+ <tr>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q2</a></span></td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_bt">Dohodek</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">15</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">29</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">44</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">53</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.7</td>
+ </tr>
+ <tr>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">34%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">66%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ </tr>
+
+
+ <tr>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q3</a></span></td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_bt">Država</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">6</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">38</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">44</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">53</td>
+ <td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.9</td>
+ </tr>
+ <tr>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">14%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">86%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td>
+ </tr>
+
+ </tbody>
+ </table>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.min.html
new file mode 100644
index 0000000..6625b21
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledNeodgovori.min.html
@@ -0,0 +1,2 @@
+
+<table class="anl_tbl anl_ba"><tbody><tr><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w70">Variabla<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Vprašanje<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Veljavni<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-1 (Ni odgovoril)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-2 (Preskok (if))<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-3 (Prekinjeno)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-4 (Naknadno vprasanje)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-5 (Prazna enota)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-97 (Neustrezno)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-98 (Zavrnil)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">-99 (Ne vem)<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Ustrezni<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Vse enote<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">NS<span></span></td></tr><tr><td rowspan="2" class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q1</a></span></td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_bt">Spol</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">10</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">34</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">44</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">53</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.8</td></tr><tr><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">23%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">77%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td></tr><tr><td rowspan="2" class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q2</a></span></td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_bt">Dohodek</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">15</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">29</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">44</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">53</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.7</td></tr><tr><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">34%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">66%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td></tr><tr><td rowspan="2" class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q3</a></span></td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_bt">Država</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">6</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">38</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">44</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">53</td><td rowspan="2" class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.9</td></tr><tr><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">14%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">86%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0%</td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledOpisne.html b/admin/survey/classes/staticHtml/AnalizaPredogledOpisne.html
new file mode 100644
index 0000000..34781b4
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledOpisne.html
@@ -0,0 +1,106 @@
+ <table class="anl_tbl anl_ba">
+ <tbody>
+ <tr>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w70">&nbsp;<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w110">Spremenljivka<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Vprašanje<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Veljavno<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Št.
+ enot<span></span>
+ </td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Povprečje<br>/&nbsp;odstotek<span></span></td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Std.
+ Odklon<span></span>
+ </td>
+ <td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Minimum<span></span></td>
+ <td class=" anl_ac anl_bck anl_variabla_line anl_bb">Maksimum<span></span></td>
+ </tr>
+ <tr>
+ <td class="anl_bck anl_ac anl_br anl_bt link_no_decoration"><span
+ class="taCenter printHide iconHide"><a
+ href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a
+ href="#"><span
+ title="Dopolnjene frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_new_gray"></span></a><a
+ href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic"></span></a><a
+ href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys_gray"></span></a></span></td>
+ <td class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span
+ class="anl_variabla"><a
+ href="#">Q1</a></span></td>
+ <td class=" anl_bck_desc_1 anl_br anl_bt">Spol</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1.67</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.50</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1</td>
+ <td class=" anl_bck_desc_1 anl_ac anl_bt">2</td>
+ </tr>
+ <tr>
+ <td class="anl_bck anl_ac anl_br anl_bt link_no_decoration"><span
+ class="taCenter printHide iconHide"><a
+ href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a
+ href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic"></span></a><a
+ href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys_gray"></span></a></span></td>
+ <td class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span
+ class="anl_variabla"><a
+ href="#">Q2</a></span></td>
+ <td class=" anl_bck_desc_1 anl_br anl_bt">Dohodek</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">&nbsp;</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">&nbsp;</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt"></td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt"></td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt"></td>
+ <td class=" anl_bck_desc_1 anl_ac anl_bt"></td>
+ </tr>
+ <tr>
+ <td class="anl_bck anl_ac anl_br link_no_decoration">&nbsp;</td>
+ <td
+ class=" anl_bck_desc_2 anl_bt_dot anl_ac anl_br link_no_decoration anl_variabla_sub">Q2</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_tin anl_br">v €</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">9</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">9</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">1,400.00</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">342.78</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">900</td>
+ <td class=" anl_bck_desc_2 anl_bt_dot anl_ac">2000</td>
+ </tr>
+ <tr>
+ <td class="anl_bck anl_ac anl_br anl_bt link_no_decoration"><span
+ class="taCenter printHide iconHide"><a
+ href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a
+ href="#"><span
+ title="Dopolnjene frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_new_gray"></span></a><a
+ href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic"></span></a><a
+ href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys_gray"></span></a></span></td>
+ <td class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span
+ class="anl_variabla"><a
+ href="#">Q3</a></span></td>
+ <td class=" anl_bck_desc_1 anl_br anl_bt">Država</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">2.89</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1.54</td>
+ <td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1</td>
+ <td class=" anl_bck_desc_1 anl_ac anl_bt">5</td>
+ </tr>
+ </tbody>
+ </table>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledOpisne.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledOpisne.min.html
new file mode 100644
index 0000000..5d70fd4
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledOpisne.min.html
@@ -0,0 +1,2 @@
+
+<table class="anl_tbl anl_ba"><tbody><tr><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w70">&nbsp;<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w110">Spremenljivka<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Vprašanje<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Veljavno<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Št. enot<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Povprečje<br>/&nbsp;odstotek<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Std. Odklon<span></span></td><td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">Minimum<span></span></td><td class=" anl_ac anl_bck anl_variabla_line anl_bb">Maksimum<span></span></td></tr><tr><td class="anl_bck anl_ac anl_br anl_bt link_no_decoration"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Dopolnjene frekvence (print, pdf, word, excel)" class="sprites analysis_sums_new_gray"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys_gray"></span></a></span></td><td class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q1</a></span></td><td class=" anl_bck_desc_1 anl_br anl_bt">Spol</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1.67</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">0.50</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1</td><td class=" anl_bck_desc_1 anl_ac anl_bt">2</td></tr><tr><td class="anl_bck anl_ac anl_br anl_bt link_no_decoration"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys_gray"></span></a></span></td><td class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q2</a></span></td><td class=" anl_bck_desc_1 anl_br anl_bt">Dohodek</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">&nbsp;</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">&nbsp;</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt"></td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt"></td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt"></td><td class=" anl_bck_desc_1 anl_ac anl_bt"></td></tr><tr><td class="anl_bck anl_ac anl_br link_no_decoration">&nbsp;</td><td class=" anl_bck_desc_2 anl_bt_dot anl_ac anl_br link_no_decoration anl_variabla_sub">Q2</td><td class=" anl_bck_desc_2 anl_bt_dot anl_tin anl_br">v €</td><td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">9</td><td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">9</td><td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">1,400.00</td><td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">342.78</td><td class=" anl_bck_desc_2 anl_bt_dot anl_br anl_ac">900</td><td class=" anl_bck_desc_2 anl_bt_dot anl_ac">2000</td></tr><tr><td class="anl_bck anl_ac anl_br anl_bt link_no_decoration"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Dopolnjene frekvence (print, pdf, word, excel)" class="sprites analysis_sums_new_gray"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys_gray"></span></a></span></td><td class=" anl_bck_desc_1 anl_ac anl_br anl_bt"><span class="anl_variabla"><a href="#">Q3</a></span></td><td class=" anl_bck_desc_1 anl_br anl_bt">Država</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">9</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">2.89</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1.54</td><td class=" anl_bck_desc_1 anl_br anl_ac anl_bt">1</td><td class=" anl_bck_desc_1 anl_ac anl_bt">5</td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.html b/admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.html
new file mode 100644
index 0000000..622cf3d
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.html
@@ -0,0 +1,43 @@
+ <table style="margin-top: 10px; min-width:370px" class="anl_tbl_crosstab">
+ <colgroup>
+ <col style="width: auto; min-width: 30px;">
+ <col style="width: auto; min-width: 30px;">
+ <col style="width: auto; min-width: 30px;">
+ <col style="width: auto; min-width: 30px;">
+ </colgroup>
+ <tbody>
+ <tr>
+ <td rowspan="2" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a
+ title="Predogled vprašanja" href="/">Spol</a></span></td>
+ <td colspan="2"
+ class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a
+ title="Predogled vprašanja" href="/">Dohodek</a></span><br>cv €</td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Povprečje</td>
+ <td
+ class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Št.
+ enot</td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Moški&nbsp;(
+ 1 )</td>
+ <td v2="" v1="" n2="Moški" n1="" k2="1" k1="" class="ct_in_cell">1,500.000</td>
+ <td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 crostabSuma">3</td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Ženski&nbsp;(
+ 2 )</td>
+ <td v2="" v1="" n2="Ženski" n1="" k2="2" k1="" class="ct_in_cell">1,350.000</td>
+ <td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 crostabSuma">6</td>
+ </tr>
+ <tr>
+ <td
+ class="anl_bb anl_bt anl_bl anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Skupaj</td>
+ <td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">1,400.000</td>
+ <td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">9</td>
+ </tr>
+ </tbody>
+ </table>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.min.html
new file mode 100644
index 0000000..ab081a9
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledPovprecja.min.html
@@ -0,0 +1,2 @@
+
+<table style="margin-top: 10px; min-width:370px" class="anl_tbl_crosstab"><colgroup><col style="width: auto; min-width: 30px;"><col style="width: auto; min-width: 30px;"><col style="width: auto; min-width: 30px;"><col style="width: auto; min-width: 30px;"></colgroup><tbody><tr><td rowspan="2" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Spol</a></span></td><td colspan="2" class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Dohodek</a></span><br>cv €</td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Povprečje</td><td class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Št. enot</td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Moški&nbsp;( 1 )</td><td v2="" v1="" n2="Moški" n1="" k2="1" k1="" class="ct_in_cell">1,500.000</td><td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 crostabSuma">3</td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Ženski&nbsp;( 2 )</td><td v2="" v1="" n2="Ženski" n1="" k2="2" k1="" class="ct_in_cell">1,350.000</td><td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 crostabSuma">6</td></tr><tr><td class="anl_bb anl_bt anl_bl anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Skupaj</td><td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">1,400.000</td><td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">9</td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.html b/admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.html
new file mode 100644
index 0000000..aef5f9c
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.html
@@ -0,0 +1,62 @@
+<div class="breakTableDiv" id="150_0">
+ <table>
+ <tbody>
+ <tr>
+ <th rowspan="2"><span class="anl_variabla"><a
+ title="" href="#">Spol(Q1)</a></span></th>
+ <th colspan="1"><span class="anl_variabla"><a
+ title="" href="#">Dohodek(Q2)</a></span></th>
+ </tr>
+ <tr>
+ <th class="sub">v €(Q2)</th>
+ </tr>
+ <tr>
+ <th>Moški</th>
+ <td>1,500.00</td>
+ </tr>
+ <tr>
+ <th>Ženski</th>
+ <td>1,350.00</td>
+ </tr>
+ </tbody>
+ </table>
+</div>
+<br>
+<div class="breakTableDiv" id="153_0">
+ <table>
+ <tbody>
+ <tr>
+ <th rowspan="2"><span class="anl_variabla"><a
+ title="" href="#">Spol(Q1)</a></span></th>
+ <th colspan="6"><span class="anl_variabla"><a
+ title="" href="#">Država(Q3)</a></span></th>
+ </tr>
+ <tr>
+ <th class="sub">Slovenija(1)</th>
+ <th class="sub">Hrvaška(2)</th>
+ <th class="sub">Avstrija(3)</th>
+ <th class="sub">Italija(4)</th>
+ <th class="sub">Madžarska(5)</th>
+ <th>povprečje</th>
+ </tr>
+ <tr>
+ <th>Moški</th>
+ <td>1</td>
+ <td>0</td>
+ <td>1</td>
+ <td>1</td>
+ <td>0</td>
+ <td>2.67</td>
+ </tr>
+ <tr>
+ <th>Ženski</th>
+ <td>1</td>
+ <td>2</td>
+ <td>1</td>
+ <td>0</td>
+ <td>2</td>
+ <td>3.00</td>
+ </tr>
+ </tbody>
+ </table>
+</div>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.min.html
new file mode 100644
index 0000000..46f4e94
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledRazbitje.min.html
@@ -0,0 +1,2 @@
+
+<div class="breakTableDiv" id="150_0"><table><tbody><tr><th rowspan="2"><span class="anl_variabla"><a title="" href="#">Spol(Q1)</a></span></th><th colspan="1"><span class="anl_variabla"><a title="" href="#">Dohodek(Q2)</a></span></th></tr><tr><th class="sub">v €(Q2)</th></tr><tr><th>Moški</th><td>1,500.00</td></tr><tr><th>Ženski</th><td>1,350.00</td></tr></tbody></table></div><br><div class="breakTableDiv" id="153_0"><table><tbody><tr><th rowspan="2"><span class="anl_variabla"><a title="" href="#">Spol(Q1)</a></span></th><th colspan="6"><span class="anl_variabla"><a title="" href="#">Država(Q3)</a></span></th></tr><tr><th class="sub">Slovenija(1)</th><th class="sub">Hrvaška(2)</th><th class="sub">Avstrija(3)</th><th class="sub">Italija(4)</th><th class="sub">Madžarska(5)</th><th>povprečje</th></tr><tr><th>Moški</th><td>1</td><td>0</td><td>1</td><td>1</td><td>0</td><td>2.67</td></tr><tr><th>Ženski</th><td>1</td><td>2</td><td>1</td><td>0</td><td>2</td><td>3.00</td></tr></tbody></table></div> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.html b/admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.html
new file mode 100644
index 0000000..57cabcc
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.html
@@ -0,0 +1,303 @@
+<table class="anl_tbl anl_bt anl_br tbl_clps">
+ <tbody>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span
+ class="anl_variabla"><a href="#">Q1</a></span></td>
+ <td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span
+ class="anl_variabla_label">Spol</span></td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span
+ class="taCenter printHide iconHide"><a href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a href="#"><span
+ title="Dopolnjene frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_new"></span></a><a href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic_gray"></span></a><a href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys_gray"></span></a></span></td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div>
+ (Moški)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">3</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">33.3%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div>
+ (Ženski)</td>
+ <td class="anl_ac anl_br anl_bck_0_1">6</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">100.0%</td>
+ </tr>
+ <tr class="anl_bb">
+ <td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span
+ value="0" class=" gray" >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>)
+ </span><span class=" gray displayNone"
+ >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>)
+ </span></td>
+ <td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td>
+ <td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td>
+ </tr>
+ <tr class="anl_dash_red_bb displayNone" >
+ <td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td>
+ <td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span
+ class="printHide anl_ita anl_detail_percent" >&nbsp;&nbsp;<a
+ href="#single_missing_6"> <span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>
+ </a></span><span class="printHide anl_ita anl_detail_percent displayNone"
+ >&nbsp;&nbsp;<a
+ href="#single_missing_6"> <span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>
+ </a></span>
+ <div
+ class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone"
+ >100.0%</div>
+ <div
+ class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"
+ ></div>
+ </td>
+ <td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span
+ >&nbsp;</span></td>
+ <td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td>
+ </tr>
+ <tr class="displayNone" >
+ <td
+ class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td>
+ <td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td>
+ <td
+ class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td>
+ <td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td>
+ </tr>
+ <tr>
+ <td colspan="6"
+ style="font-size: 1px; height: 2px; line-height: 3px; border-right: 1px solid white;"
+ class="cll_clps">&nbsp;</td>
+ </tr>
+ <tr>
+ <td colspan="2" class="anl_br">&nbsp;</td>
+ <td
+ class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Povprečje</td>
+ <td class="anl_bb anl_bt anl_br anl_ac anl_bck">1.67</td>
+ <td
+ class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Std.
+ Odklon</td>
+ <td class="anl_bb anl_bt anl_ac anl_bck">0.50</td>
+ </tr>
+ </tbody>
+</table>
+<br />
+<table class="anl_tbl anl_bt anl_br anl_bb tbl_clps">
+ <tbody>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span
+ class="anl_variabla"><a href="#">Q2</a></span></td>
+ <td colspan="7" class="anl_br anl_bb anl_al anl_bck_freq_1"><span
+ class="anl_variabla_label">Dohodek</span></td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck"><span
+ class="taCenter printHide iconHide"><a href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums"></span></a><a href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic_gray"></span></a><a href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys_gray"></span></a></span></td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Podvprašanja</td>
+ <td
+ class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Veljavno</td>
+ <td
+ class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Št.
+ enot</td>
+ <td
+ class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Povprečje</td>
+ <td
+ class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Std.
+ Odklon</td>
+ <td
+ class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Minimum</td>
+ <td
+ class="anl_bck anl_ac anl_bb anl_w70 anl_legend anl_variabla_line">Maksimum</td>
+ </tr>
+ <tr>
+ <td
+ class="anl_bck_desc_2 anl_ac anl_bl anl_br anl_variabla_sub anl_bt_dot">Q2_1</td>
+ <td class="anl_bck_desc_2 anl_al anl_br anl_bt_dot">v €</td>
+ <td class="anl_bck_desc_2 anl_ac anl_br anl_bl anl_bt_dot">9</td>
+ <td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">9</td>
+ <td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">1,400.00</td>
+ <td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">342.78</td>
+ <td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">900</td>
+ <td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">2000</td>
+ </tr>
+ </tbody>
+</table>
+<br>
+<table class="anl_tbl anl_bt anl_br tbl_clps">
+ <tbody>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span
+ class="anl_variabla"><a href="#">Q3</a></span></td>
+ <td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span
+ class="anl_variabla_label">Država</span></td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span
+ class="taCenter printHide iconHide"><a href="#"><span
+ title="Sumarne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_gray"></span></a><a href="#"><span
+ title="Dopolnjene frekvence (print, pdf, word, excel)"
+ class="sprites analysis_sums_new"></span></a><a href="#"><span
+ title="Opisne statistike (print, pdf, word, excel)"
+ class="sprites analysis_statistic_gray"></span></a><a href="#"><span
+ title="Osnovne frekvence (print, pdf, word, excel)"
+ class="sprites analysis_frequencys_gray"></span></a></span></td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td>
+ <td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div>
+ (Slovenija)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">2</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">22.2%</td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div>
+ (Hrvaška)</td>
+ <td class="anl_ac anl_br anl_bck_0_1">2</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">44.4%</td>
+ </tr>
+ <tr>
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">3</div>
+ (Avstrija)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">2</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">66.7%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">4</div>
+ (Italija)</td>
+ <td class="anl_ac anl_br anl_bck_0_1">1</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td>
+ <td class="anl_ar anl_bck_0_1 anl_pr10">77.8%</td>
+ </tr>
+ <tr >
+ <td class="anl_bl anl_ac anl_br gray">&nbsp;</td>
+ <td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">5</div>
+ (Madžarska)</td>
+ <td class="anl_ac anl_br anl_bck_0_0">2</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td>
+ <td class="anl_ar anl_bck_0_0 anl_pr10">100.0%</td>
+ </tr>
+ <tr class="anl_bb" >
+ <td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span
+ value="0" class="gray" >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>)
+ </span><span class="gray displayNone"
+ >&nbsp;(<span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>)
+ </span></td>
+ <td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td>
+ <td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td>
+ <td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td>
+ </tr>
+ <tr class="anl_dash_red_bb displayNone" >
+ <td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td>
+ <td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span
+ class="printHide anl_ita anl_detail_percent" >&nbsp;&nbsp;<a
+ href="#single_missing_8"> <span
+ style="width: 12px; height: 12px"
+ class="sprites plus_orange folder_plusminus"></span>
+ </a></span><span class="printHide anl_ita anl_detail_percent displayNone"
+ >&nbsp;&nbsp;<a
+ href="#single_missing_8"> <span
+ style="width: 12px; height: 12px"
+ class="sprites minus_orange folder_plusminus"></span>
+ </a></span>
+ <div
+ class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone"
+ >100.0%</div>
+ <div
+ class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"
+ ></div>
+ </td>
+ <td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td>
+ <td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span
+ >&nbsp;</span></td>
+ <td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td>
+ </tr>
+ <tr class="displayNone" >
+ <td
+ class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td>
+ <td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td>
+ <td
+ class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td>
+ <td
+ class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td>
+ <td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td>
+ </tr>
+ <tr>
+ <td colspan="6"
+ style="font-size: 1px; height: 2px; line-height: 3px; border-right: 1px solid white;"
+ class="cll_clps">&nbsp;</td>
+ </tr>
+ <tr>
+ <td colspan="2" class="anl_br">&nbsp;</td>
+ <td
+ class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Povprečje</td>
+ <td class="anl_bb anl_bt anl_br anl_ac anl_bck">2.89</td>
+ <td
+ class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Std.
+ Odklon</td>
+ <td class="anl_bb anl_bt anl_ac anl_bck">1.54</td>
+ </tr>
+ </tbody>
+</table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.min.html
new file mode 100644
index 0000000..6d2c2a9
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledSumarnik.min.html
@@ -0,0 +1,2 @@
+
+<table class="anl_tbl anl_bt anl_br tbl_clps"><tbody><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span class="anl_variabla"><a href="#">Q1</a></span></td><td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span class="anl_variabla_label">Spol</span></td></tr><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Dopolnjene frekvence (print, pdf, word, excel)" class="sprites analysis_sums_new"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic_gray"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys_gray"></span></a></span></td><td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div> (Moški)</td><td class="anl_ac anl_br anl_bck_0_0">3</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">33.3%</td><td class="anl_ar anl_bck_0_0 anl_pr10">33.3%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div> (Ženski)</td><td class="anl_ac anl_br anl_bck_0_1">6</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">66.7%</td><td class="anl_ar anl_bck_0_1 anl_pr10">100.0%</td></tr><tr class="anl_bb"><td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span value="0" class=" gray">&nbsp;(<span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span>) </span><span class=" gray displayNone">&nbsp;(<span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span>) </span></td><td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td><td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td></tr><tr class="anl_dash_red_bb displayNone"><td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td><td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span class="printHide anl_ita anl_detail_percent">&nbsp;&nbsp;<a href="#single_missing_6"><span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span></a></span><span class="printHide anl_ita anl_detail_percent displayNone">&nbsp;&nbsp;<a href="#single_missing_6"><span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span></a></span><div class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div><div class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"></div></td><td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span>&nbsp;</span></td><td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td></tr><tr class="displayNone"><td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td><td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td><td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td><td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td></tr><tr><td colspan="6" style="font-size: 1px; height: 2px; line-height: 3px; border-right: 1px solid white;" class="cll_clps">&nbsp;</td></tr><tr><td colspan="2" class="anl_br">&nbsp;</td><td class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Povprečje</td><td class="anl_bb anl_bt anl_br anl_ac anl_bck">1.67</td><td class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Std. Odklon</td><td class="anl_bb anl_bt anl_ac anl_bck">0.50</td></tr></tbody></table><br/><table class="anl_tbl anl_bt anl_br anl_bb tbl_clps"><tbody><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span class="anl_variabla"><a href="#">Q2</a></span></td><td colspan="7" class="anl_br anl_bb anl_al anl_bck_freq_1"><span class="anl_variabla_label">Dohodek</span></td></tr><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic_gray"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys_gray"></span></a></span></td><td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Podvprašanja</td><td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Veljavno</td><td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Št. enot</td><td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Povprečje</td><td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Std. Odklon</td><td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">Minimum</td><td class="anl_bck anl_ac anl_bb anl_w70 anl_legend anl_variabla_line">Maksimum</td></tr><tr><td class="anl_bck_desc_2 anl_ac anl_bl anl_br anl_variabla_sub anl_bt_dot">Q2_1</td><td class="anl_bck_desc_2 anl_al anl_br anl_bt_dot">v €</td><td class="anl_bck_desc_2 anl_ac anl_br anl_bl anl_bt_dot">9</td><td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">9</td><td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">1,400.00</td><td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">342.78</td><td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">900</td><td class="anl_bck_desc_2 anl_ac anl_br anl_bt_dot">2000</td></tr></tbody></table><br><table class="anl_tbl anl_bt anl_br tbl_clps"><tbody><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110"><span class="anl_variabla"><a href="#">Q3</a></span></td><td colspan="5" class="anl_br anl_bb anl_al anl_bck_freq_1"><span class="anl_variabla_label">Država</span></td></tr><tr><td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110"><span class="taCenter printHide iconHide"><a href="#"><span title="Sumarne frekvence (print, pdf, word, excel)" class="sprites analysis_sums_gray"></span></a><a href="#"><span title="Dopolnjene frekvence (print, pdf, word, excel)" class="sprites analysis_sums_new"></span></a><a href="#"><span title="Opisne statistike (print, pdf, word, excel)" class="sprites analysis_statistic_gray"></span></a><a href="#"><span title="Osnovne frekvence (print, pdf, word, excel)" class="sprites analysis_frequencys_gray"></span></a></span></td><td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">Odgovori</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Frekvenca</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Odstotek</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Veljavni</td><td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">Kumulativa</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">1</div> (Slovenija)</td><td class="anl_ac anl_br anl_bck_0_0">2</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_0 anl_pr10">22.2%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">2</div> (Hrvaška)</td><td class="anl_ac anl_br anl_bck_0_1">2</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_1 anl_pr10">44.4%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">3</div> (Avstrija)</td><td class="anl_ac anl_br anl_bck_0_0">2</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_0 anl_pr10">66.7%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_1"><div class="anl_user_text_more">4</div> (Italija)</td><td class="anl_ac anl_br anl_bck_0_1">1</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_br anl_bck_0_1 anl_pr10">11.1%</td><td class="anl_ar anl_bck_0_1 anl_pr10">77.8%</td></tr><tr><td class="anl_bl anl_ac anl_br gray">&nbsp;</td><td class="anl_br anl_bck_0_0"><div class="anl_user_text_more">5</div> (Madžarska)</td><td class="anl_ac anl_br anl_bck_0_0">2</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_br anl_bck_0_0 anl_pr10">22.2%</td><td class="anl_ar anl_bck_0_0 anl_pr10">100.0%</td></tr><tr class="anl_bb"><td class="anl_bl anl_br anl_al gray anl_ti_20 anl_bck_text_1">Veljavni<span value="0" class="gray">&nbsp;(<span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span>) </span><span class="gray displayNone">&nbsp;(<span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span>) </span></td><td class="anl_br anl_al anl_ita red anl_bck_text_1">Skupaj</td><td class="anl_ita red anl_br anl_ac anl_bck_text_1">9</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_br anl_ar anl_bck_text_1 anl_pr10">100.0%</td><td class="anl_ita red anl_ac anl_bck_text_1">&nbsp;</td></tr><tr class="anl_dash_red_bb displayNone"><td class="anl_bl anl_al anl_br gray anl_ti_20 anl_bck_text_1">Manjkajoči</td><td class="anl_br anl_ita red anl_bck_text_1">Skupaj<span class="printHide anl_ita anl_detail_percent">&nbsp;&nbsp;<a href="#single_missing_8"><span style="width: 12px; height: 12px" class="sprites plus_orange folder_plusminus"></span></a></span><span class="printHide anl_ita anl_detail_percent displayNone">&nbsp;&nbsp;<a href="#single_missing_8"><span style="width: 12px; height: 12px" class="sprites minus_orange folder_plusminus"></span></a></span><div class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div><div class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone"></div></td><td class="anl_ac anl_br anl_detail_cnt anl_ita red anl_bck_text_1">0</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10">0.0%</td><td class="anl_ar anl_br anl_ita red anl_bck_text_1 anl_pr10"><span>&nbsp;</span></td><td class="anl_ar anl_ita red anl_bck_text_1 anl_pr10">&nbsp;</td></tr><tr class="displayNone"><td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita anl_bck_text_0">SKUPAJ</td><td class="anl_dash_bt anl_br anl_bb anl_bck_text_0">&nbsp;</td><td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0">9</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">100.0%</td><td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red anl_bck_text_0 anl_pr10">&nbsp;</td><td class="anl_ac anl_dash_bt anl_bb anl_ita red anl_bck_text_0">&nbsp;</td></tr><tr><td colspan="6" style="font-size: 1px; height: 2px; line-height: 3px; border-right: 1px solid white;" class="cll_clps">&nbsp;</td></tr><tr><td colspan="2" class="anl_br">&nbsp;</td><td class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Povprečje</td><td class="anl_bb anl_bt anl_br anl_ac anl_bck">2.89</td><td class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line anl_bck">Std. Odklon</td><td class="anl_bb anl_bt anl_ac anl_bck">1.54</td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledTTest.html b/admin/survey/classes/staticHtml/AnalizaPredogledTTest.html
new file mode 100644
index 0000000..0503c76
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledTTest.html
@@ -0,0 +1,41 @@
+ <table border="0" class="ttestTable">
+ <tbody>
+ <tr>
+ <td rowspan="2" class="lightGreen"><span class="anl_variabla"><a
+ href="#">(Q1)Spol</a></span></td>
+ <td colspan="8" class="lightGreen"><span class="anl_variabla"><a
+ href="#">(Q2) v €</a></span></td>
+ </tr>
+ <tr>
+ <th>n</th>
+ <th><span class="avg">x</span></th>
+ <th>s²</th>
+ <th>se(<span class="avg">x</span>)
+ </th>
+ <th>±1,96×se(<span class="avg">x</span>)
+ </th>
+ <th>d</th>
+ <th>se(d)</th>
+ <th>t</th>
+ </tr>
+ <tr>
+ <td class="lightGreen">Moški</td>
+ <td>3</td>
+ <td>1,500.000</td>
+ <td>200.000</td>
+ <td>115.470</td>
+ <td>226.321</td>
+ <td rowspan="2">150.000</td>
+ <td rowspan="2">201.246</td>
+ <td rowspan="2">0.745</td>
+ </tr>
+ <tr>
+ <td class="lightGreen">Ženski</td>
+ <td>6</td>
+ <td>1,350.000</td>
+ <td>403.733</td>
+ <td>164.823</td>
+ <td>323.053</td>
+ </tr>
+ </tbody>
+ </table>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledTTest.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledTTest.min.html
new file mode 100644
index 0000000..44c9216
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledTTest.min.html
@@ -0,0 +1,2 @@
+
+<table border="0" class="ttestTable"><tbody><tr><td rowspan="2" class="lightGreen"><span class="anl_variabla"><a href="#">(Q1)Spol</a></span></td><td colspan="8" class="lightGreen"><span class="anl_variabla"><a href="#">(Q2) v €</a></span></td></tr><tr><th>n</th><th><span class="avg">x</span></th><th>s²</th><th>se(<span class="avg">x</span>) </th><th>±1,96×se(<span class="avg">x</span>) </th><th>d</th><th>se(d)</th><th>t</th></tr><tr><td class="lightGreen">Moški</td><td>3</td><td>1,500.000</td><td>200.000</td><td>115.470</td><td>226.321</td><td rowspan="2">150.000</td><td rowspan="2">201.246</td><td rowspan="2">0.745</td></tr><tr><td class="lightGreen">Ženski</td><td>6</td><td>1,350.000</td><td>403.733</td><td>164.823</td><td>323.053</td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledTabele.html b/admin/survey/classes/staticHtml/AnalizaPredogledTabele.html
new file mode 100644
index 0000000..a24e0aa
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledTabele.html
@@ -0,0 +1,209 @@
+<!-- <br>Χ<sup>2</sup> = 4.500--><table gd2="undefined" sp2="149_0" sq2="6" gd1="undefined" sp1="153_0"
+ sq1="8" style="padding: 0px; margin: 0px; margin-top: 10px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <colgroup>
+ <col style="width: auto; min-width: 100px;">
+ <col style="width: 20%;">
+ <col style="width: 20%;">
+ <col style="width: 20%;">
+ <col style="width: 20%;">
+ <col style="width: 20%;">
+ <col style="width: auto;">
+ </colgroup>
+ <tbody>
+ <tr>
+ <td rowspan="2" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a
+ title="Predogled vprašanja" href="/">Spol&nbsp;(Q1)</a></span></td>
+ <td colspan="5" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span
+ class="anl_variabla"><a
+ title="Predogled vprašanja" href="/">Država&nbsp;(Q3)</a></span></td>
+ <td class="anl_bl">&nbsp;</td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Slovenija<br>
+ ( 1 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Hrvaška<br>
+ ( 2 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Avstrija<br>
+ ( 3 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Italija<br>
+ ( 4 )
+ </td>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Madžarska<br>
+ ( 5 )
+ </td>
+ <td
+ class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Skupaj</td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Moški<br>
+ ( 1 )
+ </td>
+ <td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck4 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck1 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck4 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 anl_bb"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">3</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ <tr>
+ <td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Ženski<br>
+ ( 2 )
+ </td>
+ <td v2="" v1="" n2="Ženski" n1="Slovenija" k2="2" k1="1"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Ženski" n1="Hrvaška" k2="2" k1="2"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck1 ctbCll">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Ženski" n1="Avstrija" k2="2" k1="3"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck0 ctbCll">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Ženski" n1="Italija" k2="2" k1="4"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck4 ctbCll">0</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td v2="" v1="" n2="Ženski" n1="Madžarska" k2="2" k1="5"
+ class="ct_in_cell"><table class="ct_in_tbl">
+ <tbody>
+ <tr>
+ <td class="anl_ac rsdl_bck1 ctbCll">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 anl_bb"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">6</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ <tr>
+ <td
+ class="anl_bb anl_bt anl_bl anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Skupaj</td>
+ <td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">1</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">2</td>
+ </tr>
+ </tbody>
+ </table></td>
+ <td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0"><table
+ style="padding: 0px; margin: 0px;"
+ class="anl_tbl_crosstab fullWidth fullHeight">
+ <tbody>
+ <tr>
+ <td colspan="0" class="anl_ac ctbCll crostabSuma">9</td>
+ </tr>
+ </tbody>
+ </table></td>
+ </tr>
+ </tbody>
+ </table>
diff --git a/admin/survey/classes/staticHtml/AnalizaPredogledTabele.min.html b/admin/survey/classes/staticHtml/AnalizaPredogledTabele.min.html
new file mode 100644
index 0000000..d47f095
--- /dev/null
+++ b/admin/survey/classes/staticHtml/AnalizaPredogledTabele.min.html
@@ -0,0 +1,2 @@
+
+<table gd2="undefined" sp2="149_0" sq2="6" gd1="undefined" sp1="153_0" sq1="8" style="padding: 0px; margin: 0px; margin-top: 10px;" class="anl_tbl_crosstab fullWidth fullHeight"><colgroup><col style="width: auto; min-width: 100px;"><col style="width: 20%;"><col style="width: 20%;"><col style="width: 20%;"><col style="width: 20%;"><col style="width: 20%;"><col style="width: auto;"></colgroup><tbody><tr><td rowspan="2" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Spol&nbsp;(Q1)</a></span></td><td colspan="5" class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll"><span class="anl_variabla"><a title="Predogled vprašanja" href="/">Država&nbsp;(Q3)</a></span></td><td class="anl_bl">&nbsp;</td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Slovenija<br> ( 1 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Hrvaška<br> ( 2 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Avstrija<br> ( 3 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Italija<br> ( 4 ) </td><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Madžarska<br> ( 5 ) </td><td class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Skupaj</td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Moški<br> ( 1 ) </td><td v2="" v1="" n2="Moški" n1="Slovenija" k2="1" k1="1" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Hrvaška" k2="1" k1="2" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck4 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Avstrija" k2="1" k1="3" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Italija" k2="1" k1="4" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck1 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Moški" n1="Madžarska" k2="1" k1="5" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck4 ctbCll">0</td></tr></tbody></table></td><td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 anl_bb"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">3</td></tr></tbody></table></td></tr><tr><td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">Ženski<br> ( 2 ) </td><td v2="" v1="" n2="Ženski" n1="Slovenija" k2="2" k1="1" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Ženski" n1="Hrvaška" k2="2" k1="2" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck1 ctbCll">2</td></tr></tbody></table></td><td v2="" v1="" n2="Ženski" n1="Avstrija" k2="2" k1="3" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck0 ctbCll">1</td></tr></tbody></table></td><td v2="" v1="" n2="Ženski" n1="Italija" k2="2" k1="4" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck4 ctbCll">0</td></tr></tbody></table></td><td v2="" v1="" n2="Ženski" n1="Madžarska" k2="2" k1="5" class="ct_in_cell"><table class="ct_in_tbl"><tbody><tr><td class="anl_ac rsdl_bck1 ctbCll">2</td></tr></tbody></table></td><td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 anl_bb"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">6</td></tr></tbody></table></td></tr><tr><td class="anl_bb anl_bt anl_bl anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">Skupaj</td><td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">2</td></tr></tbody></table></td><td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">2</td></tr></tbody></table></td><td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">2</td></tr></tbody></table></td><td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">1</td></tr></tbody></table></td><td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">2</td></tr></tbody></table></td><td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0"><table style="padding: 0px; margin: 0px;" class="anl_tbl_crosstab fullWidth fullHeight"><tbody><tr><td colspan="0" class="anl_ac ctbCll crostabSuma">9</td></tr></tbody></table></td></tr></tbody></table> \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyAnalysis.php b/admin/survey/classes/surveyAnalysis/class.SurveyAnalysis.php
new file mode 100644
index 0000000..16e8eea
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyAnalysis.php
@@ -0,0 +1,8156 @@
+<?php
+/**
+ * @author Gorazd Veselič
+ * @date Juny 2010
+ *
+ * | -> \x7C
+ * ` -> \x60
+ * ' -> \x27
+ * " -> \x22
+ */
+
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+
+define('DATE_FORMAT', 'Y-m-d');
+define("ALLOW_HIDE_ZERRO_REGULAR", false); # omogočimo delovanje prikazovanja/skrivanja ničelnih vrednosti za navadne odgovore
+define("ALLOW_HIDE_ZERRO_MISSING", true); # omogočimo delovanje prikazovanja/skrivanja ničelnih vrednosti za missinge
+define("AUTO_HIDE_ZERRO_VALUE", 20); # nad koliko kategorij skrivamo ničelne vrednosti
+
+
+# mejne vrednosti za barvanje residualov
+define("RESIDUAL_COLOR_LIMIT1", 1.00);
+define("RESIDUAL_COLOR_LIMIT2", 2.00);
+define("RESIDUAL_COLOR_LIMIT3", 3.00);
+
+
+DEFINE (STR_DLMT, '|');
+DEFINE (NEW_LINE, "\n");
+DEFINE (TMP_EXT, '.tmp');
+DEFINE (DAT_EXT, '.dat');
+
+class SurveyAnalysis {
+
+ static public $inited = false; # ali smo razred inicializirali
+
+ static public $sid; # id ankete
+ static public $folder = ''; # pot do folderja
+ static private $headFileName = null; # pot do header fajla
+ static private $dataFileName = null; # pot do data fajla
+ static private $dataFileStatus = null; # status data datoteke
+ static private $dataFileUpdated = null; # kdaj je bilo updejtano
+ static private $noHeader = false; # errorchecking - če header datoteka ne obstaja
+
+ static private $survey = null; # podatki ankete
+
+ static public $podstran; # podstran
+ static public $db_table; # katere tabele uporabljamo
+
+ static public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ static public $_FILTRED_VARIABLES = array(); # filter po spremenljivkah
+ static public $_FILTRED_TYPES = array(); # filter po tipih spremenljivk
+ static public $_FILTRED_OTHER = array(); # filter za polja drugo
+
+ static public $_SHOW_LEGENDA = false; # ali izrisujemo legendo
+
+ static public $_LOOPS = array(); # array z loopi
+ static public $_CURRENT_LOOP = null; # v kateri zanki smo
+
+ static public $_tmp_file_prefix = null; # predpona začasnih datotek za analizo
+ static public $_tmp_file_ext = '.tmp'; # končnicazačasnih datotek za analizo
+
+ static public $appropriateStatus = array(6,5); # Statusi anket katere štejemo kot ustrezne
+ static public $unAppropriateStatus = array(4,3,2,1,0); # Statusi anket katere štejemo kot neustrezne
+ static public $unKnownStatus = array('null'); # Statusi anket katere štejemo kot neustrezne
+
+ static public $currentMissingProfile = 1; # Kateri Missing profil je izbran
+ static public $missingProfileData = null; # Nastavitve trenutno izbranega manjkajočega profila
+ //static public $currentZankaProfile = 0; # Kateri zanka profil je izbran
+ static public $currentFilterProfile = 1; # Kateri IF profil je izbran
+
+
+ static public $_PROFILE_ID_STATUS = null;
+ static public $_PROFILE_ID_VARIABLE = null;
+ static public $_PROFILE_ID_CONDITION = null;
+
+ static public $printPreview = false; # ali prikazujemo podatke kot print preview;
+
+
+ static public $_HEADERS = array(); # shranimo podatke vseh variabel
+ static public $_FREQUENCYS = array(); # v to variablo shranemo frekvence
+ static public $_DESCRIPTIVES = array(); # v to variablo shranemo opisne statistike
+
+ static public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ static public $show_spid_div = true; # ali prikazuje spremenljivke v posameznem divu ( pride prav pri ajaxu, ko loadamo v star div
+
+ static public $setUpJSAnaliza = true; # ali nastavimo __analiza = 1 v JS
+
+ static public $crossTabClass = null; # razred za crostabulacije
+
+ static public $returnAsHtml = false; # ali vrne rezultat analiz kot html ali ga izpiše
+ static public $isArchive = false; # nastavimo na true če smo v arhivu
+
+ static public $enableInspect = true; # checkbox enableInspect
+
+ static public $frequencyAddInvalid = true; # ali pri frekvencah dodajamo neveljavne
+
+ static public $_forceShowEmpty = false; # vsili prikaz spremenljivke tudi če je prazna
+
+ static public $hideEmptyValue = false; # Ali skrivamo prazne enote če je več kot 20 kategorij
+
+ static public $publicAnalyse = false; # Ali je javna analaiza
+
+ # CSS STILI
+ static public $cssColors = array (
+ '0_0' => 'anl_bck_0_0',
+ '0_1' => 'anl_bck_0_1',
+ '1_0' => 'anl_bck_1_0',
+ '1_1' => 'anl_bck_1_1',
+ '2_0' => 'anl_bck_2_0',
+ '2_1' => 'anl_bck_2_1',
+ 'text_0' => 'anl_bck_text_0',
+ 'text_1' => 'anl_bck_text_1'
+
+ );
+
+ static public $textAnswersMore = array('0'=>'10','10'=>'30','30'=>'300','300'=>'600','600'=>'900','900'=>'100000');
+
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ static function Init( $anketa = null ) {
+ global $surveySkin, $global_user_id, $site_path, $lang;
+
+ self::$folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ((int)$anketa > 0) { # če je poadan anketa ID
+
+ session_start();
+ self::$sid = $anketa;
+
+ if (self::$inited == false){
+
+ SurveyAnalysisHelper::getInstance()->Init(self::$sid);
+
+ Common::deletePreviewData($anketa);
+
+
+ // Poskrbimo za datoteko s podatki
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($anketa);
+ $SDF->prepareFiles();
+
+ self::$headFileName = $SDF->getHeaderFileName();
+ self::$dataFileName = $SDF->getDataFileName();
+ self::$dataFileStatus = $SDF->getStatus();
+ self::$dataFileUpdated = $SDF->getFileUpdated();
+
+
+ if (isset($_GET['podstran'])) {
+ self::$podstran = $_GET['podstran'];
+ } else if (isset($_POST['podstran'])) {
+ self::$podstran = $_POST['podstran'];
+ } else if (isset($_GET['m'])) {
+ self::$podstran = $_GET['m'];
+ } else {
+ self::$podstran = M_ANALYSIS_SUMMARY;
+ }
+
+ # če smo v crostabih, jih incializiramo
+ if (self::$podstran == M_ANALYSIS_CROSSTAB) {
+ self::$crossTabClass = new SurveyCrosstabs();
+ self::$crossTabClass->Init(self::$sid);
+ }
+
+ self::$_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+ # začasni folder kamor se shranjujejo začasni podatki
+ self::$_tmp_file_prefix = 'analysis_'.self::$sid.'_'.self::$podstran.'_';
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles :: Init(self::$sid,$global_user_id);
+ SurveyMissingProfiles :: Init(self::$sid,$global_user_id);
+ SurveyVariablesProfiles :: Init(self::$sid);
+ SurveyUserSetting :: getInstance()->Init(self::$sid, $global_user_id);
+
+ SurveyConditionProfiles :: Init(self::$sid, $global_user_id);
+ SurveyZankaProfiles :: Init(self::$sid, $global_user_id);
+ SurveyTimeProfiles :: Init(self::$sid, $global_user_id);
+ SurveyDataSettingProfiles :: Init(self::$sid);
+
+ $smv = new SurveyMissingValues(self::$sid);
+ $zs = new SurveyZoom(self::$sid);
+
+
+ if ( self::$dataFileStatus == FILE_STATUS_NO_DATA || self::$dataFileStatus == FILE_STATUS_SRV_DELETED) {
+ if (self::$podstran != M_ANALYSIS_ARCHIVE)
+ Common::noDataAlert();
+
+ return false;
+ }
+
+ SurveyInfo :: getInstance()->SurveyInit(self::$sid);
+ self::$survey = SurveyInfo::getInstance()->getSurveyRow();
+
+ UserSetting :: getInstance()->Init($global_user_id);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ self::$db_table = '_active';
+ }
+
+ # nastavimo vse filtre
+ self::setUpFilter();
+ self::$inited = true;
+ }
+ } else {
+ die("Napaka!");
+ }
+ }
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ static public function setUpFilter($pid=null) {
+ if (self::$dataFileStatus == FILE_STATUS_SRV_DELETED) {
+ return false;
+ }
+
+ if (self::$headFileName !== null && self::$headFileName != '' && file_exists(self::$headFileName)) {
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ self::removeSystemVariables();
+
+ #
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ self::$currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # poiščemo kateri profil variabel imamo
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+ if ($dvp != $_currentVariableProfile) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', $_currentVariableProfile);
+ }
+ self::$_PROFILE_ID_VARIABLE = $_currentVariableProfile;
+
+ # filtriranje po statusih
+ self::$_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString($pid);
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK(self::$_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+ SurveyConditionProfiles :: setHeader(self::$_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ # dodamo dodatne pogoje za GORENJE FILTRIRANJE
+ if(Common::checkModule('gorenje')){
+ $SAG = new SurveyAnalysisGorenje(self::$sid);
+ $_gorenje_filter_AWK = $SAG->getAWKString(self::$_HEADERS);
+ if($_gorenje_filter_AWK != ''){
+ // Ce imamo oba samo pripnemo dodatne filtre
+ if($_gorenje_filter_AWK != '' && $_condition_profile_AWK != '')
+ $_condition_profile_AWK .= '&&'.$SAG->getAWKString(self::$_HEADERS);
+ else
+ $_condition_profile_AWK = $SAG->getAWKString(self::$_HEADERS);
+ }
+ }
+
+ # dodamo še ife za inspect
+ $SI = new SurveyInspect(self::$sid);
+ $_inspect_condition_awk = $SI->generateAwkCondition();
+
+ # dodamo še zoom
+ $_zoom_condition = SurveyZoom::generateAwkCondition();
+
+ # ali imamo filter na testne podatke
+ #$filter_testdata = isset($_SESSION['testData'][self::$sid]['includeTestData']) && $_SESSION['testData'][self::$sid]['includeTestData'] == 'false';
+ if (isset(self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence']) && (int)self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'] > 0) {
+ $test_data_sequence = self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'];
+ $filter_testdata = SurveyStatusProfiles :: getStatusTestAsAWKString($test_data_sequence);
+ }
+
+ # ali imamo filter na uporabnost
+ if (isset(self::$_HEADERS['usability']['variables'][0]['sequence']) && (int)self::$_HEADERS['usability']['variables'][0]['sequence'] > 0) {
+ $usability_data_sequence = self::$_HEADERS['usability']['variables'][0]['sequence'];
+ $filter_usability = SurveyStatusProfiles :: getStatusUsableAsAWKString($usability_data_sequence);
+ }
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ || ($_inspect_condition_awk != "" && $_inspect_condition_awk != null)
+ || ($_time_profile_awk != "" && $_time_profile_awk != null)
+ || ($_zoom_condition != "" && $_zoom_condition != null)
+ || ($filter_testdata != null)
+ || ($filter_usability != null)) {
+ self::$_CURRENT_STATUS_FILTER = '('.self::$_CURRENT_STATUS_FILTER;
+
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ self::$_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+
+ if ($_inspect_condition_awk != "" && $_inspect_condition_awk != null ) {
+ self::$_CURRENT_STATUS_FILTER .= ' && '.$_inspect_condition_awk;
+ }
+
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ self::$_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+
+ if ($_zoom_condition != "" && $_zoom_condition != null) {
+ self::$_CURRENT_STATUS_FILTER .= ' && '.$_zoom_condition;
+ }
+
+ if ($filter_testdata != null ) {
+ self::$_CURRENT_STATUS_FILTER .= '&&('.$filter_testdata.')';
+ /*
+ $test_data_sequence = self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'];
+ if ((int)$test_data_sequence > 0) {
+ self::$_CURRENT_STATUS_FILTER .= '&&($'.$filter_testdata.')';
+ }
+ */
+ }
+
+ if ($filter_usability != null ) {
+ self::$_CURRENT_STATUS_FILTER .= '&&('.$filter_usability.')';
+ }
+
+ self::$_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ # filtriranje po spremenljivkah
+ self::$_FILTRED_VARIABLES = null;
+ self::$_FILTRED_VARIABLES = SurveyVariablesProfiles :: getProfileVariables(null);
+
+ # upoštevamo tudi filtriranje po tipu : kategorija, števila, besedilo
+ self::$_FILTRED_TYPES = SurveyDataSettingProfiles :: getSetting('spr_types');
+ self::$_FILTRED_OTHER = SurveyDataSettingProfiles :: getSetting('showOther');
+
+ # če smo radio enableInspect
+ $SI = new SurveyInspect(self::$sid);
+ self::$enableInspect = $SI->isInspectEnabled();
+
+ # ali izrisujemo legendo
+ self::$_SHOW_LEGENDA = (SurveyDataSettingProfiles :: getSetting('analiza_legenda') == true) ? true : false;
+
+
+ if (self::$dataFileStatus >= 0) {
+
+ if (isset(self::$_HEADERS['testdata'])) {
+ self::$_HAS_TEST_DATA = true;
+ }
+ }
+ }
+ else
+ {
+ self::$noHeader = true;
+ }
+ }
+
+ /** Prikazuje filtre
+ *
+ */
+ static function DisplayFilters($hq=1) {
+ global $lang;
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA || self::$noHeader == true) {
+ return false;
+ }
+
+ if (self::$dataFileStatus != FILE_STATUS_SRV_DELETED) {
+
+ if (self::$setUpJSAnaliza == true) {
+ echo '<script> window.onload = function() { __analiza = 1; } </script>';
+ }
+
+ echo '<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>';
+
+
+ # ali imamo testne podatke
+ if (self::$_HAS_TEST_DATA) {
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml(self::$sid);
+ $SSH -> displayTestDataBar(true);
+ }
+
+
+ if (self::$podstran == M_ANALYSIS_DESCRIPTOR || self::$podstran == M_ANALYSIS_FREQUENCY || self::$podstran == M_ANALYSIS_SUMMARY || self::$podstran == M_ANALYSIS_CHARTS || self::$podstran == M_ANALYSIS_LINKS || self::$podstran == M_ANALYSIS_CREPORT) {
+
+ echo '<div id="globalSetingsHolder">';
+
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyZoom :: displayZoomConditions();
+
+ echo '</div>'; # id="globalSetingsHolder"
+
+
+ // Posebni filtri za Gorenje
+ if(Common::checkModule('gorenje')){
+
+ $SAG = new SurveyAnalysisGorenje(self::$sid);
+
+ if($SAG->hasSpremenljivke()){
+ echo '<div id="gorenjeFiltersHolder">';
+ $SAG->displayFilters();
+ echo '</div>';
+ }
+ }
+ }
+ }
+ else {
+ echo "Anketa je bila izbrisana! Prikaz podatkov ni mogoč!";
+ }
+ }
+
+ /** Prikazuje podatke analize
+ *
+ */
+ static function Display() {
+ global $lang;
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA || self::$dataFileStatus == -3 || self::$noHeader == true) {
+ if (self::$podstran != M_ANALYSIS_ARCHIVE)
+ return false;
+ }
+ # zakeširamo vsebino, in jo nato po potrebi zapišpemo v html
+
+ ob_start();
+
+ # če nismo v crostabih
+ if (self::$podstran != M_ANALYSIS_CROSSTAB)
+ {
+ # v arhivih ne izpisujemo
+ if (self::$isArchive == false)
+ {
+ echo '<div id="displayFilterNotes">';
+ # če imamo filter zoom ga izpišemo
+ SurveyZoom::getConditionString();
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+ # če imamo filter ifov za inspect ga izpišemo
+ $SI = new SurveyInspect(self::$sid);
+ $SI->getConditionString();
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile();
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString();
+ # če imamo rekodiranje
+ $SR = new SurveyRecoding(self::$sid);
+ $SR -> getProfileString();
+
+ SurveyDataSettingProfiles::getVariableTypeNote();
+ echo '</div>';
+ }
+
+ }
+
+ if (self::$dataFileStatus == FILE_STATUS_OLD && self::$podstran != M_ANALYSIS_ARCHIVE) {
+ echo "Posodobljeno: ".date("d.m.Y, H:i:s", strtotime(self::$dataFileUpdated));
+ }
+
+ # krostabe naredimo
+ if(self::$podstran == M_ANALYSIS_CROSSTAB ) {
+ self::$crossTabClass->Display();
+ } else {
+ # polovimo nastavtve missing profila
+ self::$missingProfileData = SurveyMissingProfiles::getProfile(self::$currentMissingProfile);
+ if (self::$podstran != M_ANALYSIS_ARCHIVE) {
+ self::$_LOOPS = SurveyZankaProfiles::getFiltersForLoops();
+ }
+ if (!is_countable(self::$_LOOPS) || count(self::$_LOOPS) == 0) {
+
+ # če nimamo zank
+ switch (self::$podstran) {
+
+ case M_ANALYSIS_SUMMARY :
+ self::displaySums();
+ break;
+ case M_ANALYSIS_DESCRIPTOR :
+ self::displayDescriptives();
+ break;
+ case M_ANALYSIS_FREQUENCY :
+ self::displayFrequency();
+ break;
+ case M_ANALYSIS_ARCHIVE :
+ self::displayAnalysisArchive();
+ break;
+ default :
+ self::$podstran = M_ANALYSIS_SUMMARY;
+ self::Display();
+ break;
+ }
+ } else {
+ $loop_cnt = 0;
+ # če mamo zanke
+ foreach ( self::$_LOOPS AS $loop)
+ {
+ $loop_cnt++;
+ $loop['cnt'] = $loop_cnt;
+ self::$_CURRENT_LOOP = $loop;
+ echo '<h2 data-loopId="'.self::$_CURRENT_LOOP['cnt'].'">'.$lang['srv_zanka_note'].$loop['text'].'</h2>';
+ switch (self::$podstran)
+ {
+ case M_ANALYSIS_SUMMARY :
+ self::displaySums();
+ break;
+ case M_ANALYSIS_DESCRIPTOR :
+ self::displayDescriptives();
+ break;
+ case M_ANALYSIS_FREQUENCY :
+ self::displayFrequency();
+ break;
+ case M_ANALYSIS_ARCHIVE :
+ self::displayAnalysisArchive();
+ break;
+ default :
+ self::$podstran = M_ANALYSIS_SUMMARY;
+ self::Display();
+ break;
+ }
+
+ }
+ }
+
+ }
+ #ob_flush(); flush();
+ if (self::$returnAsHtml == false) {
+ ob_flush(); flush();
+ return;
+ } else {
+ $result = ob_get_clean();
+ ob_flush(); flush();
+ return $result;
+ }
+ }
+
+ /** Izrišemo opisne
+ *
+ */
+ static function displayDescriptives($_spid = null) {
+ global $site_path, $lang;
+ # preberemo header
+
+ if (self::$headFileName !== null ) {
+ #preberemo HEADERS iz datoteke
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ self::removeSystemVariables();
+
+ # polovimo frekvence
+ self::getDescriptives();
+
+ # izpišemo opisne statistike
+ $vars_count = count(self::$_FILTRED_VARIABLES);
+ $line_break = '';
+
+
+ # dodamo še kontrolo če kličemo iz displaySingleVar
+ if (isset($_spid) && $_spid !== null) {
+ self::$_HEADERS = array($_spid => self::$_HEADERS[$_spid]);
+ }
+
+ # ali prikazujemo spremenljivke brez veljavnih odgovorov
+ $show_spid = array();
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if ($spremenljivka['tip'] != 'm'
+ && ( count(self::$_FILTRED_VARIABLES) == 0 || (count(self::$_FILTRED_VARIABLES) > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ))
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES) ){
+ $only_valid = 0;
+
+ $show_enota = false;
+ # preverimo ali imamo samo eno variablo in če iammo enoto
+ if ((int)$spremenljivka['enota'] != 0 || $spremenljivka['cnt_all'] > 1 ) {
+ $show_enota = true;
+ }
+
+ # izpišemo glavno vrstico z podatki
+ $_sequence = null;
+ # za enodimenzijske tipe izpišemo podatke kar v osnovni vrstici
+ if (!$show_enota) {
+ $variable = $spremenljivka['grids'][0]['variables'][0];
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_DESCRIPTIVES[$_sequence]['validCnt'];
+ } else {
+ if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) {
+ $variable = $spremenljivka['grids'][0]['variables'][0];
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $show_enota = false;
+ }
+ #zloopamo skozi variable
+ $_sequence = null;
+ $grd_cnt=0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ # dodamo dodatne vrstice z albelami grida
+ if (count ($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable ){
+ # dodamo ostale vrstice
+ $do_show = ($variable['other'] !=1 && ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3 || $spremenljivka['tip'] == 5 || $spremenljivka['tip'] == 8 ))
+ ? false
+ : true;
+ if ($do_show) {
+ $only_valid += (int)self::$_DESCRIPTIVES[$variable['sequence']]['validCnt'];
+ }
+ }
+ }
+ } //else: if (!$show_enota)
+
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ $show_spid[$spid] = false;
+ } else {
+ $show_spid[$spid] = true;
+ }
+
+ }
+ }
+ echo '<table class="anl_tbl anl_ba" >';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w90">&nbsp;<span>'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb anl_w110">' . $lang['srv_analiza_opisne_variable'] .'<span>'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_variable_text'] .'<span>'.'</span></td>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_variable_type'] .'<span >'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_variable_expression'] .'<span >'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_variable_skala'] .'<span >'.'</span></td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_m'] .'<span >'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_num_units'] .'<span >'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_povprecje_odstotek'] .'<span >'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb">' . $lang['srv_analiza_opisne_odklon'] .'<span >'.'</span></td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_variabla_line anl_bb" >' . $lang['srv_analiza_opisne_min'] .'<span >'.'</span></td>';
+ echo '<td class=" anl_ac anl_bck anl_variabla_line anl_bb" >' . $lang['srv_analiza_opisne_max'] .'<span >'.'</span></td>';
+ echo '</tr>';
+
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ # dajemo v bufer, da da ne prikazujemo vprašanj brez veljavnih odgovorov če imamo tako nastavljeno
+
+ # preverjamo ali je meta
+ if ($show_spid[$spid] && $spremenljivka['tip'] != 'm'
+ && ( count(self::$_FILTRED_VARIABLES) == 0 || (count(self::$_FILTRED_VARIABLES) > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ))
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES) ){
+
+ $show_enota = false;
+ # preverimo ali imamo samo eno variablo in če iammo enoto
+ if ((int)$spremenljivka['enota'] != 0 || $spremenljivka['cnt_all'] > 1 ) {
+ $show_enota = true;
+ }
+
+ # izpišemo glavno vrstico z podatki
+ $_sequence = null;
+ # za enodimenzijske tipe izpišemo podatke kar v osnovni vrstici
+ if (!$show_enota) {
+ // if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3
+ // || $spremenljivka['tip'] == 4 || $spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 8) {
+ $variable = $spremenljivka['grids'][0]['variables'][0];
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ self::displayDescriptivesSpremenljivkaRow($spid, $spremenljivka,$show_enota,$_sequence);
+
+ } else {
+ if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) {
+ $variable = $spremenljivka['grids'][0]['variables'][0];
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $show_enota = false;
+ }
+ self::displayDescriptivesSpremenljivkaRow($spid, $spremenljivka,$show_enota,$_sequence);
+ #zloopamo skozi variable
+ $_sequence = null;
+ $grd_cnt=0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ if (count($spremenljivka['grids']) > 1 && $grd_cnt !== 0 && $spremenljivka['tip'] != 6) {
+ $grid['new_grid'] = true;
+ }
+ $grd_cnt++;
+ $var_cnt=0;
+ # dodamo dodatne vrstice z albelami grida
+ if (count ($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable ){
+ # dodamo ostale vrstice
+ $do_show = ($variable['other'] !=1 && ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3 || $spremenljivka['tip'] == 5 || $spremenljivka['tip'] == 8 ))
+ ? false
+ : true;
+ if ($do_show) {
+ $variable['var_cnt'] = $var_cnt;
+ self::displayDescriptivesVariablaRow($spremenljivka,$grid,$variable,$_css);
+
+ }
+ $grid['new_grid'] = false;
+ $var_cnt++;
+ }
+ }
+ } //else: if (!$show_enota)
+ } // end if $spremenljivka['tip'] != 'm'
+ } // end foreach self::$_HEADERS
+ echo '</table >';
+
+ // Izrisemo ikone na dnu
+ if ( (!isset($_spid) || $_spid == null) && (count(self::$_LOOPS) == 0 || self::$_CURRENT_LOOP['cnt'] == count(self::$_LOOPS)) && ($_GET['m'] != 'analysis_creport') )
+ self::displayBottomSettings('desc');
+
+ } // end if else ($_headFileName == null)
+
+ }
+
+ /** Izriše vrstico z opisnimi
+ *
+ * @param unknown_type $spremenljivka
+ * @param unknown_type $variable
+ */
+ static function displayDescriptivesVariablaRow($spremenljivka,$grid,$variable=null) {
+ global $lang;
+
+ $cssBack = $variable['other'] != 1 ? ' anl_bck_desc_2' : ' anl_bck_desc_3';
+ $cssMove = $variable['other'] != 1 ? ' anl_tin' : ' anl_tin1';
+ $cssBack .= (int)$grid['new_grid'] == 1 ? ' anl_bt ' : ' anl_bt_dot ';
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($_sequence != null) {
+ $_desc = self::$_DESCRIPTIVES[$_sequence];
+ }
+
+ # pokličemo objekt SpremenljivkaSkala
+ $objectSkala = new SpremenljivkaSkala($spremenljivka['spr_id']);
+
+ # če smo na začetku grida dodamo podatke podvprašanja
+ if ($variable['var_cnt'] == 0 && in_array($spremenljivka['tip'],array(16,19,20) ) ) {
+ echo '<tr>';
+ echo '<td class="anl_bck anl_ac anl_br link_no_decoration">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_variabla_sub anl_double_bt anl_bb">';
+ echo $grid['variable'];
+ echo '</td>';
+ echo '<td class="anl_al anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb" colspan="'.(self::$_SHOW_LEGENDA ? '10' : '7').'">';
+ echo $grid['naslov'];
+ echo '</td>';
+ /*
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ }
+ echo '<td class="anl_ac ss=anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td cla"anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br link_no_decoration anl_bck_desc_1 anl_double_bt anl_bb">&nbsp;</td>';
+ */
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td class="anl_bck anl_ac anl_br link_no_decoration">';
+ echo '&nbsp;';
+ echo '</td>';
+ echo '<td class="'.$cssBack.' anl_ac anl_br link_no_decoration anl_variabla_sub">';
+ echo $variable['variable'];
+ echo '</td>';
+ echo '<td class="' . $cssBack . $cssMove . ' anl_br">';
+ //echo $grid['naslov'] . ' - ' .$variable['naslov'];
+ echo $variable['naslov'];
+ echo ($spremenljivka['enota'] == 1) ? ' - '.$variable['naslov2'] : '';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="' . $cssBack . ' anl_ac anl_br" title="'.$_tip.'">'.'&nbsp;'.'</td>';
+ echo '<td class="' . $cssBack . ' anl_ac anl_br" title="'.$_tip.'">'.$_tip.'</td>';
+ echo '<td class="' . $cssBack . ' anl_ac anl_br" title="'.$_oblika.'">' .$_oblika. '</td>';
+ }
+ #veljavno
+ echo '<td class="' . $cssBack . ' anl_br anl_ac">'.(int)$_desc['validCnt'].'</td>';
+
+ #ustrezno
+ echo '<td class="' . $cssBack . ' anl_br anl_ac">'.(int)$_desc['allCnt'].'</td>';
+ echo '<td class="' . $cssBack . ' anl_br anl_ac">';
+
+
+ if ( isset($_desc['avg']) && (int)$objectSkala->getSkala() !== 1 ) {
+ echo self::formatNumber($_desc['avg'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ } else if (isset($_desc['avg']) && $spremenljivka['tip'] == 2 && (int)$objectSkala->getSkala() == 1 ) {
+ echo self::formatNumber($_desc['avg']*100,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'&nbsp;%');
+ }
+ echo '</td>';
+ echo '<td class="' . $cssBack . ' anl_br anl_ac">';
+ if (isset($_desc['div']) && (int)$objectSkala->getSkala() !== 1) {
+ echo self::formatNumber($_desc['div'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'');
+ }
+ echo '</td>';
+ echo '<td class="' . $cssBack . ' anl_br anl_ac">'.((int)$objectSkala->getSkala() !== 1 ? $_desc['min'] : '').'</td>';
+ echo '<td class="' . $cssBack . ' anl_ac">'.((int)$objectSkala->getSkala() !== 1 ? $_desc['max'] : '').'</td>';
+
+ echo '</tr>';
+
+ }
+ /** Izriše vrstico z opisnimi
+ *
+ * @param unknown_type $spremenljivka
+ * @param unknown_type $variable
+ */
+ static function displayDescriptivesSpremenljivkaRow($spid,$spremenljivka,$show_enota,$_sequence = null) {
+ global $lang;
+ $cssBack = " anl_bck_desc_1";
+ if ($_sequence != null) {
+ $_desc = self::$_DESCRIPTIVES[$_sequence];
+ }
+
+ # pokličemo objekt SpremenljivkaSkala
+ $objectSkala = new SpremenljivkaSkala($spremenljivka['spr_id']);
+
+ echo '<tr>';
+ echo '<td class="anl_bck anl_ac anl_br anl_bt link_no_decoration">';
+ self::showIcons($spid,$spremenljivka,'desc');
+ echo '</td>';
+ echo '<td class="'.$cssBack.' anl_ac anl_br anl_bt">';
+ self::showVariable($spid,$spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="' . $cssBack . ' anl_br anl_bt">';
+ echo ($spremenljivka['naslov']) . '</td>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="' . $cssBack . ' anl_ac anl_br anl_bt" title="'.$_tip.'">'.
+ self::getSpremenljivkaLegenda($spremenljivka,'tip')
+ .'</td>';
+ echo '<td class="' . $cssBack . ' anl_ac anl_br anl_bt" title="'.$_tip.'">'.(!$show_enota ? $_tip : '&nbsp').'</td>';
+ echo '<td class="' . $cssBack . ' anl_ac anl_br anl_bt" title="'.$_oblika.'">'.(!$show_enota ? $_oblika : '&nbsp;'). '</td>';
+ }
+ #veljavno
+ echo '<td class="' . $cssBack . ' anl_br anl_ac anl_bt">'.(!$show_enota ? (int)$_desc['validCnt'] : '&nbsp;') .'</td>';
+ #ustrezno
+ echo '<td class="' . $cssBack . ' anl_br anl_ac anl_bt">'.(!$show_enota ? (int)$_desc['allCnt'] : '&nbsp;').'</td>';
+
+ echo '<td class="' . $cssBack . ' anl_br anl_ac anl_bt">';
+ if (isset($_desc['avg']) && (int)$objectSkala->getSkala() !== 1) {
+ echo self::formatNumber($_desc['avg'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ }
+ echo '</td>';
+ echo '<td class="' . $cssBack . ' anl_br anl_ac anl_bt">';
+ if (isset($_desc['div']) && (int)$objectSkala->getSkala() !== 1) {
+ echo self::formatNumber($_desc['div'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'');
+ }
+ echo '</td>';
+ echo '<td class="' . $cssBack . ' anl_br anl_ac anl_bt">'.((int)$objectSkala->getSkala() !== 1 ? $_desc['min'] : '').'</td>';
+ echo '<td class="' . $cssBack . ' anl_ac anl_bt">'.((int)$objectSkala->getSkala() !== 1 ? $_desc['max'] : '').'</td>';
+
+ echo '</tr>';
+
+ }
+ /** Izrišemo fekvence
+ *
+ */
+ static function displayFrequency($_spid = null) {
+ global $site_path, $lang;
+ # preberemo header
+ if (self::$headFileName !== null ) {
+ #preberemo HEADERS iz datoteke
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ self::removeSystemVariables();
+
+ # polovimo frekvence
+ self::getFrequencys();
+ $vars_count = count(self::$_FILTRED_VARIABLES);
+ $line_break = '';
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if (($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES ))
+ && (!isset($_spid) || (isset($_spid) && $_spid == $spid))) {
+ # ali imamo sfiltrirano spremenljivko
+ if ($vars_count == 0 || ($vars_count > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ) ) {
+ # prikazujemo v odvisnosti od kategorije spremenljivke
+ switch ($spremenljivka['tip']) {
+ case 1: # radio - prikjaže navpično
+ case 2: #checkbox če je dihotomna:
+ case 3: # dropdown - prikjaže navpično
+ case 6: # multigrid
+ case 4: # text
+ case 7:# variabla tipa »število«
+ case 8: # datum
+ case 16: #multicheckbox če je dihotomna:
+ case 17: #razvrščanje če je ordinalna
+ case 18: # vsota
+ case 19: # multitext
+ case 20: # multi number
+ case 21: # besedilo*
+ case 22: # kalkulacija
+ case 25: # kvota
+ case 26: # lokacija
+ self::frequencyVertical($spid);
+ break;
+ case 5:
+ # nagovor
+ self::sumNagovor($spid,'freq');
+ break;
+
+ }
+
+ }
+
+ } // end if $spremenljivka['tip'] != 'm'
+ } // end foreach self::$_HEADERS
+
+ // Izrisemo ikone na dnu
+ if ( (!isset($_spid) || $_spid == null) && (count(self::$_LOOPS) == 0 || self::$_CURRENT_LOOP['cnt'] == count(self::$_LOOPS)) && ($_GET['m'] != 'analysis_creport') )
+ self::displayBottomSettings('freq');
+
+ } // end if else ($_headFileName == null)
+ }
+
+ /** Izriše frekvence v vertikalni obliki
+ *
+ * @param unknown_type $spid
+ */
+ static function frequencyVertical($spid) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+
+ # odstranimo še možne nepotrebne zapise za multigride
+ if ($spremenljivka['tip'] == 6 || $spremenljivka['tip'] == 16 ) {
+ $allGrids = count($spremenljivka['grids']);
+ if ($allGrids > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $cntValidInGrid = 0;
+ # dodamo dodatne vrstice z labelami grida
+ if (count($grid['variables']) > 0 ) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $cntValidInGrid+= (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ }
+ }
+ # preverjamo ali lahko prikazujemo podkategorije
+ if ($allGrids < AUTO_HIDE_ZERRO_VALUE || (int)$cntValidInGrid > 0) {
+ $gidsCanShow[$gid] = true;
+ } else {
+ $gidsCanShow[$gid] = false;
+ }
+ }
+ }
+ }
+ if (self::$hideEmptyValue == true || (is_countable(self::$_FREQUENCYS[$_sequence]['valid']) && count(self::$_FREQUENCYS[$_sequence]['valid']) > AUTO_HIDE_ZERRO_VALUE)) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $key => $valid) {
+ if ((int)$valid['cnt'] == 0) {
+ unset (self::$_FREQUENCYS[$_sequence]['valid'][$key]);
+ }
+ }
+ }
+
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+ $inline_legenda = (self::$_HEADERS[$spid]['cnt_all'] == 1 || in_array($spremenljivka['tip'],array(1,8) ) ) ? false: true;
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+ echo '<div id="freq_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_analiza_holder">';
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_br tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ self::showVariable($spid,$spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA ? 7 : 5).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if($spremenljivka['tip'] == 2){
+ echo ' <span class="anl_variabla_info">('.$lang['srv_info_checkbox'].')</span>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+
+ if (!$inline_legenda) {
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>'; # .' / '.$_oblika
+ }
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110">';
+ self::showIcons($spid,$spremenljivka,'freq');
+ echo '</td>';
+ #odgovori
+
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">'.$lang['srv_analiza_frekvence_titleAnswers'] . '</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleFrekvenca'] .'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleOdstotek'] .'</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleVeljavni'] .'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleKumulativa'] .'</td>';
+ echo '</tr>';
+ // konec naslovne vrstice
+ // zeleno vrstico prikažemo samo skupaj z legendo
+ if (self::$_SHOW_LEGENDA && $inline_legenda && in_array($spremenljivka['tip'],array(1,4,8)) ) {
+ $css_bck = 'anl_bck_0_0 ';
+ echo '<tr >';
+ echo '<td class="anl_bl anl_bb anl_br anl_al '.$css_bck.'link_no_decoration">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br anl_al '.$css_bck.'">&nbsp;</td>';
+
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq anl_w90">'.$_tip.'</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq anl_w90">'.$_oblika.'</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ }
+ echo '<td class="anl_bb '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '</tr>';
+ }
+ $_answersOther = array();
+
+ # dodamo opcijo kje izrisujemo legendo
+ $options=array('inline_legenda' => $inline_legenda, 'isTextAnswer' => false, 'isOtherAnswer' => false, 'num_show_records' => $num_show_records);
+
+ # izpišemo vlejavne odgovore
+ $_current_grid = null;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_variables_count = count($grid['variables']);
+
+ # indikator da smo na prvi variabli
+ $first_variable = true;
+
+ # dodamo še kontrolo za prikaz mgridov in mcheckov za več kot 20 vrednosti
+ if ((!is_array($gidsCanShow) && !isset($gidsCanShow[$gid]))
+ || (is_array($gidsCanShow) && isset($gidsCanShow[$gid]) && $gidsCanShow[$gid]== true))
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+
+ if (($variable['text'] != true && $variable['other'] != true)
+ || (in_array($spremenljivka['tip'],array(4,8,21,22,25,26,27)))){
+ # dodamo ime podvariable
+ //if ($_variables_count > 1 && in_array($spremenljivka['tip'],array(2,6,7,16,17,18,19,20,21))) {
+ if ($inline_legenda) {
+ # ali rišemo dvojno črto med grupami
+ if ( $_current_grid != $gid && $_current_grid !== null && $spremenljivka['tip'] != 6&& $spremenljivka['tip'] != 16) {
+ $options['doubleTop'] = true;
+ } else {
+ $options['doubleTop'] = false;
+ }
+ if ($first_variable == true && $spremenljivka['tip'] == 16) {
+ if ($_current_grid !== null) {
+ $options['doubleTop'] = true;
+ }
+ self::outputSubGridVertical($spremenljivka,$variable,$grid,$spid,$options);
+ $options['doubleTop'] = false;
+ }
+ $_current_grid = $gid;
+ self::outputSubVariablaVertical($spremenljivka,$variable,$grid,$spid,$options);
+ }
+ $counter = 0;
+ $_kumulativa = 0;
+
+
+ #po potrebi posortiramo podatke
+ if ($spremenljivka['tip'] == 7 && is_array(self::$_FREQUENCYS[$_sequence]['valid'])) {
+ ksort(self::$_FREQUENCYS[$_sequence]['valid']);
+ }
+ //self::$_FREQUENCYS[$_sequence]
+ if (count(self::$_FREQUENCYS[$_sequence]['valid'])> 0 ) {
+ # tekstovne odgovore posortiramo kronološko
+ if ($spremenljivka['tip'] == 21 || $spremenljivka['tip'] == 4) {
+ $_valid_answers = self :: sortTextValidAnswers($spid,$variable,self::$_FREQUENCYS[$_sequence]['valid']);
+ } else {
+ $_valid_answers = self::$_FREQUENCYS[$_sequence]['valid'];
+ }
+ foreach ($_valid_answers AS $vkey => $vAnswer) {
+ if ($counter < $num_show_records) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+ if (in_array($spremenljivka['tip'],array(4,7,8,19,20,21,26,27))) { // text, number, datum, mtext, mnumber, text*, lokacija,heatmap
+ $options['isTextAnswer'] = true;
+ } else {
+ $options['isTextAnswer'] = false;
+ }
+ $counter = self::outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_kumulativa,$options);
+ }
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaValidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ if (count(self::$_FREQUENCYS[$_sequence]['invalid'])> 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputInvalidAnswerVertical($counter,$ikey,$iAnswer,$_sequence,$spid,$options);
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ #izpišemo še skupno sumo
+ $counter = self::outputSumaVertical($counter,$_sequence,$spid,$options);
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ $first_variable = false;
+ }
+ }
+
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+ echo '</div>';
+ echo '<br />';
+ }
+
+ static function outputSubGridVertical($spremenljivka,$variable,$grid,$spid,$_options = array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ 'doubleTop' =>false, # ali imamo novo grupa in nardimo dvojni rob
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ $css_bck = 'anl_bck_freq_2 ';
+ echo '<tr'.($options['doubleTop'] ? ' class="anl_double_bt"' : '').'>';
+ echo '<td class="anl_bl anl_bb anl_br anl_ac '.$css_bck.'anl_variabla_sub">';
+ echo $grid['variable'];
+ #echo $variable['variable'];
+ echo '</td>';
+ echo '<td class="anl_bb anl_br anl_al '.$css_bck.'">';
+ // echo $grid['naslov'] . ' - ' .$variable['naslov'];
+ echo $grid['naslov'];
+ #echo $variable['naslov'];
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq">'.$_tip.'</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq">'.$_oblika.'</td>';
+ }
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ }
+ echo '<td class="anl_bb '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '</tr>';
+ }
+ static function outputSubVariablaVertical($spremenljivka,$variable,$grid,$spid,$_options = array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ 'doubleTop' =>false, # ali imamo novo grupa in nardimo dvojni rob
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ $css_bck = 'anl_bck_freq_2 ';
+ echo '<tr'.($options['doubleTop'] ? ' class="anl_double_bt"' : '').'>';
+ echo '<td class="anl_bl anl_bb anl_br anl_ac '.$css_bck.'anl_variabla_sub">';
+ echo $variable['variable'];
+ echo '</td>';
+ echo '<td class="anl_bb anl_br anl_al '.$css_bck.'">';
+ // echo $grid['naslov'] . ' - ' .$variable['naslov'];
+ echo $variable['naslov'];
+ echo ($spremenljivka['enota'] == 1) ? ' - '.$variable['naslov2'] : '';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq">'.$_tip.'</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq">'.$_oblika.'</td>';
+ }
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ }
+ echo '<td class="anl_bb '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '</tr>';
+ }
+
+ /** izrišemo arhive analiz
+ *
+ */
+ static function displayAnalysisArchive() {
+ global $lang;
+
+
+ if (self::$dataFileStatus != FILE_STATUS_NO_DATA && self::$dataFileStatus != -3 && self::$noHeader != true) {
+ echo '<div id="div_archive_content">';
+ SurveyAnalysisArchive :: Init(self::$sid);
+ SurveyAnalysisArchive :: ListArchive();
+ echo '</div>';
+
+ echo '<br class="clr" />';
+ }
+ else{
+ echo '<div id="div_archive_content">';
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_archive_analysis'].'</legend>';
+ Common::noDataAlert();
+ echo '</fieldset>';
+
+ echo '</div>';
+
+ echo '<br class="clr" />';
+ }
+ }
+
+ /** Izrišemo sumarnik
+ *
+ */
+ static function displaySums($_spid = null) {
+ global $site_path;
+ # preberemo header
+ if (self::$headFileName === null ) {
+ // die ('<div>NAPAKA!!! Manjkajo datoteke s podatki. <a href="#" onClick="createCollectData();return false;">Kreiraj datoteke s podatki!</a></div>');
+ } else {
+ #preberemo HEADERS iz datoteke
+ if (self::$headFileName == null) {
+ echo "<br><b>Napaka</b>";
+ die();
+ }
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ self::removeSystemVariables();
+ #print_r("<pre>");
+ #print_r(self::$_HEADERS);
+ #print_r("</pre>");
+ # polovimo frekvence
+ self::getFrequencys();
+ $vars_count = count(self::$_FILTRED_VARIABLES);
+ $line_break = '';
+
+ if (!empty(self::$_HEADERS))
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if (
+ ($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES )
+ )
+ && (!isset($_spid) || (isset($_spid) && $_spid == $spid))
+ )
+ {
+ # ali imamo sfiltrirano spremenljivko
+ if ($vars_count == 0 || ($vars_count > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ) )
+ {
+ echo $line_break;
+ #print_r($spremenljivka['tip']);
+ # prikazujemo v odvisnosti od kategorije spremenljivke
+
+ switch ($spremenljivka['tip']) {
+ case 1:
+ # radio - prikjaže navpično
+ self::sumVertical($spid,'sums');
+
+ break;
+ case 2:
+ #checkbox če je dihotomna:
+ //self::sumHorizontalCheckbox($spid);
+ self::sumVerticalCheckbox($spid,'sums');
+ break;
+ case 3:
+ # dropdown - prikjaže navpično
+ self::sumVertical($spid,'sums');
+ break;
+
+ case 6:
+
+ if ($spremenljivka['enota'] != 3) {
+ # multigrid
+ self::sumHorizontal($spid,'sums');
+ } else {
+ #imamo dvojni mgrid
+ self::sumDoubleHorizontal($spid,'sums*');
+ }
+ break;
+ case 16:
+ #multicheckbox če je dihotomna:
+ self::sumMultiHorizontalCheckbox($spid,'sums');
+ break;
+ case 17:
+
+ #razvrščanje če je ordinalna
+ self::sumHorizontal($spid,'sums');
+ break;
+ case 4: # text
+ case 8: # datum
+ # varabla tipa »besedilo« je v sumarniku IDENTIČNA kot v FREKVENCAH.
+ self::sumTextVertical($spid,'sums');
+ break;
+ case 21: # besedilo*
+ # varabla tipa »besedilo« je v sumarniku IDENTIČNA kot v FREKVENCAH.
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ self::sumTextVertical($spid,'sums');
+ } else {
+ self::sumMultiText($spid,'sums');
+ }
+ break;
+ case 19: # multitext
+ self::sumMultiText($spid,'sums');
+ break;
+ case 7:
+ case 18:
+ # variabla tipa »število« je v sumarniku identična kot v DESCRIPTIVES.
+ self::sumNumberVertical($spid,'sums');
+ break;
+ case 20:
+
+ # Če je v gridu le ene variabla naj bo default prikazan f* in ne SUMA
+ if ($spremenljivka['grids'][0]['cnt_vars'] == 1 ) {
+ # variabla tipa »število« je v sumarniku identična kot v DESCRIPTIVES.
+ self::sumMultiNumberVertical($spid,'sums');
+
+ } else {
+
+ # variabla tipa »število« je v sumarniku identična kot v DESCRIPTIVES.
+ self::sumMultiNumber($spid,'sums');
+ }
+ break;
+ case 22:
+ case 25:
+ # kalkulacija
+ self::sumNumberVertical($spid,'sums');
+ break;
+ case 26:
+ # lokacija
+ self::sumMultiText($spid,'sums');
+ break;
+ case 27:
+ # heatmap
+ self::sumMultiTextHeatMap($spid,'sums',true, true);
+
+ break;
+ case 5:
+ # nagovor
+ self::sumNagovor($spid,'sums');
+ break;
+ default:
+ print_r("TODO: Sums for type:".$spremenljivka['tip']);
+ break;
+ }
+
+ }
+
+ } // end if $spremenljivka['tip'] != 'm'
+ } // end foreach self::$_HEADERS
+
+ // Izrisemo ikone na dnu
+ if ( (!isset($_spid) || $_spid == null) && (!is_countable(self::$_LOOPS) || count(self::$_LOOPS) == 0 || self::$_CURRENT_LOOP['cnt'] == count(self::$_LOOPS)) && ($_GET['m'] != 'analysis_creport') )
+ self::displayBottomSettings('sums');
+
+ } // end if else ($_headFileName == null)
+ }
+
+ /** Izrišemo nov sumarnik za določene spremenljivke
+ *
+ */
+ static function displaySumsNew($_spid = null) {
+ global $site_path;
+ # preberemo header
+ if (self::$headFileName === null ) {
+ // die ('<div>NAPAKA!!! Manjkajo datoteke s podatki. <a href="#" onClick="createCollectData();return false;">Kreiraj datoteke s podatki!</a></div>');
+ } else {
+
+ #preberemo HEADERS iz datoteke
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ self::removeSystemVariables();
+
+ # polovimo frekvence
+ self::getFrequencys();
+ $vars_count = count(self::$_FILTRED_VARIABLES);
+ $line_break = '';
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if (($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES ))
+ && (!isset($_spid) || (isset($_spid) && $_spid == $spid))) {
+ # ali imamo sfiltrirano spremenljivko
+ if ($vars_count == 0 || ($vars_count > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ) ) {
+ echo $line_break;
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # prikazujemo v odvisnosti od kategorije spremenljivke
+ switch ($spremenljivka['tip']) {
+ case 1:
+ # radio - prikjaže navpično
+ self::sumHorizontal($spid,'sums*');
+ break;
+ case 2:
+ #checkbox če je dihotomna:
+ #self::sumVerticalCheckbox($spid,'sums*');
+ self::sumHorizontalCheckbox($spid,'sums*');
+ break;
+ case 3:
+ # dropdown - prikjaže navpično
+ self::sumVertical($spid,'sums*');
+ break;
+ case 6:
+ # multigrid
+ self::sumHorizontal($spid,'sums');
+ /*
+ if ($spremenljivka['enota'] != 3) {
+ # multigrid
+ self::sumHorizontal($spid,'sums');
+ } else {
+ #imamo dvojni mgrid
+ self::sumDoubleHorizontal($spid,'sums*');
+ }
+ */
+ break;
+ case 16:
+ #multicheckbox če je dihotomna:
+ self::sumVerticalCheckbox($spid,'sums*');
+ break;
+ case 17:
+ #razvrščanje če je ordinalna
+ self::sumHorizontal($spid,'sums*');
+ break;
+ case 4: # text
+ case 8: # datum
+ case 19: # multitext
+ case 21: # besedilo*
+ # varabla tipa »besedilo« je v sumarniku IDENTIČNA kot v FREKVENCAH.
+ self::sumTextVertical($spid,'sums*');
+ break;
+ case 7:
+ case 18:
+ # variabla tipa »število« je v sumarniku identična kot v DESCRIPTIVES.
+ self::sumNumberVertical($spid,'sums*');
+ break;
+ case 20:
+ self::sumMultiNumberVertical($spid,'sums*');
+ /*
+ # Če je v gridu le ene variabla naj bo default prikazan f* in ne SUMA
+ if ($spremenljivka['grids'][0]['cnt_vars'] == 1) {
+ # variabla tipa »število« je v sumarniku identična kot v DESCRIPTIVES.
+ self::sumMultiNumberVertical($spid,'sums');
+
+ } else {
+ # variabla tipa »število« je v sumarniku identična kot v DESCRIPTIVES.
+ self::sumMultiNumber($spid,'sums');
+ }
+ */
+ break;
+ case 26:
+ # lokacija
+ self::sumMultiText($spid,'sums');
+ break;
+ case 27:
+ # heatmap
+ self::sumMultiTextHeatMap($spid,'sums',true, true);
+ break;
+ case 5:
+ # nagovor
+ self::sumNagovor($spid,'sums*');
+ break;
+
+ }
+ if (self :: $show_spid_div == true) {
+ echo '</div>'; // id="sum_'.$keyGrupe.'">';
+ }
+ $line_break = "<br/>";
+
+ }
+
+ } // end if $spremenljivka['tip'] != 'm'
+ } // end foreach self::$_HEADERS
+ } // end if else ($_headFileName == null)
+ }
+
+
+ /** Izriše sumarnik v vertikalni obliki
+ *
+ * @param unknown_type $spid
+ */
+ static function sumVertical($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ $inline_legenda = false;
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ $options=array('inline_legenda' => $inline_legenda, 'isTextAnswer' => false, 'isOtherAnswer' => false, 'num_show_records' => $num_show_records);
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+
+ if (self::$hideEmptyValue == true || (is_countable(self::$_FREQUENCYS[$_sequence]['valid']) && count(self::$_FREQUENCYS[$_sequence]['valid']) > AUTO_HIDE_ZERRO_VALUE)) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $key => $valid) {
+ if ((int)$valid['cnt'] == 0) {
+ unset (self::$_FREQUENCYS[$_sequence]['valid'][$key]);
+ }
+ }
+ }
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_br tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ $show_valid_percent = (self::$_HEADERS[$spid]['show_valid_percent'] == true) ? 1 : 0;
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA ? (4+((int)$inline_legenda * 2)+$show_valid_percent) : (4+$show_valid_percent)).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110">';
+
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ #odgovori
+
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">'.$lang['srv_analiza_frekvence_titleAnswers'] . '</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleFrekvenca'] .'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleOdstotek'] .'</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleVeljavni'] .'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleKumulativa'] .'</td>';
+ echo '</tr>';
+ // konec naslovne vrstice
+ // zeleno vrstico prikažemo samo skupaj z legendo
+ if (self::$_SHOW_LEGENDA && false) {
+ $css_bck = 'anl_bck_0_0 ';
+ echo '<tr >';
+ echo '<td class="anl_bl anl_bb anl_br anl_al '.$css_bck.'link_no_decoration">&nbsp;</td>';
+
+ echo '<td class="anl_bb anl_br anl_al '.$css_bck.'">&nbsp;</td>';
+
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq anl_w90">'.$_tip.'</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_ac anl_legend anl_legenda_freq anl_w90">'.$_oblika.'</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_bb anl_br '.$css_bck.' anl_w70">&nbsp;</td>';
+ }
+ echo '<td class="anl_bb '.$css_bck.' anl_w70">&nbsp;</td>';
+ echo '</tr>';
+ }
+ $_answersOther = array();
+ $sum_xi_fi=0;
+ $N = 0;
+
+ $_tmp_for_div = array();
+ # izpišemo vlejavne odgovore
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['text'] != true && $variable['other'] != true) {
+ $counter = 0;
+ $_kumulativa = 0;
+ //self::$_FREQUENCYS[$_sequence]
+ if (count(self::$_FREQUENCYS[$_sequence]['valid'])> 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ // za povprečje
+ $xi = (int)$vkey;
+ $fi = (int)$vAnswer['cnt'];
+
+ $sum_xi_fi += $xi * $fi;
+ $N += $fi;
+
+ if ($counter < $num_show_records) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_kumulativa,$options);
+ }
+ }
+ # za poznejše računannje odklona
+ $_tmp_for_div[] = array('xi'=>$xi, 'fi'=>$fi, 'sequence'=>$_sequence);
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaValidAnswerVertical($counter,$_sequence,$spid,$options);
+
+ }
+ if (count(self::$_FREQUENCYS[$_sequence]['invalid'])> 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputInvalidAnswerVertical($counter,$ikey,$iAnswer,$_sequence,$spid,$options);
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ #izpišemo še skupno sumo
+ $counter = self::outputSumaVertical($counter,$_sequence,$spid,$options);
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ }
+
+ # odklon
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ #standardna diviacija
+ $div = 0;
+ $sum_pow_xi_fi_avg = 0;
+ foreach ( $_tmp_for_div as $tkey => $_tmp_div_data) {
+ $xi = (int)$_tmp_div_data['xi'];
+ $fi = (int)$_tmp_div_data['fi'];
+
+ $sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ }
+ $div = (($N -1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($N -1)) : 0;
+
+ # izpišemo še odklon in povprečje
+ if ($show_valid_percent == 1 && self::$_HEADERS[$spid]['skala'] != 1) {
+ $css_bck = 'anl_bck';
+ echo '<tr >';
+ echo '<td class="cll_clps" style="font-size: 1px; height:2px; line-height:3px; border-right: 1px solid white;" colspan="'.(self::$_SHOW_LEGENDA ? 6+((int)$inline_legenda*2) : 6+((int)$inline_legenda*2)).'">&nbsp;</td>';
+ echo '</tr>';
+ echo '<tr >';
+ echo '<td class="anl_br" colspan="'.(self::$_SHOW_LEGENDA ? 2+((int)$inline_legenda*2) : 2+((int)$inline_legenda*2)).'">&nbsp;</td>';
+ echo '<td class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line '.$css_bck.'">'.$lang['srv_analiza_opisne_povprecje'].'</td>';
+ echo '<td class="anl_bb anl_bt anl_br anl_ac '.$css_bck.'">'. self::formatNumber($avg,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'').'</td>';
+ echo '<td class="anl_bb anl_bt anl_br anl_p5 anl_ac anl_variabla_line '.$css_bck.'">'.$lang['srv_analiza_opisne_odklon'].'</td>';
+ echo '<td class="anl_bb anl_bt anl_ac '.$css_bck.'">'.self::formatNumber($div,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'').'</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** Izriše sumarnik v horizontalni obliki za multi checbox
+ *
+ * @param unknown_type $spid - spremenljivka ID
+ */
+ static function sumMultiHorizontalCheckbox($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ $gidsCanShow=array();
+ $allGrids = count($spremenljivka['grids']);
+ if ($allGrids > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $cntValidInGrid = 0;
+ # dodamo dodatne vrstice z labelami grida
+ if (count($grid['variables']) > 0 ) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ #$only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ $cntValidInGrid+= (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ }
+ }
+ # preverjamo ali lahko prikazujemo podkategorije
+ if ($allGrids < AUTO_HIDE_ZERRO_VALUE || (int)$cntValidInGrid > 0) {
+ $gidsCanShow[$gid] = true;
+ } else {
+ $gidsCanShow[$gid] = false;
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ $_answersOther = array();
+
+ # ugotovimo koliko imamo kolon
+ $gid=0;
+ $_clmn_cnt = self::$_HEADERS[$spid]['grids'][$gid]['cnt_vars']-self::$_HEADERS[$spid]['grids'][$gid]['cnt_other'];
+ # tekst vprašanja
+
+ $css_hide_enote = isset($_POST['navedbe']) && $_POST['navedbe'] == '1' ? ' displayNone' : '';
+ $css_hide_navedbe = isset($_POST['navedbe']) && $_POST['navedbe'] == '1' ? '' : ' displayNone';
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # odgovori
+ echo '<div id="div_navedbe_1_'.$spid.'" class="'.$css_hide_enote.'">';
+ echo '<table class="anl_tbl anl_ba tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_bck_desc_1">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_al anl_bck anl_bb anl_bck_desc_1" colspan="'. ($_clmn_cnt+(self::$_SHOW_LEGENDA ? 5 : 3)) .'">';
+ echo '<span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type">&nbsp;&nbsp;<span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ // echo '<span name="span_show_navedbe_1_'.$spid.'" class="span_navedbe"><a href="javascript:show_navedbe(\''.$spid.'\',\'3\');">&nbsp;(<span class="blue">'.$lang['srv_analiza_opisne_answers'].'&nbsp;</span>/<span class="blue">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '<span name="span_show_navedbe_2_'.$spid.'" class="span_navedbe'.$css_hide_enote.'"><a href="javascript:show_navedbe(\''.$spid.'\',\'2\');">&nbsp;(<span class="blue" title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '<span name="span_show_navedbe_3_'.$spid.'" class="span_navedbe'.$css_hide_navedbe.'"><a href="javascript:show_navedbe(\''.$spid.'\',\'1\');">&nbsp;(<span title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span class="blue" title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb">';
+ self::showIcons($spid,$spremenljivka,$_from, array('navedbe'=>false));
+ echo '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line">';
+ echo $lang['srv_analiza_opisne_subquestion'];
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line" colspan="'.($_clmn_cnt).'">';
+ echo $lang['srv_analiza_opisne_answers'].'&nbsp;';
+ echo '<span id="img_analysis_f_p_1_'.$spid.'" class="img_analysis_f_p"><a href="javascript:show_single_percent(\''.$spid.'\',\'2\');">&nbsp;(<span class="blue">f&nbsp;</span>/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '<span id="img_analysis_f_1_'.$spid.'" class="img_analysis_f displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'1\');">&nbsp;(<span class="blue">f&nbsp;</span>/&nbsp;%)</a></span>';
+ echo '<span id="img_analysis_p_1_'.$spid.'" class="img_analysis_p displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'0\');">&nbsp;(f&nbsp;/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_valid'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_num_units'].'</td>';
+ echo '</tr>';
+
+ $bck_css = ' anl_bck_0_0';
+ $_variables = self::$_HEADERS[$spid]['grids'][$gid]['variables'];
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb'.$bck_css .'">&nbsp;</td>';
+ echo '<td class="anl_bl anl_br anl_bb'.$bck_css .'">&nbsp;</td>';
+ if (self::$_SHOW_LEGENDA) {
+
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ echo '<td class="anl_bb anl_br anl_ac anl_legend anl_legenda_freq'.$bck_css.'">&nbsp;</td>'; //'.$_tip.'
+ echo '<td class="anl_bb anl_br anl_ac anl_legend anl_legenda_freq'.$bck_css.'">&nbsp;</td>'; // '.$_oblika.'
+ }
+ if (count($_variables) > 0) {
+ foreach ($_variables AS $vkey => $variable) {
+ if ($variable['other'] != true) {
+ echo '<td class="anl_bb anl_ac anl_dash_br'.$bck_css.'">' . $variable['naslov'].' ('.$variable['gr_id']. ') </td>';
+ }
+ }
+ }
+ //echo '<td class="anl_bb anl_ac anl_br red'.$bck_css.'">' . $lang['srv_anl_suma1'] . '</td>';
+ echo '<td class="anl_bb anl_br anl_bl anl_ac'.$bck_css.'">'. $_valid_cnt .'</td>';
+ echo '<td class="anl_bb anl_bl anl_br anl_ac'.$bck_css.'">'.$_approp_cnt. '</td>';
+ echo '</tr>';
+ foreach (self::$_HEADERS[$spid]['grids'] AS $gid => $grids) {
+ if ($gidsCanShow[$gid]) {
+ $_cnt = 0;
+ # vodoravna vrstice s podatki
+ $css_back = ' anl_bck_desc_2';
+ echo '<tr>';
+ echo '<td class="anl_br anl_bt anl_ac anl_variabla_sub'.$css_back.'">'.$grids['variable'].'</td>';
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$grids['naslov'].'</td>';
+ if (self::$_SHOW_LEGENDA) {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$_tip.'</td>';
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$_oblika.'</td>';
+ }
+
+ $_arguments = 0;
+
+ $_max_appropriate = 0;
+ $_max_cnt = 0;
+ // prikaz frekvenc
+ if (count($grids['variables']) > 0)
+ foreach ($grids['variables'] AS $vkey => $variable) {
+ $_sequence = $variable['sequence'];
+ $_valid = self::$_FREQUENCYS[$_sequence]['validCnt'];
+ $_cnt = self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ $_arguments += $_cnt;
+
+ $_max_appropriate = max($_max_appropriate, (int)self::$_FREQUENCYS[$_sequence]['allCnt']);
+ $_max_cnt = max ($_max_cnt, ((int)(self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt']+(int)self::$_FREQUENCYS[$_sequence]['valid']['0']['cnt'])));
+
+ if ($variable['other'] == true) {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vkey,'sequence'=>$_sequence);
+ }
+
+ if ($variable['other'] != true) {
+ echo '<td class="anl_bb anl_dash_br anl_ac cll_clps '.$css_back.'">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr id="'.$spid.'_'.$_sequence.'" name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac' . (self::$enableInspect == true && (int)$_cnt > 0 ? ' mc_inspect' : '').'"'
+ . (self::$enableInspect == true && (int)$_cnt > 0 ? ' vkey="1"' : '')
+ .'" style="padding:5px 0px;">'.$_cnt.'</td>';
+ echo '</tr>';
+ echo '<tr name="single_sums_percent_'.$spid.'">';
+ echo '<td style="padding:5px 0px;">';
+
+ $_percent = ($_valid > 0 ) ? $_cnt * 100 / $_valid : 0;
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr></table>';
+
+ echo '</td>';
+ }
+ }
+ # veljavno
+ echo '<td class="anl_bt anl_ac anl_br anl_bl red'.$css_back.'">'.$_max_cnt.'</td>';
+ #ustrezno
+ echo '<td class="anl_bt anl_ac anl_br'.$css_back.'">'.$_max_appropriate.'</td>';
+
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+ echo '</div>';
+
+ # navedbe
+ echo '<div id="div_navedbe_2_'.$spid.'" class="div_navedbe'.$css_hide_navedbe.'">';
+ echo '<table class="anl_tbl anl_ba tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_bck_desc_1">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_al anl_bck anl_bb anl_bck_desc_1" colspan="'. ( $_clmn_cnt +(self::$_SHOW_LEGENDA ? 4 : 2)) .'">';
+ echo '<span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type">&nbsp;&nbsp;<span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ // echo '<span name="span_show_navedbe_1_'.$spid.'" class="span_navedbe"><a href="javascript:show_navedbe(\''.$spid.'\',\'3\');">&nbsp;(<span class="blue">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span class="blue">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '<span name="span_show_navedbe_2_'.$spid.'" class="span_navedbe'.$css_hide_enote.'"><a href="javascript:show_navedbe(\''.$spid.'\',\'2\');">&nbsp;(<span class="blue" title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '<span name="span_show_navedbe_3_'.$spid.'" class="span_navedbe'.$css_hide_navedbe.'"><a href="javascript:show_navedbe(\''.$spid.'\',\'1\');">&nbsp;(<span title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span class="blue" title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb">';
+ self::showIcons($spid,$spremenljivka,$_from, array('navedbe'=>true));
+ echo '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line">';
+ echo $lang['srv_analiza_opisne_subquestion'];
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line" colspan="'.($_clmn_cnt+1).'">';
+ echo $lang['srv_analiza_opisne_arguments'].'&nbsp;';
+
+ echo '<span id="img_analysis_f_p_2_'.$spid.'" class="img_analysis_f_p "><a href="javascript:show_single_percent(\''.$spid.'\',\'2\');">&nbsp(<span class="blue">f&nbsp;</span>/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '<span id="img_analysis_f_2_'.$spid.'" class="img_analysis_f displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'1\');">&nbsp(<span class="blue">f&nbsp;</span>/&nbsp;%)</a></span>';
+ echo '<span id="img_analysis_p_2_'.$spid.'" class="img_analysis_p displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'0\');">&nbsp(f&nbsp;/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '</td>';
+ echo '</tr>';
+
+ $bck_css = ' anl_bck_0_0';
+ $_variables = self::$_HEADERS[$spid]['grids'][$gid]['variables'];
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb'.$bck_css .'">&nbsp;</td>';
+ echo '<td class="anl_bl anl_br anl_bb'.$bck_css .'">&nbsp;</td>';
+ if (self::$_SHOW_LEGENDA) {
+
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ echo '<td class="anl_bb anl_br anl_ac anl_legend anl_legenda_freq'.$bck_css.'">&nbsp;</td>'; //'.$_tip.'
+ echo '<td class="anl_bb anl_br anl_ac anl_legend anl_legenda_freq'.$bck_css.'">&nbsp;</td>'; // '.$_oblika.'
+ }
+ foreach ($_variables AS $vkey => $variable) {
+ if ($variable['other'] != true) {
+ echo '<td class="anl_bb anl_ac anl_dash_br'.$bck_css.'">' . $variable['naslov'].' ('.$variable['gr_id']. ') </td>';
+ }
+ }
+ echo '<td class="anl_bb anl_ac anl_dash_br red'.$bck_css.'">' . $lang['srv_anl_suma1'] . '</td>';
+ echo '</tr>';
+ foreach (self::$_HEADERS[$spid]['grids'] AS $gid => $grids) {
+ $_cnt = 0;
+ # vodoravna vrstice s podatki
+ $css_back = ' anl_bck_desc_2';
+ echo '<tr>';
+
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$grids['variable'].'</td>';
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$grids['naslov'].'</td>';
+ if (self::$_SHOW_LEGENDA) {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$_tip.'</td>';
+ echo '<td class="anl_br anl_bt'.$css_back.'">'.$_oblika.'</td>';
+ }
+
+ $_arguments = 0;
+
+ $_max_appropriate = 0;
+ $_max_cnt = 0;
+ // prikaz frekvenc
+ foreach ($grids['variables'] AS $vkey => $variable) {
+ $_sequence = $variable['sequence'];
+ $_valid = self::$_FREQUENCYS[$_sequence]['validCnt'];
+ $_cnt = self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ $_arguments += $_cnt;
+
+ $_max_appropriate = max($_max_appropriate, (int)self::$_FREQUENCYS[$_sequence]['allCnt']);
+ $_max_cnt = max ($_max_cnt, ((int)(self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt']+(int)self::$_FREQUENCYS[$_sequence]['valid']['0']['cnt'])));
+
+ if ($variable['other'] == true) {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vkey,'sequence'=>$_sequence);
+ }
+
+ if ($variable['other'] != true) {
+ $_percent = ($_valid > 0 ) ? $_cnt * 100 / $_valid : 0;
+ }
+ }
+ foreach ($grids['variables'] AS $vkey => $variable) {
+ if ($variable['other'] != true) {
+ $_sequence = $variable['sequence'];
+ $_cnt = self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ echo '<td class="anl_bb anl_dash_br anl_ac cll_clps '.$css_back.'">';
+
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr id="'.$spid.'_'.$_sequence.'" name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac' . (self::$enableInspect == true && (int)$_cnt > 0 ? ' mc_inspect' : '').'"'
+ . (self::$enableInspect == true && (int)$_cnt > 0 ? ' vkey="1"' : '')
+ .' style="padding:5px 0px;">'.$_cnt.'</td>';
+ echo '</tr>';
+ echo '<tr name="single_sums_percent_'.$spid.'">';
+ echo '<td style="padding:5px 0px;">';
+ $_percent = ($_arguments > 0 ) ? $_cnt * 100 / $_arguments : 0;
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr></table>';
+
+ echo '</td>';
+ }
+ }
+ echo '<td class="anl_bb anl_ac anl_dash_br cll_clps '.$css_back.'">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac" style="padding:5px 0px;">'.$_arguments.'</td>';
+ echo '</tr>';
+ echo '<tr name="single_sums_percent_'.$spid.'">';
+ echo '<td style="padding:5px 0px;">';
+ $_percent = ($_arguments > 0 ) ? $_arguments * 100 / $_arguments : 0;
+ echo self::formatNumber('100',SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr></table>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+
+ echo '</div>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** Izriše sumarnik v horizontalni obliki za checbox
+ *
+ * @param unknown_type $spid - spremenljivka ID
+ */
+ static function sumHorizontalCheckbox($spid,$_from) {
+ global $lang;
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ $_answersOther = array();
+
+ # ugotovimo koliko imamo kolon
+ $gid=0;
+ $_clmn_cnt = self::$_HEADERS[$spid]['grids'][$gid]['cnt_vars']-self::$_HEADERS[$spid]['grids'][$gid]['cnt_other'];
+ foreach (self::$_HEADERS[$spid]['grids'][$gid]['variables'] AS $vid => $variable) {
+ $_sequence = $variable['sequence'];
+
+ $_valid_cnt = max($_valid_cnt, self::$_FREQUENCYS[$_sequence]['validCnt']);
+ $_approp_cnt = max($_approp_cnt, self::$_FREQUENCYS[$_sequence]['allCnt']);
+ if ($variable['other'] == true) {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_bl tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_bck_desc_1">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_al anl_bck anl_bb anl_bck_desc_1" colspan="'. ($_clmn_cnt+(self::$_SHOW_LEGENDA ? 4 : 2)) .'">';
+ echo '<span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line" colspan="'.$_clmn_cnt.'">'.$lang['srv_analiza_opisne_answers'];
+ echo '<span id="img_analysis_f_p_1_'.$spid.'" class="img_analysis_f_p"><a href="javascript:show_single_percent(\''.$spid.'\',\'2\');">&nbsp(<span class="blue">f&nbsp;</span>/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '<span id="img_analysis_f_1_'.$spid.'" class="img_analysis_f displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'1\');">&nbsp(<span class="blue">f&nbsp;</span>/&nbsp;%)</a></span>';
+ echo '<span id="img_analysis_p_1_'.$spid.'" class="img_analysis_p displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'0\');">&nbsp(f&nbsp;/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_valid'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_num_units'].'</td>';
+ echo '</tr>';
+
+ $bck_css = ' anl_bck_desc_2';
+ $_variables = self::$_HEADERS[$spid]['grids'][$gid]['variables'];
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb'.$bck_css .'">&nbsp;</td>';
+ if (self::$_SHOW_LEGENDA) {
+
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ echo '<td class="anl_bb anl_br anl_ac anl_legend anl_legenda_freq'.$bck_css.'">'.$_tip.'</td>';
+ echo '<td class="anl_bb anl_br anl_ac anl_legend anl_legenda_freq'.$bck_css.'">'.$_oblika.'</td>';
+ }
+ foreach ($_variables AS $vkey => $variable) {
+ if ($variable['other'] != true) {
+ echo '<td class="anl_bb anl_ac anl_dash_br'.$bck_css.'">' . $variable['naslov'] . '</td>';
+ }
+ }
+ echo '<td class="anl_bb anl_bl anl_br anl_ac'.$bck_css.'">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br anl_ac'.$bck_css.'">&nbsp;</td>';
+ echo '</tr>';
+ # vodoravna vrstice s podatki
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'">';
+ echo '<td class="anl_br anl_bt anl_ar anl_ita gray anl_dash_bb" colspan="'.(self::$_SHOW_LEGENDA ? 3 : 1).'">'.$lang['srv_analiza_frekvence_titleFrekvenca'].'</td>';
+ // prikaz frekvenc
+ foreach ($_variables AS $vkey => $variable) {
+
+ if ($variable['other'] != true) {
+ $_sequence = $variable['sequence'];
+ $cnt = self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ echo '<td class="anl_p5 anl_bt anl_ac anl_dash_br anl_dash_bb">'.$cnt.'</td>';
+ }
+ }
+ echo '<td class="anl_bt anl_bl anl_ac anl_bb">'.$_valid_cnt.'</td>';
+ echo '<td class="anl_bt anl_bl anl_ac anl_bb anl_br">'.$_approp_cnt.'</td>';
+ echo '</tr>';
+
+ // dodamo še veljavne procente
+ echo '<tr name="single_sums_percent_'.$spid.'" >';
+ echo '<td class="anl_br anl_dash_bb anl_ar anl_ita gray" colspan="'.(self::$_SHOW_LEGENDA ? 3 : 1).'">'.$lang['srv_analiza_frekvence_titleOdstotekVeljavni'].'</td>';
+ foreach ($_variables AS $vkey => $variable) {
+ if ($variable['other'] != true) {
+ $_sequence = $variable['sequence'];
+ $cnt = self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ $percent = ( $_valid_cnt > 0) ? 100*$cnt / $_valid_cnt : 0;
+ echo '<td class="anl_p5 anl_ac anl_dash_br anl_dash_bb">'.self::formatNumber($percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%').'</td>';
+ }
+ }
+ echo '<td class="anl_bl">&nbsp;</td>';
+ echo '<td>&nbsp;</td>';
+ echo '</tr>';
+
+ // dodamo še procente
+ echo '<tr name="single_sums_percent_'.$spid.'" >';
+ echo '<td class="anl_br anl_ar anl_ita gray anl_bb" colspan="'.(self::$_SHOW_LEGENDA ? 3 : 1).'">'.$lang['srv_analiza_frekvence_titleOdstotekEnote'].'</td>';
+ foreach ($_variables AS $vkey => $variable) {
+ if ($variable['other'] != true) {
+ $_sequence = $variable['sequence'];
+ $cnt = self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ $percent = ( $_approp_cnt > 0) ? 100*$cnt / $_approp_cnt : 0;
+ echo '<td class="anl_p5 anl_ac anl_dash_br anl_bb">'.self::formatNumber($percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%').'</td>';
+ }
+ }
+ echo '<td class="anl_bl">&nbsp;</td>';
+ echo '<td>&nbsp;</td>';
+ echo '</tr>';
+
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ static function sumVerticalCheckbox($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $all_categories_cnt = 0;
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 ) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $all_categories_cnt++;
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ $_answersOther = array();
+
+ $inline_legenda = count ($spremenljivka['grids']) > 1;
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ # ugotovimo koliko imamo kolon
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_clmn_cnt[$gid] = $grid['cnt_vars']-$grid['cnt_other'];
+ if (count ($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable) {
+ $_sequence = $variable['sequence'];
+ $_valid_cnt[$gid] = max($_valid_cnt[$gid], self::$_FREQUENCYS[$_sequence]['validCnt']);
+ $_approp_cnt[$gid] = max($_approp_cnt[$gid], self::$_FREQUENCYS[$_sequence]['allCnt']);
+ if ($variable['other'] == true) {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ $_valid[$gid][$vid] = self::$_FREQUENCYS[$_sequence]['valid'];
+ $_navedbe[$gid] += self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ }
+ }
+ $veljavni_percent = ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16) ? true : false;
+
+ $css_txt = 'anl_variabla_line';
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ echo '<div id="div_navedbe_1_'.$spid.'">';
+ echo '<table class="anl_tbl anl_bt anl_br tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA && $inline_legenda ? 7+(int)$veljavni_percent : 5+(int)$veljavni_percent).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span> <span class="anl_variabla_info">('.$lang['srv_info_checkbox'].')</span>';
+ if (self::$_SHOW_LEGENDA && !$inline_legenda) {
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type">&nbsp;&nbsp;<span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '<span name="span_show_navedbe_2_'.$spid.'" class="span_navedbe"><a href="javascript:show_navedbe(\''.$spid.'\',\'2\');">&nbsp;(<span class="blue" title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '<span name="span_show_navedbe_3_'.$spid.'" class="span_navedbe displayNone"><a href="javascript:show_navedbe(\''.$spid.'\',\'1\');">&nbsp;(<span title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span class="blue" title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '</td>';
+ echo '</tr>';
+ $css_txt = 'anl_variabla_line';
+
+ echo '<tr>';
+ echo '<td class="anl_p5 anl_bl anl_br anl_ac anl_bck anl_bb anl_w110 '.$css_txt.'">';
+ self::showIcons($spid,$spremenljivka,$_from, array('navedbe'=>false));
+ echo '</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb '.$css_txt.'" style="width:280px">'.$lang['srv_analiza_opisne_subquestion'].'</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda) {
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb anl_w70 '.$css_txt.'">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb anl_w110 '.$css_txt.'">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb anl_w70 '.$css_txt.'">'.$lang['srv_analiza_opisne_frequency'].'</td>';
+
+ echo '<td class="anl_p5 anl_ac anl_dash_br anl_bck anl_bb anl_w70 '.$css_txt.'">'.$lang['srv_analiza_opisne_valid'].'</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb anl_w70 '.$css_txt.'">% - '.$lang['srv_analiza_opisne_valid'].'</td>';
+
+ echo '<td class="anl_p5 anl_'.($veljavni_percent?'dash_':'').'br anl_ac anl_bck anl_bb anl_w70 '.$css_txt.'">'.$lang['srv_analiza_num_units_valid'].'</td>';
+ if ($veljavni_percent) {
+ echo '<td class="anl_p5 anl_ac anl_bck anl_bb anl_w70 '.$css_txt.'">% - '.$lang['srv_analiza_num_units_valid'].'</td>';
+ }
+ echo '</tr>';
+
+ $cssBack = "anl_bck anl_variabla_line ";
+
+ $_max_valid = 0;
+ $_max_appropriate = 0;
+ if (count ($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] as $gid => $grid) {
+ $_max_valid = 0;
+ $_max_appropriate = 0;
+ if (count ($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable) {
+ $_sequence = $variable['sequence'];
+ #po potrebi prikažemo samo tiste ki imajo vrednosti
+ if (($all_categories_cnt <= AUTO_HIDE_ZERRO_VALUE) || (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'] > 0 )
+ if ($variable['other'] != 1) {
+
+
+ # dodamo labele podvprašanja
+ if ($spremenljivka['tip'] == 16 && (($vid == 0 && $gid != 0) || ($vid == 0 && $gid == 0))) {
+ $cssBack = "anl_bck_desc_2 ".($vid == 0 && $gid != 0 ? 'anl_double_bt ' : '');
+ echo '<tr>';
+ echo '<td class="'.$cssBack.'anl_bl anl_br anl_bb anl_ac anl_variabla_sub">'.$grid['variable'].'</td>';
+ echo '<td class="'.$cssBack.'anl_br anl_bb" colspan="'.(self::$_SHOW_LEGENDA && $inline_legenda ? 7+(int)$veljavni_percent : 5+(int)$veljavni_percent ).'">'.$grid['naslov'].'</td>';
+ echo '</tr>';
+ }
+ $cssBack = "anl_bck_desc_2 ";
+ echo '<tr id="'.$spid.'_'.$_sequence.'" name="valid_row_'.$_sequence.'" vkey="1">';
+ echo '<td class="anl_p5 anl_tin1 '.$cssBack.'anl_bl anl_br anl_bb anl_ac anl_variabla_sub">'.$variable['variable'].'</td>';
+ echo '<td class="anl_p5 anl_tin1 '.$cssBack.'anl_br anl_bb">'.$variable['naslov'].'</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda) {
+ echo '<td class="anl_p5 '.$cssBack.'anl_br anl_bb anl_ac">'.$_tip.'</td>';
+ echo '<td class="anl_p5 '.$cssBack.'anl_br anl_bb anl_ac">'.$_oblika.'</td>';
+ }
+ echo '<td class="anl_p5 anl_bb anl_ac anl_br '.$cssBack.( self::$enableInspect == true ? ' fr_inspect' : '').'" >';
+ echo (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ echo '</td>';
+
+ $_max_appropriate = max($_max_appropriate, (int)self::$_FREQUENCYS[$_sequence]['allCnt']);
+ $_max_valid = max ($_max_valid, ((int)(self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt']+(int)self::$_FREQUENCYS[$_sequence]['valid']['0']['cnt'])));
+
+ # veljavno
+ echo '<td class="anl_p5 anl_dash_br anl_ac anl_bb '.$cssBack.'">';
+ echo (int)(self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt']+(int)self::$_FREQUENCYS[$_sequence]['valid']['0']['cnt']);
+ echo '</td>';
+ echo '<td class="anl_p5 anl_bb anl_br anl_ac '.$cssBack.'" >';
+ $_percent = (self::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'] / self::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ #ustrezno
+ echo '<td class="anl_p5 anl_'.($veljavni_percent?'dash_':'').'br anl_ac anl_bb '.$cssBack.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['allCnt'];
+ echo '</td>';
+ # veljavno %
+ if ($veljavni_percent) {
+
+ $valid = (int)(self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt']+(int)self::$_FREQUENCYS[$_sequence]['valid']['0']['cnt']);
+ $valid = (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'];
+ $_percent = ($_max_appropriate > 0 ) ? 100*$valid / $_max_appropriate : 0;
+
+ echo '<td class="anl_p5 anl_br anl_ac anl_bb '.$cssBack.'">';
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ }
+ echo '</tr>';
+
+ } else {
+ # drugo
+ }
+ }
+ $cssBack = " anl_bck_2 red";
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb anl_al anl_ita'.$cssBack.'" >&nbsp;</td>';
+ echo '<td class="anl_p5 anl_tin1 anl_br anl_bl anl_bb anl_al anl_ita'.$cssBack.'" colspan="'.(self::$_SHOW_LEGENDA && $inline_legenda ? 3 : 1).'">'.$lang['srv_anl_suma_valid'].'</td>';
+ echo '<td class="anl_bb anl_ac anl_br anl_ita'.$cssBack.'" >&nbsp;</td>'; //.$_approp_cnt[$gid].
+ echo '<td class="anl_p5 anl_ac anl_dash_br anl_bb anl_ita'.$cssBack.'">'.$_max_valid.'</td>';
+ echo '<td class="anl_bb anl_br'.$cssBack.'">&nbsp;</td>'; //.self::formatNumber('100',SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%')
+
+
+ echo '<td class="anl_p5 anl_'.($veljavni_percent?'dash_':'').'br anl_ac anl_bb anl_ita'.$cssBack.'">'.$_max_appropriate.'</td>'; //$lang['srv_anl_suma_entries']
+ if ($veljavni_percent) {
+ $_percent = ($_max_appropriate > 0 ) ? 100*$_max_valid / $_max_appropriate : 0;
+ echo '<td class="anl_p5 anl_br anl_ac anl_bb anl_ita'.$cssBack.'">';
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ }
+ echo '</tr>';
+
+ }
+ echo '</table>';
+ echo '</div>'; // div_navedbe_1_'.$spid.'
+
+ # še navedbe
+ echo '<div id="div_navedbe_2_'.$spid.'" class="div_navedbe displayNone">';
+ echo '<table class="anl_tbl anl_bt anl_br tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA && $inline_legenda? 5 : 3).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA && !$inline_legenda) {
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type">&nbsp;&nbsp;<span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '<span name="span_show_navedbe_2_'.$spid.'" class="span_navedbe"><a href="javascript:show_navedbe(\''.$spid.'\',\'2\');">&nbsp;(<span class="blue" title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '<span name="span_show_navedbe_3_'.$spid.'" class="span_navedbe displayNone"><a href="javascript:show_navedbe(\''.$spid.'\',\'1\');">&nbsp;(<span title="'.$lang['srv_enote_navedbe_1'].'">'.$lang['srv_analiza_opisne_units'].'&nbsp;</span>/<span class="blue" title="'.$lang['srv_enote_navedbe_2'].'">&nbsp;'.$lang['srv_analiza_opisne_arguments'].'</span>)</a></span>';
+ echo '</td>';
+ echo '</tr>';
+ $css_txt = 'anl_variabla_line';
+ echo '<tr>';
+ echo '<td class="anl_p5 anl_bl anl_br anl_ac anl_bck anl_bb anl_w110 '.$css_txt.'">';
+ self::showIcons($spid,$spremenljivka,$_from, array('navedbe'=>true));
+ echo '</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb '.$css_txt.'" style="width:280px">'.$lang['srv_analiza_opisne_subquestion'].'</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda) {
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb anl_w70 '.$css_txt.'">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb anl_w110 '.$css_txt.'">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_p5 anl_dash_br anl_ac anl_bck anl_bb '.$css_txt.'">'.$lang['srv_analiza_opisne_frequency'].'</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb '.$css_txt.'">%</td>';
+ echo '</td>';
+ echo '</tr>';
+
+ $cssBack = "anl_bck anl_variabla_line ";
+
+ if (count ($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] as $gid => $grid) {
+ if (count ($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable) {
+ $_sequence = $variable['sequence'];
+ #po potrebi prikažemo samo tiste ki imajo vrednosti
+ if (($all_categories_cnt <= AUTO_HIDE_ZERRO_VALUE) || (int)self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'] > 0 )
+ if ($variable['other'] != 1) {
+
+ # dodamo labele podvprašanja
+ if ($spremenljivka['tip'] == 16 && (($vid == 0 && $gid != 0) || ($vid == 0 && $gid == 0))) {
+ $cssBack = 'anl_bck_desc_2'.($vid == 0 && $gid != 0 ? ' anl_double_bt ' : '');
+ echo '<tr>';
+ echo '<td class="anl_p5 '.$cssBack.' anl_bl anl_br anl_bb anl_ac anl_variabla_sub">'.$grid['variable'].'</td>';
+ echo '<td class="anl_p5 '.$cssBack.' anl_br anl_bb"'.(self::$_SHOW_LEGENDA && $inline_legenda ? ' colspan="5"' : ' colspan="3"' ).'>'.$grid['naslov'].'</td>';
+ echo '</tr>';
+ }
+ $cssBack = "anl_bck_desc_2 ";
+ echo '<tr>';
+ echo '<td class="anl_p5 anl_tin1 '.$cssBack.'anl_bl anl_br anl_bb anl_ac anl_variabla_sub">'.$variable['variable'].'</td>';
+ echo '<td class="anl_p5 anl_tin1 '.$cssBack.'anl_br anl_bb">'.$variable['naslov'].'</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda) {
+ echo '<td class="anl_p5 '.$cssBack.'anl_br anl_bb anl_ac">'.$_tip.'</td>';
+ echo '<td class="anl_p5 '.$cssBack.'anl_br anl_bb anl_ac">'.$_oblika.'</td>';
+ }
+
+ echo '<td class="anl_p5 anl_dash_br anl_ac anl_bb '.$cssBack.'">'. self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'].'</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bb '.$cssBack.'">';
+ $_percent = ($_navedbe[$gid] > 0 ) ? 100*self::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'] / $_navedbe[$gid] : 0;
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr>';
+
+ } else {
+ # drugo
+ }
+ }
+ $cssBack = " anl_bck_2 red";
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb anl_al anl_ita'.$cssBack.'" >&nbsp;</td>';
+ echo '<td class="anl_p5 anl_tin1 anl_bl anl_br anl_bb anl_al anl_ita'.$cssBack.'" colspan="'.(self::$_SHOW_LEGENDA && $inline_legenda ? 3 : 1).'">'.$lang['srv_anl_suma_valid'].'</td>';
+ echo '<td class="anl_p5 anl_dash_br anl_ac anl_bb anl_ita'.$cssBack.'">'.$_navedbe[$gid].'</td>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bb anl_ita'.$cssBack.'">'.self::formatNumber('100',SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%').'</td>';
+ echo '</tr>';
+
+ }
+ echo '</table>';
+ echo '</div>'; // Konec div_navedbe_2_$spid
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+
+ }
+
+ /** Izriše sumarnik v horizontalni obliki za multigrid
+ *
+ * @param unknown_type $spid - spremenljivka ID
+ */
+ static function sumHorizontal($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ #$_invalidAnswers = self :: getInvalidAnswers (MISSING_TYPE_FREQUENCY);
+ $_invalidAnswers = self :: getInvalidAnswers (MISSING_TYPE_DESCRIPTOR);
+ #$_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+
+ # opcije nareedimo posebej, da po potrebi zajamemo tudi misinge
+ $str_qry = "SELECT id, spr_id, REPLACE(REPLACE(REPLACE(naslov,'\n',' '),'\r','<br>'),'|',' ') as naslov, variable, other, part, REPLACE(REPLACE(REPLACE(naslov_graf,'\n',' '),'\r','<br>'),'|',' ') as naslov_graf, vrstni_red FROM srv_grid WHERE spr_id='".$spid."' ORDER BY vrstni_red";
+ $qry = sisplet_query($str_qry);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ if ($row['other'] != 0 && !isset($_invalidAnswers[$row['other']])) {
+ # če prikazujemo misinge dodamo -99 kot mising
+ $spremenljivka['options'][$row['other']] = $row['naslov'];
+ }
+ }
+
+ $_answersOther = array();
+ $_clmn_cnt = count($spremenljivka['options']);
+
+ # pri razvrščanju dodamo dva polja za povprečje in odklon
+ $additional_field = false;
+ $add_fld = 0;
+
+ if ($spremenljivka['tip'] == 17 || $spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3 || ($spremenljivka['tip'] == 6 && $spremenljivka['skala'] != 1)) {
+ $additional_field = true;
+ $add_fld = 2;
+ }
+
+ # pri radiu in dropdown ne prikazujemo podvprašanj
+ $_sub_question_col = 1;
+ if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) {
+ $_sub_question_col = 0;
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ echo '<table class="anl_tbl anl_ba tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_bck_desc_1">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_al anl_bck anl_bb anl_bck_desc_1" colspan="'. ($_clmn_cnt+$add_fld+(self::$_SHOW_LEGENDA ? 5+$_sub_question_col : 3+$_sub_question_col)) .'">';
+ echo '<span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ $css_txt = 'anl_variabla_line';
+
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ if ($_sub_question_col) {
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb '.$css_txt.'" style="width:280px">'.$lang['srv_analiza_opisne_subquestion'].'</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line" colspan="'.($_clmn_cnt+1).'">'.$lang['srv_analiza_opisne_answers'];
+ echo '<span id="img_analysis_f_p_1_'.$spid.'" class="img_analysis_f_p"><a href="javascript:show_single_percent(\''.$spid.'\',\'2\');">&nbsp(<span class="blue">f&nbsp;</span>/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '<span id="img_analysis_f_1_'.$spid.'" class="img_analysis_f displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'1\');">&nbsp(<span class="blue">f&nbsp;</span>/&nbsp;%)</a></span>';
+ echo '<span id="img_analysis_p_1_'.$spid.'" class="img_analysis_p displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'0\');">&nbsp(f&nbsp;/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_valid'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_num_units'].'</td>';
+ if ($additional_field) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_povprecje'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_odklon'].'</td>';
+ }
+ echo '</tr>';
+
+ $cssBack = "anl_bck_0_0 ";
+ $_variables = $grid['variables'];
+ echo '<tr>';
+ echo '<td class="anl_tin ' . $cssBack . 'anl_bl anl_br anl_bb">&nbsp;</td>';
+ if ( $_sub_question_col ) {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">&nbsp;</td>'; //$_tip
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">&nbsp;</td>'; // $_oblika
+ }
+
+ //nastavitve iz baze za ureditev pravilnega izrisa analize za tabelo s trakom
+ $row = Cache::srv_spremenljivka($spid);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $diferencial_trak = ($spremenljivkaParams->get('diferencial_trak') ? $spremenljivkaParams->get('diferencial_trak') : 0);
+ $diferencial_trak_starting_num = ($spremenljivkaParams->get('diferencial_trak_starting_num') ? $spremenljivkaParams->get('diferencial_trak_starting_num') : 0);
+ //nastavitve iz baze za ureditev pravilnega izrisa analize za tabelo s trakom
+
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ if($diferencial_trak){ //ce je trak, je potrebno naslove stolpcev spremeniti v vrednosti na traku
+ $_label = $diferencial_trak_starting_num;
+ $diferencial_trak_starting_num++;
+ }else{
+ // misinge imamo zdruzene
+ $_label = $kategorija;
+ }
+
+ echo '<td class="' . $cssBack . ' anl_bb anl_ac anl_dash_br ">'.$_label.'</td>';
+ }
+ }
+
+ echo '<td class="' . $cssBack . ' anl_bb anl_br anl_ac red anl_w70">'.$lang['srv_anl_suma1'].'</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ if ($additional_field) {
+
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ }
+ echo '</tr>';
+
+
+ $part=null;
+ #zlopamo skozi gride
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ # za dvojne gride
+ if ((int)$grid['part'] > 0) {
+ if ($part == null || $part == $grid['part'] ) {
+ $part_css = '';
+ } else {
+ $part_css = ' anl_double_bt ';
+ }
+ $part = $grid['part'];
+ }
+ else {
+ $part_css = '';
+ }
+
+ $cssBack = "anl_bck_desc_2 ";
+ # zloopamo skozi variable
+ if (count($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable ) {
+ $_sequence = $variable['sequence'];
+ #popotrebi izpisujemo samo veljavne
+ if ((count($spremenljivka['grids']) <= AUTO_HIDE_ZERRO_VALUE ||
+ (self::$_FREQUENCYS[$_sequence]['allCnt'] - self::$_FREQUENCYS[$_sequence]['invalidCnt']) > 0))
+ if ($variable['other'] != true) {
+ echo '<tr id="'.$spid.'_'.$_sequence.'"'.($part_css != '' ? ' class="'.$part_css.'"' : '').'>';
+ if ($_sub_question_col) {
+ echo '<td class="anl_tin1 ' . $cssBack . 'anl_bl anl_br anl_bb anl_ac anl_variabla_sub">';
+
+ echo $variable['variable'];
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">';
+
+ echo $variable['naslov'];
+
+ // dodatek desne strani sem. diferenciala
+ echo ($spremenljivka['enota'] == 1) ? ' - '.$variable['naslov2'] : '';
+ echo '</td>';
+ } else {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">'.$_tip.'</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">'.$_oblika.'</td>';
+ }
+ # za odklon in povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ if ($additional_field) { # za odklon in povprečje
+ $xi = $key;
+ $fi = self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+ }
+ echo '<td class="anl_bb anl_dash_br anl_ac cll_clps ' . $cssBack . '">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac'.(self::$enableInspect == true && (int)self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'] > 0 ? ' mg_inspect' : '').'"'
+ .(self::$enableInspect == true && (int)self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'] > 0 ? ' vkey="'.$key.'"' : '')
+ .' style="padding:5px 0px;">'.self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'].'</td>';
+ echo '</tr><tr name="single_sums_percent_'.$spid.'">';
+ echo '<td style="padding:5px 0px;">';
+ $_percent = (self::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'] * 100 / self::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr></table>';
+ echo '</td>';
+
+
+ }
+ }
+ // suma
+ echo '<td class="anl_bb anl_br anl_ac cll_clps ' . $cssBack . '">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac red" style="padding:5px 0px;">'.((int)self::$_FREQUENCYS[$_sequence]['validCnt']).'</td>';
+ echo '</tr><tr name="single_sums_percent_'.$spid.'">';
+ echo '<td class="red" style="padding:5px 0px;">'.self::formatNumber(100,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%').'</td>';
+ echo '</tr></table>';
+ echo '</td>';
+ // zamenjano veljavni ustrezni
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac" >';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ echo '</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac" >'.(int)self::$_FREQUENCYS[$_sequence]['allCnt'].'</td>';
+ if ($additional_field) { # za odklon in povprečje
+ # povprečje
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ #standardna diviacija
+ $div = 0;
+ $sum_pow_xi_fi_avg = 0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $xi => $kategorija) {
+ $fi = self::$_FREQUENCYS[$_sequence]['valid'][$xi]['cnt'];
+ $sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ }
+ }
+ $div = (($N -1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($N -1)) : 0;
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac" >';
+ echo self::formatNumber($avg,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac" >';
+ echo self::formatNumber($div,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'');
+ echo '</td>';
+ }
+ echo '</tr>';
+
+ } else {
+ # immamo polje drugo
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ }
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** Izriše sumarnik v horizontalni obliki za dvojni multigrid
+ *
+ * @param unknown_type $spid - spremenljivka ID
+ */
+ static function sumDoubleHorizontal($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ $_answersOther = array();
+ $_clmn_cnt = count($spremenljivka['options'])*2;
+
+ # pri radiu in dropdown ne prikazujemo podvprašanj
+ $_sub_question_col = 6;
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ echo '<table class="anl_tbl anl_ba tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_bck_desc_1">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_br anl_al anl_bck anl_bb anl_bck_desc_1" colspan="'. ($_clmn_cnt+2+$_sub_question_col+(self::$_SHOW_LEGENDA ? 2 : 0)) .'">';
+ echo '<span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ $css_txt = 'anl_variabla_line';
+
+ echo '<tr>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ if ($_sub_question_col) {
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck anl_bb '.$css_txt.'" style="width:280px">'.$lang['srv_analiza_opisne_subquestion'].'</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w110 anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line" colspan="'.($_clmn_cnt+6).'">'.$lang['srv_analiza_opisne_answers'];
+ echo '<span id="img_analysis_f_p_1_'.$spid.'" class="img_analysis_f_p"><a href="javascript:show_single_percent(\''.$spid.'\',\'2\');">&nbsp(<span class="blue">f&nbsp;</span>/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '<span id="img_analysis_f_1_'.$spid.'" class="img_analysis_f displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'1\');">&nbsp(<span class="blue">f&nbsp;</span>/&nbsp;%)</a></span>';
+ echo '<span id="img_analysis_p_1_'.$spid.'" class="img_analysis_p displayNone"><a href="javascript:show_single_percent(\''.$spid.'\',\'0\');">&nbsp(f&nbsp;/<span class="blue">&nbsp;%</span>)</a></span>';
+ echo '</td>';
+ #št. enot
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_variabla_line" >&nbsp;</td>';
+ echo '</tr>';
+ #naslovi podskupin
+ $cssBack = "anl_bck_0_0 ";
+ $_variables = $grid['variables'];
+ echo '<tr>';
+ echo '<td class="anl_tin ' . $cssBack . 'anl_bl anl_br anl_bb">&nbsp;</td>';
+ if ( $_sub_question_col ) {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">&nbsp;</td>'; //$_tip
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">&nbsp;</td>'; // $_oblika
+ }
+ echo '<td class="' . $cssBack . ' anl_bb anl_ac anl_br" colspan="'.(count($spremenljivka['options'])+3).'">'.($spremenljivka['double'][1]['subtitle'] == '' ? $lang['srv_grid_subtitle_def'].' 1' : $spremenljivka['double'][1]['subtitle']).'</td>';
+ echo '<td class="' . $cssBack . ' anl_bb anl_ac anl_br" colspan="'.(count($spremenljivka['options'])+3).'">'.($spremenljivka['double'][2]['subtitle'] == '' ? $lang['srv_grid_subtitle_def'].' 2' : $spremenljivka['double'][2]['subtitle']).'</td>';
+ #št. enot
+ echo '<td class="' . $cssBack . ' anl_bb anl_ac anl_br" >&nbsp;</td>';
+
+ echo '</tr>';
+
+ # naslovi variabel
+ $cssBack = "anl_bck_0_0 ";
+ $_variables = $grid['variables'];
+ echo '<tr>';
+ echo '<td class="anl_tin ' . $cssBack . 'anl_bl anl_br anl_bb">&nbsp;</td>';
+ if ( $_sub_question_col ) {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">&nbsp;</td>'; //$_tip
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">&nbsp;</td>'; // $_oblika
+ }
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ // misinge imamo zdruzene
+ $_label = $kategorija;
+ echo '<td class="' . $cssBack . ' anl_bb anl_ac anl_dash_br ">'.$_label.'</td>';
+ }
+ }
+ echo '<td class="' . $cssBack . ' anl_bb anl_br anl_ac red anl_w70">'.$lang['srv_anl_suma1'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_povprecje'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_odklon'].'</td>';
+
+
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ // misinge imamo zdruzene
+ $_label = $kategorija;
+ echo '<td class="' . $cssBack . ' anl_bb anl_ac anl_dash_br ">'.$_label.'</td>';
+ }
+ }
+ echo '<td class="' . $cssBack . ' anl_bb anl_br anl_ac red anl_w70">'.$lang['srv_anl_suma1'].'</td>';
+ echo '<td class="' . $cssBack . ' anl_bb anl_br anl_ac anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_povprecje'].'</td>';
+ echo '<td class="' . $cssBack . ' anl_bb anl_br anl_ac anl_w70 anl_variabla_line">'.$lang['srv_analiza_opisne_odklon'].'</td>';
+
+ # št enot
+ echo '<td class="' . $cssBack . ' anl_bb anl_br anl_ac anl_w70 anl_variabla_line">'.$lang['srv_analiza_num_units'].'</td>';
+
+ echo '</tr>';
+ #zloopamo skozi gride in nardimo
+ $_tmp_table = array();
+ $_part = 1;
+ $cnt = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if ( $_part == $grid['part'] ) {
+ $cnt++;
+ } else {
+ $_part = $grid['part'];
+ $cnt = 1;
+ }
+ # zloopamo skozi variable
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ) {
+
+ $_sequence = $variable['sequence'];
+ if ($variable['other'] != true) {
+ # za odklon in povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ $xi = $key;
+ $fi = self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+
+ $_percent = (self::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'] * 100 / self::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_tmp_table[$grid['part']][$cnt]['variables'][] = array('key'=>$key, 'freq'=>self::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'],'percent'=>$_percent);
+ }
+ }
+ $_tmp_table[$grid['part']][$cnt]['seq'] = $variable['seq'];
+ $_tmp_table[$grid['part']][$cnt]['vr_id'] = $variable['vr_id'];
+ $_tmp_table[$grid['part']][$cnt]['variable'] = substr($variable['variable'], 0, strrpos($variable['variable'], "_"));
+ $_tmp_table[$grid['part']][$cnt]['naslov'] = $variable['naslov'];
+ $_tmp_table[$grid['part']][$cnt]['suma'] = self::$_FREQUENCYS[$_sequence]['validCnt'];
+ $_tmp_table[$grid['part']][$cnt]['allCnt'] = (int)self::$_FREQUENCYS[$_sequence]['allCnt'];
+
+ # odklon
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ #standardna diviacija
+ $div = 0;
+ $sum_pow_xi_fi_avg = 0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $xi => $kategorija) {
+ $fi = self::$_FREQUENCYS[$_sequence]['valid'][$xi]['cnt'];
+ $sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ }
+ }
+ $div = (($N -1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($N -1)) : 0;
+
+ $_tmp_table[$grid['part']][$cnt]['avg'] = $avg;
+ $_tmp_table[$grid['part']][$cnt]['div'] = $div;
+ } //end if ($variable['other'] != true)
+ } // end foreach variables
+ }
+ }
+ }
+
+
+
+ #zlopamo skozi gride
+ if (count($_tmp_table[1]) > 0) {
+ foreach ($_tmp_table[1] AS $tkey => $grid) {
+ $cssBack = "anl_bck_desc_2 ";
+ echo '<tr id="'.$spid.'_'.$grid['vr_id'].'">';
+ if ($_sub_question_col) {
+ echo '<td class="anl_tin1 ' . $cssBack . 'anl_bl anl_br anl_bb anl_ac anl_variabla_sub">'.$grid['variable'].'</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">'.$grid['naslov'].'</td>';
+ } else {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb">&nbsp;</td>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">'.$_tip.'</td>';
+ echo '<td class="anl_p5 ' . $cssBack . 'anl_br anl_bb anl_ac">'.$_oblika.'</td>';
+ }
+
+ # zloopamo skozi variable
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ) {
+ #mg_inspectž
+ echo '<td class="anl_bb anl_dash_br anl_ac cll_clps '.$cssBack.'">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac'.(self::$enableInspect == true && (int)$variable['freq'] > 0 ? ' dmg_inspect' : '').'" style="padding:5px 0px;"'.(self::$enableInspect == true && (int)$variable['freq'] > 0 ? ' gid="'.$variable['key'].'_1"' : '').'>'.$variable['freq'].'</td>';
+ echo '</tr><tr name="single_sums_percent_'.$spid.'">';
+ echo '<td style="padding:5px 0px;">';
+ echo self::formatNumber($variable['percent'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr></table>';
+ echo '</td>';
+ } // end foreach variables
+ } // end if (count($grid['variables']) > 0)
+ // suma
+ echo '<td class="anl_bb anl_br anl_ac cll_clps ' . $cssBack . '">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac red" style="padding:5px 0px;">'.(int)$grid['suma'].'</td>';
+ echo '</tr><tr name="single_sums_percent_'.$spid.'">';
+ echo '<td class="red" style="padding:5px 0px;">'.self::formatNumber(100,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%').'</td>';
+ echo '</tr></table>';
+ echo '</td>';
+
+ // povpreje
+ echo '<td class="anl_bb anl_br anl_ac ' . $cssBack . '" >';
+ echo self::formatNumber($grid['avg'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+
+ // odklon
+ echo '<td class="anl_bb anl_br anl_ac ' . $cssBack . '" >';
+ echo self::formatNumber($grid['div'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+
+ # dodamo desni del grida
+ $_right_grid = $_tmp_table[2][$tkey];
+ if (count($_right_grid['variables']) > 0) {
+ foreach ($_right_grid['variables'] AS $vid => $variable ) {
+ echo '<td class="anl_bb anl_dash_br anl_ac cll_clps '.$cssBack.'">';
+ #mg_inspect
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac'.(self::$enableInspect == true && (int)$variable['freq'] > 0 ? ' dmg_inspect' : '').'" style="padding:5px 0px;"'.(self::$enableInspect == true && (int)$variable['freq'] > 0 ? ' gid="'.$variable['key'].'_2"' : '').'>'.$variable['freq'].'</td>';
+ echo '</tr><tr name="single_sums_percent_'.$spid.'">';
+ echo '<td style="padding:5px 0px;">';
+ echo self::formatNumber($variable['percent'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '</td>';
+ echo '</tr></table>';
+ echo '</td>';
+ } // end foreach variables
+ } // end if (count($grid['variables']) > 0)
+ // suma
+ echo '<td class="anl_bb anl_br anl_ac cll_clps '.$cssBack.'">';
+ echo '<table class="fullWidth anl_ac tbl_clps">';
+ echo '<tr name="single_sums_percent_cnt_'.$spid.'" class="anl_dash_bb">';
+ echo '<td class="anl_ac red" style="padding:5px 0px;">'.(int)$_right_grid['suma'].'</td>';
+ echo '</tr><tr name="single_sums_percent_'.$spid.'">';
+ echo '<td class="red" style="padding:5px 0px;">'.self::formatNumber(100,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%').'</td>';
+ echo '</tr></table>';
+ echo '</td>';
+
+ // povpreje
+ echo '<td class="anl_bb anl_br anl_ac ' . $cssBack . '" >';
+ echo self::formatNumber($_right_grid['avg'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+
+ # odklon
+ echo '<td class="anl_bb anl_br anl_ac ' . $cssBack . '" >';
+ echo self::formatNumber($_right_grid['div'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+
+ # št enot
+ echo '<td class="anl_bb anl_br anl_ac ' . $cssBack . '" >';
+ echo $grid['allCnt'];
+ echo '</td>';
+ echo '</tr>';
+ } // end foreach ($_tmp_table[1] AS $tkey => $grid)
+ }
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+
+ }
+
+ /** Izriše multi number odgovore. izpiše samo povprečja
+ *
+ * @param unknown_type $spid
+ */
+ static function sumMultiNumber($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+
+ $_cols = $spremenljivka['cnt_all'] / $spremenljivka['cnt_grids'];
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_bb tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA ? 3+$_cols : 1+$_cols).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ #odgovori
+
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">'.$lang['srv_analiza_opisne_subquestion'] . '</td>';
+ if (self::$_SHOW_LEGENDA){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line" colspan="'.($_cols).'">'. $lang['srv_analiza_sums_average'] .'</td>';
+
+ echo '</tr>';
+ // konec naslovne vrstice
+
+ $_answersOther = array();
+ $_grids_count = count($spremenljivka['grids']);
+ if ($_grids_count > 0) {
+ # naslovna vrstica
+ $_row = $spremenljivka['grids'][0];
+ echo '<tr>';
+ echo '<td class="anl_bl anl_bb anl_bck">&nbsp;</td>';
+ echo '<td class="anl_bl anl_br anl_bb anl_bck">&nbsp;</td>';
+
+ if (self::$_SHOW_LEGENDA){
+ echo '<td class="anl_br anl_bb anl_bck">&nbsp;</td>';
+ echo '<td class="anl_br anl_bb anl_bck">&nbsp;</td>';
+ }
+ if (count($_row['variables']) > 0 )
+ foreach ($_row['variables'] AS $rid => $_col ){
+ $_sequence = $_col['sequence']; # id kolone z podatki
+
+ if ($_col['other'] != true) {
+ echo '<td class="anl_br anl_bb anl_bck anl_ac">';
+ // echo $_col['variable'];
+ echo $_col['naslov'];
+ echo '</td>';
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ echo '</tr>';
+ $_css_bck = 'anl_bck_desc_2 anl_ac anl_bt_dot ';
+ $last = 0;
+ //anl_bck_desc_2 anl_bl anl_br anl_variabla_sub
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_variables_count = count($grid['variables']);
+ echo '<tr class="'.$_css_bck.'">';
+ echo '<td class="anl_bl anl_br anl_variabla_sub">';
+ echo $grid['variable'];
+ echo '</td>';
+ echo '<td class="anl_br anl_al">';
+ echo $grid['naslov'];
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA){
+ echo '<td class="anl_br">'.$_tip.'</td>';
+ echo '<td class="anl_br">'.$_oblika.'</td>';
+ }
+
+ if ($_variables_count > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ if ($variable['other'] != true) {
+ # tabela z navedbami
+ echo '<td class="anl_at anl_br">';
+ echo self::formatNumber(self::$_FREQUENCYS[$_sequence]['average'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+
+ }
+ }
+
+ }
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** Izriše multi number odgovore. v Navpični obliki (podobno kot opisne)
+ *
+ * @param unknown_type $spid
+ */
+ static function sumMultiNumberVertical($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+ $inline_legenda = (self::$_HEADERS[$spid]['cnt_all'] == 1 || in_array($spremenljivka['tip'],array(1,8) ) ) ? false: true;
+ $options=array('inline_legenda' => $inline_legenda, 'isTextAnswer' => false, 'isOtherAnswer' => false);
+
+ # ali izpisujemo enoto:
+ $show_enota = true;
+ if ((int)$spremenljivka['enota'] == 0 && self::$_HEADERS[$spid]['cnt_all'] == 1) {
+ $show_enota = false;
+ }
+
+ # ugotovimo koliko imamo kolon
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_clmn_cnt[$gid] = $grid['cnt_vars']-$grid['cnt_other'];
+ if (count($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable) {
+ $_sequence = $variable['sequence'];
+ $_approp_cnt[$gid] = max($_approp_cnt[$gid], self::$_FREQUENCYS[$_sequence]['allCnt']);
+
+ # za povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ $min = null;
+ $max = null;
+
+ if (count(self::$_FREQUENCYS[$_sequence]['valid']) > 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $xi => $_validFreq) {
+
+ # popravimo morebitne . in -
+ $fnkey = (float)$xi;
+
+ if (is_numeric($xi) && is_numeric($fnkey) && trim($fnkey) != '') {
+ $fi = $_validFreq['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+
+ $min = $min != null ? min($min,$fnkey) : $fnkey;
+ $max = $max != null ? max($max,$fnkey) : $fnkey;
+
+ }
+ }
+ }
+ # povprešje
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+
+ self::$_FREQUENCYS[$_sequence]['validAvg'] = $avg;
+ self::$_FREQUENCYS[$_sequence]['validMin'] = $min;
+ self::$_FREQUENCYS[$_sequence]['validMax'] = $max;
+
+ #standardna diviacija
+ $div = 0;
+ $sum_pow_xi_fi_avg = 0;
+ if (count(self::$_FREQUENCYS[$_sequence]['valid']) > 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $xi => $_validFreq) {
+ $fi = $_validFreq['cnt'];
+ $sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ }
+ }
+ self::$_FREQUENCYS[$_sequence]['validDiv'] = (($N -1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($N -1)) : 0;
+
+ #določimo še polja drugo za kasnejši prikaz
+ if ($variable['other'] == true) {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ }
+ $isSingleGrid = ($spremenljivka['cnt_all'] == $spremenljivka['cnt_grids']) ? true : false;
+
+ # če je cnt_all == cnt_grids pomeni da imamo samo 1 grid
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_br anl_bb tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA ? 7+(int)$inline_legenda*2 : 7).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+
+ if (!$inline_legenda) {
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck">';
+
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+
+
+ if ($show_enota) {
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">';
+ if ($spremenljivka['tip'] == 20 || $spremenljivka['tip'] == 7) {
+ echo $lang['srv_analiza_opisne_subquestion'];
+ } else {
+ echo $lang['srv_analiza_opisne_variable_text'];
+ }
+ echo'</td>';
+ } else { # če mamo number brez labele izrisujemo drugače
+ echo '<td class="anl_br">';
+ echo '&nbsp;';
+ echo'</td>';
+ }
+
+ if (self::$_SHOW_LEGENDA && $inline_legenda){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line" >'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line" >'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_m'] . '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_num_units'] . '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_povprecje'] . '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_odklon'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_min'] . '</td>';
+ echo '<td class="anl_bck anl_ac anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_max'] . '</td>';
+ echo '</tr>';
+
+ $_answersOther = array();
+ $_grupa_cnt = 0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($spremenljivka['grids']) > 1 && $_grupa_cnt !== 0 && $spremenljivka['tip'] != 6) {
+ $grid['new_grid'] = true;
+ }
+
+ $_grupa_cnt ++;
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true) {
+ $_sequence = $variable['sequence'];
+
+ $cssBrdr = (int)$grid['new_grid'] == 1 && $isSingleGrid == false? ' anl_double_bt' : ' anl_bt_dot';
+
+ echo '<tr>';
+ if (!$show_enota && $spremenljivka['tip'] == 7) {
+ echo '<td style="border-bottom:1px solid white;">' ;
+ } else {
+ echo '<td class="anl_bck_desc_2 anl_ac anl_bl anl_br anl_variabla_sub'.$cssBrdr.'">' ;
+ }
+ echo $_css_double_line;
+ # za number (7) ne prikazujemo variable
+ if ($spremenljivka['tip'] != 7 ) {
+ echo $variable['variable'];
+ }
+ echo '</td>' ;
+ if (!$show_enota && $spremenljivka['tip'] == 7) {
+ echo '<td style="border-bottom:1px solid white;">' ;
+ } else {
+ echo '<td class="anl_bck_desc_2 anl_al anl_br'.$cssBrdr.'">' ;
+ }
+
+ if ($show_enota) {
+ # če ni enojni grid
+ if ($isSingleGrid == false) {
+ echo (count($grid['variables']) > 1 && $spremenljivka['tip'] == 20 ? $grid['naslov'] . ' - ' : '' ).$variable['naslov'];
+ } else {
+ # če je enojni, izpišemo labele variable
+ echo $grid['naslov'];
+ }
+ } else {
+ echo '&nbsp;';
+ }
+ echo '</td>' ;
+ if (self::$_SHOW_LEGENDA && $inline_legenda) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'" title="'.$_tip.'">'.$_tip.'</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'" title="'.$_oblika.'">' .$_oblika. '</td>';
+ }
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br anl_bl'.$cssBrdr.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo (int)$_approp_cnt[$gid];
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo self::formatNumber(self::$_FREQUENCYS[$_sequence]['validAvg'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo self::formatNumber(self::$_FREQUENCYS[$_sequence]['validDiv'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'');
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validMin'];
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validMax'];;
+ echo '</td>';
+
+ echo '</tr>';
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ $grid['new_grid'] = false;
+ }
+
+ }
+ }
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+ /** Izriše number odgovore v vertikalni obliki
+ *
+ * @param unknown_type $spid
+ */
+ static function sumNumberVertical($spid,$_from) {
+ global $lang;
+ $spremenljivka = self::$_HEADERS[$spid];
+
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+ $inline_legenda = (self::$_HEADERS[$spid]['cnt_all'] == 1 || in_array($spremenljivka['tip'],array(1,8) ) ) ? false: true;
+ $options=array('inline_legenda' => $inline_legenda, 'isTextAnswer' => false, 'isOtherAnswer' => false);
+
+ # ali izpisujemo enoto:
+ $show_enota = true;
+ if (((int)$spremenljivka['enota'] == 0 && self::$_HEADERS[$spid]['cnt_all'] == 1) || $spremenljivka['tip'] == 22 || $spremenljivka['tip'] == 25) {
+ $show_enota = false;
+ }
+ $sum_avg = 0;
+ # ugotovimo koliko imamo kolon
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_clmn_cnt[$gid] = $grid['cnt_vars']-$grid['cnt_other'];
+ if (count($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable) {
+ $_sequence = $variable['sequence'];
+ $_approp_cnt[$gid] = max($_approp_cnt[$gid], self::$_FREQUENCYS[$_sequence]['allCnt']);
+
+ # za povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+
+ $min = null;
+ $max = null;
+ if (count(self::$_FREQUENCYS[$_sequence]['valid']) > 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $xi => $_validFreq) {
+
+ # popravimo morebitne . in -
+ $fnkey = (float)$xi;
+
+ if (is_numeric($xi) && is_numeric($fnkey) && trim($fnkey) != '') {
+ $fi = $_validFreq['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+ $min = $min != null ? min($min,$fnkey) : $fnkey;
+ $max = $max != null ? max($max,$fnkey) : $fnkey;
+ }
+ }
+ }
+
+ #povprečje
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ $sum_avg += $avg;
+ self::$_FREQUENCYS[$_sequence]['validAvg'] = $avg;
+ self::$_FREQUENCYS[$_sequence]['validMin'] = $min;
+ self::$_FREQUENCYS[$_sequence]['validMax'] = $max;
+
+ #standardna diviacija
+ $div = 0;
+ $sum_pow_xi_fi_avg = 0;
+ if (count(self::$_FREQUENCYS[$_sequence]['valid']) > 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $xi => $_validFreq) {
+ $fi = $_validFreq['cnt'];
+ $sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ }
+ }
+ self::$_FREQUENCYS[$_sequence]['validDiv'] = (($N -1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($N -1)) : 0;
+
+ #določimo še polja drugo za kasnejši prikaz
+ if ($variable['other'] == true) {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_br anl_bb tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ $num_cols = 7 + ($spremenljivka['tip'] == 18 ? 1 : 0);
+ #odgovori
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA ? $num_cols+(int)$inline_legenda*2 : $num_cols).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+
+ if (!$inline_legenda) {
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+
+
+ if ($show_enota == true) {
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">';
+ if ($spremenljivka['tip'] == 20 || $spremenljivka['tip'] == 7) {
+ echo $lang['srv_analiza_opisne_subquestion'];
+ } else {
+ echo $lang['srv_analiza_opisne_variable_text'];
+ }
+ echo'</td>';
+ } else { # če mamo number brez labele izrisujemo drugače
+ echo '<td class="anl_br">';
+ echo '&nbsp;';
+ echo'</td>';
+ }
+
+ if (self::$_SHOW_LEGENDA && $inline_legenda){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line" >'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line" >'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_m'] . '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_num_units'] . '</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_povprecje'] . '</td>';
+ if ($spremenljivka['tip'] == 18) {
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">%</td>';
+ }
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_odklon'].'</td>';
+ echo '<td class="anl_br anl_ac anl_bck anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_min'] . '</td>';
+ echo '<td class="anl_bck anl_ac anl_bb anl_w70 anl_legend anl_variabla_line">' . $lang['srv_analiza_opisne_max'] . '</td>';
+ echo '</tr>';
+
+ $_answersOther = array();
+ $_grupa_cnt = 0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($spremenljivka['grids']) > 1 && $_grupa_cnt !== 0 && $spremenljivka['tip'] != 6) {
+ $grid['new_grid'] = true;
+ }
+
+ $_grupa_cnt ++;
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true) {
+ $_sequence = $variable['sequence'];
+
+ $cssBrdr = (int)$grid['new_grid'] == 1 ? ' anl_double_bt' : ' anl_bt_dot';
+
+ echo '<tr>';
+ if (!$show_enota && $spremenljivka['tip'] == 7) {
+ echo '<td style="border-bottom:1px solid white;">' ;
+ } else {
+ echo '<td class="anl_bck_desc_2 anl_ac anl_bl anl_br anl_variabla_sub'.$cssBrdr.'">' ;
+ }
+ echo $_css_double_line;
+ # za number (7) ne prikazujemo variable
+ if ($spremenljivka['tip'] != 7 || ($show_enota == true && $spremenljivka['tip'] == 7 )) {
+ if ($variable['variable'] == $spremenljivka['variable']) {
+ echo $variable['variable'].'_1';
+ } else {
+ echo $variable['variable'];
+ }
+ }
+ echo '</td>' ;
+ if ((!$show_enota && $spremenljivka['tip'] == 7 ) || $spremenljivka['tip'] == 22 || $spremenljivka['tip'] == 25) {
+ echo '<td style="border-bottom:1px solid white;">' ;
+ } else {
+ echo '<td class="anl_bck_desc_2 anl_al anl_br'.$cssBrdr.'">' ;
+ }
+ if ($show_enota) {
+ echo (count($grid['variables']) > 1 && $spremenljivka['tip'] == 20 ? $grid['naslov'] . ' - ' : '' ).$variable['naslov'];
+ } else {
+ echo '&nbsp;';
+ }
+ echo '</td>' ;
+ if (self::$_SHOW_LEGENDA && $inline_legenda) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'" title="'.$_tip.'">'.$_tip.'</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'" title="'.$_oblika.'">' .$_oblika. '</td>';
+ }
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br anl_bl'.$cssBrdr.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo (int)$_approp_cnt[$gid];
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo self::formatNumber(self::$_FREQUENCYS[$_sequence]['validAvg'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+ if ($spremenljivka['tip'] == 18) {
+ $_percent = ($sum_avg > 0 ) ? 100 * self::$_FREQUENCYS[$_sequence]['validAvg'] / $sum_avg : 0;
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo self::formatNumber($_percent,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'%');
+ echo '</td>';
+ }
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo self::formatNumber(self::$_FREQUENCYS[$_sequence]['validDiv'],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'');
+ echo '</td>';
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validMin'];
+ echo '<td class="anl_bck_desc_2 anl_ac anl_br'.$cssBrdr.'">';
+ echo (int)self::$_FREQUENCYS[$_sequence]['validMax'];;
+ echo '</td>';
+
+ echo '</tr>';
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ $grid['new_grid'] = false;
+ }
+
+ }
+ }
+ if ($spremenljivka['tip'] == 18) {
+ $css_back = 'anl_bck_text_1 anl_bt';
+ echo '<tr>';
+ echo '<td class="'.$css_back.' anl_bl red">';
+ echo $lang['srv_anl_suma1'];
+ echo '</td>';
+ echo '<td class="'.$css_back.'">&nbsp;</td>';
+
+ if (self::$_SHOW_LEGENDA && $inline_legenda){
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ }
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ echo '<td class="'.$css_back.' anl_ac anl_bl anl_br" >';
+ echo self::formatNumber($sum_avg,SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_DEVIATION'),'');
+ echo '</td>';
+ # skupna suma
+ echo '<td class="'.$css_back.' anl_br anl_ac" >100%</td>';
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ echo '<td class="'.$css_back.'" >&nbsp;</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** Izriše nagovor
+ *
+ */
+ static function sumNagovor($spid,$_from) {
+ global $lang;
+ $spremenljivka = self::$_HEADERS[$spid];
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ $cssBack = "anl_bck_freq_1 ";
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ echo '<table class="anl_tbl_inner anl_ba" >';
+ echo '<tr>';
+ echo '<td class="anl_p5 anl_br anl_ac anl_bck_desc_1 anl_bb anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ echo '<td class="anl_p5 anl_br anl_al anl_bck_desc_1 anl_bb"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ echo '</table>';
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** Izriše tekstovne odgovore kot tabelo z navedbami
+ *
+ * @param unknown_type $spid
+ */
+ //static function sumMultiText($spid,$_from, $lokacija=false) {
+ static function sumMultiText($spid,$_from) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+ $lokacija=false;
+ $heatmap=false;
+ if($spremenljivka['tip'] == 26)
+ $lokacija=true;
+ else if ($spremenljivka['tip'] == 27)
+ $heatmap=true;
+
+ $anketa = self::$sid;
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+
+ $_cols = $spremenljivka['cnt_all'] / $spremenljivka['cnt_grids'];
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ // $num_show_records = $_max_answers_cnt <= (int)$num_show_records ? $_max_answers_cnt : $num_show_records;
+
+ //za tip lokacija (ne enota 3) se rabi user_id, ker se kasneje delajo linki
+ $need_user_id = !($spremenljivka['tip'] != 26 || ($spremenljivka['tip'] == 26 && $spremenljivka['enota'] == 3));
+ $_answers = self::getAnswers($spremenljivka, $num_show_records, $need_user_id);
+
+ $_all_valid_answers_cnt = $_answers['validCnt'];
+ $_valid_answers = $_answers['valid'];
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_bb tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(!$lokacija ? (self::$_SHOW_LEGENDA ? 3+$_cols : 1+$_cols) : 3+$_cols).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ #odgovori
+
+ if(!$lokacija)
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">'.$lang['srv_analiza_opisne_subquestion'] . '</td>';
+ if (self::$_SHOW_LEGENDA){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ if(!$lokacija){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line" colspan="'.(!$lokacija ? $_cols : 3+$_cols).'">'. $lang['srv_analiza_opisne_arguments'] .'</td>';
+ echo '</tr>';
+ }
+ // konec naslovne vrstice
+
+ $_answersOther = array();
+ $_grids_count = count($spremenljivka['grids']);
+ if ($_grids_count > 0) {
+ # naslovna vrstica
+ $_row = $spremenljivka['grids'][0];
+ if(!$lokacija){
+ echo '<tr>';
+ echo '<td class="anl_bl anl_bb anl_bck">&nbsp;</td>';
+ echo '<td class="anl_bl anl_br anl_bb anl_bck">&nbsp;</td>';
+ }
+
+ if (self::$_SHOW_LEGENDA){
+ echo '<td class="anl_br anl_bb anl_bck">&nbsp;</td>';
+ echo '<td class="anl_br anl_bb anl_bck">&nbsp;</td>';
+ }
+ if (count($_row['variables'])>0)
+ foreach ($_row['variables'] AS $rid => $_col ){
+
+ $_sequence = $_col['sequence']; # id kolone z podatki
+ if ($_col['other'] != true) {
+ echo '<td class="anl_br anl_bb anl_bck anl_ac">';
+ // echo $_col['variable'];
+ echo $_col['naslov'];
+ echo '</td>';
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ echo '</tr>';
+ $_css_bck = 'anl_bck_desc_2 anl_ac anl_bt_dot ';
+ $last = 0;
+ //anl_bck_desc_2 anl_bl anl_br anl_variabla_sub
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $_variables_count = count($grid['variables']);
+ echo '<tr class="'.$_css_bck.'">';
+ echo '<td class="anl_bl anl_br anl_variabla_sub">';
+ if(!$lokacija)
+ echo $grid['variable'];
+ //else{
+ else if ($lokacija && $heatmap == false){
+ //echo $grid['naslov'].'<br>';//ni potrebno, ker je ze v glavi?
+ $sprid = explode('_',$spid);
+ $loopid = $sprid[1];
+ $sprid = $sprid[0];
+
+ self::displayMapDataAll($spid);
+ }
+ elseif($heatmap){
+ //echo $grid['naslov'].'<br>';//ni potrebno, ker je ze v glavi?
+ $sprid = explode('_',$spid);
+ $loopid = $sprid[1];
+ $sprid = $sprid[0];
+ SurveyUserSession::Init($anketa);
+
+ $heatmapId = 'heatmap'.$sprid;
+ //echo $heatmapId;
+ //SurveyChart::displayExportIcons($sprid);
+ echo '<a class="fHeatMap" id="heatmap_'.$sprid.'" title="'.$lang['srv_view_data_on_map'].
+ '" href="javascript:void(0);" onclick="passHeatMapData('.$sprid.', -1, '.$loopid.', '.$anketa.');">';
+
+ echo 'Heatmap';
+ echo '</a>';
+ }
+ echo '</td>';
+ if(!$lokacija){
+ echo '<td class="anl_br anl_al">';
+ echo $grid['naslov'];
+ echo '</td>';
+ }
+ if (self::$_SHOW_LEGENDA){
+ echo '<td class="anl_br">'.$_tip.'</td>';
+ echo '<td class="anl_br">'.$_oblika.'</td>';
+ }
+
+ if ($_variables_count > 0) {
+ # preštejemo max vrstic na grupo
+ $_max_i = 0;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_max_i = max($_max_i,min($num_show_records,self::$_FREQUENCYS[$_sequence]['validCnt']));
+ }
+
+ # za barvanje
+ $last = ($last & 1) ? 0 : 1 ;
+ $moreBound = 3;
+
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true) {
+ # tabela z navedbami
+ echo '<td class=" anl_at cll_clps">';
+ echo '<table id="'.$spid.'_'.$_sequence.'" class="fullWidth anl_ac tbl_clps" style="vertical-align:top;">';
+ #$_valid_cnt = count(self::$_FREQUENCYS[$_sequence]['valid']);
+ $index=0;
+ if (count($_valid_answers) > 0) {
+ foreach ($_valid_answers AS $key => $answer) {
+ $index++;
+ $cssBck = ' '.self::$cssColors['0_' . ($index & 1)];
+ $_ans = $answer[$_sequence];
+
+ if($index <= $moreBound){
+ //if($index < $moreBound){
+ echo '<tr class="notmore">';
+ echo '<td class="'.$cssBck.' anl_br anl_user_text'
+ .($_ans != null && $_ans != '' && self::$enableInspect == true ? ' mt_inspect' : '')
+ .'"'
+ .($index == 1 && $_ans != null && $_ans != '' && self::$enableInspect == true ? ' vkey="'.$_ans.'"' : '').'>';
+ # narišemo printereček za izpis posameznih textovnih odgovorov
+ if ($index == 1) {
+ //echo '<span class="anl_single_ans_ico as_link" onclick="showSpremenljivkaTextAnswersPopup(\''.$spid.'\',\''.$_sequence.'\'); return false;">';
+
+ //TODO! zakomentiral, ker nima funkcije, ikona pa pokvarjena
+ /*echo '<span class="anl_single_ans_ico as_link">';
+ echo '&nbsp;';
+ echo '</span>';*/
+ }
+ if ($_ans != null && $_ans != '') {
+ if(!($need_user_id && $lokacija))
+ echo $_ans;
+ else
+ echo '<a class="fMap" title="'.$lang['srv_view_data_on_map'].
+ '" href="javascript:void(0);" onclick="passMapData('.$sprid.', '
+ .$key.', '.$loopid.', '.$anketa.');">'.$_ans.'</a>';
+ } else {
+ echo '&nbsp;';
+ }
+
+ if($index == $moreBound){
+ #more - več
+ echo '<br />';
+ echo '&nbsp;';
+ echo '<div class="srv_heatmap_info_more_'.$sprid.' as_link" onclick="$(\'.more_'.$sprid.', .srv_heatmap_info_more_'.$sprid.', .srv_objava_info_more2_'.$sprid.'\').toggle();">'.$lang['srv_more'].'</div>';
+ #more - več - konec
+ }
+ echo '</td>';
+ echo '</tr>';
+ }
+ else {
+ echo '<tr class="more_'.$sprid.' displayNone" >';
+ echo '<td class="'.$cssBck.' anl_br anl_user_text'
+ .($_ans != null && $_ans != '' && self::$enableInspect == true ? ' mt_inspect' : '')
+ .'"'
+ .($index == 1 && $_ans != null && $_ans != '' && self::$enableInspect == true ? ' vkey="'.$_ans.'"' : '').'>';
+ # narišemo printereček za izpis posameznih textovnih odgovorov
+ if ($index == 1) {
+ //echo '<span class="anl_single_ans_ico as_link" onclick="showSpremenljivkaTextAnswersPopup(\''.$spid.'\',\''.$_sequence.'\'); return false;">';
+
+ //TODO! zakomentiral, ker nima funkcije, ikona pa pokvarjena
+ /*echo '<span class="anl_single_ans_ico as_link">';
+ echo '&nbsp;';
+ echo '</span>';*/
+ }
+ if ($_ans != null && $_ans != '') {
+ if(!($need_user_id && $lokacija))
+ echo $_ans;
+ else
+ echo '<a class="fMap" title="'.$lang['srv_view_data_on_map'].
+ '" href="javascript:void(0);" onclick="passMapData('.$sprid.', '
+ .$key.', '.$loopid.', '.$anketa.');">'.$_ans.'</a>';
+ } else {
+ echo '&nbsp;';
+ }
+
+ if($index == $_max_i){
+ #less - manj
+ echo '<br />';
+ echo '&nbsp;';
+ echo '<div class="srv_heatmap_info_more2_'.$sprid.' as_link" onclick="$(\'.more_'.$sprid.', .srv_heatmap_info_more_'.$sprid.', .srv_heatmap_info_more2_'.$sprid.' \').toggle();">'.$lang['srv_less'].'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ }
+ }
+ }
+
+ if ($_all_valid_answers_cnt > $index) {
+ $index++;
+ $cssBck = ' '.self::$cssColors['0_' . ($index & 1)];
+ echo '<tr>';
+ echo '<td class="'.$cssBck.' anl_br anl_user_text">';
+ // Pri javni povezavi drugace izpisemo
+ if(self::$printPreview == false)
+ echo '<div id="valid_row_togle_more_'.$vid.'" class="floatRight blue pointer anl_more" onclick="showHidenTextTable(\''.$spid.'\', \''.$num_show_records.'\', \''.self::$_CURRENT_LOOP['cnt'].'\');return false;">'.$lang['srv_anl_more'].'</div>';
+ else
+ echo '<div id="valid_row_togle_more_'.$vid.'" class="floatRight anl_more">'.$lang['srv_anl_more'].'</div>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+
+ echo '</td>';
+ }
+ }
+ $last = $_max_i;
+
+ }
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /**
+ *
+ * @global type $lang
+ * @param string $spid - [spremenljivka_id]_[loop_id]
+ */
+ private static function displayMapDataAll($spid){
+ global $lang;
+
+ $sprid = explode('_',$spid);
+ $loopid = $sprid[1];
+ $sprid = $sprid[0];
+
+ $spremenljivka = Cache::srv_spremenljivka($sprid);
+ $enota = $spremenljivka["enota"];
+
+ //za choose location naredi isto, kot za vsak userja posebej - dobi direkt iz baze ne glede na filterje
+ if($enota == 3){
+ echo '<a class="fMap" title="'.$lang['srv_view_data_on_map'].
+ '" href="javascript:void(0);" onclick="passMapData('.$sprid.', -1, '.$loopid.', '.self::$sid.', \'mapData\');">';
+ echo '<img src="img_0/Google_Maps_Icon.png" height="24" width="24" />';
+ echo '</a>';
+ }
+ //prikaz glede na filterje
+ else{
+ echo '<a class="fMap" title="'.$lang['srv_view_data_on_map'].
+ '" href="javascript:void(0);" onclick="passMapData('.$sprid.', -1, '.$loopid.', '.self::$sid.', \'mapDataAll\');">';
+ echo '<img src="img_0/Google_Maps_Icon.png" height="24" width="24" />';
+ echo '</a>';
+ }
+ }
+
+
+ /** Izriše tekstovne odgovore v vertikalni obliki
+ *
+ * @param unknown_type $spid
+ */
+ static function sumTextVertical($spid,$_from) {
+ global $lang;
+ # dajemo v bufer, da da ne prikazujemo vprašanj brez veljavnih odgovorov če imamo tako nastavljeno
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+ $inline_legenda = (self::$_HEADERS[$spid]['cnt_all'] == 1 || in_array($spremenljivka['tip'],array(1,8) ) ) ? false: true;
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ $options=array('inline_legenda' => $inline_legenda, 'isTextAnswer' => false, 'isOtherAnswer' => false, 'num_show_records' => $num_show_records);
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_br tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(self::$_SHOW_LEGENDA ? 5+(int)$inline_legenda*2 : 5).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ if (self::$_SHOW_LEGENDA) {
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+
+ if (!$inline_legenda) {
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+
+ echo '<div class="anl_variable_type"><span>'.$lang['srv_analiza_opisne_variable_type'].': </span>'.self::getSpremenljivkaLegenda($spremenljivka,'tip').'</div>';
+ }
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110">';
+ self::showIcons($spid,$spremenljivka,$_from);
+ echo '</td>';
+ #odgovori
+
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_variabla_line">'.$lang['srv_analiza_frekvence_titleAnswers'] . '</td>';
+ if (self::$_SHOW_LEGENDA && $inline_legenda){
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_legend anl_variabla_line">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleFrekvenca'] .'</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleOdstotek'] .'</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleVeljavni'] .'</td>';
+ }
+ echo '<td class="anl_br anl_bb anl_ac anl_bck anl_w70 anl_variabla_line">'. $lang['srv_analiza_frekvence_titleKumulativa'] .'</td>';
+ echo '</tr>';
+ // konec naslovne vrstice
+ $_answersOther = array();
+ $_grids_count = count($spremenljivka['grids']);
+ if ($_grids_count > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_variables_count = count($grid['variables']);
+ if ($_variables_count > 0)
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ if ($variable['other'] != true) {
+ # dodamo dodatne vrstice z labelami grida
+ if ($_variables_count > 1) {
+ self::outputGridLabelVertical($gid,$grid,$vid,$variable,$spid,$options);
+ }
+
+ $counter = 0;
+ $_kumulativa = 0;
+ //self::$_FREQUENCYS[$_sequence]
+ if (count(self::$_FREQUENCYS[$_sequence]['valid'])> 0 ) {
+ $_valid_answers = self :: sortTextValidAnswers($spid,$variable,self::$_FREQUENCYS[$_sequence]['valid']);
+
+ foreach ($_valid_answers AS $vkey => $vAnswer) {
+ if ($counter < $num_show_records || self::$isArchive) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+ $options['isTextAnswer']=true;
+ $counter = self::outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_kumulativa,$options);
+ }
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaValidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ if (count(self::$_FREQUENCYS[$_sequence]['invalid'])> 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputInvalidAnswerVertical($counter,$ikey,$iAnswer,$_sequence,$spid,$options);
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ #izpišemo še skupno sumo
+ $counter = self::outputSumaVertical($counter,$_sequence,$spid,$options);
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ }
+
+ echo '</table>';
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ /** za multi grid tekstovne vrstice doda vrstico z labeliami grida
+ *
+ * @param $gkey
+ * @param $gAnswer
+ * @param $spid
+ * @param $_options
+ */
+ static function outputGridLabelVertical($gid,$grid,$vid,$variable,$spid,$_options=array()) {
+ echo '<tr id="'.$spid.'_'.$counter.'">';
+ echo '<td class="anl_bck_freq_2 anl_bl anl_bb anl_br anl_ac anl_variabla_sub">';
+ echo $variable['variable'];
+ echo '</td>';
+ echo '<td class="anl_bck_freq_2 anl_al anl_bb anl_br">';
+ //echo ($grid['naslov'] != '' ? $grid['naslov']. '&nbsp;-&nbsp;' : '').$variable['naslov'];
+ echo $variable['naslov'];
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA) {
+
+ $spremenljivka = self::$_HEADERS[$spid];
+ if ($variable['other'] != '1' && $variable['text'] != '1') {
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'izrazanje');
+ $_oblika = self::getSpremenljivkaLegenda($spremenljivka,'skala');
+ } else {
+ global $lang;
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ }
+
+ echo '<td class="anl_bck_freq_2 anl_ac anl_bb anl_br ">'.$_tip.'</td>';
+ echo '<td class="anl_bck_freq_2 anl_ac anl_bb anl_br ">'.$_oblika.'</td>';
+ }
+ echo '<td class="anl_bck_freq_2 anl_bb anl_br">&nbsp;</td>';
+
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_bck_freq_2 anl_bb anl_br">&nbsp;</td>';
+ }
+ echo '<td class="anl_bck_freq_2 anl_bb anl_br">&nbsp;</td>';
+ echo '<td class="anl_bck_freq_2 anl_bb anl_br">&nbsp;</td>';
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,&$_kumulativa,$_options=array()) {
+ global $lang;
+ # opcije
+
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ $cssBck = ' '.self::$cssColors['0_' . ($counter & 1)];
+
+ $_valid = (self::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / self::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (self::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / self::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_kumulativa += $_valid;
+
+ # če smo v arhivih dodamovse odgovore vendar so nekateri skriti
+ if ($counter >= $options['num_show_records'] && self::$isArchive) {
+ $cssHide=' class="displayNone"';
+ }
+ echo '<tr id="'.$spid.'_'.$_sequence.'_'.$counter.'" name="valid_row_'.$_sequence.'"'.(self::$enableInspect == true && (int)$vAnswer['cnt'] > 0 ? ' vkey="'.$vkey.'"' : '').$cssHide.'>';
+ echo '<td class="anl_bl anl_ac anl_br gray">&nbsp;</td>';
+ echo '<td class="anl_br'.$cssBck.'">';
+ echo '<div class="anl_user_text_more">'.$vkey.'</div>';
+ echo (($options['isTextAnswer'] == false && (string)$vkey != $vAnswer['text']) ? ' ('.$vAnswer['text'] .')' : '');
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true ) {
+ echo '<td class="anl_ac anl_br'.$cssBck.'">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br'.$cssBck.'">&nbsp;</td>';
+ }
+
+ echo '<td class="anl_ac anl_br'.$cssBck.(self::$enableInspect == true && $options['isOtherAnswer']== false && (int)$vAnswer['cnt'] > 0 ? ' fr_inspect' : '').'">';
+ echo (int)$vAnswer['cnt'];
+ echo '</td>';
+ echo '<td class="anl_ar anl_br'.$cssBck.' anl_pr10">';
+ echo self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br'.$cssBck.' anl_pr10">';
+ echo self::formatNumber($_valid, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ echo '<td class="anl_ar'.$cssBck.' anl_pr10">';
+ echo self::formatNumber($_kumulativa, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+
+ echo '</td>';
+ echo '</tr>';
+
+ # če mamo več
+ if ( $counter+1 == $options['num_show_records'] && $options['num_show_records'] < count(self::$_FREQUENCYS[$_sequence]['valid'])) {
+ if (self::$isArchive == false ) {
+ echo '<tr id="'.$spid.'_'.$_sequence.'_'.$counter.'" name="valid_row_'.$_sequence.'" >';
+ echo '<td class="anl_bl anl_ac anl_br gray">&nbsp;</td>';
+ echo '<td class="anl_br'.$cssBck.'">';
+ // Pri javni povezavi drugace izpisemo
+ if(self::$printPreview == false){
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatLeft blue pointer anl_more" onclick="showHidenTextTable(\''.$spid.'\', \''.$options['num_show_records'].'\', \''.self::$_CURRENT_LOOP['cnt'].'\');return false;">'.$lang['srv_anl_more'].'</div>';
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatRight blue pointer anl_more" onclick="showHidenTextTable(\''.$spid.'\', \''.$options['num_show_records'].'\', \''.self::$_CURRENT_LOOP['cnt'].'\');return false;">'.$lang['srv_anl_more'].'</div>';
+ }
+ else{
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatLeft anl_more">'.$lang['srv_anl_more'].'</div>';
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatRight anl_more">'.$lang['srv_anl_more'].'</div>';
+ }
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true ) {
+ echo '<td class="anl_ac anl_br'.$cssBck.'">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br'.$cssBck.'">&nbsp;</td>';
+ }
+ echo '<td class="anl_ac anl_br'.$cssBck.'">'.'</td>';
+ echo '<td class="anl_ar anl_br'.$cssBck.' anl_pr10">'.'</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br'.$cssBck.' anl_pr10">'.'</td>';
+ }
+ echo '<td class="anl_ar'.$cssBck.' anl_pr10">'.'</td>';
+ echo '</tr>';
+ } else {
+ #v arhivie dodamo vse odgovore vendar so skriti
+ echo '<tr id="'.$spid.'_'.$_sequence.'_'.$counter.'" name="valid_row_'.$_sequence.'" >';
+ echo '<td class="anl_bl anl_ac anl_br gray">&nbsp;</td>';
+ echo '<td class="anl_br'.$cssBck.'">';
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatLeft blue pointer" onclick="$(this).parent().parent().parent().find(\'tr.displayNone\').removeClass(\'displayNone\');$(this).parent().parent().addClass(\'displayNone\');return false;">'.$lang['srv_anl_all'].'</div>';
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatRight blue pointer" onclick="$(this).parent().parent().parent().find(\'tr.displayNone\').removeClass(\'displayNone\');$(this).parent().parent().addClass(\'displayNone\');return false;">'.$lang['srv_anl_all'].'</div>';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true ) {
+ echo '<td class="anl_ac anl_br'.$cssBck.'">&nbsp;</td>';
+ echo '<td class="anl_ac anl_br'.$cssBck.'">&nbsp;</td>';
+ }
+ echo '<td class="anl_ac anl_br'.$cssBck.'">'.'</td>';
+ echo '<td class="anl_ar anl_br'.$cssBck.' anl_pr10">'.'</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br'.$cssBck.' anl_pr10">'.'</td>';
+ }
+ echo '<td class="anl_ar'.$cssBck.' anl_pr10">'.'</td>';
+ echo '</tr>';
+ }
+ }
+
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaValidAnswerVertical($counter,$_sequence,$spid,$_options=array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ // $cssBck = ' '.self::$cssColors['0_' . ($counter & 1)]; $_percent = (self::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*self::$_FREQUENCYS[$_sequence]['validCnt'] / self::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $cssBck = ' '.self::$cssColors['text_1'];
+
+ $_brez_MV = ((int)self::$missingProfileData['display_mv_type'] === 0 ) ? TRUE : FALSE;
+ $_hide_minus = ((int)self::$missingProfileData['display_mv_type'] === 2 ) ? TRUE : FALSE;
+ $value =((int)self::$missingProfileData['display_mv_type'] === 0 ) ? 0 : 1;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="anl_click_missing_tr_'.$_sequence.$_sufix.'" class="'.($_brez_MV ? 'anl_bb' : 'anl_dash_red_bb').'">';
+ echo '<td class="anl_bl anl_br anl_al gray anl_ti_20'.$cssBck.'">'.$lang['srv_anl_valid'];
+
+ echo '<span id="click_missing_'.$_sequence.$_sufix.'" class="anl_click_missing gray'.($_brez_MV ? '' : ' displayNone').'" value="'.$value.'">&nbsp;&nbsp;<span class="faicon plus_orange icon-orange_hover_red folder_plusminus"></span></span>';
+ echo '<span id="single_missing_title_'.$_sequence.$_sufix.'" class="anl_click_missing_hide gray'.($_brez_MV || $_hide_minus? ' displayNone' : '').'">&nbsp;&nbsp;<span class="faicon minus_orange icon-orange_hover_red folder_plusminus"></span></span>';
+ echo '</td>';
+
+ echo '<td class="anl_br anl_al anl_ita red'.$cssBck.'" >'.$lang['srv_anl_suma1'].'</td>';
+
+
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<th class="anl_ita red anl_br anl_ac'.$cssBck.'">&nbsp;</th>';
+ echo '<th class="anl_ita red anl_br anl_ac'.$cssBck.'">&nbsp;</th>';
+ }
+ echo '<td class="anl_ita red anl_br anl_ac'.$cssBck.'" >';
+
+ echo self::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ? self::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ echo '</td>';
+ $_percent = self::$_FREQUENCYS[$_sequence]['allCnt'] > 0
+ ? 100 * self::$_FREQUENCYS[$_sequence]['validCnt'] / self::$_FREQUENCYS[$_sequence]['allCnt']
+ : 0;
+ echo '<td class="anl_ita red anl_br anl_ar'.$cssBck.' anl_pr10">' . self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%') . '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_ita red anl_br anl_ar'.$cssBck.' anl_pr10">' . self::formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%') . '</td>';
+ }
+ echo '<td class="anl_ita red anl_ac'.$cssBck.'">&nbsp;</td>';
+ echo '</tr>';
+ // $counter++;
+ return $counter;
+
+ }
+
+ static function outputInvalidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_options=array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ //$cssBck = ' '.self::$cssColors['text_' . ($counter & 1)];
+ $cssBck = ' '.self::$cssColors['0_' . ($counter & 1)];
+
+ $_percent = (self::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / self::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (self::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / self::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ $_Z_MV = ((int)self::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ echo '<tr name="missing_detail_'.$_sequence.$_sufix.'"'.($_Z_MV ? '': ' class="displayNone"').'>';
+ echo '<td class="anl_bl anl_br anl_ac gray" style="width:10px">&nbsp;</td>';
+ echo '<td class="anl_br'.$cssBck.'">';
+ echo '<div class="floatLeft"><div class="anl_tin2">'.'<span class="anl_user_text">' . $vkey . '</span>' . ' (' . $vAnswer['text'].')'.'</div></div>';
+ echo '<div class="floatRight anl_detail_percent anl_w50 anl_ac anl_dash_bl">'.self::formatNumber($_invalid, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%').'</div>';
+ echo '<div class="floatRight anl_detail_percent anl_w30 anl_ac">'.$vAnswer['cnt'].'</div>';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<th class="anl_ac anl_br'.$cssBck.'">&nbsp;</th>';
+ echo '<th class="anl_ac anl_br'.$cssBck.'">&nbsp;</th>';
+ }
+ echo '<td class="anl_ac anl_br'.$cssBck.'">';
+ echo (int)$vAnswer['cnt'];
+ echo '</td>';
+ echo '<td class="anl_ar anl_br'.$cssBck.'">';
+ echo self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br anl_detail_percent anl_ita'.$cssBck.'">';
+ echo '&nbsp;';
+ echo '</td>';
+ }
+ echo '<td class="'.$cssBck.'" >';
+ echo '&nbsp;';
+ echo '</td>';
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,$_options = array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ //$cssBck = ' '.self::$cssColors['text_' . ($counter & 1)];
+ $cssBck = ' '.self::$cssColors['text_1'];
+ $_percent = (self::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*self::$_FREQUENCYS[$_sequence]['invalidCnt'] / self::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $_brez_MV = ((int)self::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+ $_hide_minus = ((int)self::$missingProfileData['display_mv_type'] === 1 || (int)self::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="click_missing_1_'.$_sequence.$_sufix.'" class="anl_dash_red_bb'.($_brez_MV ?' displayNone' : '').'">';
+ echo '<td class="anl_bl anl_al anl_br gray anl_ti_20'.$cssBck.'">';
+ echo $lang['srv_anl_missing'];
+ echo '</td>';
+ echo '<td class="anl_br anl_ita red'.$cssBck.'" >';
+ echo $lang['srv_analiza_manjkajocevrednosti'];
+ // podrobno za missinge
+ echo '<span id="single_missing_0'.$_sequence.$_sufix.'" class="printHide anl_ita anl_detail_percent'.($_hide_minus ? '' : ' displayNone').'">&nbsp;&nbsp;';
+ echo '<a href="#single_missing_'.$_sequence.$_sufix.'" onclick="show_single_missing(\''.$_sequence.$_sufix.'\', 0);return false;" > ' ;
+ //echo $lang['srv_analiza_missingSpremenljivke'] ;
+ echo ' <span class="faicon plus_orange icon-orange_hover_red folder_plusminus"></span> </a>';
+ echo '</span>';
+ echo '<span id="single_missing_1'.$_sequence.$_sufix.'" class="printHide anl_ita anl_detail_percent'.($_hide_minus ? ' displayNone' : '').'">&nbsp;&nbsp;';
+ echo '<a href="#single_missing_'.$_sequence.$_sufix.'" onclick="show_single_missing(\''.$_sequence.$_sufix.'\', 1);return false;" > ' ;
+ // echo $lang['srv_analiza_missingSpremenljivke'] ;
+ echo ' <span class="faicon minus_orange icon-orange_hover_red folder_plusminus"></span> </a>';
+ echo '</span>';
+
+ echo '<div id="single_missing_suma_'.$_sequence.$_sufix.'" class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div>';
+ echo '<div id="single_missing_suma_freq_'.$_sequence.$_sufix.'" class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone">'.self::$_FREQUENCYS[$_sequence]['invalidCnt'].'</div>';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<th class="anl_ac anl_br anl_ita red'.$cssBck.'">&nbsp;</th>';
+ echo '<th class="anl_ac anl_br anl_ita red'.$cssBck.'">&nbsp;</th>';
+ }
+
+ echo '<td class="anl_ac anl_br anl_detail_cnt anl_ita red'.$cssBck.'">';
+ $answer['cnt'] = self::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ? self::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+ echo (int)$answer['cnt'];
+ echo '</td>';
+ echo '<td class="anl_ar anl_br anl_ita red'.$cssBck.' anl_pr10">';
+ echo self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br anl_ita red'.$cssBck.' anl_pr10">';
+ echo '<span id="single_missing_percent_'.$_sequence.$_sufix.'" class="'.($detail ? 'displayNone' : '' ).'">&nbsp;</span>';
+ echo '</td>';
+ }
+ echo '<td class="anl_ar anl_ita red'.$cssBck.' anl_pr10">&nbsp;</td>';
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaVertical($counter,$_sequence,$spid, $_options = array()) {
+ global $lang;
+ # opcije
+
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ // $cssBck = ' '.self::$cssColors['0_' .($counter & 1)];
+ $cssBck = ' anl_bck_text_0';
+ $_brez_MV = ((int)self::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="click_missing_suma_'.$_sequence.$_sufix.'" class="'.($_brez_MV ? 'displayNone' : '').'">';
+ //echo '<td class="anl_bl anl_ac anl_dash_bt anl_br anl_bb gray">&nbsp;</td>'; // $lang['srv_anl_appropriate']
+ //echo '<td class="anl_al anl_dash_bt anl_br anl_bb red anl_ita'.$cssBck.'">'.$lang['srv_anl_suma2'].'</td>';
+ echo '<td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita'.$cssBck.'">'.$lang['srv_anl_suma2'].'</td>';
+ echo '<td class="anl_dash_bt anl_br anl_bb'.$cssBck.'">&nbsp;</td>';
+
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita'.$cssBck.'" >&nbsp;</td>';
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita'.$cssBck.'" >&nbsp;</td>';
+ }
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.'" >' . (self::$_FREQUENCYS[$_sequence]['allCnt'] ? self::$_FREQUENCYS[$_sequence]['allCnt'] : 0) . '</td>';
+ echo '<td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.' anl_pr10">' . self::formatNumber('100', SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%') . '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.' anl_pr10">&nbsp;</td>';
+ }
+ echo '<td class="anl_ac anl_dash_bt anl_bb anl_ita red'.$cssBck.'">&nbsp;</td>';
+ echo '</tr>';
+
+ }
+
+
+
+ static function outputSumaValidAnswerHeatmap($counter,$_sequence,$spid,$_options=array(), $validHeatmapRegion) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ $cssBck = ' '.self::$cssColors['text_1'];
+
+ $_brez_MV = ((int)self::$missingProfileData['display_mv_type'] === 0 ) ? TRUE : FALSE;
+ $_hide_minus = ((int)self::$missingProfileData['display_mv_type'] === 2 ) ? TRUE : FALSE;
+ $value =((int)self::$missingProfileData['display_mv_type'] === 0 ) ? 0 : 1;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="anl_click_missing_tr_'.$_sequence.$_sufix.'" class="'.($_brez_MV ? 'anl_bb' : 'anl_dash_red_bb').'">';
+ echo '<td class="anl_bl anl_br anl_al gray anl_ti_20'.$cssBck.'">'.$lang['srv_anl_valid'];
+
+ echo '<span id="click_missing_'.$_sequence.$_sufix.'" class="anl_click_missing gray'.($_brez_MV ? '' : ' displayNone').'" value="'.$value.'">&nbsp;&nbsp;<span class="faicon plus_orange icon-orange_hover_red folder_plusminus"></span></span>';
+ echo '<span id="single_missing_title_'.$_sequence.$_sufix.'" class="anl_click_missing_hide gray'.($_brez_MV || $_hide_minus? ' displayNone' : '').'">&nbsp;&nbsp;<span class="faicon minus_orange icon-orange_hover_red folder_plusminus"></span></span>';
+ echo '</td>';
+ echo '<td class="anl_br anl_al anl_ita red'.$cssBck.'" >'.$lang['srv_anl_suma1'].'</td>';
+
+
+
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<th class="anl_ita red anl_br anl_ac'.$cssBck.'">&nbsp;</th>';
+ echo '<th class="anl_ita red anl_br anl_ac'.$cssBck.'">&nbsp;</th>';
+ }
+
+ //Veljavni - Skupaj
+ echo '<td class="anl_ita red anl_br anl_ac'.$cssBck.'" >';
+ echo $validHeatmapRegion;
+ //echo self::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ? self::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ echo '</td>';
+
+
+/* $_percent = self::$_FREQUENCYS[$_sequence]['allCnt'] > 0
+ ? 100 * self::$_FREQUENCYS[$_sequence]['validCnt'] / self::$_FREQUENCYS[$_sequence]['allCnt']
+ : 0;
+ echo '<td class="anl_ita red anl_br anl_ar'.$cssBck.' anl_pr10">' . self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%') . '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent'] == true) {
+ echo '<td class="anl_ita red anl_br anl_ar'.$cssBck.' anl_pr10">' . self::formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%') . '</td>';
+ }
+ echo '<td class="anl_ita red anl_ac'.$cssBck.'">&nbsp;</td>'; */
+ echo '</tr>';
+ // $counter++;
+ return $counter;
+
+ }
+
+ static function outputInvalidAnswerHeatmap($counter,$vkey,$vAnswer,$_sequence,$spid,$_options=array(), $manjkajoci) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ //$cssBck = ' '.self::$cssColors['text_' . ($counter & 1)];
+ $cssBck = ' '.self::$cssColors['0_' . ($counter & 1)];
+
+ $_percent = (self::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / self::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (self::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / self::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ $_Z_MV = ((int)self::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ echo '<tr name="missing_detail_'.$_sequence.$_sufix.'"'.($_Z_MV ? '': ' class="displayNone"').'>';
+ echo '<td class="anl_bl anl_br anl_ac gray" style="width:10px">&nbsp;</td>';
+ echo '<td class="anl_br'.$cssBck.'">';
+ echo '<div class="floatLeft"><div class="anl_tin2">'.'<span class="anl_user_text">' . $vkey . '</span>' . ' (' . $vAnswer['text'].')'.'</div></div>';
+ echo '<div class="floatRight anl_detail_percent anl_w50 anl_ac anl_dash_bl">'.self::formatNumber($_invalid, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%').'</div>';
+ echo '<div class="floatRight anl_detail_percent anl_w30 anl_ac">'.$vAnswer['cnt'].'</div>';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<th class="anl_ac anl_br'.$cssBck.'">&nbsp;</th>';
+ echo '<th class="anl_ac anl_br'.$cssBck.'">&nbsp;</th>';
+ }
+ echo '<td class="anl_ac anl_br'.$cssBck.'">';
+ echo (int)$vAnswer['cnt'];
+ echo '</td>';
+ echo '<td class="anl_ar anl_br'.$cssBck.'">';
+ echo self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br anl_detail_percent anl_ita'.$cssBck.'">';
+ echo '&nbsp;';
+ echo '</td>';
+ }
+ echo '<td class="'.$cssBck.'" >';
+ echo '&nbsp;';
+ echo '</td>';
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaInvalidAnswerHeatmap($counter,$_sequence,$spid,$_options = array(), $manjkajoci) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ //$cssBck = ' '.self::$cssColors['text_' . ($counter & 1)];
+ $cssBck = ' '.self::$cssColors['text_1'];
+ $_percent = (self::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*self::$_FREQUENCYS[$_sequence]['invalidCnt'] / self::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $_brez_MV = ((int)self::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+ $_hide_minus = ((int)self::$missingProfileData['display_mv_type'] === 1 || (int)self::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="click_missing_1_'.$_sequence.$_sufix.'" class="anl_dash_red_bb'.($_brez_MV ?' displayNone' : '').'">';
+
+ echo '<td class="anl_bl anl_al anl_br gray anl_ti_20'.$cssBck.'">';
+ echo $lang['srv_anl_missing'];
+ echo '</td>';
+
+ echo '<td class="anl_br anl_ita red'.$cssBck.'" >';
+ echo $lang['srv_analiza_manjkajocevrednosti'];
+
+ // podrobno za missinge
+ echo '<span id="single_missing_0'.$_sequence.$_sufix.'" class="printHide anl_ita anl_detail_percent'.($_hide_minus ? '' : ' displayNone').'">&nbsp;&nbsp;';
+ echo '<a href="#single_missing_'.$_sequence.$_sufix.'" onclick="show_single_missing(\''.$_sequence.$_sufix.'\', 0);return false;" > ' ;
+ //echo $lang['srv_analiza_missingSpremenljivke'] ;
+ echo ' <span class="faicon plus_orange icon-orange_hover_red folder_plusminus"></span> </a>';
+ echo '</span>';
+ echo '<span id="single_missing_1'.$_sequence.$_sufix.'" class="printHide anl_ita anl_detail_percent'.($_hide_minus ? ' displayNone' : '').'">&nbsp;&nbsp;';
+ echo '<a href="#single_missing_'.$_sequence.$_sufix.'" onclick="show_single_missing(\''.$_sequence.$_sufix.'\', 1);return false;" > ' ;
+ // echo $lang['srv_analiza_missingSpremenljivke'] ;
+ echo ' <span class="faicon minus_orange icon-orange_hover_red folder_plusminus"></span> </a>';
+ echo '</span>';
+
+ echo '<div id="single_missing_suma_'.$_sequence.$_sufix.'" class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent displayNone">100.0%</div>';
+ //echo '<div id="single_missing_suma_freq_'.$_sequence.$_sufix.'" class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone">'.self::$_FREQUENCYS[$_sequence]['invalidCnt'].'</div>';
+ echo '<div id="single_missing_suma_freq_'.$_sequence.$_sufix.'" class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent displayNone">'.$manjkajoci.'</div>';
+ echo '</td>';
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<th class="anl_ac anl_br anl_ita red'.$cssBck.'">&nbsp;</th>';
+ echo '<th class="anl_ac anl_br anl_ita red'.$cssBck.'">&nbsp;</th>';
+ }
+
+ //Mankajoci - Skupaj
+ echo '<td class="anl_ac anl_br anl_detail_cnt anl_ita red'.$cssBck.'">';
+ echo $manjkajoci;
+ //$answer['cnt'] = self::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ? self::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+ //echo (int)$answer['cnt'];
+ echo '</td>';
+
+ //stolpec "Veljavni kliki"
+/* echo '<td class="anl_ar anl_br anl_ita red'.$cssBck.' anl_pr10">';
+ echo self::formatNumber($_percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ */
+
+/* if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_br anl_ita red'.$cssBck.' anl_pr10">';
+ echo '<span id="single_missing_percent_'.$_sequence.$_sufix.'" class="'.($detail ? 'displayNone' : '' ).'">&nbsp;</span>';
+ echo '</td>';
+ } */
+
+ echo '<td class="anl_ar anl_ita red'.$cssBck.' anl_pr10">&nbsp;</td>';
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaHeatmap($counter,$_sequence,$spid, $_options = array(), $ustrezniHeatmapRegion) {
+ global $lang;
+ # opcije
+
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ // $cssBck = ' '.self::$cssColors['0_' .($counter & 1)];
+ $cssBck = ' anl_bck_text_0';
+ $_brez_MV = ((int)self::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+
+ $_sufix = (self::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(self::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.self::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="click_missing_suma_'.$_sequence.$_sufix.'" class="'.($_brez_MV ? 'displayNone' : '').'">';
+ //echo '<td class="anl_bl anl_ac anl_dash_bt anl_br anl_bb gray">&nbsp;</td>'; // $lang['srv_anl_appropriate']
+ //echo '<td class="anl_al anl_dash_bt anl_br anl_bb red anl_ita'.$cssBck.'">'.$lang['srv_anl_suma2'].'</td>';
+ echo '<td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita'.$cssBck.'">'.$lang['srv_anl_suma2'].'</td>';
+ echo '<td class="anl_dash_bt anl_br anl_bb'.$cssBck.'">&nbsp;</td>';
+
+ if (self::$_SHOW_LEGENDA && $options['isOtherAnswer'] == false && $options['inline_legenda'] == true) {
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita'.$cssBck.'" >&nbsp;</td>';
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita'.$cssBck.'" >&nbsp;</td>';
+ }
+
+ //SKUPAJ
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.'" >' .$ustrezniHeatmapRegion. '</td>';
+
+ //echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.'" >' . (self::$_FREQUENCYS[$_sequence]['allCnt'] ? self::$_FREQUENCYS[$_sequence]['allCnt'] : 0) . '</td>';
+
+ //echo '<td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.' anl_pr10">' . self::formatNumber('100', SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%') . '</td>';
+ /*if (self::$_HEADERS[$spid]['show_valid_percent']) {
+ echo '<td class="anl_ar anl_dash_bt anl_br anl_bb anl_ita red'.$cssBck.' anl_pr10">&nbsp;</td>';
+ } */
+ //echo '<td class="anl_ac anl_dash_bt anl_bb anl_ita red'.$cssBck.'">&nbsp;</td>';
+ echo '</tr>';
+
+ }
+
+ /** izpišemo tabelo z tekstovnimi odgovori drugo
+ *
+ * @param $skey
+ * @param $oAnswers
+ * @param $spid
+ */
+ static function outputOtherAnswers($oAnswers) {
+ global $lang;
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ $spid = $oAnswers['spid'];
+ $_variable = self::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+ $_frekvence = self::$_FREQUENCYS[$_variable['sequence']];
+
+ echo '<table class="anl_tbl anl_bt anl_bl anl_br tbl_clps">';
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_desc_1 anl_w110 anl_variabla_sub" >'. $_variable['variable'] . '</td>';
+ echo '<td class="anl_bl anl_br anl_bb anl_al anl_bck_desc_1" colspan="'.(self::$_SHOW_LEGENDA && false ? 7 : 5).'">';
+ echo '<span class="anl_variabla_label">'.self::$_HEADERS[$oAnswers['spid']]['variable'].' ('.$_variable['naslov'].' )</span>';
+ if (self::$_SHOW_LEGENDA) {
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+ echo '<div class="floatRight"><span>&nbsp;('.$_tip.')</span>'.'</div>';
+ }
+ if (self::$_SHOW_LEGENDA) {
+ echo self::getSpremenljivkaLegenda(0,'tip');
+ }
+
+ echo '</td>';
+ echo '</tr>';
+ $css_txt = 'anl_variabla_line';
+ echo '<tr>';
+ echo '<td class="anl_bb anl_bl anl_br anl_ac anl_bck anl_w110"><span class="anl_variabla">';
+ //self::showIcons($spid,$spremenljivka,$_from);
+ echo '</span></td>';
+
+ echo '<td class="anl_bb anl_br anl_ac anl_bck '.$css_txt.'">'. $lang['srv_analiza_frekvence_titleAnswers'] .'</td>';
+ if (self::$_SHOW_LEGENDA && false){
+ echo '<td class="anl_bb anl_br anl_ac anl_bck anl_w70 '.$css_txt.'">'.$lang['srv_analiza_opisne_variable_expression'].'</td>';
+ echo '<td class="anl_bb anl_br anl_ac anl_bck anl_w70 '.$css_txt.'">'.$lang['srv_analiza_opisne_variable_skala'].'</td>';
+ }
+ echo '<td class="anl_bb anl_br anl_ac anl_bck anl_w70 '.$css_txt.'">'. $lang['srv_analiza_frekvence_titleFrekvenca'] .'</td>';
+ echo '<td class="anl_bb anl_br anl_ac anl_bck anl_w70 '.$css_txt.'">'. $lang['srv_analiza_frekvence_titleOdstotek'] .'</td>';
+ echo '<td class="anl_bb anl_br anl_ac anl_bck anl_w70 '.$css_txt.'">'. $lang['srv_analiza_frekvence_titleVeljavni'] .'</td>';
+ echo '<td class="anl_bb anl_br anl_ac anl_bck anl_w70 '.$css_txt.'">'. $lang['srv_analiza_frekvence_titleKumulativa'] .'</td>';
+ echo '</tr>';
+ // konec naslovne vrstice
+ if (self::$_SHOW_LEGENDA && false){
+ $cssBck = 'anl_bck ';
+ echo '<tr>';
+ echo '<td class="anl_tin anl_bl anl_bb anl_br anl_al '.$cssBck.'link_no_decoration">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br anl_al '.$cssBck.'">'.'</td>';
+
+ $_tip = $lang['srv_analiza_vrsta_bese'];
+ $_oblika = $lang['srv_analiza_oblika_nomi'];
+
+ echo '<td class="anl_bb anl_br '.$cssBck.'anl_ac anl_w90">'.$_tip.'</td>';
+ echo '<td class="anl_bb anl_br '.$cssBck.'anl_ac anl_w90 ">'.$_oblika.'</td>';
+
+ echo '<td class="anl_bb anl_br '.$cssBck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br '.$cssBck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb anl_br '.$cssBck.' anl_w70">&nbsp;</td>';
+ echo '<td class="anl_bb '.$cssBck.' anl_w70">&nbsp;</td>';
+ echo '</tr>';
+ }
+ $counter = 1;
+ $_kumulativa = 0;
+ if ( is_countable(self::$_FREQUENCYS[$_sequence]['valid']) && count(self::$_FREQUENCYS[$_sequence]['valid']) > 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ if ($vAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ if ($counter < $num_show_records) {
+ $counter = self::outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_kumulativa,array('isOtherAnswer'=>true,'num_show_records' => $num_show_records));
+ }
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaValidAnswerVertical($counter,$_sequence,$spid,array('isOtherAnswer'=>true));
+ }
+ if (count(self::$_FREQUENCYS[$_sequence]['invalid'])> 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputInvalidAnswerVertical($counter,$ikey,$iAnswer,$_sequence,$spid,array('isOtherAnswer'=>true));
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,array('isOtherAnswer'=>true));
+ }
+ #izpišemo še skupno sumo
+ $counter = self::outputSumaVertical($counter,$_sequence,$spid,array('isOtherAnswer'=>true));
+
+ echo '</table>';
+ }
+
+ static public function showVariable($spid,$variable,$_options= array()) {
+ global $lang;
+ # globalne nastavitve funkcije
+ $options = array('prev'=>true,'align'=>'center');
+ #ponastavimo uporabniške funkcije
+ if (count($_options) > 0) {
+ foreach ($_options as $okey => $option) {
+ $options[$okey] = $option;
+ }
+ }
+
+ $sccFloat = ($options['align'] == 'center')
+ ? ''
+ : ( $options['align'] == 'left'
+ ? ' floatLeft'
+ : ' floatRight');
+
+ echo '<span class="spaceLeft anl_variabla'.$sccFloat.'">';
+ if (self::$isArchive == false && self::$printPreview == false){
+ echo '<a href="#" onclick="showspremenljivkaSingleVarPopup(\''.$spid.'\'); return false;">';
+ #echo '<a href="/" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="(\'' . $spid . '\'); return false;">'
+ echo $variable;
+ echo '</a>';
+ }
+ else{
+ echo $variable;
+ }
+ echo '</span>';
+ }
+
+
+ static public function showIcons($spid, $spremenljivka, $_from = 'freq', $additional=array()) {
+ global $lang;
+
+ $sccFloat = 'taCenter ';
+ #kateri skin
+ $skin = 0;
+ $options = array('sums'=>true,'sums*'=>true,'desc'=>true,'freq'=>true,'sums_spec'=>false);
+ $from_navedbe = (isset($additional['navedbe']) && $additional['navedbe'] == true) ? true : false;
+ $showReport = (isset($additional['noReport']) && $additional['noReport'] == true) ? false: true;
+ $showChart = (isset($additional['showChart']) && $additional['showChart'] == false) ? false: true;
+ $printIcon = (isset($additional['printIcon']) && $additional['printIcon'] == true) ? true: false;
+
+ if ($_from == 'para') {
+ $showReport = false;
+ }
+
+ switch ($_from) {
+ case 'freq':
+ case 'para':
+ case 'charts':
+ switch ($spremenljivka['tip']) {
+ case 1: # radio - prikjaže navpično
+ if ($spremenljivka['show_valid_percent'] == true && $spremenljivka['skala'] != 1) {
+ # če za ordinalno prikazujemo povprečje in st. oddklon
+ $options['sums'] = true;
+ $options['sums*'] = true;
+ } else {
+ # za nominalno ne prikazujemo povprečje in st. oddklon, zato je F == F*
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ }
+ break;
+ case 2: #checkbox če je dihotomna:
+ break;
+ case 3: # dropdown - prikjaže navpično
+ break;
+ case 6: # multigrid
+ $options['sums*'] = false;
+ if ( $spremenljivka['enota'] == 3 ) {
+ $options['sums_spec'] = true;
+ }
+ break;
+ case 7: # variabla tipa »število«
+ $options['sums*'] = false;
+ break;
+ case 8: # datum
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ break;
+ case 16: #multicheckbox če je dihotomna:
+ break;
+ case 17: #razvrščanje če je ordinalna
+ $options['sums'] = false;
+ break;
+ case 18: # vsota
+ $options['sums*'] = false;
+ break;
+ case 19: # multitext
+ $options['sums*'] = false;
+ break;
+ case 20: # multi number
+
+ break;
+ case 4: # text
+ case 21: # besedilo*
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ break;
+ case 26: # lokacija
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ break;
+ case 27: # heatmap
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ break;
+ case 22: # kalkulacija
+ case 25: # kvota
+ $options['sums*'] = false;
+ break; # kalkulacija
+ }
+ $export = ($_from == 'charts') ? 'charts' : 'frequency';
+ break;
+ case 'desc':
+ switch ($spremenljivka['tip']) {
+ case 1: # radio - prikjaže navpično
+ if ($spremenljivka['skala'] == 1) {
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ }
+ break;
+ case 2: #checkbox če je dihotomna:
+ break;
+ case 3: # dropdown - prikjaže navpično
+ break;
+ case 6: # multigrid
+ $options['sums*'] = false;
+ if ( $spremenljivka['enota'] == 3 ) {
+ $options['sums_spec'] = true;
+ }
+ break;
+ case 7: # variabla tipa »število«
+ $options['sums*'] = false;
+ break;
+ case 8: # datum
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ break;
+ case 16: #multicheckbox če je dihotomna:
+ break;
+ case 17: #razvrščanje če je ordinalna
+ $options['sums'] = false;
+ break;
+ case 18: # vsota
+ $options['sums*'] = false;
+ break;
+ case 19: # multitext
+ $options['sums*'] = false;
+ break;
+ case 20: # multi number
+ break;
+ case 4: # text
+ case 21: # besedilo*
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ break;
+ case 26: # Lokacija
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ break;
+ case 27: # heatmap
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ break;
+ case 22: # kalkulacija
+ case 25: # kvota
+ $options['sums*'] = false;
+ break; # kalkulacija
+ }
+ $export = 'statistics';
+ break;
+ case 'sums':
+ switch ($spremenljivka['tip']) {
+ case 1: # radio - prikjaže navpično
+ if ($spremenljivka['skala'] == 1) {
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ $_from = 'freq';
+ } else {
+ $_from = 'sums*';
+ }
+ break;
+ case 2: #checkbox če je dihotomna
+ $_from = 'sums*';
+ break;
+ case 3: # dropdown - prikjaže navpično
+ break;
+ case 6: # multigrid
+ $options['sums*'] = false;
+ if ( $spremenljivka['enota'] == 3 ) {
+ $options['sums_spec'] = true;
+ $_from = 'sums*';
+ }
+ break;
+ case 7: # variabla tipa »število«
+ $options['sums*'] = false;
+ break;
+ case 8: # datum
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ $_from = 'freq';
+ break;
+
+ case 16: #multicheckbox če je dihotomna
+ break;
+ case 17: #razvrščanje če je ordinalna
+ $options['sums'] = false;
+ $_from = 'sums*';
+ break;
+ case 18: # vsota
+ $options['sums*'] = false;
+ break;
+ case 19: # multitext
+ $options['sums*'] = false;
+ break;
+ case 20: # multi number
+ break;
+ case 21: # besedilo*
+ $_from = 'sums';
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ $options['sums'] = false;
+ $_from = 'freq';
+ }
+
+ $options['sums*'] = false;
+ break;
+ case 26: # lokacija
+ $_from = 'sums';
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ $_from = 'freq';
+ }
+
+ $options['sums*'] = false;
+ break;
+ case 27: # heatmap
+ $_from = 'sums';
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ $_from = 'freq';
+ }
+
+ $options['sums*'] = false;
+ break;
+ case 4: # text
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ $_from = 'freq';
+ break;
+ case 22: # kalkulacija
+ case 25: # kvota
+ $options['sums*'] = false;
+ break; # kalkulacija
+ }
+ $export = 'sums';
+ break;
+ case 'sums*':
+ switch ($spremenljivka['tip']) {
+ case 1: # radio - prikjaže navpično
+ if ($spremenljivka['skala'] == 1) {
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ $_from = 'freq';
+ } else {
+ $_from = 'sums';
+ }
+ break;
+ case 2: #checkbox če je dihotomna:
+ $_from = 'sums';
+ break;
+ case 3: # dropdown - prikjaže navpično
+ break;
+ case 6: # multigrid
+ $options['sums*'] = false;
+ if ( $spremenljivka['enota'] == 3 ) {
+ $options['sums_spec'] = true;
+ $_from = 'sums';
+ }
+ break;
+ case 7: # variabla tipa »število«
+ $options['sums*'] = false;
+ $_from = 'sums';
+ break;
+ case 8: # datum
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ break;
+
+ case 16: #multicheckbox če je dihotomna:
+ break;
+ case 17: #razvrščanje če je ordinalna
+ $options['sums'] = false;
+ break;
+ case 18: # vsota
+ $options['sums*'] = false;
+ $_from = 'sums';
+ break;
+ case 19: # multitext
+ $options['sums*'] = false;
+ break;
+ case 20: # multi number
+ break;
+ case 4: # text
+ $options['sums'] = false;
+ $options['sums*'] = false;
+ $_from = 'freq';
+ break;
+ case 21: # besedilo*
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ $_from = 'freq';
+ break;
+ case 26: # lokacija
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ $_from = 'freq';
+ break;
+ case 27: # heatmap
+ if ($spremenljivka['cnt_all'] == 1) {
+ $options['sums'] = false;
+ }
+ $options['sums*'] = false;
+ $_from = 'freq';
+ break;
+ case 22: # kalkulacija
+ case 25: # kvota
+ $options['sums*'] = false;
+ $_from = 'sums';
+ break; # kalkulacija
+ }
+ $export = 'sums';
+ break;
+ case 'none':
+ break;
+ }
+
+ // Javna povezava nima teh ikon
+ if ($printIcon == false && self::$printPreview == false) {
+
+ echo '<span class="'.$sccFloat.'printHide iconHide">';
+
+ if ($options['sums'] == true) {
+ if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3 ) {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_SUMMARY_NEW.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ } else {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_SUMMARY.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ }
+
+ echo '<span class="faicon an_sigma large '.($_from == 'sums' ? '' : 'icon-blue_soft_link').'" title="' . $lang['srv_analysis_icon_sumary'] . '"></span> ';
+ echo '</a>';
+ }
+
+ if ($options['sums_spec'] == true) {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_SUMMARY_NEW.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ echo '<span class="faicon an_sigmax large '.($_from == 'sums*' ? '' : 'icon-blue_soft_link').'" title="' . $lang['srv_analysis_icon_frequency*'] . '"></span> ';
+ echo '</a>';
+ }
+
+ if ($options['sums*'] == true) {
+ if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3) {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_SUMMARY.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ }else {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_SUMMARY_NEW.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ }
+ echo '<span class="faicon an_freqx large '.($_from == 'sums*' ? '' : 'icon-blue_soft_link').'" title="' . $lang['srv_analysis_icon_frequency*'] . '"></span> ';
+ echo '</a>';
+ }
+ if ($options['desc'] == true) {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_DESCRIPTOR.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ echo '<span class="faicon an_stat large '.($_from == 'desc' ? '' : 'icon-blue_soft_link').'" title="' . $lang['srv_analysis_icon_descriptor'] . '"></span> ';
+ echo '</a>';
+ }
+ if ($options['freq'] == true) {
+ echo '<a href="#" onclick="showAnalizaSingleVarPopup(\''.$spid.'\',\''.M_ANALYSIS_FREQUENCY.'\',\''.$from_navedbe.'\',\''.self::$_CURRENT_LOOP['cnt'].'\'); return false;">';
+ echo '<span class="faicon an_freq large '.($_from == 'freq' ? '' : 'icon-blue_soft_link').'" title="' . $lang['srv_analysis_icon_frequency'] . '"></span> ';
+ echo '</a>';
+ }
+
+ // Ikona za prikaz grafa
+ if($showChart == true && in_array($spremenljivka['tip'],array(1,2,3,6,7,8,16,17,18,20,22)) && $_from != 'charts'){
+ echo '<a href="#" onclick="showAnalizaSingleChartPopup(\''.$spid.'\',\''.M_ANALYSIS_CHARTS.'\'); return false;">';
+ echo '<span class="faicon an_chart_bar icon-blue_soft_link" title="' . $lang['6'] . '"></span> ';
+ echo '</a>';
+ }
+
+ // Ikona za vkljucitev v porocilo
+ switch ($_from) {
+ case 'sums':
+ case 'sums*':
+ $type=1;
+ break;
+ case 'freq':
+ $type=2;
+ break;
+ case 'desc':
+ $type=3;
+ break;
+ case 'charts':
+ $type=4;
+ break;
+ }
+ if ($showReport == true) {
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type, $sub_type=0, $spid);
+ }
+
+
+ echo '</span>';
+ } else {
+
+ }
+ }
+
+
+
+ /** polovi opisne za vse spremenljivke
+ *
+ */
+ static public function getDescriptives() {
+ global $site_path;
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ #array za imeni tmp fajlov, ki jih nato izbrišemo
+ $tmp_files = array( 'filtred'=>$folder . 'tmp_export_'.self::$sid.'_filtred'.TMP_EXT,
+ 'filtred1'=>$folder . 'tmp_export_'.self::$sid.'_filtred1'.TMP_EXT,
+ 'frequency'=>$folder . 'tmp_export_'.self::$sid.'_freqency'.'.php',
+ 'frequency1'=>$folder . 'tmp_export_'.self::$sid.'_freqency1'.'.php');
+
+ # naredimo datoteko z frekvencami
+ # za windows sisteme in za linux sisteme
+
+ # dodamo filter za loop-e
+ if (isset(self::$_CURRENT_LOOP['filter']) && self::$_CURRENT_LOOP['filter'] != '') {
+ $status_filter = self::$_CURRENT_STATUS_FILTER.' && '.self::$_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = self::$_CURRENT_STATUS_FILTER;
+ }
+
+ # s katero sekvenco se začnejo podatki, da ne delamo po nepotrebnem za ostala polja
+ $start_sequence = (isset(self::$_HEADERS['_settings']['dataSequence']) && (int)self::$_HEADERS['_settings']['dataSequence'] > 0 )
+ ? (int)self::$_HEADERS['_settings']['dataSequence']
+ : 8;
+
+ if (IS_WINDOWS) {
+ # sfiltriramo statuse
+ # $cmdLn1 = 'awk -F"|" "BEGIN {{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '.$status_filter.' {for (i=4;i<=NF;i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}" '.self::$dataFileName. ' > '.$tmp_files['filtred'];
+ # odstranimo '
+ # $cmdLn2 = 'sed "s*\x27*`*g" '.$tmp_files['filtred'].' > '.$tmp_files['filtred1'];
+ # v loopu naredimo frekvence za vsa polja razen za prva 3 ki so tako unikatna
+ # $cmdLn3 = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} { print \"$frequency[\",$1,\"]\",\"[\x27\",$2,\"\x27]\",\"=\x27\",$3,\"\x27;\"}" '.$tmp_files['filtred1'].' >> '.$tmp_files['frequency'];
+
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '.$status_filter.' {for (i='.$start_sequence.';i<=NF;i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}" '.self::$dataFileName;
+ $command .= ' | sed "s*\x27*`*g"';
+ $command .= ' | awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} { print \"$frequency[\",$1,\"]\",\"[\x27\",$2,\"\x27]\",\"=\x27\",$3,\"\x27;\"}" >> '.$tmp_files['frequency'];
+ } else {
+ #$cmdLn1 = 'awk -F"|" \'BEGIN {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} '.$status_filter.' {for (i=4;i<=NF;i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}\' '.self::$dataFileName. ' > '.$tmp_files['filtred'];
+ #$cmdLn2 = 'sed \'s*\x27*`*g\' '.$tmp_files['filtred'].' > '.$tmp_files['filtred1'];
+ #$cmdLn3 = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} { print "$frequency[",$1,"]","[\x27",$2,"\x27]","=\x27",$3,"\x27;"}\' '.$tmp_files['filtred1'].' >> '.$tmp_files['frequency'];
+
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" \'BEGIN {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} '.$status_filter.' {for (i='.$start_sequence.';i<=NF;i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}\' '.self::$dataFileName;
+ $command .= ' | sed \'s*\x27*`*g\'';
+ $command .= ' | awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} { print "$frequency[",$1,"]","[\x27",$2,"\x27]","=\x27",$3,"\x27;"}\' >> '.$tmp_files['frequency'];
+ }
+
+ #$out1 = shell_exec($cmdLn1);
+ #$out2 = shell_exec($cmdLn2);
+ $file_handler = fopen($tmp_files['frequency'],"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+ #$out3 = shell_exec($cmdLn3);
+
+ $out = shell_exec($command);
+
+ $file_handler = fopen($tmp_files['frequency'],"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_files['frequency']);
+
+
+ if (file_exists($tmp_files['frequency'])) {
+ unlink($tmp_files['frequency']);
+ }
+
+ if ($_GET['debug'] == 1) {
+ print_r("<pre>");
+ print_r("cl:".$command);
+ print_r("<br>Out".$out);
+ print_r("</pre>");
+ }
+
+ # inicializiramo
+ self::$_DESCRIPTIVES = array();
+
+ # kateri odgovori so z profilom nastavljeni kot manjkajoči
+ # se dodelijo k missing values in se ne upoštevajo pri povprečju
+ $_invalidAnswers = self :: getInvalidAnswers (MISSING_TYPE_DESCRIPTOR);
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ # izračunamo vse kar rabimo pri opisnih
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ # kadar imamo pri spremenljvki missinge, tudi prikazujemmo veljavne procente najprej damo na false
+ # preverjamo da ni meta variabla
+ $vars_count = count(self::$_FILTRED_VARIABLES);
+ # frekvence delamo samo za izbrane variable
+ if ($spremenljivka['tip'] != 'm'
+ # filter po id spremenljivki
+ && ($vars_count == 0 || ($vars_count > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ) )
+ # filter po tipu (kategorije, besedila, number, drugo)
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES ) )
+ { // if != m
+
+ if (count($spremenljivka['grids'])>0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_freq = $frequency[$_sequence];
+ $min = null;
+ $max = null;
+
+ $_tmp_div = array();
+ self::$_DESCRIPTIVES[$_sequence]['sum_xi_fi'] = null;
+
+ #najprej odstranimo neveljavne, vse kaj ostane je veljavno
+ foreach ($_invalidAnswers AS $ikey =>$iAnswer) {
+ if (isset($_freq[$ikey])) {
+ self::$_DESCRIPTIVES[$_sequence]['invalidCnt'] += $_freq[$ikey];
+ self::$_DESCRIPTIVES[$_sequence]['allCnt'] += $_freq[$ikey];
+
+ unset($_freq[$ikey]);
+
+ }
+ }
+ # poiščemo minimum in maximum in povprečje
+
+ # opcijske odgovore dodamo samo vprašanjem ki niso tipa other in text
+ # zloopamo skozi vse opcije in jih dodamo k veljavnim
+ if ($variable['text'] != true && $variable['other'] != true && count($spremenljivka['options']) > 0) {
+ if (count($_freq) > 0) {
+
+ foreach($_freq AS $fKey => $fCnt) {
+ $flKey = (float)$fKey;
+
+ if (is_numeric($flKey) && trim($flkey) != '' ) {
+
+ self::$_DESCRIPTIVES[$_sequence]['validCnt'] += $fCnt;
+ self::$_DESCRIPTIVES[$_sequence]['allCnt'] += $fCnt;
+
+ $min = $min === null ? $flKey : min($min,$flKey) ;
+ $max = $max === null ? $flKey : max($max,$flKey) ;
+ self::$_DESCRIPTIVES[$_sequence]['sum_xi_fi'] += $flKey * $fCnt;
+ #vrednosti si shranimo za računanje divergence
+ $_tmp_div[$flKey] = $fCnt;
+ unset($_freq[$fKey]);
+ } else if (is_numeric($fKey) ) {
+ self::$_DESCRIPTIVES[$_sequence]['validCnt'] += $fCnt;
+ self::$_DESCRIPTIVES[$_sequence]['allCnt'] += $fCnt;
+
+ $min = $min === null ? $fKey : min($min,$fKey) ;
+ $max = $max === null ? $fKey : max($max,$fKey) ;
+ self::$_DESCRIPTIVES[$_sequence]['sum_xi_fi'] += $fKey * $fCnt;
+ #vrednosti si shranimo za računanje divergence
+ $_tmp_div[$fKey] = $fCnt;
+ unset($_freq[$fKey]);
+
+ }
+ }
+ }
+ }
+
+ #porihtamo še numerične in datumske spremenljivke
+ if (($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 8 || $spremenljivka['tip'] == 20 || $spremenljivka['tip'] == 18)
+ && ($variable['text'] != true && $variable['other'] != true)) {
+ if (count($_freq) > 0) {
+ foreach ($_freq AS $nkey => $nCnt) {
+ $fnkey = (float)$nkey; # popravimo morebitne .
+
+ if (is_numeric($nkey) && is_numeric($fnkey) && trim($fnkey) != '') {
+ self::$_DESCRIPTIVES[$_sequence]['validCnt'] += $nCnt;
+ self::$_DESCRIPTIVES[$_sequence]['allCnt'] += $nCnt;
+
+ $min = $min != null ? min($min,$fnkey) : $fnkey;
+ $max = $max != null ? max($max,$fnkey) : $fnkey;
+ self::$_DESCRIPTIVES[$_sequence]['sum_xi_fi'] += $fnkey * $nCnt;
+ #vrednosti si shranimo za računanje divergence
+ $_tmp_div[$fnkey] = $nCnt;
+ unset($_freq[$nkey]);
+ }
+ }
+ }
+
+ }
+ # lahko bi še za datum
+
+ # vse kaj ostane so textovni odgovori ali pa opcijski z nenumeričnim ključem
+ if (count($_freq) > 0) {
+ foreach ($_freq AS $tkey => $tCnt) {
+ if (isset($_allMissing_answers[$tkey])) {
+ $text = $_allMissing_answers[$tkey];
+ } else {
+ $text = $tkey;
+ }
+ self::$_DESCRIPTIVES[$_sequence]['valid'][$tkey] = array('text'=>$text,'cnt'=>$tCnt);
+
+ # samo prištejemo veljavne
+ self::$_DESCRIPTIVES[$_sequence]['validCnt'] += $tCnt;
+ self::$_DESCRIPTIVES[$_sequence]['allCnt'] += $tCnt;
+ unset($_freq[$tkey]);
+ }
+ }
+
+ # minimum in maximum
+ self::$_DESCRIPTIVES[$_sequence]['min'] = $min;
+ self::$_DESCRIPTIVES[$_sequence]['max'] = $max;
+ # povprečje
+
+ if (isset(self::$_DESCRIPTIVES[$_sequence]['sum_xi_fi'])) {
+ self::$_DESCRIPTIVES[$_sequence]['avg'] = self::$_DESCRIPTIVES[$_sequence]['validCnt'] > 0 ? self::$_DESCRIPTIVES[$_sequence]['sum_xi_fi'] / self::$_DESCRIPTIVES[$_sequence]['validCnt'] : 0;
+ }
+ #standardna diviacija
+ if (isset (self::$_DESCRIPTIVES[$_sequence]['avg'])) {
+ $N = self::$_DESCRIPTIVES[$_sequence]['validCnt'];
+ $avg = self::$_DESCRIPTIVES[$_sequence]['avg'];
+ $div = 0;
+ $sum_pow_xi_fi_avg = 0;
+ foreach ($_tmp_div as $xi => $fi) {
+ $sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ }
+ self::$_DESCRIPTIVES[$_sequence]['div'] = (($N -1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($N -1)) : 0;
+ }
+ }
+ }
+ }
+ }
+ } // end if tip != m
+ } // end foreach
+ }
+
+ /** polovi frekvence za vse spremenljivke
+ *
+ */
+ static public function getFrequencys($awk_filter = null) {
+ global $site_path;
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ # pobrišemo morebitne stare vrednosti
+ self::$_FREQUENCYS = array();
+
+ #array za imeni tmp fajlov, ki jih nato izbrišemo
+ $tmp_files = array( 'frequency'=>$folder . 'tmp_export_'.self::$sid.'_freqency'.'.php');
+
+
+ # dodamo filter za loop-e
+ if (isset(self::$_CURRENT_LOOP['filter']) && self::$_CURRENT_LOOP['filter'] != '') {
+ $status_filter = self::$_CURRENT_STATUS_FILTER.' && '.self::$_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = self::$_CURRENT_STATUS_FILTER;
+ }
+
+ # dodamo še dodaten awk filter če je nastavljen - (za break)
+ if ($awk_filter != null) {
+ $status_filter = '('.$status_filter.'&&'.$awk_filter.')';
+ }
+
+ # s katero sekvenco se začnejo podatki, da ne delamo po nepotrebnem za ostala polja
+ $start_sequence = (isset(self::$_HEADERS['_settings']['dataSequence']) && (int)self::$_HEADERS['_settings']['dataSequence'] > 0 )
+ ? (int)self::$_HEADERS['_settings']['dataSequence']
+ : 8;
+
+ # s katero sekvenco se končajo podatki da ne delamo po nepotrebnem za ostala polja
+ $end_sequence = $start_sequence;
+ if (!empty(self::$_HEADERS))
+ {
+ foreach (self::$_HEADERS AS $skey => $spremenljivka)
+ {
+ $tip = $spremenljivka['tip'];
+
+ if (is_numeric($tip)) {
+
+ if (count($spremenljivka['grids'] ) > 0) {
+
+ foreach ($spremenljivka['grids'] as $gid => $grid ){
+
+ if (is_countable($grid['variables']) && count($grid['variables']) > 0) {
+
+ foreach ($grid['variables'] as $vid => $variable ){
+ $end_sequence = max($end_sequence, (int)$variable['sequence']);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ # naredimo datoteko z frekvencami
+ # za windows sisteme in za linux sisteme
+ if (IS_WINDOWS ) {
+ # TEST z LINUX načinom
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}" '.self::$dataFileName;
+ $command .= ' | sed "s*\x27*`*g" ';
+ $command .= ' | awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} { print \"$frequency[\",$1,\"]\",\"[\x27\",$2,\"\x27]\",\"=\x27\",$3,\"\x27;\"}" >> '.$tmp_files['frequency'];
+ }
+ else {
+ # združimo v eno vrstico da bo strežnik bol srečen
+ $command = 'awk -F"|" \'BEGIN {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} '.$status_filter.' {for (i='.$start_sequence.';i<='.$end_sequence.';i++) { arr[i,$i]++}} END {{for (n in arr) { print n,arr[n]}}}\' '.self::$dataFileName;
+ $command .= ' | sed \'s*\x27*`*g\' ';
+ $command .= ' | awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} { print "$frequency[",$1,"]","[\x27",$2,"\x27]","=\x27",$3,"\x27;"}\' >> '.$tmp_files['frequency'];
+ }
+
+ $file_handler = fopen($tmp_files['frequency'],"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+
+ $out = shell_exec($command);
+
+ $file_handler = fopen($tmp_files['frequency'],"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_files['frequency']);
+
+
+ # pobrišemo sfiltrirane podatke, ker jih več ne rabimo
+ if (file_exists($tmp_files['frequency'])) {
+ unlink($tmp_files['frequency']);
+ }
+
+
+ # kateri odgovori so z profilom nastavljeni kot manjkajoči
+ # se dodelijo k missing values in se ne upoštevajo pri povprečju
+ # dodano se za break, ker drugace so bila v breaku negativna povprecja. Mozno da to ne bo ok za nekatere primere breaka??
+ if (self::$podstran == M_ANALYSIS_BREAK || self::$podstran == M_ANALYSIS_SUMMARY || self::$podstran == M_ANALYSIS_SUMMARY_NEW || self::$podstran == 'sums' || self::$podstran == 'sums_rtf' || self::$podstran == 'sums_xls') {
+ $_invalidAnswers = self :: getInvalidAnswers (MISSING_TYPE_DESCRIPTOR);
+ } else {
+ $_invalidAnswers = self :: getInvalidAnswers (MISSING_TYPE_FREQUENCY);
+ }
+
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ # izračunamo vse frekvence oziroma vse kar rabimo pri analizah
+ if(!empty(self::$_HEADERS))
+ foreach (self::$_HEADERS AS $spid => $spremenljivka)
+ {
+ # kadar imamo pri spremenljvki missinge, tudi prikazujemmo veljavne procente najprej damo na false
+ self::$_HEADERS[$spid]['show_valid_percent'] = false;
+ # preverjamo da ni meta variabla
+ $vars_count = count(self::$_FILTRED_VARIABLES);
+ # frekvence delamo samo za izbrane variable
+ if ($spremenljivka['tip'] != 'm'
+ # filter po id spremenljivki
+ && ($vars_count == 0 || ($vars_count > 0 && isset(self::$_FILTRED_VARIABLES[$spid]) ) )
+ # filter po tipu (kategorije, besedila, number, drugo)
+ && in_array($spremenljivka['tip'], self::$_FILTRED_TYPES ) ) {
+
+
+ if ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) {
+ self::$_HEADERS[$spid]['show_valid_percent'] = true;
+ }
+ if (count ($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0)
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_freq = $frequency[$_sequence];
+
+ #najprej dodamo neveljavne, vse kaj ostane je veljavno
+ foreach ($_invalidAnswers AS $ikey =>$iAnswer) {
+ if (self::$frequencyAddInvalid) {
+ self::$_FREQUENCYS[$_sequence]['invalid'][$ikey] = $iAnswer;
+ }
+ if (isset($_freq[$ikey])) {
+ if (self::$frequencyAddInvalid) {
+ self::$_FREQUENCYS[$_sequence]['invalid'][$ikey]['cnt'] = $_freq[$ikey];
+ self::$_FREQUENCYS[$_sequence]['invalidCnt'] += $_freq[$ikey];
+ self::$_FREQUENCYS[$_sequence]['allCnt'] += $_freq[$ikey];
+ }
+ unset($_freq[$ikey]);
+
+ # kadar imamo pri spremenljvki missinge, tudi prikazujemmo veljavne procente
+ self::$_HEADERS[$spid]['show_valid_percent'] = true;
+ }
+ }
+ # opcijske odgovore dodamo samo vprašanjem ki niso tipa other in text
+ # zloopamo skozi vse opcije in jih dodamo k veljavnim
+ if ($variable['text'] != true && $variable['other'] != true && is_countable($spremenljivka['options']) && count($spremenljivka['options']) > 0) {
+ foreach ($spremenljivka['options'] AS $okey => $oAnswer) {
+
+ self::$_FREQUENCYS[$_sequence]['valid'][$okey]['text'] = $oAnswer;
+ self::$_FREQUENCYS[$_sequence]['valid'][$okey]['text_graf'] = $spremenljivka['options_graf'][$okey];
+ self::$_FREQUENCYS[$_sequence]['valid'][$okey]['cnt'] = 0;
+
+ if (isset($_freq[$okey])) {
+ self::$_FREQUENCYS[$_sequence]['valid'][$okey]['cnt'] = $_freq[$okey];
+ self::$_FREQUENCYS[$_sequence]['validCnt'] += $_freq[$okey];
+ self::$_FREQUENCYS[$_sequence]['allCnt'] += $_freq[$okey];
+
+ unset($_freq[$okey]);
+ }
+
+ }
+ }
+
+ # vse kaj ostane so textovni ali numerični odgovori
+ if (is_countable($_freq) && count($_freq) > 0) {
+ $_ifreq = array();
+ # nardimo case-insensitive
+ foreach ($_freq AS $tkey => $tCnt) {
+ //if($spremenljivka['tip'] != 26)
+ if($spremenljivka['tip'] != 26 && $spremenljivka['tip'] != 27)
+ $tkey = mb_strtolower($tkey,'UTF-8');
+ $_ifreq[$tkey] += $tCnt;
+ }
+
+ $_average = array();
+
+ if(is_countable($spremenljivka['options']))
+ $i = count($spremenljivka['options']) + 1;
+ else
+ $i = 0;
+
+ foreach ($_ifreq AS $tkey => $tCnt) {
+
+ # preverimo ali je slučanjo odgovor missing vendar je določen kot veljavni odgovor
+ if (isset($_allMissing_answers[$tkey])) {
+ $text = $tkey . ' '.$_allMissing_answers[$tkey];
+ }
+ else {
+ $text = $tkey;
+ }
+
+ self::$_FREQUENCYS[$_sequence]['valid'][$tkey] = array('text'=>$text,'cnt'=>$tCnt,'text_graf'=>$spremenljivka['options_graf'][$i]);
+ self::$_FREQUENCYS[$_sequence]['validCnt'] += $tCnt;
+ self::$_FREQUENCYS[$_sequence]['allCnt'] += $tCnt;
+ //Uros dodal, ker se drugace pri radio ne ve, kaksen je text opcije drugo
+ if($variable['other'])
+ self::$_FREQUENCYS[$_sequence]['valid'][$tkey]['other'] = $variable['naslov'];
+
+ # povprečje
+ if (is_numeric($tkey)) {
+ $_average['product'] = $_average['product'] + ($tkey * $tCnt);
+ $_average['cnt'] = $_average['cnt'] + $tCnt;
+ }
+ unset($_freq[$tkey]);
+
+ $i++;
+ }
+ self::$_FREQUENCYS[$_sequence]['average'] = ($_average['cnt'] > 0) ? $_average['product'] / $_average['cnt'] : $_average['cnt'];
+ }
+ unset($frequency[$_sequence]);
+ }
+ }
+ } // end if tip != m
+ }
+ unset($frequency);
+
+ return self::$_FREQUENCYS;
+ }
+
+ static function frequencyAddInvalid($doAdd = true) {
+ self::$frequencyAddInvalid = $doAdd;
+ }
+ /** polovi dejanske odgovore za spremenljivko
+ * @param $need_user_id - ali se rabi tudi vrniti user_id?
+ */
+ static public function getAnswers($spremenljivka, $limit=10, $need_user_id = false) {
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $result = array();
+ $sequences = array();
+ $sequenc_filter = array();
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ) {
+ $sequences[] = '$'.$variable['sequence'];
+ if (IS_WINDOWS ) {
+ $sequenc_filter[] = '\''.$variable['sequence'].'\'=\x3E\",\"\x27\",$'.$variable['sequence'].',\"\x27';
+ } else {
+ $sequenc_filter[] = '\''.$variable['sequence'].'\'=\x3E","\x27",$'.$variable['sequence'].',"\x27';
+ }
+ }
+ }
+ }
+ }
+
+ # pobrišemo morebitne stare vrednosti
+ #array za imeni tmp fajlov, ki jih nato izbrišemo
+ $tmp_files = array( 'filtred'=>$folder . 'tmp_export_'.self::$sid.'_filtred'.TMP_EXT,
+ 'filtred1'=>$folder . 'tmp_export_'.self::$sid.'_filtred1'.TMP_EXT,
+ 'filtred_pagination'=>$folder . 'tmp_export_'.self::$sid.'_pagination'.TMP_EXT,
+ 'answers'=>$folder . 'tmp_export_'.self::$sid.'_answers'.'.php');
+
+ # dodamo filter za loop-e
+ if (isset(self::$_CURRENT_LOOP['filter']) && self::$_CURRENT_LOOP['filter'] != '') {
+ $status_filter = self::$_CURRENT_STATUS_FILTER.' && '.self::$_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = self::$_CURRENT_STATUS_FILTER;
+ }
+
+ // Limit po novem omejimo z filtriranjem array-a
+ //$_REC_LIMIT = ' NR==1,NR=='.$limit;
+
+ //za tip lokacija (ne enota 3) se rabi user_id, ker se kasneje delajo linki
+ $array_key = $need_user_id ? '{x=$1}' : '{x++}';
+
+ # naredimo datoteko z frekvencami
+ # za windows sisteme in za linux sisteme
+ if (IS_WINDOWS ) {
+ # TEST z LINUX načinom
+ # $cmdLn1 = 'awk -F"|" "BEGIN {{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '.$status_filter.' { print $0}" '.self::$dataFileName. ' > '.$tmp_files['filtred'];
+ # $cmdLn2 = 'sed "s*\x27*`*g" '.$tmp_files['filtred'].' > '.$tmp_files['filtred1'];
+ # $cmdLn4 = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} {x++} { print \"$answers[\",x,\"]=array('.implode(',',$sequenc_filter).');\"}" '.$tmp_files['filtred1'].' >> '.$tmp_files['answers'];
+
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\x7C\"} {ORS=\"\n\"} {FS=\"\x7C\"} {SUBSEP=\"\x7C\"}} '.$status_filter.' { print $0}" '.self::$dataFileName;
+ $command .= ' | sed "s*\x27*`*g"';
+ $command .= ' | awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$array_key.' { print \"$answers[\",x,\"]=array('.implode(',',$sequenc_filter).');\"}" >> '.$tmp_files['answers'];
+ } else {
+ # $cmdLn1 = 'awk -F"|" \'BEGIN {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} '.$status_filter.' {print $0}\' '.self::$dataFileName. ' > '.$tmp_files['filtred'];
+ # $cmdLn2 = 'sed \'s*\x27*`*g\' '.$tmp_files['filtred'].' > '.$tmp_files['filtred1'];
+ # $cmdLn4 = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} {x++} { print "$answers[",x,"]=array('.implode(',',$sequenc_filter).');"}\' '.$tmp_files['filtred1'].' >> '.$tmp_files['answers'];
+
+ $command = 'awk -F"|" \'BEGIN {{OFS="|"} {ORS="\n"} {FS="|"} {SUBSEP="|"}} '.$status_filter.' {print $0}\' '.self::$dataFileName;
+ $command .= ' | sed \'s*\x27*`*g\'';
+ $command .= ' | awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$array_key.' { print "$answers[",x,"]=array('.implode(',',$sequenc_filter).');"}\' >> '.$tmp_files['answers'];
+ }
+
+ #$out1 = shell_exec($cmdLn1);
+ #$out2 = shell_exec($cmdLn2);
+ $file_handler = fopen($tmp_files['answers'],"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+ // limit po novem omejimo z filtriranjem arraya
+ #$out3 = shell_exec($cmdLn3);
+ #$out4 = shell_exec($cmdLn4);
+ $out = shell_exec($command);
+
+ $file_handler = fopen($tmp_files['answers'],"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_files['answers']);//tukaj se deklarira spremenljivka $answers
+
+
+ if (file_exists($tmp_files['answers'])) {
+ unlink($tmp_files['answers']);
+ }
+
+ # PREFILTRIRAMO PODATKE PO POTREBI ODSTRANIMO MANJKAJOČE VREDNOSTI
+ # zloopamo skozi celotne odgovore in odstranimo tiste ki so missingi
+
+ # kateri odgovori so z profilom nastavljeni kot manjkajoči
+ # se dodelijo k missing values in se ne upoštevajo pri povprečju
+ $_invalidAnswers = self :: getInvalidAnswers (MISSING_TYPE_FREQUENCY);
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_result_answers = array();
+ $_result_answers['validCnt'] = 0;
+
+ if (count($answers) > 0) {
+ foreach ($answers AS $akey => $answer) {
+ $cnt++;
+ $all_invalid = true; # ali je vse neveljavno
+ foreach ($answer AS $seq => $value) {
+ # preverimo ali je kateri odgovor od userja vlejaven
+ if (!isset($_allMissing_answers[$value]) && !isset($_invalidAnswers[$value])) {
+ $all_invalid = false;
+ }
+ # ločimo odgovore na veljavne in nevlejavne
+ }
+
+ if ($all_invalid == FALSE) {
+ # imamo vsaj en veljaven odgovor
+ if ($limit == -1 || $_result_answers['validCnt'] < $limit) {
+ //ce smo nastavili $need_user_id, vkljucimo user_id kot key odgovorov v valid array
+ if(!$need_user_id)
+ $_result_answers['valid'][] = $answer;
+ else
+ $_result_answers['valid'][$akey] = $answer;
+ }
+ # koliko je vseh veljavnih
+ $_result_answers['validCnt']++;
+ } else {
+ # vsi odgovori so neveljavni
+ $_result_answers['invalid'][] = $answer;
+ $_result_answers['invalidCnt']++;
+ }
+ $_result_answers['allCnt']++;
+ }
+ }
+ return $_result_answers;
+ }
+
+ public static function showspremenljivkaSingleVarPopup($id) {
+ global $lang;
+
+ self::$_forceShowEmpty = true;
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
+
+ $anketa = $_REQUEST['anketa'];
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ # vse elemente forem
+ echo "<script>"."\n";
+ echo "$(document).ready(function(){ $('#div_analiza_single_var input:[type=radio], #div_analiza_single_var input:[type=checkbox], #div_analiza_single_var input:[type=text], #div_analiza_single_var select, #div_analiza_single_var textarea').attr('disabled',true); })"."\n";
+ echo "</script>";
+ echo '</head>';
+
+ echo '<body onBlur="window.close()" style="margin:5px; padding:5px;">';
+ echo '<input type="hidden" name="podstran" id="srv_meta_podstran" value="' . $zaPodstran . '" />';
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $_REQUEST['anketa'] . '" />';
+ $id = $_POST['id'];
+ $spremenljivka = self::$_HEADERS[$id];
+ $_tip = self::getSpremenljivkaLegenda($spremenljivka,'tip');
+ $zaPodstran = $_POST['zaPodstran'];
+
+ $legend = Cache::spremenljivkaLegenda($id);
+
+ echo '<span class="spaceRight">';
+ self::showIcons($id,$spremenljivka,'desc');
+ echo '</span>';
+ echo '<span class="spaceRight">'.$lang['srv_analiza_opisne_variable_type'].': ';
+ echo $_tip.' ';
+ echo '('.$legend['izrazanje'].' - '.$legend['lestvica'].')';
+ echo ' </span>';
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+ echo '<div id="div_analiza_single_var" class="container"> ';
+ self:: showPreviewSpremenljivka($id);
+ echo '</div>';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_win(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="icons/icons/printer.png" alt="'.$lang['hour_print2'].'" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '</body>';
+ echo '</html>';
+ }
+
+ public static function showSpremenljivkaTextAnswersPopup($id,$seq) {
+ global $lang;
+ self::$_forceShowEmpty = true;
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
+
+ $anketa = $_REQUEST['anketa'];
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body onBlur="window.close()" style="margin:5px; padding:5px;">';
+
+ echo '<input type="hidden" name="podstran" id="srv_meta_podstran" value="' . $zaPodstran . '" />';
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $_REQUEST['anketa'] . '" />';
+ echo '<div id="div_analiza_single_var" class="container">';
+ $id = $_POST['id'];
+ $seq = $_POST['seq'];
+ $zaPodstran = $_POST['zaPodstran'];
+ $spremenljivka = self::$_HEADERS[$id];
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ $num_show_records = 9999999;
+ # poiščemo navedbe textovne spremenljivke tako kot v grafih
+ $_answers = self::getAnswers($spremenljivka,$num_show_records);
+ if (count($_answers['valid']) > 0) {
+ echo '<table class="anl_tbl anl_bl anl_bt tbl_clps">';
+ foreach ($_answers['valid'] AS $vkey => $valid) {
+ $_valid = $valid[$seq];
+
+
+ echo '<tr><td class="anl_bck_0_1 anl_br anl_bb anl_user_text">';
+ echo $_valid;
+ echo '</td></tr>';
+ }
+ echo '</table>';
+ echo '<br />';
+ }
+ echo '</div>';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_win(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="icons/icons/printer.png" alt="'.$lang['hour_print2'].'" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '</body>';
+ echo '</html>';
+ }
+
+ /** Prikaže opsine, frekvence, sumarnik, za samo eno variablo
+ *
+ * @param unknown_type $id
+ */
+ public static function DisplaySingleVarPopup ($id,$zaPodstran)
+ {
+ global $site_url, $lang;
+ self::$_forceShowEmpty = true;
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
+
+ $anketa = $_REQUEST['anketa'];
+
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;} .chart_settings {display: none;} .chart_holder{width: 800px;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ #echo '<body onBlur="window.close()" style="margin:5px; padding:5px;">';
+ echo '<body style="margin:5px; padding:5px;">';
+ echo '<input type="hidden" name="podstran" id="srv_meta_podstran" value="' . $zaPodstran . '" />';
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $_REQUEST['anketa'] . '" />';
+
+ echo '<div id="div_analiza_single_var" class="container">';
+ $id = $_POST['id'];
+ $zaPodstran = $_POST['zaPodstran'];
+
+ # polovimo nastavtve missing profila
+ self::$missingProfileData = SurveyMissingProfiles::getProfile(self::$currentMissingProfile);
+ if (self::$podstran != M_ANALYSIS_ARCHIVE)
+ {
+ self::$_LOOPS = SurveyZankaProfiles::getFiltersForLoops();
+ }
+ if (!is_array(self::$_LOOPS))
+ {
+ self::$_LOOPS[] = array('filter'=>null,'text'=>null);
+ }
+
+ $loop_cnt = 0;
+ # ce mamo zanke
+ foreach ( self::$_LOOPS AS $loop)
+ {
+ if ($loop['filter'] != null)
+ {
+ $loop_cnt++;
+ $loop['cnt'] = $loop_cnt;
+ self::$_CURRENT_LOOP = $loop;
+ if ((int)$loop_cnt == (int)$_POST['loop'])
+ {
+
+ echo '<h2 data-loopId="'.self::$_CURRENT_LOOP['cnt'].'">'.$lang['srv_zanka_note'].$loop['text'].'</h2>';
+ }
+ }
+ if ((int)$loop_cnt == (int)$_POST['loop'])
+ {
+ switch ($zaPodstran)
+ {
+ case M_ANALYSIS_SUMMARY_NEW :
+ self::displaySumsNew($id);
+ $export = 'sums';
+ break;
+ case M_ANALYSIS_SUMMARY :
+ self::displaySums($id);
+ $export = 'sums';
+ break;
+ case M_ANALYSIS_DESCRIPTOR :
+ self::displayDescriptives($id);
+ $export = 'statistics';
+ break;
+ case M_ANALYSIS_FREQUENCY :
+ self::displayFrequency($id);
+ $export = 'frequency';
+ break;
+ case M_ANALYSIS_CHARTS :
+ $chartClass = new SurveyChart();
+ $chartClass->Init($anketa);
+ $chartClass->displaySingle($id);
+ $export = 'charts';
+ break;
+ }
+ //Izvoz v PDF/RTF
+ $loop_exp = (isset(self::$_CURRENT_LOOP)) ? self::$_CURRENT_LOOP['cnt'] : 'undefined';
+ $_url1 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'm'=>$export,
+ 'anketa'=>$anketa,
+ 'sprID'=>$id,
+ 'loop'=>$loop_exp)));
+ $_url2 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'm'=>$export.'_rtf',
+ 'anketa'=>$anketa,
+ 'sprID'=>$id,
+ 'loop'=>$loop_exp)));
+ $_url3 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'm'=>$export.'_xls',
+ 'anketa'=>$anketa,
+ 'sprID'=>$id,
+ 'loop'=>$loop_exp)));
+
+ echo '<div id="single_export" class="printHide">';
+ echo '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf"></span></a>';
+ echo '&nbsp;&nbsp;<a href="'.$_url2.'" target="_blank"><span class="faicon rtf"></span>&nbsp;</a>';
+ //if($export == 'frequency')
+ if($zaPodstran != M_ANALYSIS_CHARTS )
+ {
+ echo '&nbsp;&nbsp;<a href="'.$_url3.'" target="_blank"><span class="faicon xls"></span>&nbsp;</a>';
+ }
+ }
+
+ }
+
+ echo '</div>';
+ echo '<div class="clr"></div>';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_win(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="icons/icons/printer.png" alt="'.$lang['hour_print2'].'" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+ echo '</body>';
+ echo '</html>';
+ }
+
+ /** Sestavi array nepravilnih odgovorov
+ *
+ */
+ static function getInvalidAnswers($type) {
+ $result = array();
+ $missingValuesForAnalysis = SurveyMissingProfiles :: GetMissingValuesForAnalysis($type);
+
+ foreach ($missingValuesForAnalysis AS $k => $answer) {
+ $result[$k] = array('text'=>$answer,'cnt'=>0);
+ }
+ return $result;
+ }
+
+
+ static function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands) . $sufix;
+
+ return $result;
+ }
+
+ static function getSpremenljivkaLegenda ($spremenljivka, $what='') {
+
+ $legenda = Cache::spremenljivkaLegenda($spremenljivka['spr_id']);
+
+ return $legenda[$what];
+ }
+
+
+ /** razdelek za Ajax klice
+ *
+ */
+ public function ajax() {
+ if (isset ($_POST['corssVar1']))
+ $corssVar1 = $_POST['corssVar1'];
+ if (isset ($_POST['corssVar2']))
+ $corssVar2 = $_POST['corssVar2'];
+ if (isset ($_POST['corssZanka']))
+ $corssZanka = $_POST['corssZanka'];
+ if (isset ($_POST['crossChk0']))
+ $crossChk0 = $_POST['crossChk0'];
+ if (isset ($_POST['crossChk1']))
+ $crossChk1 = $_POST['crossChk1'];
+ if (isset ($_POST['crossChk2']))
+ $crossChk2 = $_POST['crossChk2'];
+ if (isset ($_POST['crossChk3']))
+ $crossChk3 = $_POST['crossChk3'];
+ if (isset ($_POST['crossChkEC']))
+ $crossChkEC = $_POST['crossChkEC'];
+ if (isset ($_POST['crossChkRE']))
+ $crossChkRE = $_POST['crossChkRE'];
+ if (isset ($_POST['crossChkSR']))
+ $crossChkSR = $_POST['crossChkSR'];
+ if (isset ($_POST['crossChkAR']))
+ $crossChkAR = $_POST['crossChkAR'];
+ if (isset ($_POST['doColor']))
+ $doColor = $_POST['doColor'];
+
+ switch ($_GET['a']) {
+ case 'loadMissingProfile' :
+ self :: loadMissingProfile();
+ break;
+ case 'reloadData' :
+ self :: Display();
+ break;
+ case 'showAnalizaSingleVarPopup' :
+ self :: DisplaySingleVarPopup($_POST['id'],$_POST['zaPodstran']);
+ break;
+ case 'showspremenljivkaSingleVarPopup' :
+ self :: showspremenljivkaSingleVarPopup($_POST['id']);
+ break;
+ case 'showSpremenljivkaTextAnswersPopup' :
+ self :: showSpremenljivkaTextAnswersPopup($_POST['id'],$_POST['seq']);
+ break;
+ case 'show_crostabs_dropdowns' :
+ self :: displayDropdowns($corssVar1, $corssVar2, $corssZanka);
+ break;
+ case 'show_crostabs_table' :
+ self :: displayCrosstabsTable($corssVar1, $corssVar2, $corssZanka, $crossChk0, $crossChk1, $crossChk2, $crossChk3, $crossChkEC, $crossChkRE, $crossChkSR, $crossChkAR, $doColor);
+ break;
+ case 'preview_spremenljivka' :
+ self:: showPreviewSpremenljivka($_POST['spremenljivka']);
+ break;
+ case 'printPreview_spremenljivka' :
+ self:: printPreviewSpremenljivka($_POST['id']);
+ break;
+ case 'toggleAnalysisAdvanced' :
+ self:: toggleAnalysisAdvanced();
+ break;
+ case 'changeAnalizaPreview' :
+ self:: changeAnalizaPreview();
+ break;
+ case 'show_spid_more_table' :
+ self:: show_sum_more_table();
+ break;
+ case 'changeSpremenljivkaLestvica' :
+ self:: changeSpremenljivkaLestvica();
+ break;
+ default:
+ echo 'Error! (class: SurveyAnalysis->ajax() - missing action)';
+ break;
+ }
+ }
+ /** izpiše linke - povezave do pdf ,rtf datotek vprašalnika in analiz
+ *
+ */
+ public static function DisplayReportsLinks() {
+ global $lang, $global_user_id;
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA || self::$dataFileStatus == -3 || self::$noHeader == true) {
+ return false;
+ }
+
+ SurveyUserSetting :: getInstance()->Init(self::$sid, $global_user_id);
+
+ SurveyAnalysis::DisplayFilters();
+
+ /*
+ // Link na navadna porocila
+ echo '<div id="custom_report_switch" class="creport"><a href="index.php?anketa='.self::$sid.'&a=analysis&m=analysis_links"><span>'.$lang['srv_standard_report'].'</span></a></div>';
+ // Link na porocilo po meri
+ echo '<div id="custom_report_switch"><a href="index.php?anketa='.self::$sid.'&a=analysis&m=analysis_creport"><span>'.$lang['srv_custom_report'].'</span></a></div>';
+ */
+
+ echo '<table class="analysis_reports"><tr>';
+
+ // ANALIZE
+ echo '<td>';
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_analiza'].'</legend>';
+
+ # linki - analize sumarnik
+ echo '<span class="subtitle">' . $lang['srv_sumarnik'] . '</span>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=sums&anketa='.self::$sid).'" target="_blank">' .
+ '<span class="faicon pdf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=sums_rtf&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon rtf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;DOC - (Microsoft Word)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=sums_xls&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon xls" title="' . $lang['srv_reporti'] . '"></span>&nbsp;XLS - (Microsoft Excel)</a>';
+
+ # linki - analize opisne statistike
+ echo '<span class="subtitle">' . $lang['srv_descriptor'] . '</span>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=statistics&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon pdf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=statistics_rtf&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon rtf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;DOC - (Microsoft Word)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=statistics_xls&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon xls" title="' . $lang['srv_reporti'] . '"></span>&nbsp;XLS - (Microsoft Excel)</a>';
+
+ # linki - analize frekvence
+ echo '<span class="subtitle">' . $lang['srv_frequency'] . '</span>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=frequency&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon pdf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=frequency_rtf&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon rtf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;DOC - (Microsoft Word)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=frequency_xls&anketa=' . self::$sid).'" target="_blank">' .
+ '<span class="faicon xls" title="' . $lang['srv_reporti'] . '"></span>&nbsp;XLS - (Microsoft Excel)</a>';
+
+ echo '</fieldset>';
+
+ // VPRASALNIK
+ echo '</td><td>';
+ echo '<fieldset style="padding-top: 10px;">';
+ echo '<legend>'.$lang['srv_analysis_links_survey'].'</legend>';
+
+ # linki - vprašalnik
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=' . A_REPORT_VPRASALNIK_PDF . '&anketa=' . self::$sid) . '" target="_blank">' .
+ '<span class="faicon pdf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=' . A_REPORT_VPRASALNIK_RTF . '&anketa=' . self::$sid) . '" target="_blank">' .
+ '<span class="faicon rtf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;DOC - (Microsoft Word)</a>';
+
+ echo '</fieldset>';
+
+ // IZPIS
+ echo '</td><td>';
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_statistic'].'</legend>';
+
+ # linki - vpogled
+ echo '<span class="subtitle">' . $lang['srv_analysis_links_vpogled'] . '</span>';
+ echo '<a href="index.php?anketa='.self::$sid.'&a=data&m=quick_edit&quick_view=1" >' .
+ '<span title="' . $lang['srv_link_data_view'] . '"></span>' . $lang['srv_link_data_view'] . '</a>';
+
+ # linki - izpis vseh odgovorov
+ echo '<span class="subtitle">' . $lang['srv_analysis_links_allAnswers'] . '</span>';
+ echo '<span class="clr">' . $lang['srv_analysis_links_allAnswers_note'] . '</span><br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=pdf_results&anketa=' . self::$sid) . '" target="_blank">' .
+ '<span class="faicon pdf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;PDF - (Adobe Acrobat)</a>';
+ echo '<br/>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?a=rtf_results&anketa=' . self::$sid) . '" target="_blank">' .
+ '<span class="faicon rtf" title="' . $lang['srv_reporti'] . '"></span>&nbsp;DOC - (Microsoft Word)</a>';
+
+ echo '</fieldset>';
+ echo '</td>';
+
+ echo '</tr></table>';
+ }
+
+ private static function printAnalizaSingleVar() {
+ global $lang;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+
+ $anketa = $_REQUEST['anketa'];
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body onBlur="window.close()" style="margin:5px; padding:5px;">';
+ echo '<div class="container"> ';
+ $id = $_POST['id'];
+ $zaPodstran = $_POST['zaPodstran'];
+ switch ($zaPodstran) {
+ case M_ANALYSIS_SUMMARY_NEW :
+ self::displaySumsNew($id);
+ break;
+ case M_ANALYSIS_SUMMARY :
+ self::displaySums($id);
+ break;
+ case M_ANALYSIS_DESCRIPTOR :
+ self::displayDescriptives($id);
+ break;
+ case M_ANALYSIS_FREQUENCY :
+ self::displayFrequency($id);
+ break;
+ }
+ echo '</div>';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceLeft"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_win(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="print_win(); return false;"><span><img src="icons/icons/printer.png" alt="'.$lang['hour_print2'].'" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<br class="clr"/>';
+ echo '</div>';
+ echo '</body>';
+ echo '</html>';
+
+ }
+
+ function showPreviewSpremenljivka($spremenljivka) {
+ global $lang, $site_path;
+
+ SurveyInfo :: getInstance()->SurveyInit($anketa);
+
+ $offset = 0;
+ $zaporedna = 0;
+ $count_type = SurveyInfo :: getInstance()->getSurveyCountType();
+
+ if ($count_type) {
+
+ // Preštejemo koliko vprašanj je bilo do sedaj
+ $sqlg = sisplet_query("SELECT vrstni_red FROM srv_grupa WHERE id = (SELECT gru_id FROM srv_spremenljivka WHERE id = '" . $spremenljivka . "')");
+ $rowg = mysqli_fetch_assoc($sqlg);
+ $vrstni_red = $rowg['vrstni_red'];
+
+ $sqlCountPast = sisplet_query("SELECT count(*) as cnt FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='" . self :: $sid . "' AND s.gru_id=g.id AND g.vrstni_red < '$vrstni_red' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ $rowCount = mysqli_fetch_assoc($sqlCountPast);
+ $offset = $rowCount['cnt'];
+
+ // poiscemo vprasanja / spremenljivke
+ $sql = sisplet_query("SELECT id FROM srv_spremenljivka WHERE gru_id=(SELECT gru_id FROM srv_spremenljivka WHERE id = '" . $spremenljivka . "') AND visible='1' ORDER BY vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['id'] == $spremenljivka) {
+ $zaporedna++;
+ break;
+ }
+ }
+ }
+
+ echo '<div id="preview_spremenljivka">';
+
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+
+ if (isset($_POST['lang_id'])) {
+ save('lang_id', (int)$_POST['lang_id']);
+ }
+ echo ' <div id="spremenljivka_preview">';
+ if ( $spremenljivka == -1 ) {
+ \App\Controllers\BodyController::getInstance()->displayIntroduction();
+ }
+ elseif ( $spremenljivka == -2 ) {
+ \App\Controllers\BodyController::getInstance()->displayKonec();
+ }
+ elseif ( $spremenljivka == -3 ) {
+ \App\Controllers\StatisticController::displayStatistika();
+ }
+ else {
+ save('forceShowSpremenljivka', true);
+ \App\Controllers\Vprasanja\VprasanjaController::getInstance()->displaySpremenljivka($spremenljivka, $offset, $zaporedna);
+ }
+ echo ' </div>';
+ echo '<div class="clr"></div>';
+
+ echo '</div>';
+
+
+ }
+
+ function printPreviewSpremenljivka($spremenljivka) {
+ global $lang;
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
+
+ $anketa = $_REQUEST['anketa'];
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+ echo '<body onBlur="window.close()" style="margin:5px; padding:5px;" >';
+
+ global $lang, $site_path;
+
+ SurveyInfo :: getInstance()->SurveyInit($anketa);
+
+ $offset = 0;
+ $zaporedna = 0;
+ $count_type = SurveyInfo :: getInstance()->getSurveyCountType();
+
+ if ($count_type) {
+
+ // Preštejemo koliko vprašanj je bilo do sedaj
+ $sqlg = sisplet_query("SELECT vrstni_red FROM srv_grupa WHERE id = (SELECT gru_id FROM srv_spremenljivka WHERE id = '" . $spremenljivka . "')");
+ $rowg = mysqli_fetch_assoc($sqlg);
+ $vrstni_red = $rowg['vrstni_red'];
+
+ $sqlCountPast = sisplet_query("SELECT count(*) as cnt FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='" . self :: $sid . "' AND s.gru_id=g.id AND g.vrstni_red < '$vrstni_red' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ $rowCount = mysqli_fetch_assoc($sqlCountPast);
+ $offset = $rowCount['cnt'];
+
+ // poiscemo vprasanja / spremenljivke
+ $sql = sisplet_query("SELECT id FROM srv_spremenljivka WHERE gru_id=(SELECT gru_id FROM srv_spremenljivka WHERE id = '" . $spremenljivka . "') AND visible='1' ORDER BY vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+ if ($row['id'] == $spremenljivka) {
+ $zaporedna++;
+ break;
+ }
+ }
+ }
+
+
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+
+ if (isset($_POST['lang_id'])) {
+ save('lang_id', (int)$_POST['lang_id']);
+ }
+ echo '<div id="spremenljivka_preview" class="container">';
+ if ( $spremenljivka == -1 ) {
+ \App\Controllers\BodyController::getInstance()->displayIntroduction();
+ }
+ elseif ( $spremenljivka == -2 ) {
+ \App\Controllers\BodyController::getInstance()->displayKonec();
+ }
+ elseif ( $spremenljivka == -3 ) {
+ \App\Controllers\StatisticController::displayStatistika();
+ } else {
+ save('forceShowSpremenljivka', true);
+ \App\Controllers\Vprasanja\VprasanjaController::getInstance()->displaySpremenljivka($_GET['spremenljivka']);
+ }
+
+ echo '</div>';// id="spremenljivka_preview"
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceLeft"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_win(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="print_win(); return false;"><span><img src="icons/icons/printer.png" alt="'.$lang['hour_print2'].'" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<br class="clr"/>';
+ echo '</div>';
+ echo '</body>';
+ echo '</html>';
+
+ }
+
+ static function show_sum_more_table() {
+ self :: $show_spid_div = false;
+ self::$_LOOPS = SurveyZankaProfiles::getFiltersForLoops();
+ if (count(self::$_LOOPS) == 0 ) {
+ if ($_POST['podstran'] == M_ANALYSIS_SUMMARY) {
+ self :: displaySums($_POST['spid']);
+ } else if ($_POST['podstran'] == M_ANALYSIS_SUMMARY_NEW) {
+ self :: displaySumsNew($_POST['spid']);
+ } else if ($_POST['podstran'] == M_ANALYSIS_FREQUENCY) {
+ self :: displayFrequency($_POST['spid']);
+ }
+ } else {
+ # če mamo zanke
+ $loop_cnt = 0;
+ foreach ( self::$_LOOPS AS $loop) {
+ $loop_cnt++;
+ $loop['cnt'] = $loop_cnt;
+ self::$_CURRENT_LOOP = $loop;
+
+ if ($loop['cnt'] == $_POST['loop_id']) {
+ if ($_POST['podstran'] == M_ANALYSIS_SUMMARY) {
+ self :: displaySums($_POST['spid']);
+ } else if ($_POST['podstran'] == M_ANALYSIS_SUMMARY_NEW) {
+ self :: displaySumsNew($_POST['spid']);
+ } else if ($_POST['podstran'] == M_ANALYSIS_FREQUENCY) {
+ self :: displayFrequency($_POST['spid']);
+ }
+ }
+ }
+ }
+
+ echo '<script type="text/javascript" charset="utf-8">
+ analiza_init ();
+ </script>';
+ }
+
+ static function getNumRecords() {
+ if (isset($_POST['num_records']) && (int)$_POST['num_records'] > 0) {
+ $result = (int)self::$textAnswersMore[$_POST['num_records']];
+ } else {
+ $result = (int)SurveyDataSettingProfiles :: getSetting('numOpenAnswers');
+ }
+ return $result;
+ }
+
+
+ /** @desc: Prikaže vsebino diva za izbiro filtriranja
+ *
+ */
+ function showFilterProfiles ($pid = -1) {
+ global $lang;
+
+ // profili za filtriranje
+ echo '<div style="float:left; width:auto; text-align: center;">';
+
+ echo '<span class="as_link" id="link_filter_profile" title="'.$lang['srv_analiza_filter'].'">'.$lang['srv_analiza_filter'].'</span><br />';
+ SurveyFilterProfiles::Init(self::$sid, $global_user_id);
+ $current_filter_profiles = SurveyFilterProfiles::getCurrentProfile();
+ $available_filter_profiles = SurveyFilterProfiles::getAvailableProfiles();
+
+ echo '<span id="div_analiza_filter_profile_dropdown">';
+ echo '<select id="analiza_current_filter_profile" name="analize_current_filter_profile" onchange="changeFilterProfileDropdown();">';
+ foreach ($available_filter_profiles AS $key => $val) {
+ echo ' <option value="'.$val['id'].'"'.($val['id']==$current_filter_profiles['id']?' selected="selected"':'').'>'.$val['name'].'</option>';
+ }
+ echo '</select>';
+ echo '</span>';
+
+ echo '</div>';
+ }
+
+ /**
+ *
+ * # odstranimo sistemske variable tipa email, ime, priimek, geslo oz. ce imamo vklopljeno nastavitev da skrivamo vse sistemske skrijemo vse sistem == 1
+ */
+ static function removeSystemVariables() {
+ if (!empty(self::$_HEADERS))
+ {
+ foreach (self::$_HEADERS AS $skey => $spremenljivka) {
+ if ((int)$spremenljivka['hide_system'] == 1 && in_array($spremenljivka['variable'],array('email','ime','priimek','telefon','naziv','drugo'))) {
+ unset(self::$_HEADERS[$skey]);
+ }
+ else if ((int)$spremenljivka['sistem'] == 1 && SurveyDataSettingProfiles :: getSetting('hideAllSystem') == 1) {
+ unset(self::$_HEADERS[$skey]);
+ }
+ }
+ }
+ }
+
+ /*
+ * posortiramo veljavne odgovore kronološko, po datumu
+ *
+ */
+ static function sortTextValidAnswers($_spid,$variable,$answers) {
+ if (is_string($answers)) {
+ $answers = mb_strtolower($answers,'UTF-8');
+ }
+
+ # Polovimo kronološki potek odgovorov
+ $spid = explode('_',$_spid);
+ $spid = $spid[0];
+ $result = array();
+
+ $string = "SELECT distinct TRIM(REPLACE(REPLACE(REPLACE(sdt.text,'\n',' '),'\r',' '),'|',' ')) as text FROM srv_data_text".self::$db_table." AS sdt JOIN srv_user AS u ON sdt.usr_id = u.id WHERE sdt.spr_id = '".$spid."' AND sdt.vre_id = '".$variable['vr_id']."' ORDER BY u.time_insert ASC";
+
+ $sql = sisplet_query($string);
+ while ( list($text) = mysqli_fetch_row($sql) ) {
+ $text = mb_strtolower($text,'UTF-8');
+ $text = str_replace('\'','`',addslashes(strip_tags($text)));
+ if (isset($answers[$text])) {
+ $result[$text] = $answers[$text];
+ }
+ }
+
+ return $result;
+ }
+
+ static function setUpReturnAsHtml($returnAsHtml = false) {
+ self::$returnAsHtml = $returnAsHtml; # ali vrne rezultat analiz kot html ali ga izpiše
+ }
+ static function setUpIsForArchive($isArchive = false) {
+ self::$isArchive = $isArchive; # nastavimo da smo v arhivu
+ }
+ static function setForceShowEmpty($_forceShowEmpty = false) {
+ self::$_forceShowEmpty = $_forceShowEmpty;
+ }
+
+
+ function showChartColorProfiles(){
+ global $lang;
+ $skin = SurveyUserSetting :: getInstance()->getSettings('default_chart_profile_skin');
+ echo '<span style="display: inline; font-weight: bold;">'.$lang['srv_chart_skin_long'].'</span><br/>';
+ echo '<span style="font-size: 10px; font-style: italic;">'.$lang['srv_chart_skin_info'].'</span><br/>';
+ echo '<select id="chart_skin" name="chart_skin" onchange="changeChartGlobalSettings(\'skin\', this.value); return false;" >';
+ echo '<option' . ($skin == 0 ? ' selected="selected"' : '') . ' value="0">'.$lang['srv_chart_skin_0'].'</option>';
+ echo '<option' . ($skin == 1 ? ' selected="selected"' : '') . ' value="1">'.$lang['srv_chart_skin_1'].'</option>';
+ echo '<option' . ($skin == 6 ? ' selected="selected"' : '') . ' value="6">'.$lang['srv_chart_skin_6'].'</option>';
+ echo '<option' . ($skin == 2 ? ' selected="selected"' : '') . ' value="2">'.$lang['srv_chart_skin_2'].'</option>';
+ echo '<option' . ($skin == 3 ? ' selected="selected"' : '') . ' value="3">'.$lang['srv_chart_skin_3'].'</option>';
+ echo '<option' . ($skin == 4 ? ' selected="selected"' : '') . ' value="4">'.$lang['srv_chart_skin_4'].'</option>';
+ echo '<option' . ($skin == 5 ? ' selected="selected"' : '') . ' value="5">'.$lang['srv_chart_skin_5'].'</option>';
+ echo '</select>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_chartColor(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ }
+
+ function toggleAnalysisAdvanced() {
+
+ session_start();
+ $_SESSION['AnalysisAdvancedLinks'][self::$sid] = ($_POST['what'] == 1) ? true : false;
+ $SSH = new SurveyStaticHtml(self::$sid);
+
+ # izrišemo desne linke do posameznih nastavitev
+ $SSH -> displayAnalizaRightOptions($_POST['podstran'],true);
+
+ }
+
+ function changeAnalizaPreview() {
+ global $global_user_id;
+ UserSetting :: getInstance()->Init($global_user_id);
+ UserSetting:: getInstance()->setUserSetting('showAnalizaPreview', (int)$_POST['value'] );
+ UserSetting:: getInstance()->saveUserSetting();
+ $SSH = new SurveyStaticHtml(self::$sid);
+ $SSH -> displayAnalizaSubNavigation(false);
+
+ }
+
+ static function addCustomReportElement($type, $sub_type, $spr1, $spr2=''){
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type, $sub_type=0, $spid);
+ }
+
+ // Nastavitve na dnu
+ static function displayBottomSettings($page){
+ global $site_path;
+ global $lang;
+ global $global_user_id;
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $lan_print = ' title="'.$lang['PRN_Izpis'].'"';
+ $lan_pdf = ' title="'.$lang['PDF_Izpis'].'"';
+ $lan_rtf = ' title="'.$lang['RTF_Izpis'].'"';
+ $lan_xls = ' title="'.$lang['XLS_Izpis'].'"';
+
+ echo '<div class="analysis_bottom_settings printHide">';
+
+ // Pri javni povezavi nimamo tega
+ if(self::$printPreview == false){
+ // Nastavitve na dnu pri sumarniku
+ if($page == 'sums'){
+
+ echo '<a href="#" onClick="addCustomReportAllElementsAlert(1);" title="'.$lang['srv_custom_report_comments_add_hover'].'" class="'.(!$userAccess->checkUserAccess('analysis_analysis_creport') ? 'user_access_locked' : '').'" user-access="analysis_analysis_creport" style="margin-right: 40px;"><span class="spaceRight faicon comments_creport" ></span><span class="bold">'.$lang['srv_custom_report_comments_add'].'</span></a>';
+
+ echo '<a href="#" onClick="printAnaliza(\'Sumarnik\'); return false;"'.$lan_print.' class="srv_ico"><span class="faicon print icon-grey_dark_link"></span></a>';
+
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=sums&anketa=' . self::$sid) . '" target="_blank"'.$lan_pdf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon pdf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=sums_rtf&anketa=' . self::$sid) . '" target="_blank"'.$lan_rtf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon rtf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=sums_xls&anketa=' . self::$sid) . '" target="_blank"'.$lan_xls.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon xls black very_large"></span></a>';
+
+ echo '<a href="#" onclick="doArchiveAnaliza();" title="'.$lang['srv_analiza_arhiviraj_ttl'].'" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv black very_large"></span></a>';
+ echo '<a href="#" onclick="createArchiveBeforeEmail();" title="'.$lang['srv_analiza_arhiviraj_email_ttl'] . '" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv_mail black very_large"></span></a>';
+ }
+
+ // Nastavitve na dnu pri frekvencah
+ elseif($page == 'freq'){
+
+ echo '<a href="#" onClick="addCustomReportAllElementsAlert(2);" title="'.$lang['srv_custom_report_comments_add_hover'].'" class="'.(!$userAccess->checkUserAccess('analysis_analysis_creport') ? 'user_access_locked' : '').'" user-access="analysis_analysis_creport" style="margin-right: 40px;"><span class="spaceRight faicon comments_creport" ></span><span class="bold">'.$lang['srv_custom_report_comments_add'].'</span></a>';
+
+ echo '<a href="#" onClick="printAnaliza(\'Frekvence\'); return false;"'.$lan_print.' class="srv_ico"><span class="faicon print icon-grey_dark_link"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=frequency&anketa=' . self::$sid) . '" target="_blank"'.$lan_pdf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon pdf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=frequency_rtf&anketa=' . self::$sid) . '" target="_blank"'.$lan_rtf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon rtf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=frequency_xls&anketa=' . self::$sid) . '" target="_blank"'.$lan_xls.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon xls black very_large"></span></a>';
+
+ echo '<a href="#" onclick="doArchiveAnaliza();" title="'.$lang['srv_analiza_arhiviraj_ttl'].'" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv black very_large"></span></a>';
+ echo '<a href="#" onclick="createArchiveBeforeEmail();" title="'.$lang['srv_analiza_arhiviraj_email_ttl'] . '" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv_mail black very_large"></span></a>';
+ }
+
+ // Nastavitve na dnu pri opisnih statistikah
+ else{
+
+ echo '<a href="#" onClick="addCustomReportAllElementsAlert(3);" title="'.$lang['srv_custom_report_comments_add_hover'].'" class="'.(!$userAccess->checkUserAccess('analysis_analysis_creport') ? 'user_access_locked' : '').'" user-access="analysis_analysis_creport" style="margin-right: 40px;"><span class="spaceRight faicon comments_creport" ></span><span class="bold">'.$lang['srv_custom_report_comments_add'].'</span></a>';
+
+ echo '<a href="#" onClick="printAnaliza(\'Opisne statistike\'); return false;"'.$lan_print.' class="srv_ico"><span class="faicon print icon-grey_dark_link"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=statistics&anketa=' . self::$sid) . '" target="_blank"'.$lan_pdf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon pdf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=statistics_rtf&anketa=' . self::$sid) . '" target="_blank"'.$lan_rtf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon rtf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=statistics_xls&anketa=' . self::$sid) . '" target="_blank"'.$lan_xls.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon xls black very_large"></span></a>';
+
+ echo '<a href="#" onclick="doArchiveAnaliza();" title="'.$lang['srv_analiza_arhiviraj_ttl'].'" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv black very_large"></span></a>';
+ echo '<a href="#" onclick="createArchiveBeforeEmail();" title="'.$lang['srv_analiza_arhiviraj_email_ttl'] . '" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv_mail black very_large"></span></a>';
+ }
+ }
+
+ echo '</div>';
+
+ // Javascript s katerim povozimo urlje za izvoze, ki niso na voljo v paketu
+ global $app_settings;
+ if($app_settings['commercial_packages'] == true){
+ echo '<script> userAccessExport(); </script>';
+ }
+ }
+
+ static function displayQuickIcons($id) {
+ global $site_url;
+ global $global_user_id;
+
+ $return = '<span class="" style="">';
+ $anketa = self::$sid;
+ switch (self::$podstran) {
+
+ case M_ANALYSIS_SUMMARY_NEW :
+ $export = 'sums';
+ break;
+
+ case M_ANALYSIS_SUMMARY :
+ $export = 'sums';
+ break;
+
+ case M_ANALYSIS_DESCRIPTOR :
+ $export = 'statistics';
+ break;
+
+ case M_ANALYSIS_FREQUENCY :
+ $export = 'frequency';
+ break;
+
+ case M_ANALYSIS_CHARTS :
+ $export = 'charts';
+ break;
+ }
+
+ $loop = (isset(self::$_CURRENT_LOOP)) ? self::$_CURRENT_LOOP['cnt'] : 'undefined';
+
+ //Izvoz v PDF/RTF
+ $_url1 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'm'=>$export,
+ 'anketa'=>$anketa,
+ 'sprID'=>$id,
+ 'loop'=>$loop)));
+ $_url2 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'm'=>$export.'_rtf',
+ 'anketa'=>$anketa,
+ 'sprID'=>$id,
+ 'loop'=>$loop)));
+ $_url3 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'm'=>$export.'_xls',
+ 'anketa'=>$anketa,
+ 'sprID'=>$id,
+ 'loop'=>$loop)));
+
+ $return = '<span class="faicon print_small icon-grey_dark_link" onclick="printCurrentAnalysis(\''.$id.'\');"></span>&nbsp;&nbsp';
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+ if($userAccess->checkUserAccess($what='data_export')){
+ $return .= '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf"></span></a>';
+ $return .= '&nbsp;&nbsp;<a href="'.$_url2.'" target="_blank"><span class="faicon rtf"></span></a>';
+
+ if(self::$podstran != M_ANALYSIS_CHARTS ) {
+ $return .= '&nbsp;&nbsp;<a href="'.$_url3.'" target="_blank"><span class="faicon xls"></span></a>';
+ }
+ }
+ else{
+ $return .= '<a href="#" onClick="popupUserAccess(\'analysis_export\');"><span class="faicon pdf user_access_locked"></span></a>';
+ $return .= '&nbsp;&nbsp;<a href="#" onClick="popupUserAccess(\'analysis_export\');"><span class="faicon rtf user_access_locked"></span></a>';
+
+ if(self::$podstran != M_ANALYSIS_CHARTS ) {
+ $return .= '&nbsp;&nbsp;<a href="#" onClick="popupUserAccess(\'analysis_export\');"><span class="faicon xls user_access_locked"></span></a>';
+ }
+ }
+
+ $return .= '</span>';
+
+ return $return;
+ }
+
+ function changeSpremenljivkaLestvica() {
+
+ #shranimo nastavitve
+ $spremenljivka = $_POST['spid'];
+ $skala = $_POST['skala'];
+
+ # popravimo skalo spremenljivke
+ # skala - 0 Ordinalna
+ # skala - 1 Nominalna
+ if ( isset($skala) && (int)$spremenljivka) {
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET skala='".$skala."' WHERE id='$spremenljivka'");
+ #Common::updateEditStamp();
+ # popravimo v header datoteki
+ self::$_HEADERS[$spremenljivka]['skala'] = $skala;
+ file_put_contents(self::$headFileName, serialize(self::$_HEADERS));
+ }
+
+ }
+
+ static function displaySpremenljivkaIcons($spid) {
+
+ if (self::$isArchive == false){
+ echo '<div class="div_analiza_icons">'.self::displayQuickIcons($spid).'</div>';
+
+ // Javna povezava nima js preklopov
+ if(self::$printPreview == false)
+ self::displayQuickScale($spid);
+ }
+ }
+
+ static function displayQuickScale($spid) {
+ global $lang;
+
+ $spr_id = self::$_HEADERS[$spid]['spr_id'];
+
+ # pokličemo objekt SpremenljivkaSkala
+ $objectSkala = new SpremenljivkaSkala($spr_id);
+
+ if ($objectSkala->canChangeSkala()) {
+ echo '<div class="div_analiza_scale">';
+ if ($objectSkala->is(SpremenljivkaSkala::ORD)) {
+ echo '<a href="#" onclick="changeSpremenljivkaLestvica(\''.$spid.'\',\''.SpremenljivkaSkala::NOM.'\'); return false;">';
+ echo '<span class="strong" title="'.$lang['srv_skala_long_'.SpremenljivkaSkala::ORD].'">';
+ echo $lang['srv_skala_'.SpremenljivkaSkala::ORD];
+ echo '</span>';
+ echo ' / ';
+ echo '<span title="'.$lang['srv_skala_long_'.SpremenljivkaSkala::NOM].'">';
+ echo $lang['srv_skala_'.SpremenljivkaSkala::NOM];
+ echo '</span>';
+ echo '</a>';
+ }
+ if ($objectSkala->is(SpremenljivkaSkala::NOM)) {
+ echo '<a href="#" onclick="changeSpremenljivkaLestvica(\''.$spid.'\',\''.SpremenljivkaSkala::ORD.'\'); return false;">';
+ echo '<span title="'.$lang['srv_skala_long_'.SpremenljivkaSkala::ORD].'">';
+ echo $lang['srv_skala_'.SpremenljivkaSkala::ORD];
+ echo '</span>';
+ echo ' / ';
+ echo '<span class="strong" title="'.$lang['srv_skala_long_'.SpremenljivkaSkala::NOM].'">';
+ echo $lang['srv_skala_'.SpremenljivkaSkala::NOM];
+ echo '</span>';
+ echo '</a>';
+ }
+ echo '</div>';
+ } else {
+ echo '<div class="div_analiza_scale">';
+ echo '<span title="'.$lang['srv_skala_long_'.$objectSkala->getSkala()].'">';
+ echo $lang['srv_skala_'.$objectSkala->getSkala()];
+ echo '</span>';
+ echo '</div>';
+ }
+ }
+
+ static function displayPublicAnalysis($properties = array()) {
+ global $lang;
+ global $site_url;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+
+ $anketa = self::$sid;
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ self::Init($anketa);
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body style="margin:5px; padding:5px;" >';
+ echo '<h2>'.$lang['srv_publc_analysis_title_for'].self::$survey['naslov'].'</h2>';
+
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $anketa . '" />';
+ echo '<div id="analiza_data">';
+
+ if (isset($properties['profile_id_variable']))
+ {
+ self::$_PROFILE_ID_VARIABLE = $properties['profile_id_variable'];
+
+ SurveyVariablesProfiles::setCurrentProfileId(self::$_PROFILE_ID_VARIABLE);
+ }
+
+ if (isset($properties['profile_id_condition']))
+ {
+ self::$_PROFILE_ID_CONDITION = $properties['profile_id_condition'];
+
+ SurveyConditionProfiles::setCurrentProfileId(self::$_PROFILE_ID_CONDITION);
+ }
+
+
+ self::$printPreview = true;
+
+ # ponastavimo nastavitve- filter
+ self::Display();
+ echo '</div>';
+
+ echo '<div id="navigationBottom" class="printHide">';
+
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/printer.png" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<span class="spaceRight floatRight printHide" style="margin-top:6px;">';
+ echo '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url2.'" target="_blank"><span class="faicon rtf"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url3.'" target="_blank"><span class="faicon xls"></span></a>';
+ echo '</span>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+
+ echo '</body>';
+ echo '</html>';
+ }
+
+ static function heatmapGraph($spid,$_from, $lokacija=false, $heatmap=false) {
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+ $anketa = self::$sid;
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+
+ $_cols = $spremenljivka['cnt_all'] / $spremenljivka['cnt_grids'];
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ // $num_show_records = $_max_answers_cnt <= (int)$num_show_records ? $_max_answers_cnt : $num_show_records;
+
+ $_answers = self::getAnswers($spremenljivka,$num_show_records);
+
+ $_all_valid_answers_cnt = $_answers['validCnt'];
+ $_valid_answers = $_answers['valid'];
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ //self::displaySpremenljivkaIcons($spid);
+ }
+
+ //echo '<div class="heatmapGrapshContainer" style=" width: 800px; text-align:center; margin-left:auto; margin-right:auto;">';
+ echo '<div class="heatmapGrapshContainer" style=" width: 600px; text-align:center; margin-left:auto; margin-right:auto;">';
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_bb tbl_clps">';
+ # naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ //echo self::showVariable($spid, $spremenljivka['variable']);
+ echo $spremenljivka['variable'].' - '.$spremenljivka['naslov'];
+ echo '</td>';
+
+ echo '</tr>';
+ echo '<tr>';
+ #variabla
+
+ // konec naslovne vrstice
+
+ $_answersOther = array();
+ $_grids_count = count($spremenljivka['grids']);
+ if ($_grids_count > 0) {
+
+ $_css_bck = 'anl_bck_desc_2 anl_ac anl_bt_dot ';
+ $last = 0;
+ //anl_bck_desc_2 anl_bl anl_br anl_variabla_sub
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $_variables_count = count($grid['variables']);
+ echo '<tr class="'.$_css_bck.'">';
+ echo '<td class="anl_bl anl_br anl_variabla_sub">';
+ if($heatmap){
+ //echo $grid['naslov'].'<br>';//ni potrebno, ker je ze v glavi?
+ $sprid = explode('_',$spid);
+ $loopid = $sprid[1];
+ $sprid = $sprid[0];
+ SurveyUserSession::Init($anketa);
+
+ $heatmapId = 'heatmap'.$sprid;
+ //echo $heatmapId;
+
+ echo '<a class="fHeatMap" id="heatmap_'.$sprid.'" title="'.$lang['srv_view_data_on_map'].
+ '" href="javascript:void(0);" onclick="passHeatMapData('.$sprid.', -1, '.$loopid.', '.$anketa.');">';
+ //echo '<img src="img_0/Google_Maps_Icon.png" alt="Smiley face" height="24" width="24" />';
+ echo 'Heatmap';
+ echo '</a>';
+ }
+ echo '</td>';
+
+
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+ echo '</div>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ // ikone za izvoz za heatmap porocila
+ static function displayExportIcons4Heatmap($spid, $anketa){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = self::$_HEADERS[$spid];
+
+ $loop = (isset(self::$_CURRENT_LOOP)) ? self::$_CURRENT_LOOP['cnt'] : 'undefined';
+
+ // linki
+ echo '<div class="chart_setting_exportLinks">'.$lang['srv_export_as'].': ';
+
+ //Izvoz heatmap slike
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=heatmap_image&anketa='.$anketa.'&sprID='.$spid.'&loop='.$loop).'" target="_blank" onclick="exportHeatmapAsImage(\''.$spid.'\');" class="srv_ico" title="'.$lang['heatMapGenerateImage'].'"><span class="sprites heatmapImageSave"></span></a>';
+
+ //Izvoz heatmap slike v pdf
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=heatmap_image_pdf&anketa='.$anketa.'&sprID='.$spid.'&loop='.$loop) . '" target="_blank" onclick="exportHeatmapAsImage(\''.$spid.'\');" title="'.$lang['PDF_Izpis'].'" class="srv_ico"><span class="faicon pdf"></span></a>';
+
+ //Izvoz heatmap slike v rtf
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=heatmap_image_rtf&anketa='.$anketa.'&sprID='.$spid.'&loop='.$loop) . '" target="_blank" onclick="exportHeatmapAsImage(\''.$spid.'\');" title="'.$lang['RTF_Izpis'].'" class="srv_ico"><span class="faicon rtf"></span></a>';
+
+ //Izvoz heatmap slike v ppt
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=heatmap_image_ppt&anketa='.$anketa.'&sprID='.$spid.'&loop='.$loop) . '" target="_blank" onclick="exportHeatmapAsImage(\''.$spid.'\');" title="'.$lang['PPT_Izpis'].'" class="srv_ico"><span class="faicon ppt"></span></a>';
+
+ echo '</div>';
+ }
+
+ /** Izriše tekstovne odgovore kot tabelo za heatmap
+ *
+ * @param unknown_type $spid
+ */
+ static function sumMultiTextHeatMap($spid,$_from, $lokacija=false, $heatmap=false) {
+ global $lang;
+
+ $RegionPresent = true;
+ $spremenljivka = self::$_HEADERS[$spid];
+ $anketa = self::$sid;
+
+ # preverimo ali prikazujemo spremenljivko, glede na veljavne odgovore in nastavitev
+ $only_valid = 0;
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ # dodamo dodatne vrstice z albelami grida
+ if (count($grid['variables']) > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $only_valid += (int)self::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ }
+ }
+ if (SurveyDataSettingProfiles :: getSetting('hideEmpty') == 1 && $only_valid == 0 && self::$_forceShowEmpty == false) {
+ return;
+ }
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+
+ $_cols = $spremenljivka['cnt_all'] / $spremenljivka['cnt_grids'];
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = self::getNumRecords();
+
+ // $num_show_records = $_max_answers_cnt <= (int)$num_show_records ? $_max_answers_cnt : $num_show_records;
+
+ $_answers = self::getAnswers($spremenljivka,$num_show_records);
+
+ $_all_valid_answers_cnt = $_answers['validCnt'];
+ $_valid_answers = $_answers['valid'];
+
+ if (self :: $show_spid_div == true) {
+ echo '<div id="sum_'.$spid.'" loop="'.self::$_CURRENT_LOOP['cnt'].'" class="div_sum_variable div_analiza_holder">';
+ }
+
+ self::displaySpremenljivkaIcons($spid);
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_bb tbl_clps">'; //zacetek tabele
+ # 1. vrstica - naslovna vrstica
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck_freq_1 anl_w110">';
+ echo self::showVariable($spid, $spremenljivka['variable']);
+ echo '</td>';
+ #odgovori
+ //echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="'.(!$lokacija ? (self::$_SHOW_LEGENDA ? 3+$_cols : 1+$_cols) : 3+$_cols).'"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+ echo '<td class="anl_br anl_bb anl_al anl_bck_freq_1" colspan="6"><span class="anl_variabla_label">'.$spremenljivka['naslov'].'</span>';
+
+ echo '</td>';
+ echo '</tr>';
+ //konec 1. vrstice
+
+ //2. vrstica - prikazovanje povezave do heatmap
+ echo '<tr>';
+ #variabla
+ echo '<td class="anl_bl anl_br anl_bb anl_ac anl_bck anl_w110">';
+ //self::showIcons($spid,$spremenljivka,$_from); //za enkrat skrijem ikone za izvoze in druge moznosti
+ echo '</td>';
+ echo '<td class="anl_br anl_bb anl_ac" colspan="6">';
+ //echo $grid['naslov'].'<br>';//ni potrebno, ker je ze v glavi?
+ $sprid = explode('_',$spid);
+ $loopid = $sprid[1];
+ $sprid = $sprid[0];
+ SurveyUserSession::Init($anketa);
+
+ $heatmapId = 'heatmap'.$sprid;
+ //echo $heatmapId;
+ //SurveyChart::displayExportIcons($sprid);
+ echo '<a class="fHeatMap" id="heatmap_'.$sprid.'" title="'.$lang['srv_view_data_heatmap'].
+ '" href="javascript:void(0);" onclick="passHeatMapData('.$sprid.', -1, '.$loopid.', '.$anketa.');">';
+ //echo '<img src="img_0/Google_Maps_Icon.png" alt="Smiley face" height="24" width="24" />';
+ echo 'Heatmap ';
+ echo '</a>';
+
+ echo '</td>';
+ echo '</tr>';
+ //konec - 2. vrstice
+
+ //Koordinate
+ //naslovna vrstica za koordinate
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bck anl_bb anl_ac" colspan="7">';
+ echo '<b>'.$lang['srv_analiza_heatmap_clicked_coords'].'</b>';
+ echo '</td>';
+ echo '</tr>';
+ //naslovna vrstica za koordinate - konec
+ //vrstica s podnaslovi celic
+ echo '<tr>';
+ echo '<td class="anl_variabla_line anl_bl anl_br anl_bb anl_bck anl_ac">';
+ echo $lang['coordinates'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_bl anl_br anl_bb anl_bck anl_ac anl_w70">';
+ echo $lang['srv_analiza_opisne_valid_heatmap'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac anl_w70">';
+ echo $lang['srv_analiza_num_units_valid_heatmap'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac anl_w70">';
+ echo $lang['srv_means_label'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac anl_w70">';
+ echo $lang['srv_analiza_opisne_odklon'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac anl_w70">';
+ echo $lang['srv_analiza_opisne_min'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac anl_w70">';
+ echo $lang['srv_analiza_opisne_max'];
+ echo '</td>';
+ echo '</tr>';
+ //vrstica s podnaslovi celic - konec
+
+ //vrstica za x
+ echo '<tr>';
+ //1. stolpcev z imenom koordinate
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">';
+ echo 'x';
+ echo '</td>';
+ //1. stolpcev z imenom koordinate - konec
+
+ //2. stolpec - Veljavni
+ $validHeatmapRegion = self::validHeatmapRegion($spremenljivka['grids'], $spid, $_valid_answers);
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$validHeatmapRegion.'</td>';
+ //2. stolpec - Veljavni - konec
+
+ //3. stolpec - Ustrezni
+ $ustrezniHeatmapRegion = self::ustrezniHeatmapRegion($spid, $_valid_answers, $_sequence); //vsi mozni kliki
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$ustrezniHeatmapRegion.'</td>';
+ //3. stolpec - Ustrezni - konec
+
+ //4. stolpec - Povprecje
+ $povprecjeHeatmapClicksX = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'x', $validHeatmapRegion, 'povprecje'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$povprecjeHeatmapClicksX.'</td>';
+ //4. stolpec - Povprecje - konec
+
+ //5. stolpec - Standardni odklon
+ $stdevHeatmapClicksX = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'x', $validHeatmapRegion, 'stdev'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$stdevHeatmapClicksX.'</td>';
+ //5. stolpec - Standardni odklon - konec
+
+ //6. stolpec - Minimum
+ $minHeatmapClicksX = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'x', $validHeatmapRegion, 'min'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$minHeatmapClicksX.'</td>';
+ //6. stolpec - Minimum - konec
+
+ //7. stolpec - Max
+ $maxHeatmapClicksX = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'x', $validHeatmapRegion, 'max'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$maxHeatmapClicksX.'</td>';
+ //7. stolpec - Max - konec
+
+ echo '</tr>';
+ //vrstica za x - konec
+
+ //vrstica za y
+ echo '<tr>';
+ //1. stolpcev z imenom koordinate
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">';
+ echo 'y';
+ echo '</td>';
+ //1. stolpcev z imenom koordinate - konec
+
+ //2. stolpec - Veljavni
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$validHeatmapRegion.'</td>';
+ //2. stolpec - Veljavni - konec
+
+ //3. stolpec - Ustrezni
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$ustrezniHeatmapRegion.'</td>';
+ //3. stolpec - Ustrezni - konec
+
+ //4. stolpec - Povprecje
+ $povprecjeHeatmapClicksY = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'y', $validHeatmapRegion, 'povprecje'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$povprecjeHeatmapClicksY.'</td>';
+ //4. stolpec - Povprecje - konec
+
+ //5. stolpec - Standardni odklon
+ $stdevHeatmapClicksY = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'y', $validHeatmapRegion, 'stdev'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$stdevHeatmapClicksY.'</td>';
+ //5. stolpec - Standardni odklon - konec
+
+ //6. stolpec - Minimum
+ $minHeatmapClicksY = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'y', $validHeatmapRegion, 'min'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$minHeatmapClicksY.'</td>';
+ //6. stolpec - Minimum - konec
+
+ //7. stolpec - Max
+ $maxHeatmapClicksY = self::formatNumber(self::heatmapClicksCalc($spremenljivka['grids'], $spid, $_valid_answers, 'y', $validHeatmapRegion, 'max'),SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$maxHeatmapClicksY.'</td>';
+ //7. stolpec - Max - konec
+
+ echo '</tr>';
+ //vrstica za y - konec
+
+ //Koordinate - konec
+
+ //preveri, ali je prisotno kaksno obmocje, nadaljuj izris tabele
+ $RegionPresent = self::HeatmapRegionPresence($spremenljivka['grids'], $spid, $_valid_answers);
+ //preveri, ali je prisotno kaksno obmocje, nadaljuj izris tabele - konec
+
+ if($RegionPresent){ //ce imamo obmocja
+ //3. vrstica - naslovna za obmocja
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bck anl_bb anl_ac" colspan="7">';
+ echo '<b>'.$lang['srv_analiza_heatmap_clicked_regions'].'</b>';
+ echo '</td>';
+ echo '</tr>';
+ //konec - 3. vrstice
+
+ $_answersOther = array();
+ $_grids_count = count($spremenljivka['grids']);
+ $_css_bck = 'anl_bck_desc_2 anl_ac anl_bt_dot ';
+ $last = 0;
+
+ if ($_grids_count > 0) {
+ $_row = $spremenljivka['grids'][0];
+ $indeks = 0;
+ //$veljavnaSkupnaFreq = 0;
+ if (count($_row['variables'])>0)
+ foreach ($_row['variables'] AS $rid => $_col ){
+
+ $_sequence = $_col['sequence']; # id kolone z podatki
+ if ($_col['other'] != true) {
+ echo '<tr>';
+ if($indeks == 0) //4. vrstica, naslovna vrstica
+ {
+ echo '<td class="anl_variabla_line anl_bl anl_br anl_bb anl_bck anl_ac" colspan="2">';
+ echo $lang['srv_hot_spot_regions_menu'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac">';
+ echo $lang['srv_analiza_opisne_frequency_heatmap'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac">';
+ echo $lang['srv_analiza_opisne_valid_heatmap'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac">';
+ echo '% - '.$lang['srv_analiza_opisne_valid_heatmap'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac">';
+ echo $lang['srv_analiza_num_units_valid_heatmap'];
+ echo '</td>';
+
+ echo '<td class="anl_variabla_line anl_br anl_bb anl_bck anl_ac">';
+ echo '% - '.$lang['srv_analiza_num_units_valid_heatmap'];
+ echo '</td>';
+ }else //od 5. vrstice dalje, kjer so po vrsticah obmocja in njihovi podatki
+ {
+ //1. stolpcev z imenom obmocja
+ echo '<td class="anl_bl anl_br anl_bb anl_ac" colspan="2">';
+ echo $_col['naslov'];
+ echo '</td>';
+ //1. stolpcev z imenom obmocja - konec
+
+ //2. stolpec - Frekvenca
+ $freqHeatmapRegion = self::freqHeatmapRegion($spremenljivka['grids'], $spid, $_valid_answers, $indeks);
+ $veljavnaSkupnaFreq = $veljavnaSkupnaFreq + $freqHeatmapRegion;
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$freqHeatmapRegion.'</td>';
+ //2. stolpec - Frekvenca - konec
+
+ //3. stolpec - Veljavni
+ //$validHeatmapRegion = self::validHeatmapRegion($spremenljivka['grids'], $spid, $_valid_answers);
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$validHeatmapRegion.'</td>';
+ //3. stolpec - Veljavni - konec
+
+ //4. stolpec - % Veljavni
+ $_procentValidHeatmapRegion = ($validHeatmapRegion > 0 ) ? 100*$freqHeatmapRegion / $validHeatmapRegion : 0;
+ $_procentValidHeatmapRegion = self::formatNumber($_procentValidHeatmapRegion, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$_procentValidHeatmapRegion.'</td>';
+ //4. stolpec - % Veljavni - konec
+
+ //5. stolpec - Ustrezni
+ $ustrezniHeatmapRegion = self::ustrezniHeatmapRegion($spid, $_valid_answers, $_sequence); //vsi mozni kliki
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$ustrezniHeatmapRegion.'</td>';
+ //5. stolpec - Ustrezni - konec
+
+ //6. stolpec - % Ustrezni
+ $_procentUstrezniHeatmapRegion = ($ustrezniHeatmapRegion > 0 ) ? 100*$freqHeatmapRegion / $ustrezniHeatmapRegion : 0;
+ $_procentUstrezniHeatmapRegion = self::formatNumber($_procentUstrezniHeatmapRegion, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'),'%');
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$_procentUstrezniHeatmapRegion.'</td>';
+ //6. stolpec - % Ustrezni - konec
+ }
+
+ //echo '</td>';
+ echo '</tr>';
+
+ //*********** Izris veljavnih in manjkajocih vrednosti
+ if($indeks != 0) //ce ni naslovna vrsticam je potrebno dodati se dodatne poglede veljavnih in manjkajocih vrednosti
+ {
+ echo '<tr>';
+ $counter = 0;
+ $options['isTextAnswer'] = false;
+ $manjkajoci = $ustrezniHeatmapRegion - $validHeatmapRegion;
+ $counter = self::outputSumaValidAnswerHeatmap($counter,$_sequence,$spid,$options, $validHeatmapRegion);
+
+ if (count(self::$_FREQUENCYS[$_sequence]['invalid'])> 0 ) {
+ foreach (self::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki niso 0
+ $counter = self::outputInvalidAnswerHeatmap($counter,$ikey,$iAnswer,$_sequence,$spid,$options, $manjkajoci);
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaInvalidAnswerHeatmap($counter,$_sequence,$spid,$options, $manjkajoci);
+ }
+ #izpišemo še skupno sumo
+ $counter = self::outputSumaHeatmap($counter,$_sequence,$spid,$options, $ustrezniHeatmapRegion);
+ echo '</tr>';
+ $veljavnaSkupnaFreq = 0;
+ }
+ //*********** Izris veljavnih in manjkajocih vrednosti - konec
+
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ $indeks++;
+ }
+ }
+ }
+ echo '</table>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && self::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div class="div_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+ }
+ }
+
+ if (self :: $show_spid_div == true) {
+ echo '</div>';
+ echo '<br/>';
+ }
+ }
+
+ static function freqHeatmapRegion($spremenljivkaGrids, $spid, $_valid_answers, $indeks, $export=0){
+ $steviloPodatkov = count($_valid_answers);
+ $freqHeatMapRegion = 0;
+ foreach ($spremenljivkaGrids AS $gid => $grid)
+ {
+ $_variables_count = count($grid['variables']);
+ if ($_variables_count > 0)
+ {
+ # preštejemo max vrstic na grupo
+ $_max_i = 0;
+ //$numObmocij = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_max_i = max($_max_i,min($num_show_records,self::$_FREQUENCYS[$_sequence]['validCnt']));
+ //$numObmocij++;
+ }
+
+ $indeksZaObmocja = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true)
+ {
+ #$_valid_cnt = count(self::$_FREQUENCYS[$_sequence]['valid']);
+
+ if (count($_valid_answers) > 0) {
+
+ foreach ($_valid_answers AS $answer) {
+ $_ans = $answer[$_sequence];
+
+ //if ($_ans != null && $_ans != '' && $indeksZaObmocja == count($_valid_answers)+$indeks) {
+ if ($_ans != null && $_ans != '' && $indeksZaObmocja >= count($_valid_answers)*$indeks && $steviloPodatkov != 0)
+ {
+ $freqHeatMapRegion = $freqHeatMapRegion + $_ans;
+ $steviloPodatkov--;
+ }
+ else {
+ if($export==0){
+ echo '&nbsp;';
+ }
+ }
+ $indeksZaObmocja++;
+ }
+ }
+ }
+
+ }
+
+ }
+ }
+ return $freqHeatMapRegion;
+ }
+
+ static function validHeatmapRegion($spremenljivkaGrids, $spid, $_valid_answers, $export=0){
+ $validHeatmapRegion = 0;
+ foreach ($spremenljivkaGrids AS $gid => $grid)
+ {
+ $_variables_count = count($grid['variables']);
+ if ($_variables_count > 0)
+ {
+ //$numObmocij = 0;
+ $brs = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true)
+ {
+ #$_valid_cnt = count(self::$_FREQUENCYS[$_sequence]['valid']);
+ if (count($_valid_answers) > 0) {
+ //echo '<script>console.log("count($_valid_answers):'.count($_valid_answers).'"); </script>';
+ //$brs = 0;
+ foreach ($_valid_answers AS $answer) {
+ $_ans = $answer[$_sequence];
+ $vejice = substr_count($_ans, ",");
+ if ($_ans != null && $_ans != '' && $vejice != 0)
+ {
+ //echo '<script>console.log("$_ans:'.$_ans.'"); </script>';
+ $brs = $brs + substr_count($_ans, "<br>");
+ //echo '<script>console.log("<br>s in $_ans:'.$brs.'"); </script>';
+ }
+ else {
+ if($export == 0){
+ echo '&nbsp;';
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ $validHeatmapRegion = $brs;
+ //echo '<script>console.log("validHeatmapRegion konec:'.$validHeatmapRegion.'"); </script>';
+ return $validHeatmapRegion;
+ }
+
+ static function ustrezniHeatmapRegion($spid, $_valid_answers, $_sequence){
+ $row = Cache::srv_spremenljivka($spid);
+ $spremenljivkaParams = new enkaParameters($row['params']);
+ $heatmap_num_clicks = ($spremenljivkaParams->get('heatmap_num_clicks') ? $spremenljivkaParams->get('heatmap_num_clicks') : 1);
+ return self::$_FREQUENCYS[$_sequence]['validCnt'] * $heatmap_num_clicks; //vrni vse mozne klike = stev. odgovorov * stev. moznih klikov
+ }
+
+ static function HeatmapRegionPresence($spremenljivkaGrids, $spid, $_valid_answers){
+ $HeatmapRegionPresence = false;
+ foreach ($spremenljivkaGrids AS $gid => $grid)
+ {
+ $_variables_count = count($grid['variables']);
+ if ($_variables_count > 0)
+ {
+ # preštejemo max vrstic na grupo
+ $_max_i = 0;
+ //$numObmocij = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_max_i = max($_max_i,min($num_show_records,self::$_FREQUENCYS[$_sequence]['validCnt']));
+ //$numObmocij++;
+ }
+
+ $indeksZaObmocja = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true)
+ {
+ if (count($_valid_answers) > 0) {
+
+ foreach ($_valid_answers AS $answer) {
+ $_ans = $answer[$_sequence];
+ if ($_ans != null && $_ans != '' && $indeksZaObmocja >= count($_valid_answers))
+ {
+ $HeatmapRegionPresence = true;
+ }
+ $indeksZaObmocja++;
+ }
+ }
+ }
+
+ }
+
+ }
+ }
+ return $HeatmapRegionPresence;
+ }
+
+ static function heatmapClicksCalc($spremenljivkaGrids, $spid, $_valid_answers, $coords, $veljavnikliki, $what, $export=0){
+ $heatmapClicksCalc = 0;
+ $stdevCoordsArray = array();
+ $minCoords = 0;
+ $maxCoords = 0;
+ foreach ($spremenljivkaGrids AS $gid => $grid)
+ {
+ $_variables_count = count($grid['variables']);
+ if ($_variables_count > 0)
+ {
+ # preštejemo max vrstic na grupo
+ $_max_i = 0;
+ //$numObmocij = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_max_i = max($_max_i,min($num_show_records,self::$_FREQUENCYS[$_sequence]['validCnt']));
+ //$numObmocij++;
+ }
+
+ $indeksZaObmocja = 0;
+ foreach ($grid['variables'] AS $vid => $variable )
+ {
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($variable['other'] != true)
+ {
+ #$_valid_cnt = count(self::$_FREQUENCYS[$_sequence]['valid']);
+
+ if (count($_valid_answers) > 0) {
+
+ foreach ($_valid_answers AS $answer) {
+ $_ans = $answer[$_sequence];
+ if ($_ans != null && $_ans != '' && $_ans >= 0 && $indeksZaObmocja < count($_valid_answers))
+ {
+ //$validHeatmapRegion = $validHeatmapRegion + $_ans;
+ //echo '<td>'.$_ans.'</td>';
+ $_ans = substr($_ans, 4); //odstrani <br> iz zacetka koordinat
+ $coordinates = explode('<br>',$_ans);
+ foreach($coordinates AS $key => $coordinate){
+ $coordinate = explode(',',$coordinate);
+ foreach($coordinate AS $coordskey => $subcoords)
+ {
+ if($coords == 'x' && ($coordskey == 0 || $coordskey%2 == 0) )
+ {
+ array_push($stdevCoordsArray, $subcoords);
+ }else if($coords == 'y' && ($coordskey != 0 || $coordskey%2 != 0) )
+ {
+ array_push($stdevCoordsArray, $subcoords);
+ }
+ }
+ }
+ }
+ else {
+ if($export == 0){
+ echo '&nbsp;';
+ }
+ }
+ $indeksZaObmocja++;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if($what == 'povprecje')
+ {
+ $heatmapClicksCalc = array_sum($stdevCoordsArray) / count($stdevCoordsArray);
+ }else if($what == 'stdev')
+ {
+ if(is_array($stdevCoordsArray)){
+ $mean = array_sum($stdevCoordsArray) / count($stdevCoordsArray);
+ foreach($stdevCoordsArray as $key => $num) $devs[$key] = pow($num - $mean, 2);
+ if(count($devs) != 1)
+ $heatmapClicksCalc = sqrt(array_sum($devs) / (count($devs) - 1));
+ }
+ }else if($what == 'min')
+ {
+ $heatmapClicksCalc = min($stdevCoordsArray);
+ }else if($what == 'max')
+ {
+ $heatmapClicksCalc = max($stdevCoordsArray);
+ }
+
+ return $heatmapClicksCalc;
+ }
+
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyAnalysisArchive.php b/admin/survey/classes/surveyAnalysis/class.SurveyAnalysisArchive.php
new file mode 100644
index 0000000..6d937c5
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyAnalysisArchive.php
@@ -0,0 +1,1264 @@
+<?php
+/**
+* @author Gorazd Veselič
+* @date May 2010
+*
+* Funkcije za arhive analiz
+*
+* Polja v tabeli - srv_analysis_archive:
+* - id int(11) NOT NULL auto_increment # id arhiva
+* - sid int(11) NOT NULL default 0, # id ankete
+* - uid int(11) NOT NULL default 0, # id uporabnika kateri je skreiral arhiv
+* - name varchar(200) NOT NULL, # dodaljeno ime arhiva
+* - filename varchar(50) NOT NULL, # dodeljeno ime datoteke na FS
+* - date datetime NOT NULL, # datum kreacije
+* - note varchar(200) NOT NULL, # opomba
+* - access TINYINT NOT NULL DEFAULT 0; # 0 - vidijo vsi, 1 - vidijo samo uporabniki z dostopom
+* - type TINYINT NOT NULL DEFAULT 0; # 0 - sumarnik, 1 - opisne, 2 - frekvence, 3 - crostabi, 4 - means, 5 - ttest, 6 - break, 7 - charts, 8 - creport
+* - duration date NOT NULL; # datum do kdaj je arhiv aktiven, potem se briše iz baze in FS
+* - editid int(11) NOT NULL default 0; # id avtorja ki je zadnji spremnijal
+*
+*/
+
+
+define("SAA_FOLDER", "AnalysisArchive");
+define("DEFAULT_DURATION", " +3 month"); // privzet čas trajanja athiva
+
+class SurveyAnalysisArchive {
+
+
+ static private $sid;
+
+ // konstrutor
+ protected function __construct() {}
+ // kloniranje
+ final private function __clone() {}
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ static function Init( $anketa = null )
+ {
+ if ($anketa)
+ self::$sid = $anketa;
+
+ # pobrišemo linke, ki so pretekli
+ $s = sisplet_query("SELECT id FROM srv_analysis_archive WHERE date_add(duration, INTERVAL 1 DAY) < NOW()");
+ while ($row = mysqli_fetch_assoc($s)) {
+ $successDelete = self::DoDeleteArchive($row['id']);
+ }
+ }
+
+ /**
+ * @desc Vrne ID trenutnega uporabnika (ce ni prijavljen vrne 0)
+ */
+ static function uid() {
+ global $global_user_id;
+
+ return $global_user_id;
+ }
+
+ static function ListArchive($fields=array()) {
+ global $lang, $site_url;
+ $defaultFields = array(
+ 'create_new'=>true, #fieldset z linkom za generiranje novega arhiva
+ 'delete'=>true, #stolpec delete
+ 'edit'=>true, #stolpec editiraj
+ 'email'=>true, #stolpec pošlji po mailu
+ 'name'=>true, #stolpec ime
+ 'note'=>true, #stolpec opomba
+ 'date'=>true, #stolpec datum
+ 'access'=>true, #stolpec access (dostop) # 0 - vsi, 1 - uporabniki iz srv_dostop
+ 'type'=>true, #stolpec type (vrsta analize) # 0 - sumarnik, 1 - opisne, 2 - frekvence, 3 - crostabi, 4 - means, 5 - ttest, 6 - break, 7 - charts, 8 - creport
+ 'name_link' => true,#ali se ime pokaže kot link
+ 'duration' => true, #stolpec trajanje (duration)
+ 'insert' => true, #stolpec autor
+ 'edit' => true #stolpec spreminajl
+
+ );
+ $ArchiveTypes = array(M_ANALIZA_SUMS => 0, M_ANALIZA_DESCRIPTOR=>1, M_ANALIZA_FREQUENCY=>2, M_ANALIZA_CROSSTAB=>3, M_ANALYSIS_MEANS=>4, M_ANALYSIS_TTEST=>5, M_ANALYSIS_BREAK=>6, M_ANALYSIS_CHARTS=>7, M_ANALYSIS_CREPORT=>8);
+ #ponastavimo želene vrednosti
+ foreach ($fields AS $key => $value) {
+ $defaultFields[$key] = $value;
+ }
+
+ $users = array();
+ $qry = "SELECT saa.*, UNIX_TIMESTAMP(saa.date) as insert_date, UNIX_TIMESTAMP(saa.duration) as duration_d, DATEDIFF(saa.duration, CURDATE()) as days_left"
+ # da ne delamo vlkege poizvedbe kadar ni potrebno
+ . ($defaultFields['insert'] ? " , us1.name as iname, us1.surname as isurname, us1.email as iemail " : "" )
+ . ($defaultFields['edit'] ? " , us2.name as ename, us2.surname as esurname, us2.email as eemail " : "" )
+ . " FROM srv_analysis_archive as saa "
+ . ($defaultFields['insert'] ? " LEFT OUTER JOIN ( SELECT us1.name, us1.surname, us1.id, us1.email FROM users as us1 ) AS us1 ON us1.id = saa.uid " : "" )
+ . ($defaultFields['edit'] ? " LEFT OUTER JOIN ( SELECT us2.name, us2.surname, us2.id, us2.email FROM users as us2 ) AS us2 ON us2.id = saa.editid " : "" )
+ . " WHERE sid='".self::$sid."' ORDER BY date DESC";
+
+ $s = sisplet_query($qry);
+ if (mysqli_num_rows($s) > 0 ) {
+
+ if($defaultFields['create_new']){
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_archive_analysis'].'</legend>';
+
+ echo $lang['srv_analiza_archive_generate_quick'];
+
+ echo '</fieldset>';
+
+ echo '<br />';
+ }
+
+ echo '<table class="arch_tbl anl_bt anl_bl" style="width:100%">';
+ echo '<tr>';
+ if ($defaultFields['delete'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_delete'].'</td>';
+ if ($defaultFields['edit'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_edit'].'</td>';
+ if ($defaultFields['email'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_send'].'</td>';
+ if ($defaultFields['name'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_name'].'</td>';
+ if ($defaultFields['note'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_note'].'</td>';
+ if ($defaultFields['access'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_access'].'</td>';
+ if ($defaultFields['type'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_type'].'</td>';
+ if ($defaultFields['date'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_date'].'</td>';
+ if ($defaultFields['duration'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_duration'].'</td>';
+ if ($defaultFields['insert'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_author'].'</td>';
+ if ($defaultFields['edit'])
+ echo '<td class="anl_bck gray anl_bb anl_br anl_ac">'.$lang['srv_analiza_archive_lbl_editor'].'</td>';
+ echo '</tr>';
+
+ while ($row = mysqli_fetch_assoc($s)) {
+ echo '<tr id="AnalysisArchiveRow_'.$row['id'].'">';
+ if ($defaultFields['delete']) {
+ echo '<td class="anl_bb anl_br anl_ac">';
+ echo '<span>';
+ echo '<a href="/" onclick="AnalysisArchiveDelete(\'' . $row['id'] . '\'); return false;" title="">';
+ echo '<img src="img_0/delete_red.png" alt="" />';
+ echo '</a>';
+ echo '</span>';
+ echo '</td>';
+ }
+ if ($defaultFields['edit']) {
+ echo '<td class="anl_bb anl_br anl_ac">';
+ echo '<span>';
+ echo '<a href="/" onclick="AnalysisArchiveEdit(\'' . $row['id'] . '\'); return false;" title="">';
+ echo '<img src="img_0/edit.png" alt="" />';
+ echo '</a>';
+ echo '</span>';
+ echo '</td>';
+ }
+ if ($defaultFields['email']) {
+ echo '<td class="anl_bb anl_br anl_ac">';
+ echo '<span>';
+ echo '<a href="/" onclick="emailArchiveAnaliza(\'' . $row['id'] . '\'); return false;" title="">';
+ echo '<img src="icons/icons/email_link.png" alt="" />';
+ echo '</a>';
+ echo '</span>';
+ echo '</td>';
+ }
+ if ($defaultFields['name']) {
+ echo '<td class="anl_bb anl_br">';
+ echo '<span>';
+ if ($defaultFields['name_link']) {
+ echo '<a href="'.$site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='. $row['id'] . '" target="_blank" title="' . $row['name'] . '">';
+ echo $row['name'];
+ echo '</a>';
+ } else {
+ echo $row['name'];
+ }
+ echo '</span>';
+
+ echo '</td>';
+ }
+ if ($defaultFields['note']) {
+ echo '<td class="anl_bb anl_br">'.$row['note'].'</td>';
+ }
+ if ($defaultFields['access']) {
+ echo '<td class="anl_bb anl_br">'.$lang['srv_analiza_arhiviraj_access_'.$row['access']].'</td>';
+ }
+ if ($defaultFields['type']) {
+ $key = $lang['srv_analiza_arhiviraj_type_'.$row['type']];
+ echo '<td class="anl_bb anl_br anl_ac">'.$key.'</td>';
+ }
+ if ($defaultFields['date']) {
+ echo '<td class="anl_bb anl_br anl_ac" title="'.date('d.m.Y H:m:s',$row['insert_date']).'">';
+ echo date('d.m.Y',$row['insert_date']);
+ echo '</td>';
+ }
+ if ($defaultFields['duration']) {
+ # koliko dni damo v title
+ $days = ($row['days_left'] == 1)
+ ? $lang['1day']
+ : $row['days_left'].' '.$lang['hour_days'];
+ echo '<td class="anl_bb anl_br anl_ac" title="'.$days.'">';
+ echo date('d.m.Y',$row['duration_d']);
+ echo '</td>';
+ }
+ if ($defaultFields['insert']) {
+ $users = array();
+ echo '<td class="anl_bb anl_br" title="'.$row['iname'].' '.$row['isurname'].'">';
+ echo $row['iemail'];
+ echo '</td>';
+ }
+ if ($defaultFields['edit']) {
+ echo '<td class="anl_bb anl_br" title="'.$row['ename'].' '.$row['esurname'].'">';
+ echo $row['eemail'];
+ echo '</td>';
+ }
+ echo '</tr>';
+ }
+ echo '</table>';
+ }
+ else {
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_archive_analysis'].'</legend>';
+
+ echo $lang['srv_analiza_archive_note_no_archive'];
+ echo '<br/><br/>';
+ echo $lang['srv_analiza_archive_generate_quick'];
+
+ echo '</fieldset>';
+ }
+ }
+
+ /** Skreira tekstovni fajl in shrani zapis o fajlu v bazo.
+ *
+ * @param unknown_type $content
+ * @param unknown_type $name
+ */
+ static function CreateArchive($content,$name=null, $note=null, $access='0',$type=null,$duration=null,$durationType='0',$settings=array(), $access_password=null) {
+ global $site_path, $site_url, $global_user_id, $lang;
+
+ #če ni imena ga zgeneriramo
+ if ($name==null) {
+
+ $name = 'Arhiv: '.date("d.m.Y H:i:s");
+ }
+ $folder = $site_path . 'admin/survey/'.SAA_FOLDER.'/';
+ $filename = 'saa_'.self::$sid.'_'.time().'.txt';
+
+ # če imamo durationType = 2, imamo trajen arhiv (do leta 2038 - max za 32bit server)
+ if ($durationType == 2) {
+ $duration = strtotime(date("d.m.Y", strtotime('1.1.2038')));
+ }
+ else{
+ # če imamo durationType = 0, imamo privzet interval 3 mesece
+ if ($durationType == 0) {
+ $duration = null;
+ }
+ if ( $duration == null ) { #če ni časa trajanja ga zgeneriramo
+ $duration = date("Y-m-d");// current date
+ $duration = strtotime(date("Y-m-d", strtotime($duration)) . DEFAULT_DURATION);
+ } else { # če je ga pretvorimo v datum
+ $duration = strtotime(date("d.m.Y", strtotime($duration)));
+ }
+ }
+ $duration = date("Y-m-d",$duration);
+
+ $settings = serialize($settings);
+ #dodamo zapis o arhivu v bazo
+ $s = sisplet_query("INSERT INTO srv_analysis_archive (sid, uid, name, filename, date, note, access, type, duration, editid, settings, access_password) "
+ ."VALUES ('".self::$sid."', '$global_user_id', '$name', '$filename', NOW(), '$note', '$access', '$type', '$duration', '$global_user_id', '$settings', '$access_password')");
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+
+ // Na zacetek dodamo glavo -> po novem se shrani v file
+ SurveyInfo::getInstance()->SurveyInit(self::$sid);
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('akronim');
+ if ($naslov == null || trim($naslov) == '') {
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('naslov');
+ }
+
+ $text = '<div id="arch_body_div">';
+
+ SurveySetting::getInstance()->Init(self::$sid);
+ $survey_hide_title = SurveySetting::getInstance()->getSurveyMiscSetting('survey_hide_title');
+
+ // Ce ne prikazujemo naslova ankete to skrijemo
+ if($survey_hide_title == 0){
+ $text .= '<div class="arch_head_date">'
+ .$lang['srv_analiza_archive_date_created']
+ .date("d.m.Y")
+ .'</div><h2>'.$naslov.'</h2>';
+ }
+
+ // Porocilo po meri ima custom naslov
+ $text .= ($survey_hide_title == 1) ? '<h2>' : '<h3>';
+ if($type == 8){
+ $SCR = new SurveyCustomReport(self::$sid);
+ $creport_title = $SCR->getTitle();
+ $text .= $creport_title;
+ }
+ else{
+ $text .= $lang['srv_analiza_archive_title'].$lang['srv_analiza_arhiviraj_type_'.$type];
+ }
+ $text .= ($survey_hide_title == 1) ? '</h2>' : '</h3>';
+
+ $content = $text.$content;
+
+
+ if ($id) { # če smo dodali zapis v bazo shranimo še datoteko
+ # zapišemo fajl na disk
+ $fh = fopen($folder.$filename, 'w') or die("can't open file");
+ fwrite($fh, $content);
+ fclose($fh);
+
+ }
+ self :: DisplayCreatedArchive($id,$name);
+ }
+
+ static function DisplayDoArchive() {
+ global $lang, $site_url;
+
+ echo '<div id="div_analiza_archive_name" class="divPopUp">'."\n";
+
+ echo '<div class="popup_close"><a href="#" onClick="cancleArchiveAnaliza(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_analiza_arhiv'].'</h2>';
+
+ echo $lang['srv_analiza_arhiviraj_ime'];
+ echo ':&nbsp;<input id="newAnalysisArchiveName" name="newAnalysisArchiveName" type="text" size="60" />'."\n";
+
+ echo '<br class="clr" />';
+
+ echo '<div>';
+ echo $lang['srv_analiza_archive_note'].':';
+ echo '<textarea name="newAnalysisArchiveNote" id="newAnalysisArchiveNote" style="height:50px; width:100%"></textarea>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ echo '<div>';
+ // dostop
+ echo '<div class="floatLeft">';
+ echo $lang['srv_analiza_archive_access'].':';
+ echo '<br/><input type="radio" name="newAnalysisArchiveAccess" value="0" checked="true" onchange="toggleAnalysisArchiveAccessPassword();"/>&nbsp;'.$lang['srv_analiza_archive_access_all'];
+ echo '<br/><input type="radio" name="newAnalysisArchiveAccess" value="1" onchange="toggleAnalysisArchiveAccessPassword();"/>&nbsp;'.$lang['srv_analiza_archive_access_admins'];
+ echo '<br/><input type="radio" name="newAnalysisArchiveAccess" value="2" onchange="toggleAnalysisArchiveAccessPassword();"/>&nbsp;'.$lang['srv_analiza_archive_access_password'];
+ echo '<br/><div id="newAnalysisArchiveAccessPasswordDiv" style="visibility: hidden;">'.$lang['srv_analiza_archive_access_password_label'].'<input type="text" name="newAnalysisArchiveAccessPassword" id="newAnalysisArchiveAccessPassword" maxlength="25" />';
+ echo '</div></div>';
+ echo '<div class="floatLeft anl_w110" >&nbsp;</div>';
+
+ // trajanje
+ echo '<div class="floatLeft">';
+ echo $lang['srv_analiza_archive_duration'].':';
+ echo '<br/>';
+ $date = date("Y-m-d");// current date
+ $duration = strtotime(date("Y-m-d", strtotime($date)) . " +3 month");
+ $duration = date("d.m.Y",$duration);
+ echo '<input type="radio" name="newAADurationType" id="newAADurationFixed" value="0" checked="true" />';
+ printf ($lang['srv_analiza_archive_duration_default'], $duration);
+ echo '<br/>';
+ echo '<input type="radio" name="newAADurationType" id="newAADurationUser" value="1" />'.$lang['srv_analiza_archive_duration_custom'].'&nbsp;<input id="newAnalysisArchiveDuration" type="text" name="newAnalysisArchiveDuration" value="' . $duration . '" disabled/>
+ <span class="faicon calendar_icon icon-as_link" id="duration_img"></span>
+ <script type="text/javascript">
+ Calendar.setup({
+ inputField : "newAnalysisArchiveDuration",
+ ifFormat : "%d.%m.%Y",
+ button : "duration_img",
+ singleClick : true
+ });
+ </script>
+ ';
+ echo '<br/>';
+ echo '<input type="radio" name="newAADurationType" id="newAADurationPermanent" value="2" />'.$lang['srv_permanent_archive'];
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+ echo '</div>';
+
+ echo '<div class="div_curent_archives">'."\n";
+ echo $lang['srv_analiza_current_archives'];
+ if (true) {
+ self :: ListArchive(array('create_new'=>false, 'delete'=>false, 'edit'=>false, 'email'=>false, 'access'=>false, 'note'=>false, 'type'=>true, 'access'=>false, 'name_link'=>true,'duration'=>false, 'insert'=>true, 'edit'=>false));
+ #self :: ListArchive(array('delete'=>false, 'edit'=>false, 'email'=>false, 'access'=>false, 'note'=>false, 'type'=>false, 'access'=>false, 'name_link'=>true, 'duration'=>false, 'insert'=>false, 'edit'=>false));
+ } else {
+ echo $lang['srv_analiza_no_current_archives'];
+ }
+
+ echo '</div>'."\n"; // end: div_curent_archives
+
+
+ if ($_GET['podstran'] == M_ANALYSIS_CROSSTAB || $_POST['podstran'] == M_ANALYSIS_CROSSTAB) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveCrosstabs(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ } else if ($_GET['podstran'] == M_ANALYSIS_MEANS || $_POST['podstran'] == M_ANALYSIS_MEANS) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveMeans(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ } else if ($_GET['podstran'] == M_ANALYSIS_TTEST || $_POST['podstran'] == M_ANALYSIS_TTEST) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveTTest(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ } else if ($_GET['podstran'] == M_ANALYSIS_BREAK || $_POST['podstran'] == M_ANALYSIS_BREAK) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveBreak(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ } else if ($_GET['podstran'] == M_ANALYSIS_CHARTS || $_POST['podstran'] == M_ANALYSIS_CHARTS) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveChart(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ } else if ($_GET['podstran'] == M_ANALYSIS_CREPORT || $_POST['podstran'] == M_ANALYSIS_CREPORT) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveCReport(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ } else {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_create'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="submitArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_create'].'</span></a></span></span>'."\n";
+ }
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_cancle'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="cancleArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_cancle'].'</span></a></span></span>'."\n";
+
+
+ echo '</div>'."\n"; // end div_analiza_archive_name
+ }
+
+ static function DisplayCreatedArchive($aid=null, $name) {
+ global $lang, $site_url;
+
+ echo '<div id="div_analiza_archive_name" class="divPopUp">'."\n";
+
+ echo '<div class="popup_close"><a href="#" onClick="closeArchiveAnaliza(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_analiza_arhiv'].'</h2>';
+
+ $CAE = self::CheckArchiveExistance($aid);
+ if ( $CAE > 0) {
+ echo '<div>';
+ printf( $lang['srv_analiza_arhiviraj_success'],$name);
+ echo '</div>';
+ echo '<br/>';
+
+ echo '<div>';
+ echo $lang['srv_analiza_arhiviraj_success_note'];
+ echo '<br/>';
+ echo '<span>';
+ echo '<a href="'.$site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='. $aid . '" target="_blank" title="">';
+ echo $site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='. $aid;
+ echo '</a>';
+ echo '</span>';
+ echo '</div>';
+
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_close'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="closeArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_close'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_send_mail'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="emailArchiveAnaliza(\''.$aid.'\'); return false;" ><span><img src="icons/icons/email_link.png" alt="" /> '.$lang['srv_analiza_arhiviraj_send_mail'].'</span></a></span></span>'."\n";
+ } else {
+ self::DisplayError($CAE);
+ }
+
+ # seznam arhivov
+ echo '<br class="clr" />';
+ echo '<div class="div_curent_archives">'."\n";
+ echo $lang['srv_analiza_current_archives'];
+ if (true) {
+ self :: ListArchive(array('delete'=>false, 'edit'=>false, 'email'=>false, 'access'=>false, 'note'=>false, 'type'=>true, 'access'=>false, 'name_link'=>true,'duration'=>false, 'insert'=>true, 'edit'=>false));
+ } else {
+ echo $lang['srv_analiza_no_current_archives'];
+ }
+ echo '</div>'."\n"; // end: div_curent_archives
+
+ echo '</div>'."\n"; // end div_analiza_archive_name
+ }
+
+ static function EmailArchive($aid) {
+ global $lang;
+
+ echo '<div id="div_analiza_archive_name" class="divPopUp">'."\n";
+
+ echo '<div class="popup_close"><a href="#" onClick="cancleArchiveAnaliza(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_analiza_arhiv'].'</h2>';
+
+ # preverimo obstoj datoteke, in dostop
+ $CAE = self::CheckArchiveExistance($aid);
+
+ if ( $CAE > 0) {
+ # vsebina emaila in naslovi
+ echo '<div id="div_archives_email_left">'."\n";
+
+ echo '<p>'.$lang['srv_analiza_archive_message_note'].'</p>';
+
+ echo '<div ><label for="email_archive_list">'.$lang['srv_analiza_archive_message_emails'].':</label>'."\n";
+ echo '<textarea name="email_archive_list" rows="4" id="email_archive_list" ></textarea>'."\n";
+ echo '</div>';
+
+ echo '<br>';
+
+ echo '<div class="anl_dash_bt">';
+ echo '<br/><label for="subject">' . $lang['subject'] . ': </label>';
+ echo '<input type="text" name="email_archive_subject" id="email_archive_subject" value="'.$lang['srv_analiza_arhiviraj_mail_subject'].'" size="90"/></p>';
+ echo '<p><label for="email_archive_text">' . $lang['text'] . ':</label>'."\n";
+
+ $signature = Common::getEmailSignature();
+ echo '<textarea name="email_archive_text" id="email_archive_text" rows="2" >' . nl2br($lang['srv_analiza_arhiviraj_mail_text'].$signature). '</textarea>'."\n";
+ echo '</div>';
+
+ echo '<script type="text/javascript">'."\n";
+ echo 'if ($("#email_archive_text")) {'."\n";
+ echo ' create_editor(\'email_archive_text\', false);'."\n";
+ echo '}'."\n";
+ echo '</script>'."\n";
+
+ echo '</div>'."\n";
+ #gumbi
+ echo '<div id="div_archives_email_right" >'."\n";
+
+ echo '<div id="div_archives_email_buttons">';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_do_send_mail'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="sendEmailArchiveAnaliza(\''.$aid.'\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_do_send_mail'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_close'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="cancleArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_close'].'</span></a></span></span>'."\n";
+ echo '<br class="clr" />';
+ echo '</div>';
+ echo '<div id="div_error">';
+ # navodila
+ echo $lang['srv_analiza_arhiviraj_mail_note_0'];
+ echo '</div>';
+ echo '<br/>';
+ echo '<br/>';
+ echo '<div id="div_error">';
+ # navodila
+ echo $lang['srv_analiza_arhiviraj_mail_note_1'];
+ echo '</div>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ } else {
+ self::DisplayError($CAE);
+ }
+ echo '</div>'."\n"; // end div_analiza_archive_name
+ }
+
+ static function SendEmailArchive($aid = null, $subject, $text, $emails) {
+ global $lang, $site_url, $site_path, $global_user_id;
+
+ echo '<div id="div_analiza_archive_name" class="divPopUp">'."\n";
+
+ echo '<div class="popup_close"><a href="#" onClick="cancleArchiveAnaliza(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_analiza_arhiv'].'</h2>';
+
+ $CAE = self::CheckArchiveExistance($aid);
+ if ( $CAE > 0) {
+ if (isset($emails) && trim($emails) != "") {
+ $_subject = ( isset($subject) && trim($subject) != "" )
+ ? stripcslashes ($subject)
+ : stripcslashes ($lang['srv_analiza_arhiviraj_mail_subject']);
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+
+ $_text = ( isset($text) && trim($text) != "" )
+ ? stripcslashes ($text)
+ : stripcslashes (nl2br($lang['srv_analiza_arhiviraj_mail_text'].$signature));
+
+ # polovimo podatke ankete
+ SurveyInfo::getInstance()->SurveyInit(self::$sid);
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ #polovimo podatke arhiva
+ $archQry = sisplet_query("SELECT date FROM srv_analysis_archive WHERE sid='".self::$sid."' AND id='".$aid."'");
+ $archRow = mysqli_fetch_assoc($archQry);
+
+ $userQry = sisplet_query("SELECT name, surname, id, email FROM users WHERE id='$global_user_id'");
+ $userRow = mysqli_fetch_assoc($userQry);
+
+ /* zamenjave
+ [LINK]</dt><dd>HTML povezava do arhiva
+ [URL]</dt><dd>URL povezave do arhiva
+ [NAME]</dt><dd>ime uporabnika (iz baze (CMS))
+ [SURVEY]</dt><dd>ime ankete
+ [DATE]</dt><dd>datum
+ [SITE]</dt><dd>URL do ankete</dd></dl>",
+ */
+ $in = array('[LINK]','[URL]','[NAME]','[SURVEY]','[DATE]','[SITE]');
+
+ $repl_link = '<a href="'.$site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='.$aid.'">'.$site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='.$aid.'</a>';
+ $repl_url = $site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='.$aid;
+ $repl_name = $userRow['name'].' '.$userRow['surname'].' ('.$userRow['email'].')';
+ $repl_survey = $row['naslov'];
+ $repl_date = $archRow['date'];
+ $repl_site = $site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid;
+
+ $out = array($repl_link,$repl_url,$repl_name,$repl_survey,$repl_date,$repl_site);
+
+ $_subject = str_replace($in,$out,$_subject);
+ $_text= str_replace($in,$out,$_text);
+
+ # v loopu pošljemo maile
+ $email_addresses = explode("\n", $emails);
+ if (count($email_addresses)) {
+
+ $status_success = array();
+ $status_error = array();
+ foreach ($email_addresses AS $email) {
+ $email = trim($email);
+ if (strlen ($email) > 1) {
+ // Posljemo mail vsakemu uporabniku posebej
+ try
+ {
+ $MA = new MailAdapter(self::$sid, $type='alert');
+ $MA->addRecipients($email);
+ $resultX = $MA->sendMail($_text, $_subject);
+ }
+ catch (Exception $e)
+ {
+ }
+
+ if ($resultX) {
+ $status_success[] = $email; // poslalo ok
+ } else {
+ $status_error[] = $email; // ni poslalo
+ }
+ }
+ } // end foreach
+
+ // zlistamo uspešne in neuspešne naslove
+ echo '<b>Sporočilo:</b><br/><br/>' . $_subject . ',<br/> ' . $_text . '<br/>';
+ if (count($status_success) > 0) {
+ echo '<b>je bilo uspešno poslano na naslednje naslove:<br/></b>';
+ foreach ($status_success as $email) {
+ echo $email . ",<br/>";
+ }
+ echo "<br/>";
+ }
+ if (count($status_error) > 0) {
+ echo '<br/><b>ni bilo uspešno poslano na naslednje naslove:<br/></b>';
+ foreach ($status_error as $email) {
+ echo $email . ",<br/>";
+ }
+ }
+
+ } else {
+ echo 'No email adress!';
+ }
+
+ } else {
+ echo 'Pri pošiljanju e-mailov je prišlo do napake!';
+ }
+
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_close'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="cancleArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_close'].'</span></a></span></span>'."\n";
+ echo '<br class="clr" />';
+ } else {
+ self::DisplayError($CAE);
+ }
+
+ echo '</div>'."\n"; // end div_analiza_archive_name
+ }
+
+ static function EditArchive($aid) {
+ global $lang, $site_url, $site_path, $global_user_id;
+
+ echo '<div id="div_analiza_archive_name" class="divPopUp">'."\n";
+
+ echo '<div class="popup_close"><a href="#" onClick="cancleArchiveAnaliza(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_analiza_arhiv'].'</h2>';
+
+ $CAE = self::CheckArchiveExistance($aid);
+ if ( $CAE > 0) {
+ # polovimo podatke o arhivu
+ $s = sisplet_query("SELECT *, UNIX_TIMESTAMP(duration) as duration_d FROM srv_analysis_archive WHERE id='".$aid."' AND sid='".self::$sid."'");
+ $row = mysqli_fetch_assoc($s);
+
+ echo $lang['srv_analiza_arhiviraj_ime'];
+ echo ':&nbsp;<input id="newAnalysisArchiveName" name="newAnalysisArchiveName" type="text" size="60" value="'.$row['name'].'"/>'."\n";
+
+ echo '<br class="clr" />';
+ echo '<div>';
+ echo $lang['srv_analiza_archive_note'].':';
+ echo '<textarea name="newAnalysisArchiveNote" id="newAnalysisArchiveNote" style="height:50px; width:100%">'.$row['note'].'</textarea>';
+ echo '</div>';
+ echo '<div>';
+ // dostop
+ echo '<div class="floatLeft">';
+ echo $lang['srv_analiza_archive_access'].':';
+ echo '<br/><input type="radio" name="newAnalysisArchiveAccess" value="0"'.((int)$row['access'] == 0 ? ' checked="true"' : '').' onchange="toggleAnalysisArchiveAccessPassword();"/>&nbsp;'.$lang['srv_analiza_archive_access_all'];
+ echo '<br/><input type="radio" name="newAnalysisArchiveAccess" value="1"'.((int)$row['access'] == 1 ? ' checked="true"' : '').' onchange="toggleAnalysisArchiveAccessPassword();"/>&nbsp;'.$lang['srv_analiza_archive_access_admins'];
+ echo '<br/><input type="radio" name="newAnalysisArchiveAccess" value="2"'.((int)$row['access'] == 2 ? ' checked="true"' : '').' onchange="toggleAnalysisArchiveAccessPassword();"/>&nbsp;'.$lang['srv_analiza_archive_access_password'];
+ echo '<br/><div id="newAnalysisArchiveAccessPasswordDiv" style="visibility: '.((int)$row['access'] == 2 ? 'visible' : 'hidden').';">'.$lang['srv_analiza_archive_access_password_label'].'<input type="text" name="newAnalysisArchiveAccessPassword" id="newAnalysisArchiveAccessPassword" maxlength="25" value="'.$row['access_password'].'"/>';
+ echo '</div></div>';
+
+ echo '<div class="floatLeft anl_w110" >&nbsp;</div>';
+ // trajanje
+ echo '<div class="floatLeft">';
+ echo $lang['srv_analiza_archive_duration'].':';
+ echo '<br/>';
+ echo '<input id="newAnalysisArchiveDuration" type="text" name="newAnalysisArchiveDuration" value="' . date('d.m.Y',$row['duration_d']) . '" disabled/>
+ <span class="faicon calendar_icon icon-as_link" id="duration_img"></span>
+ <script type="text/javascript">
+ Calendar.setup({
+ inputField : "newAnalysisArchiveDuration",
+ ifFormat : "%d.%m.%Y",
+ button : "duration_img",
+ singleClick : true
+ });
+ </script>
+ ';
+
+ echo '</div>';
+ echo '<div class="clr"></div>';
+ echo '</div>';
+
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="saveArchiveAnaliza(\''.$aid.'\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_close'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="cancleArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_close'].'</span></a></span></span>'."\n";
+ echo '<br class="clr" />';
+ } else {
+ self::DisplayError($CAE);
+ }
+ echo '</div>'."\n"; // end div_analiza_archive_name
+ }
+
+ static function SaveArchive($aid,$name,$note,$access,$duration,$access_password) {
+ global $lang, $site_url, $site_path, $global_user_id;
+
+ $CAE = self::CheckArchiveExistance($aid);
+ if ( $CAE > 0) {
+ if ($name==null || trim($name) == "") {
+ $name = 'Arhiv: '.date("d.m.Y H:i:s");
+ }
+
+ if ( $duration == null ) { #če ni časa trajanja ga zgeneriramo
+ $duration = date("Y-m-d");// current date
+ $duration = strtotime(date("Y-m-d", strtotime($duration)) . DEFAULT_DURATION);
+ } else { # če je ga pretvorimo v datum
+ $duration = strtotime(date("d.m.Y", strtotime($duration)));
+ }
+ # pripravimo pravilno obliko datuma za insert v bazo
+ $duration = date("Y-m-d",$duration);
+
+ $updated = sisplet_query("UPDATE srv_analysis_archive SET name= '$name', note='$note', access='$access', duration='$duration', editid='$global_user_id', access_password='$access_password' WHERE id = '$aid'");
+
+ echo $updated;
+ } else {
+ echo $CAE;
+ }
+
+ }
+
+ /**
+ *
+ * @param $aid
+ *
+ * @return -1 = invalid $aid
+ * @return -2 = file not exist
+ * @return -3 = no access
+ * @return -4 = invalid profile id
+ * @return -5 = no access, pass needed
+ */
+ static function CheckArchiveExistance($aid) {
+ global $site_path;
+
+ if ($aid < 1 || $aid == null || trim($aid) == "") {
+ # invalid $aid
+ return -1;
+ }
+
+ #podtki profila
+ $s = sisplet_query("SELECT filename, access FROM srv_analysis_archive WHERE id='".$aid."' AND sid='".self::$sid."'");
+ if ($_GET['debug'] == 1) {
+ print_r("SELECT * FROM srv_analysis_archive WHERE id='".$aid."' AND sid='".self::$sid."'");
+ }
+ if (mysqli_num_rows($s)) {
+
+ $row = mysqli_fetch_assoc($s);
+
+ # najprej preverimo obstoj datoteke
+ $filename = $site_path . 'admin/survey/'.SAA_FOLDER.'/'.$row['filename'];
+ if (file_exists($filename)) {
+ #preverimo dostop
+ if ($row['access'] == '0') {
+ return true;
+ } else {
+ # preverimo ali ima trenuten uid dostop do ankete
+ if (self::CheckArchiveAccess()) {
+ return true;
+ }
+ #dostop z geslom
+ elseif($row['access'] == '2'){
+ if(isset($_SESSION['archive_access'][$aid]) && $_SESSION['archive_access'][$aid] == '1')
+ #uporabnik je vpisal pravileno geslo
+ return true;
+ else
+ #uporabnik nima dostopa, za dostop vpogleda je potrebno geslo
+ return -5;
+ }
+ else {
+ # uporabnik nima dostopa
+ return -3;
+ }
+ }
+
+ } else { # return -2 => file not exist
+ # pobrišemo morebiten zapis iz baze
+ $sqlDelete = sisplet_query("DELETE FROM srv_analysis_archive WHERE id='".$aid."' AND sid='".self::$sid."'");
+
+ return -2;
+ }
+
+ } else {
+ #invalid profile ID;
+ return -4;
+ }
+ }
+
+ static function CheckArchiveAccess($uid=null) {
+ global $global_user_id, $admin_type;
+
+ if ($uid == null) {
+ $uid = $global_user_id;
+ }
+
+ #podtki dostopa
+ $a = sisplet_query("SELECT ank_id, uid FROM srv_dostop WHERE ank_id = '".self::$sid."' AND uid='".$uid."'");
+
+ if (mysqli_num_rows($a) || $admin_type === '0') {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+
+ static function ViewArchive($aid) {
+ global $site_path, $global_user_id, $lang, $site_url;
+
+ #izpišemo osnovni html
+ $sql = sisplet_query("SELECT * FROM misc WHERE what='name'");
+ $row = mysqli_fetch_array($sql);
+
+ // nastavimo jezik
+ if (self::$sid > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '".self::$sid."'");
+ $row = mysqli_fetch_array($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_array($sql);
+ $lang_admin = $row['value'];
+ }
+
+ // Naložimo jezikovno datoteko (da se datumin naslov izpiseta v pravem jeziku)
+ $file = '../../lang/'.$lang_admin.'.php';
+ include($file);
+ $_SESSION['langX'] = $site_url .'lang/'.$lang_admin.'.php';
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
+ echo '<head>'."\n";
+ echo '<title>'.$row['value'].'</title>'."\n";
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n";
+ echo '<script type="text/javascript" src="script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ if ($_GET['mode'] != 'old') {
+ echo '<script type="text/javascript" src="minify/g=jsnew"></script>'."\n";
+ } else {
+ echo '<script type="text/javascript" src="minify/g=js"></script>'."\n";
+ }
+ echo '<link type="text/css" href="minify/g=css" media="screen" rel="stylesheet" />'."\n";
+ echo '<link type="text/css" href="minify/g=cssPrint" media="print" rel="stylesheet" />'."\n";
+ echo '<style type="text/css">.iconHide{display:none;}</style>'."\n";
+
+ echo '</head>'."\n";
+ echo '<body id="arch_body" >'."\n";
+
+ #polovimo podatke ankete
+ SurveyInfo::getInstance()->SurveyInit(self::$sid);
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('akronim');
+ if ($naslov == null || trim($naslov) == '') {
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('naslov');
+ }
+
+ # podatki arhiva
+ $s = sisplet_query("SELECT filename, date, type FROM srv_analysis_archive WHERE id='".$aid."'");
+ $row = mysqli_fetch_assoc($s);
+
+ $CAE = self::CheckArchiveExistance($aid);
+
+ if ( $CAE > 0) {
+ $folder = $site_path . 'admin/survey/'.SAA_FOLDER.'/';
+
+
+ $fh = fopen($folder.$row['filename'], 'r');
+ $theData = fread($fh, filesize($folder.$row['filename']));
+ fclose($fh);
+
+ $in = array('\"', "\'");
+ $out = array('"', "'",);
+
+ $theData = str_replace($in, $out, $theData);
+
+ // Zaradi kompatibilnosti za nazaj -> ko se se ni naslov in datum shranjeval v file
+ if(substr($theData, 0, 24) != '<div id="arch_body_div">'){
+ echo '<div id="arch_body_div">'."\n";
+
+ echo '<div class="arch_head_date">';
+ echo $lang['srv_analiza_archive_date_created'];
+ $datetime = strtotime($row['date']);
+ echo date("d.m.Y",$datetime);
+ echo '</div>';
+
+ echo '<h2>'.$naslov.'</h2>';
+
+ echo '<h3>'.$lang['srv_analiza_archive_title'].$lang['srv_analiza_arhiviraj_type_'.$row['type']].'</h3>';
+ }
+
+ echo $theData;
+
+ }
+ else {
+ // Zaradi kompatibilnosti za nazaj -> ko se se ni naslov in datum shranjeval v file
+ if(substr(0, 25, $theData) != '<div id="arch_body_div">'){
+ echo '<div id="arch_body_div">'."\n";
+
+ echo '<div class="arch_head_date">';
+ echo $lang['srv_analiza_archive_date_created'];
+ $datetime = strtotime($row['date']);
+ echo date("d.m.Y",$datetime);
+ echo '</div>';
+ }
+
+ //to access, password is needed
+ if($CAE == -5){
+ // form for access with password
+ self::DisplayAccessPassword($aid);
+ }
+ //no access/other error
+ else{
+ // Izpišemo error
+ self::DisplayError($CAE,false);
+ }
+ }
+
+ #izpišemo še zaključek html
+ echo '</div>'."\n";
+ echo '</body>'."\n";
+ echo '</html>';
+ }
+
+ static function DisplayError($CAE, $showButton=true) {
+ global $lang;
+
+ echo '<div>';
+ echo $lang['srv_analiza_arhiviraj_error_'.$CAE];
+ echo '</div>';
+
+ if ($showButton) {
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_close'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="closeArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_close'].'</span></a></span></span>'."\n";
+ echo '<br class="clr" />';
+ }
+ }
+
+ /**
+ * Display from for password to access archive
+ * @global type $lang
+ * @param type $aid - archive id
+ */
+ static function DisplayAccessPassword($aid) {
+ global $lang, $site_url;
+
+ echo '<br><div style="float:left"><fieldset>';
+ echo '<legend>' . $lang['srv_analiza_archive_access'] . '</legend>';
+
+ echo '<form name="archive_access_pass_form" id="archive_access_pass_form" method="post" action="'.$site_url.'admin/survey/AnalysisArchive.php?anketa='.self::$sid.'&aid='. $aid . '">';
+ //echo '<input type="hidden" name="archive_id" value="' . $aid . '">';
+
+ //user insertet wrong password
+ if(isset($_SESSION['archive_access'][$aid]) && $_SESSION['archive_access'][$aid] == '0')
+ echo '<i class="red" id="archive_access_wrong_pass_warning">' . $lang['srv_analiza_archive_access_wrong_pass'] . '</i><br>';
+
+ echo '<br>'.$lang['srv_analiza_archive_access_password_label'].': ';
+ echo '<input type="password" name="archive_access_pass" id="archive_access_pass" maxlength="25" value="" /><br><br>';
+
+ echo '<span class="spaceRight floatLeft"><div class="buttonwrapper">'
+ . '<a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="$(\'#archive_access_pass_form\').submit();">';
+ echo $lang['srv_analiza_archive_access_button'];
+ echo '</a></div></span><br><br>';
+ echo '</form></fieldset></div>';
+ }
+
+ /**
+ * Check if archive access password matches
+ * @return boolean
+ */
+ static function CheckArchiveAccessPass() {
+ $sql = sisplet_query("SELECT access_password AS pass FROM srv_analysis_archive WHERE id = '".$_POST['archive_id']."'");
+ if($sql){
+ $row = mysqli_fetch_array($sql);
+ if($row['pass'] == $_POST['archive_access_pass'])
+ return true;
+ else
+ return false;
+ }
+ return false;
+ }
+
+ static function AskDeleteArchive($aid) {
+ global $lang;
+
+ echo '<div id="div_analiza_archive_name" class="divPopUp">'."\n";
+
+ $CAE = self::CheckArchiveExistance($aid);
+
+ if ( $CAE > 0) {
+ echo '<h2>Ali ste prepričani?</h2>';
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_delete'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="doDeleteArchiveAnaliza(\''.$aid.'\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_delete'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper" title="'.$lang['srv_analiza_arhiviraj_cancle'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="cancleArchiveAnaliza(); return false;"><span>'.$lang['srv_analiza_arhiviraj_cancle'].'</span></a></span></span>'."\n";
+
+ echo '<br class="clr" />';
+ }
+ else {
+ #izpišemo error
+ self::DisplayError($CAE,true);
+ }
+
+ echo '</div>'."\n"; // end: div_analiza_archive_name
+ }
+
+ static function DoDeleteArchive($aid) {
+ global $site_path;
+
+ $CAE = self::CheckArchiveExistance($aid);
+
+ if ( $CAE > 0) {
+ $sqlSelect = sisplet_query("SELECT filename FROM srv_analysis_archive WHERE id='".$aid."' AND sid='".self::$sid."'");
+ $rowSelect = mysqli_fetch_assoc($sqlSelect);
+
+ #izbrišemo datoteko
+ $filename = $site_path . 'admin/survey/'.SAA_FOLDER.'/'.$rowSelect['filename'];
+ unlink($filename);
+
+ #izbrišemo zapis iz baze
+ $sqlDelete = sisplet_query("DELETE FROM srv_analysis_archive WHERE id='".$aid."' AND sid='".self::$sid."'");
+ return 1;
+ } else {
+ #vrnemo error
+ return $CAE;
+ }
+ }
+
+ static function archiveCrosstabBeforeEmail() {
+ global $site_path, $site_url, $global_user_id, $lang;
+
+ $ArchiveTypes = array(M_ANALIZA_SUMS => 0, M_ANALIZA_DESCRIPTOR=>1, M_ANALIZA_FREQUENCY=>2, M_ANALIZA_CROSSTAB=>3, M_ANALYSIS_MEANS=>4, M_ANALYSIS_TTEST=>5, M_ANALYSIS_BREAK=>6, M_ANALYSIS_CHARTS=>7, M_ANALYSIS_CREPORT=>8);
+ if (isset($_POST['podstran'])) {
+ $type = $ArchiveTypes[$_POST['podstran']];
+ }
+
+ $content = $_POST['content'];
+
+ if (isset($content) && trim($content) != null) {
+
+ #ime zgeneriramo
+ $name = 'Arhiv: '.date("d.m.Y H:i:s");
+ $access = 0;
+
+ $folder = $site_path . 'admin/survey/'.SAA_FOLDER.'/';
+ $filename = 'saa_'.self::$sid.'_'.time().'.txt';
+
+ #če ni časa trajanja ga zgeneriramo
+ $duration = date("Y-m-d");// current date
+ $duration = strtotime(date("Y-m-d", strtotime($duration)) . DEFAULT_DURATION);
+ # pripravimo pravilno obliko datuma za insert v bazo
+ $duration = date("Y-m-d",$duration);
+
+ #dodamo zapis o arhivu v bazo
+ $s = sisplet_query("INSERT INTO srv_analysis_archive (sid, uid, name, filename, date, note, access, type, duration, editid) "
+ ."VALUES ('".self::$sid."', '$global_user_id', '$name', '$filename', NOW(), '', '$access', '$type', '$duration', '$global_user_id')");
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+
+ // Na zacetek dodamo glavo -> po novem se shrani v file
+ SurveyInfo::getInstance()->SurveyInit(self::$sid);
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('akronim');
+ if ($naslov == null || trim($naslov) == '') {
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('naslov');
+ }
+
+ $text = '<div id="arch_body_div"><div class="arch_head_date">'
+ .$lang['srv_analiza_archive_date_created']
+ .date("d.m.Y")
+ .'</div><h2>'.$naslov.'</h2>';
+
+ $text .= '<h3>'.$lang['srv_analiza_archive_title'].$lang['srv_analiza_arhiviraj_type_'.$type].'</h3>';
+
+ $content = $text.$content;
+
+
+ if ($id > 0) { # če smo dodali zapis v bazo shranimo še datoteko
+ # zapišemo fajl na disk
+ $fh = fopen($folder.$filename, 'w') or die("can't open file");
+ fwrite($fh, $content);
+ fclose($fh);
+
+ echo $id;
+ return $id;
+
+ } else {
+ echo 0;
+ return 0;
+ }
+ } else {
+ echo '-1';
+ return '-1';
+ }
+ }
+
+ static function createArchiveBeforeEmail() {
+ global $site_path, $site_url, $global_user_id, $lang;
+
+ $ArchiveTypes = array(M_ANALIZA_SUMS => 0, M_ANALIZA_DESCRIPTOR=>1, M_ANALIZA_FREQUENCY=>2, M_ANALIZA_CROSSTAB=>3, M_ANALYSIS_MEANS=>4, M_ANALYSIS_TTEST=>5, M_ANALYSIS_BREAK=>6, M_ANALYSIS_CHARTS=>7, M_ANALYSIS_CREPORT=>8);
+ if (isset($_POST['podstran'])) {
+ $type = $ArchiveTypes[$_POST['podstran']];
+ }
+
+ SurveyAnalysis::Init(self::$sid);
+ SurveyAnalysis::setUpReturnAsHtml(true);
+
+ if($_POST['podstran'] == 'charts'){
+ # kreiramo arhiv za grafe
+ $SC = new SurveyChart();
+ $SC->Init(self::$sid);
+ $SC->setUpReturnAsHtml(true);
+ $chartTime = $SC->setUpIsForArchive(true);
+ $content = $SC->display();
+ $settings = array( 'chartTime' => $chartTime);
+ }
+ elseif($_POST['podstran'] == 'analysis_creport'){
+ #kreiramo arhiv za creport
+ $SCR = new SurveyCustomReport(self::$sid);
+ $SCR->setUpReturnAsHtml(true);
+ $SCR->setUpIsForArchive(true);
+ $content = $SCR->displayReport();
+ }
+ else{
+ if (isset($_POST['content']) && trim($_POST['content']) != '') {
+ $content = $_POST['content'];
+ } else {
+ $content = SurveyAnalysis::Display();
+ }
+ }
+
+ if (isset($content) && trim($content) != null) {
+
+ #ime zgeneriramo
+ $name = 'Arhiv: '.date("d.m.Y H:i:s");
+ $access = 0;
+
+ $folder = $site_path . 'admin/survey/'.SAA_FOLDER.'/';
+ $filename = 'saa_'.self::$sid.'_'.time().'.txt';
+
+ #če ni časa trajanja ga zgeneriramo
+ $duration = date("Y-m-d");// current date
+ $duration = strtotime(date("Y-m-d", strtotime($duration)) . DEFAULT_DURATION);
+ # pripravimo pravilno obliko datuma za insert v bazo
+ $duration = date("Y-m-d",$duration);
+
+ #dodamo zapis o arhivu v bazo
+ $s = sisplet_query("INSERT INTO srv_analysis_archive (sid, uid, name, filename, date, note, access, type, duration, editid) "
+ ."VALUES ('".self::$sid."', '$global_user_id', '$name', '$filename', NOW(), '', '$access', '$type', '$duration', '$global_user_id')");
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+
+ // Na zacetek dodamo glavo -> po novem se shrani v file
+ SurveyInfo::getInstance()->SurveyInit(self::$sid);
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('akronim');
+ if ($naslov == null || trim($naslov) == '') {
+ $naslov = SurveyInfo::getInstance()->getSurveyColumn('naslov');
+ }
+
+ $text = '<div id="arch_body_div">';
+
+ SurveySetting::getInstance()->Init(self::$sid);
+ $survey_hide_title = SurveySetting::getInstance()->getSurveyMiscSetting('survey_hide_title');
+
+ // Ce ne prikazujemo naslova ankete to skrijemo
+ if($survey_hide_title == 0){
+ $text .= '<div class="arch_head_date">'
+ .$lang['srv_analiza_archive_date_created']
+ .date("d.m.Y")
+ .'</div><h2>'.$naslov.'</h2>';
+ }
+
+ // Porocilo po meri ima custom naslov
+ $text .= ($survey_hide_title == 1) ? '<h2>' : '<h3>';
+ if($type == 8){
+ $SCR = new SurveyCustomReport(self::$sid);
+ $creport_title = $SCR->getTitle();
+ $text .= $creport_title;
+ }
+ else{
+ $text .= $lang['srv_analiza_archive_title'].$lang['srv_analiza_arhiviraj_type_'.$type];
+ }
+ $text .= ($survey_hide_title == 1) ? '</h2>' : '</h3>';
+
+ $content = $text.$content;
+
+
+ if ($id > 0) { # če smo dodali zapis v bazo shranimo še datoteko
+ # zapišemo fajl na disk
+ $fh = fopen($folder.$filename, 'w') or die("can't open file");
+ fwrite($fh, $content);
+ fclose($fh);
+
+ echo $id;
+ return $id;
+
+ } else {
+ echo 0;
+ return 0;
+ }
+ } else {
+ echo '-1';
+ return '-1';
+ }
+
+ }
+
+ /** zgenerira html iz analize in ga shrani kot arhiv.
+ *
+ */
+ static function createArchiveFromAnaliza() {
+ $content = null;
+ if($_POST['podstran'] == 'charts'){
+ # kreiramo arhiv za grafe
+ $SC = new SurveyChart();
+ $SC->Init(self::$sid);
+ $SC->setUpReturnAsHtml(true);
+ $chartTime = $SC->setUpIsForArchive(true);
+ $content = $SC->display();
+ $settings = array( 'chartTime' => $chartTime);
+ }
+ elseif($_POST['podstran'] == 'analysis_creport'){
+ #kreiramo arhiv za creport
+ $SCR = new SurveyCustomReport(self::$sid);
+ $SCR->setUpReturnAsHtml(true);
+ $SCR->setUpIsForArchive(true);
+ $content = $SCR->displayReport();
+ }
+ else{
+ if ($_POST['podstran'] == 'anal_arch') {
+ $_POST['podstran'] = 'sumarnik';
+ }
+ if (!isset($_POST['content'])) {
+ SurveyAnalysis::Init(self::$sid);
+ SurveyAnalysis::setUpIsForArchive(true);
+ SurveyAnalysis::setUpReturnAsHtml(true);
+
+ $content = SurveyAnalysis::Display();
+ } else {
+ $content = $_POST['content'];
+ }
+ }
+
+ $name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : null;
+ $note = (isset($_POST['note']) && trim($_POST['note'])) ? trim($_POST['note']) : null;
+ $access = (isset($_POST['access']) && trim($_POST['access'])) ? trim($_POST['access']) : 0;
+ $access_password = (isset($_POST['access_password']) && trim($_POST['access_password'])) ? trim($_POST['access_password']) : null;
+ $duration = (isset($_POST['duration']) && trim($_POST['duration'])) ? trim($_POST['duration']) : null;
+ $durationType = (isset($_POST['durationType']) && trim($_POST['durationType'])) ? trim($_POST['durationType']) : 0;
+
+ $ArchiveTypes = array(M_ANALIZA_SUMS => 0, M_ANALIZA_DESCRIPTOR=>1, M_ANALIZA_FREQUENCY=>2, M_ANALIZA_CROSSTAB=>3, M_ANALYSIS_MEANS=>4, M_ANALYSIS_TTEST=>5, M_ANALYSIS_BREAK=>6, M_ANALYSIS_CHARTS=>7, M_ANALYSIS_CREPORT=>8);
+ if (isset($_POST['podstran']))
+ $type = $ArchiveTypes[$_POST['podstran']];
+ if (isset($content) && trim($content) != null && self::$sid > 0) {
+
+ SurveyAnalysisArchive :: Init(self::$sid);
+ SurveyAnalysisArchive :: CreateArchive($content,$name,$note,$access,$type,$duration,$durationType,$settings,$access_password);
+
+ } else {
+ echo 'Error! (SurveyAnalysisArchive :: CreateArchive)';
+ }
+
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyAnalysisHelper.php b/admin/survey/classes/surveyAnalysis/class.SurveyAnalysisHelper.php
new file mode 100644
index 0000000..5c0a562
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyAnalysisHelper.php
@@ -0,0 +1,126 @@
+<?php
+class SurveyAnalysisHelper {
+
+ static private $instance;
+ static private $anketa;
+ static private $db_table = '';
+
+ /**
+ * Poskrbimo za samo eno instanco
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveyAnalysisHelper();
+ }
+ return self::$instance;
+ }
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ function Init( $anketa = null )
+ {
+ if ($anketa) {
+ self::$anketa = $anketa;
+
+ SurveyInfo::getInstance()->SurveyInit(self::$anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ self::$db_table = '_active';
+
+ }
+ }
+
+ function addCustomReportElement($type, $sub_type, $spr1, $spr2=''){
+ global $lang;
+ global $global_user_id;
+
+ if($_GET['m'] != 'analysis_creport' && $_GET['t'] != 'custom_report'){
+ $creportProfile = SurveyUserSetting :: getInstance()->getSettings('default_creport_profile');
+ $creportProfile = isset($creportProfile) ? $creportProfile : 0;
+
+ $creportAuthor = SurveyUserSetting :: getInstance()->getSettings('default_creport_author');
+ $creportAuthor = isset($creportAuthor) ? $creportAuthor : $global_user_id;
+
+ $sql = sisplet_query("SELECT id FROM srv_custom_report WHERE ank_id='".self::$anketa."' AND usr_id='".$creportAuthor."' AND type='$type' AND sub_type='$sub_type' AND spr1='$spr1' AND spr2='$spr2' AND profile='$creportProfile'");
+ $insert = (mysqli_num_rows($sql)) ? 0 : 1;
+ $id = $type.'-'.$sub_type.'-'.$spr1.'-'.$spr2;
+ // Samo zvezdica (sums, grafi, freq...)
+ if($type < 5)
+ echo '<a href="#" title="'.($insert == 0 ? $lang['srv_custom_report_inserted_title'] : $lang['srv_custom_report_insert_title']).'" onClick="addCustomReportElement(\''.$type.'\', \''.$sub_type.'\', \''.$spr1.'\', \''.$spr2.'\', 0); return false;"><span style="margin-left: 3px;" id="'.$id.'" class="faicon pointer '.($insert == 0 ? ' star_on' : ' star_off').'"></span></a>';
+ // Zvezdica s textom
+ else{
+ echo '<div class="custom_report_include">';
+
+ echo '<a href="#" title="'.($insert == 0 ? $lang['srv_custom_report_inserted_title'] : $lang['srv_custom_report_insert_title']).'" onClick="addCustomReportElement(\''.$type.'\', \''.$sub_type.'\', \''.$spr1.'\', \''.$spr2.'\', 1); return false;">';
+ echo '<span id="'.$id.'" class="faicon pointer '.($insert == 0 ? ' star_on' : ' star_off').'"></span>';
+ echo '<span id="'.$id.'_insert" '.($insert == 0 ? ' style="display:none;" ' : '').'> '.$lang['srv_custom_report_insert'].'</span>';
+ echo '<span id="'.$id.'_inserted" '.($insert == 0 ? '' : ' style="display:none;" ').'> '.$lang['srv_custom_report_inserted'].'</span>';
+ echo '</a>';
+
+ echo '</div>';
+ }
+ }
+ }
+
+ function displayMissingLegend(){
+ global $lang;
+
+ echo '<div id="bottom_data_legend" class="floatLeft">';
+ echo '<div>';
+ echo '<div id="bdld1" class="as_link strong" onclick="$(\'#bottom_data_legend_detail, #bdld1, #bdld2\').toggle();"><span class="faicon plus"></span></div>';
+ echo '<div id="bdld2" class="as_link strong" style="display:none" onclick="$(\'#bottom_data_legend_detail, #bdld1, #bdld2\').toggle();"><span class="faicon minus"></span></div> '.$lang['srv_bottom_data_legend_note'];
+ echo '</div>';
+ echo '<div id="bottom_data_legend_detail" style="display:none">';
+ echo '<ul>';
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li1'].'</li>';
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li2'].'</li>';
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li3'].'</li>';
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li4'].'</li>';
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li5'].'</li>';
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li0'].'</li>';
+ echo '</ul>';
+ echo '</div>';
+ echo '</div>';
+ }
+
+ function displayStatusLegend(){
+ global $lang;
+
+ echo '<div id="bottom_data_legend" class="floatLeft bg_blue">';
+ echo '<div>';
+ echo '<div id="bdlds1" class="as_link strong" onclick="$(\'#bottom_data_legend_detail_status, #bdlds1, #bdlds2\').toggle();"><span class="faicon plus"></span></div>';
+ echo '<div id="bdlds2" class="as_link strong" style="display:none" onclick="$(\'#bottom_data_legend_detail_status, #bdlds1, #bdlds2\').toggle();"><span class="faicon minus"></span></div> '.$lang['srv_bottom_data_legend_status_note'];
+ echo '</div>';
+ echo '<div id="bottom_data_legend_detail_status" style="display:none">';
+ echo '<ul>';
+ for ($i = 0; $i <= 6; $i++) {
+ echo '<li>'.$i.' - '.$lang['srv_userstatus_'.$i].'</li>';
+ }
+ echo '<li>'.$lang['srv_bottom_data_legend_note_li0'].'</li>';
+ echo '</ul>';
+ echo '</div>';
+ echo '</div>';
+ }
+
+ function displayTestLegend(){
+ global $lang;
+
+ echo '<div id="bottom_data_legend" class="floatLeft test">';
+ echo '<div>';
+ echo '<div id="bdldt1" class="as_link strong" onclick="$(\'#bottom_data_legend_detail_test, #bdldt1, #bdldt2\').toggle();"><span class="faicon plus"></span></div>';
+ echo '<div id="bdldt2" class="as_link strong" style="display:none" onclick="$(\'#bottom_data_legend_detail_test, #bdldt1, #bdldt2\').toggle();"><span class="faicon minus"></span></div> '.$lang['srv_bottom_data_legend_test_note'];
+ echo '</div>';
+ echo '<div id="bottom_data_legend_detail_test" style="display:none">';
+ echo '<ul>';
+ echo '<li>0 - '.$lang['srv_bottom_data_legend_test_note_li0'].'</li>';
+ echo '<li>1 - '.$lang['srv_bottom_data_legend_test_note_li1'].'</li>';
+ echo '<li>2 - '.$lang['srv_bottom_data_legend_test_note_li2'].'</li>';
+ echo '</ul>';
+ echo '</div>';
+ echo '</div>';
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyBreak.php b/admin/survey/classes/surveyAnalysis/class.SurveyBreak.php
new file mode 100644
index 0000000..aa2a829
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyBreak.php
@@ -0,0 +1,1578 @@
+<?php
+/** Class ki skrbi za T-test
+ * December 2011
+ *
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+define("BREAK_OPTION_LIMIT", 15);
+
+class SurveyBreak
+{
+ private $sid; # id ankete
+ private $db_table; # katere tabele uporabljamo
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo break(zakeširamo)
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ public $break_percent = false; # ali prikazujemo procente
+ public $break_charts = 0; # ali prikazujemo 0->tabele ali 1->grafe
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+ private $SurveyAnaliza; # klas analiza
+ private $SurveyCrosstab; # klas Crosstab
+
+
+ private $decimal_point = ',';
+ private $thousands = '.';
+ private $num_digit_average = NUM_DIGIT_AVERAGE;
+ private $num_digit_percent = NUM_DIGIT_PERCENT;
+
+ function __construct($sid) {
+ if ((int)$sid > 0) {
+ $this->sid = $sid;
+
+ SurveyAnalysisHelper::getInstance()->Init($this->sid);
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->sid);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->sid);
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyUserSetting::getInstance()->Init($this->sid, $global_user_id);
+
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyMissingProfiles :: Init($this->sid,$global_user_id);
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+ SurveyZankaProfiles :: Init($this->sid, $global_user_id);
+ SurveyTimeProfiles :: Init($this->sid, $global_user_id);
+ SurveyVariablesProfiles :: Init($this->sid, $global_user_id);
+
+ SurveyDataSettingProfiles :: Init($this->sid);
+ # polovimo decimalna mesta in vejice za tisočice
+ $this->decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $this->thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+ $this->num_digit_average = SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE');
+ $this->num_digit_percent = SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT');
+
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->sid);
+ $this->sessionData = SurveyUserSession::getData();
+
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_NO_FILE || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ Common::noDataAlert();
+ exit();
+ }
+
+ if ($this->headFileName !== null && $this->headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ $this->SurveyAnaliza = new SurveyAnalysis();
+ $this->SurveyAnaliza->Init($this->sid);
+
+ $this->SurveyCrosstab = new SurveyCrosstabs();
+ $this->SurveyCrosstab->Init($this->sid);
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ } else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+ function ajax() {
+
+ # spremenljivko in sekvenco shranimo v session
+ if (isset($_POST['spr'])) {
+ $this->sessionData['break']['spr'] = $_POST['spr'];
+ if (isset($_POST['seq'])) {
+ $this->sessionData['break']['seq'] = $_POST['seq'];
+ }
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ # izvedemo akcijo
+ switch ($_GET['a']) {
+ case 'spremenljivkaChange':
+ $this->doBreakForSpremenljivka();
+ break;
+ case 'change_break_percent':
+ $this->setSessionPercent();
+ break;
+ break;
+ case 'change_break_charts':
+ $this->setSessionCharts();
+ break;
+ break;
+ default:
+ print_r("<pre>");
+ print_r($_GET);
+ print_r($_POST);
+ print_r("</pre>");
+ break;
+ }
+ }
+
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter() {
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ # ali prikazujemo procente
+ $this->break_percent = (isset($this->sessionData['break']['break_percent']) && (int)$this->sessionData['break']['break_percent'] == 1) ? true : false;
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) || ($_time_profile_awk != "" && $_time_profile_awk != null)) {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD) {
+
+ if (isset($this->_HEADERS['testdata'])) {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+
+ }
+
+ function Display() {
+ global $lang;
+
+ # ali imamo testne podatke
+ if ($this->_HAS_TEST_DATA) {
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml($this->sid);
+ $SSH -> displayTestDataBar(true);
+ }
+
+ /*echo '<div id="dataOnlyValid">';
+ SurveyStatusProfiles::displayOnlyValidCheckbox();
+ echo '</div>';*/
+
+ # ali prikazujemo tabele ali grafe
+ $this->break_charts = (isset($this->sessionData['break']['break_show_charts']) && (int)$this->sessionData['break']['break_show_charts'] == 1) ? 1 : 0;
+
+ //$this->DisplayLinks();
+ //$this->DisplayFilters();
+
+ echo '<div id="div_break_data">';
+ $this->displayData();
+ echo '</div>'; #id="div_break_data"
+
+ }
+
+
+ function DisplayLinks() {
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->sid);
+ $SSH -> displayAnalizaSubNavigation();
+ }
+
+
+ /** Prikazuje filtre
+ *
+ */
+ function DisplayFilters() {
+ global $lang;
+
+ if ($this->dataFileStatus == FILE_STATUS_SRV_DELETED || $this->dataFileStatus == FILE_STATUS_NO_DATA){
+ return false;
+ }
+
+
+ if ($this->setUpJSAnaliza == true) {
+ echo '<script>
+ window.onload = function() {
+ __analiza = 1;
+ __tabele = 1;
+ }
+ </script>';
+ }
+
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->sid);
+ # izrišemo desne linke do posameznih nastavitev
+ $SSH -> displayAnalizaRightOptions(M_ANALYSIS_BREAK);
+ }
+
+ function displayData() {
+ global $lang;
+ echo '<div id="break_variables">';
+ $variables = $this->getVariableList(2);
+
+ echo '<span id="breakSpremenljivkaSpan" class="floatLeft spaceRight">';
+ echo $lang['srv_break_label1'];
+ echo '<br />';
+ echo '<select id="breakSpremenljivka" name="breakSpremenljivka" onchange="breakSpremenljivkaChange();" autocomplete="off">';
+ echo '<option value="0" selected="selected" >'. $lang['srv_break_select1_option'] . '</option>';
+ if (count($variables)) {
+ foreach ($variables as $variable) {
+ echo '<option value="'.$variable['spr_id'].'"'
+ . ( isset($variable['sequence']) ? ' seq="'.$variable['sequence'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ .($this->sessionData['break']['seq'] == $variable['sequence'] && (int)$variable['canChoose'] == 1 ? ' selected="selected"':'')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] . '</option>';
+ }
+ }
+ echo '</select>'; # name="breakSpremenljivka"
+ echo '</span>';
+
+ echo '<span id="div_crossCheck" class="floatLeft spaceLeft" style="margin-top:14px;">' ;
+ $this->displayLinePercent();
+ $this->displayLineCharts(); // V DELU...
+ echo '</span>';
+
+ echo '<br class="clr" />';
+ echo '</div>'; # id="break_variables"
+ if (isset($this->sessionData['break']['spr']) && (int)$this->sessionData['break']['spr'] > 0
+ && isset($this->sessionData['break']['seq']) && (int)$this->sessionData['break']['seq'] > 0) {
+ echo '<div id="breakResults" >';
+ $this->doBreakForSpremenljivka();
+ echo '</div>'; # id="breakResults"
+ } else {
+ echo '<div id="breakResults" />';
+ }
+ }
+
+ /** funkcija vrne seznam primern variabel za crostabe
+ *
+ */
+ function getVariableList($witch) {
+ # pobrišemo array()
+ $this->variablesList = array();
+ # zloopamo skozi header in dodamo variable (potrebujemo posamezne sekvence)
+ foreach ($this->_HEADERS AS $skey => $spremenljivka) {
+
+ $tip = $spremenljivka['tip'];
+ {
+ #drugi dropdown
+ # tekstovnih in numeričnih tipov ne dodajamo
+ $_dropdown_condition = is_numeric($tip)
+ #&& $tip != 2# checkbox - 21.11.2012 baje mormo checkboxe p
+ && $tip != 4 #text
+ && $tip != 5 #label
+ && $tip != 7 #number
+ && $tip != 8 #datum
+ && $tip != 9 #SN-imena
+ && $tip != 16 #multicheck
+ && $tip != 18 #vsota
+ && $tip != 19 #multitext
+ && $tip != 20 #multinumber
+ && $tip != 21 #besedilo*
+ && $tip != 22 #compute
+ && $tip != 25 #kvota
+ ? true : false;
+ }
+
+ if ($_dropdown_condition) {
+ $cnt_all = (int)$spremenljivka['cnt_all'];
+ # radio in select in checkbox
+ if ($cnt_all == '1' || $tip == 1 || $tip == 3 || $tip == 2) {
+ # pri tipu radio ali select dodamo tisto variablo ki ni polje "drugo"
+ if ($tip == 1 || $tip == 3 ) {
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][$vid]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+
+ }
+ }
+ }
+ }
+ } else if ($tip == 2){
+ if ($witch == 1) {
+ #pri checkboxu ponudimo vsako podvariablo posebej
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # imampo samo eno sekvenco grids[0]
+ if (count ($spremenljivka['grids'][0]['variables']) > 0) {
+
+ foreach ($spremenljivka['grids'][0]['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'vr_id'=>$vid,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } else {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+
+ } else {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+
+ } else if ($cnt_all > 1){
+ # imamo več skupin ali podskupin, zato zlopamo skozi gride in variable
+ if (count($spremenljivka['grids']) > 0 ) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # ali imamo en grid, ali več (tabele
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } else if($tip == 16||$tip == 18) {
+ # imamo multicheckbox
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>$gid,
+ 'sequence'=>$grid['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ } else {
+ # imamo več gridov - tabele
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>$sub);
+ }
+ if (count ($grid['variables']) > 0) {
+ $sub++;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>$sub);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ return $this->variablesList;
+ }
+
+ function doBreakForSpremenljivka() {
+ global $lang;
+
+ # ali prikazujemo procente
+ $this->break_percent = isset($this->sessionData['break']['break_percent']) && (int)$this->sessionData['break']['break_percent'] == 1 ? true : false;
+ $this->break_charts = isset($this->sessionData['break']['break_show_charts']) && (int)$this->sessionData['break']['break_show_charts'] == 1 ? 1 : 0;
+
+ if (isset($this->sessionData['break']['spr']) && $this->sessionData['break']['spr'] != 0){
+ $_spr = explode('_',$this->sessionData['break']['spr']);
+ $spr = $this->sessionData['break']['spr'];
+ # poiščemo pripadajoče variable
+ $_spr_data = $this->_HEADERS[$this->sessionData['break']['spr']];
+
+ # poiščemo sekvenco
+ $sekvenca = $this->sessionData['break']['seq'];
+
+ # poiščemo opcije
+ $opcije = $_spr_data['options'];
+
+ # izrisemo ikone za izvoz pdf/rtf
+ $this->displayExport($spr, $sekvenca);
+
+ if ((int)$_spr_data['tip'] != 2) {
+ $seqences[] = $sekvenca;
+ $options = $opcije;
+ } else {
+ # za checkboxe imamo več sekvenc
+ $seqences = explode('_',$_spr_data['sequences']);
+ $options[1] = $opcije[1];
+ }
+
+
+ # za vsako opcijo posebej izračunamo povprečja za vse spremenljivke
+ $frequencys = array();
+ if (count($seqences) > 0) {
+ foreach ($seqences as $seq) {
+
+ if (count($options) > 0) {
+ foreach ($options as $oKey => $option) {
+ # zloopamo skozi variable
+ $oKeyfrequencys = $this->getAllFrequencys($oKey, $seq, $spr);
+ if ($oKeyfrequencys != null) {
+ $frequencys[$seq][$oKey] = $oKeyfrequencys;
+ }
+ }
+ }
+ }
+ }
+ $this->displayBreak($spr,$frequencys);
+
+ } else {
+ echo '<br class="clr">';
+ echo '<p class="red strong">'.$lang['srv_break_error_note_1'].'</p>';
+ }
+ }
+
+ /** za posamezno opcijo izračunamo frekvence za vse spremenljivke
+ *
+ * @param unknown_type $oKey
+ * @param unknown_type $seq
+ */
+ function getAllFrequencys($oKey, $seq, $spr) {
+ $result = null;
+ # sestavimo dodaten awk filter
+ $awk_filter = $this->getAwkFilter($oKey, $seq, $spr);
+ if ($awk_filter != null) {
+ # pridobimo frekvence
+ $this->SurveyAnaliza->setUpFilter();
+ $this->SurveyAnaliza->frequencyAddInvalid(false);
+ $result = $this->SurveyAnaliza->getFrequencys($awk_filter);
+ }
+ return $result;
+ }
+
+ function getAwkFilter($oKey, $seq, $spr) {
+ $result = null;
+ $_spr_data = $this->_HEADERS[$spr];
+ $tip = $_spr_data['tip'];
+
+ $result = '$'.$seq.'=='.$oKey;
+ return $result;
+
+ }
+
+ function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+
+ $result = number_format($result, $digit, $this->decimal_point, $this->thousands) . $sufix;
+
+ return $result;
+ }
+
+ function displayBreak($forSpr, $frequencys) {
+
+
+ ob_start(); // outer buffer
+ # če imamo filter spremenljivk ga izpišemo
+ echo '<br/>';
+
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile(false);
+
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString(true);
+ SurveyDataSettingProfiles :: getVariableTypeNote();
+
+ # filtriranje po spremenljivkah
+ $_FILTRED_VARIABLES = SurveyVariablesProfiles::getProfileVariables(SurveyVariablesProfiles::checkDefaultProfile(), true);
+ foreach ($this->_HEADERS AS $skey => $spremenljivka) {
+
+ if ((int)$spremenljivka['hide_system'] == 1 && in_array($spremenljivka['variable'],array('email','ime','priimek','telefon','naziv','drugo'))) {
+ continue;
+ }
+ $spremenljivka['id'] = $skey;
+ $tip = $spremenljivka['tip'];
+ if ( is_numeric($tip)
+ && $tip != 4 #text
+ && $tip != 5 #label
+ && $tip != 8 #datum
+ && $tip != 9 #SN-imena
+ && $tip != 19 #multitext
+ && $tip != 21 #besedilo*
+ && ( count($_FILTRED_VARIABLES) == 0 || (count($_FILTRED_VARIABLES) > 0 && isset($_FILTRED_VARIABLES[$skey]) ))
+ ) {
+
+ $this->displayBreakSpremenljivka($forSpr,$frequencys,$spremenljivka);
+ } else if ( is_numeric($tip)
+ && (
+ $tip == 4 #text
+ || $tip == 19 #multitext
+ || $tip == 21 #besedilo*
+ || $tip == 20 #multi numer*
+ ) && ( count($_FILTRED_VARIABLES) == 0 || (count($_FILTRED_VARIABLES) > 0 && isset($_FILTRED_VARIABLES[$skey]) ) )
+ ) {
+ $this->displayBreakSpremenljivka($forSpr,$frequencys,$spremenljivka);
+ }
+
+ ob_end_flush();
+ }
+
+ // Izpisemo nastavitve na dnu (izvozi, arhiv, vabila...)
+ $this->displayBottomSettings();
+ }
+
+ function displayBreakSpremenljivka($forSpr,$frequencys,$spremenljivka) {
+
+ $tip = $spremenljivka['tip'];
+
+ if ($forSpr != $spremenljivka['id']) {
+
+ switch ($tip) {
+ # radio, dropdown
+ case 1:
+ case 3:
+ $this->displayCrosstabTable($forSpr,$frequencys,$spremenljivka);
+ break;
+
+ #multigrid
+ case 6:
+ $skala = Common::getSpremenljivkaSkala($spremenljivka['id']);
+ if ($skala == 0) {
+ $this->displayBreakTableMgrid($forSpr,$frequencys,$spremenljivka);
+ }
+ else {
+ $this->displayCrosstabTable($forSpr,$frequencys,$spremenljivka);
+ }
+ break;
+
+ # checkbox
+ case 2:
+ $this->displayCrosstabTable($forSpr,$frequencys,$spremenljivka);
+ break;
+ #number
+ case 7:
+ #ranking
+ case 17:
+ #vsota
+ case 18:
+ #multinumber
+ case 20:
+ $this->displayBreakTableNumber($forSpr,$frequencys,$spremenljivka);
+ break ;
+
+ case 19:
+ $this->displayBreakTableText($forSpr,$frequencys,$spremenljivka);
+ break ;
+ #multicheck
+ case 16:
+ $this->displayCrosstabTable($forSpr,$frequencys,$spremenljivka);
+ break;
+
+ case 4:
+ case 21:
+ # po novem besedilo izpisujemo v klasični tabeli
+ $this->displayBreakTableText($forSpr,$frequencys,$spremenljivka);
+
+ #$this->displayCrosstabTable($forSpr,$frequencys,$spremenljivka);
+ break;
+
+ default:
+ $this->displayCrosstabTable($forSpr,$frequencys,$spremenljivka);
+ break;
+ }
+ }
+ }
+
+ function displayBreakTableMgrid($forSpr,$frequencys,$spremenljivka){
+ #mgrid - 16:
+
+ // Ce izrisujemo graf
+ if($this->break_charts == 1){
+ $tableChart = new SurveyTableChart($this->sid, $this, 'break');
+ $tableChart->setBreakVariables($forSpr,$frequencys,$spremenljivka);
+ $tableChart->display();
+ }
+
+ // Ce izrisujemo tabelo
+ else{
+
+ $keysCount = count($frequencys);
+ $sequences = explode('_',$spremenljivka['sequences']);
+ $forSpremenljivka = $this->_HEADERS[$forSpr];
+ $tip = $spremenljivka['tip'];
+
+ # izračunamo povprečja za posamezne sekvence
+ $means = array();
+ $totalMeans = array();
+ $totalFreq = array();
+ foreach ($frequencys AS $fkey => $options) {
+ foreach ($options AS $oKey => $option) {
+ foreach ($sequences AS $sequence) {
+ $txt = $this->getMeansFromKey($option[$sequence]);
+ if ($txt) {
+ $cnt[$fkey]++;
+ $means[$fkey][$oKey][$sequence] = $txt;
+ }
+ }
+ }
+ }
+
+ # ce imamo vec kot 20 kategorij,izpisujemo samo tiste ki imajo vrednosti
+ $displayAll = (count($options) > 20) ? false : true;
+
+ echo '<div id="'.$spremenljivka['id'].'" class="breakTableDiv">';
+ if (isset($spremenljivka['double']) && $spremenljivka['double'] > 1) {
+ $doubleGridParts = $spremenljivka['double'];
+ $multiply = 1;
+ $isDoubleGrid = true;
+ } else {
+ $doubleGridParts[1]['subtitle'] = '';
+ $multiply = 2;
+ $isDoubleGrid = false;
+ }
+
+
+ # če imamo dvojno tabelo
+
+ $rowspan = ' rowspan="3"';
+ $colspan = ' colspan="'.($multiply*count($sequences)).'"';
+
+ foreach ($doubleGridParts AS $part => $doubleGridTitle) {
+ echo '<br/>';
+ # če ni multicheck in multi grid
+ echo '<table>';
+ echo '<tr>';
+ echo '<th'.$rowspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $forSpr . '\'); return false;">';
+ echo $forSpremenljivka['naslov'];
+ echo '('.$forSpremenljivka['variable'].')';
+ echo '</a>';
+ echo '</span>';
+
+ echo '</th>';
+ echo '<th'.$colspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $spremenljivka['id'] . '\'); return false;">';
+ echo $spremenljivka['naslov'];
+ echo '('.$spremenljivka['variable'].')';
+ echo '</a>';
+ if (isset ($doubleGridTitle['subtitle'])) {
+ echo ' - '.$doubleGridTitle['subtitle'];
+ }
+ echo '</span>';
+ echo '</th>';
+ echo '</tr>';
+
+ echo '<tr>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ if ($isDoubleGrid == false || ($isDoubleGrid == true && $grid['part'] == $part)) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+
+ echo '<th class="sub" colspan="2">';
+ echo $variable['naslov'];
+ echo '('.$variable['variable'].')';
+ echo '</th>';
+ }
+ }
+ }
+ echo '</tr>';
+ echo '<tr>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ if ($isDoubleGrid == false || ($isDoubleGrid == true && $grid['part'] == $part)) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ echo '<th class="sub">Povprečje'.$lang[''];
+ echo '</th>';
+ echo '<th class="sub red">Št. enot'.$lang[''];
+ echo '</th>';
+ }
+ }
+ }
+ echo '</tr>';
+ $cnt=0;
+ foreach ($frequencys AS $fkey => $fkeyFrequency) {
+ $cbxLabel = $forSpremenljivka['grids'][0]['variables'][$cnt]['naslov'];
+ $cnt++;
+ foreach ($options AS $oKey => $option) {
+ if ($means[$fkey][$oKey] != null || $displayAll) {
+ echo '<tr>';
+ echo '<td'.$break_percentRowSpan.' class="rsdl_bck_variable1">';
+ if ($forSpremenljivka['tip'] == 2) {
+ echo $cbxLabel;
+ } else {
+ echo $forSpremenljivka['options'][$oKey];
+ }
+ echo '</td>';
+ $css = '';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ if ($isDoubleGrid == false || ($isDoubleGrid == true && $grid['part'] == $part)) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($variable['other'] != 1) {
+ #povprečja
+ echo '<td'.$css.$break_percentRowSpan.'>';
+ echo $this->formatNumber($means[$fkey][$oKey][$sequence],$this->num_digit_average,'');
+ echo '</td>';
+ # enote
+ echo '<td class="red strong">';
+ echo (int)$frequencys[$fkey][$oKey][$sequence]['validCnt'];
+ echo '</td>';
+ $totalMeans[$sequence] += ($means[$fkey][$oKey][$sequence]*(int)$frequencys[$fkey][$oKey][$sequence]['validCnt']);
+ $totalFreq[$sequence]+= (int)$frequencys[$fkey][$oKey][$sequence]['validCnt'];
+ }
+
+ }
+ }
+ }
+ echo '</tr>';
+ }
+ }
+ }
+ #dodamo še skupno sumo in povprečje
+ echo '<tr>';
+ echo '<td class="rsdl_bck_variable1 red">';
+ echo 'Skupaj';
+ echo '</td>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ if ($isDoubleGrid == false || ($isDoubleGrid == true && $grid['part'] == $part)) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+
+ $sequence = $variable['sequence'];
+ if ($variable['other'] != 1) {
+ #povprečja
+ echo '<td class="red strong">';
+ $totalMean = $totalFreq[$sequence] > 0 ? $totalMeans[$sequence] / $totalFreq[$sequence] : 0;
+ echo $this->formatNumber($totalMean ,$this->num_digit_average,'');
+ echo '</td>';
+ # enote
+ echo '<td class="red strong">';
+ echo (int)$totalFreq[$sequence];
+ echo '</td>';
+ }
+
+ }
+ }
+ }
+ echo '</tr>';
+ echo '</table>';//$forSpremenljivka['grids'][0]['variables']
+
+ }
+ // Zvezdica za vkljucitev v porocilo
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $spremenljivka['grids'][0]['variables'][0]['sequence'].'-'.$spremenljivka['id'].'-undefined';
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type=9, $sub_type=0, $spr1, $spr2);
+ echo '</div>';
+ }
+ }
+
+ function displayBreakTableNumber($forSpr,$frequencys,$spremenljivka){
+ #number - 7:
+ #ranking - 17:
+ #vsota - 18:
+ #multinumber - 20:
+
+ $keysCount = count($frequencys);
+ $sequences = explode('_',$spremenljivka['sequences']);
+ $forSpremenljivka = $this->_HEADERS[$forSpr];
+ $tip = $spremenljivka['tip'];
+
+ # izračunamo povprečja za posamezne sekvence
+ $means = array();
+ $totalMeans = array();
+ $totalFreq = array();
+ foreach ($frequencys AS $fkey => $options) {
+ foreach ($options AS $oKey => $option) {
+ foreach ($sequences AS $sequence) {
+ $txt = $this->getMeansFromKey($option[$sequence]);
+ if ($txt) {
+ $means[$fkey][$oKey][$sequence] = $txt;
+ }
+ }
+ }
+ }
+ # ce imamo vec kot 20 kategorij,izpisujemo samo tiste ki imajo vrednosti
+ $displayAll = (count($options) > 20) ? false : true;
+
+ // Ce izrisujemo graf
+ if($this->break_charts == 1){
+
+ // Number, vsota, ranking graf
+ if($tip != 20 ){
+ $tableChart = new SurveyTableChart($this->sid, $this, 'break');
+ $tableChart->setBreakVariables($forSpr,$frequencys,$spremenljivka);
+ $tableChart->display();
+ }
+
+ // Multinumber graf
+ else{
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+
+ // Izrisujemo samo 1 graf v creportu
+ if($_GET['m'] == 'analysis_creport'){
+
+ if($spremenljivka['break_sub_table']['key'] == $gkey){
+ $tableChart = new SurveyTableChart($this->sid, $this, 'break');
+ $tableChart->setBreakVariables($forSpr,$frequencys,$spremenljivka);
+ $tableChart->display();
+ }
+ }
+
+ // Izrisujemo vse zaporedne grafe
+ else{
+ $spremenljivka['break_sub_table']['key'] = $gkey;
+ $spremenljivka['break_sub_table']['sequence'] = $grid['variables'][0]['sequence'];
+
+ $tableChart = new SurveyTableChart($this->sid, $this, 'break');
+ $tableChart->setBreakVariables($forSpr,$frequencys,$spremenljivka);
+ $tableChart->display();
+ }
+ }
+ }
+
+ }
+ // Ce izrisujemo tabelo
+ else{
+
+ echo '<div id="'.$spremenljivka['id'].'" class="breakTableDiv">';
+ echo '<br/>';
+ # za multi number naredimo po skupinah
+ if ($tip != 20 ) {
+ $rowspan = ' rowspan="3"';
+ $colspan = ' colspan="'.(2*count($sequences)).'"';
+
+ # ali prikazujemo procente
+ if ((int)$this->break_percent > 0) {
+ $break_percentRowSpan = ' rowspan="2"';
+ }
+ # če ni multicheck in multi grid
+ echo '<table>';
+ echo '<tr>';
+ echo '<th'.$rowspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $forSpr . '\'); return false;">';
+ echo $forSpremenljivka['naslov'];
+ echo '('.$forSpremenljivka['variable'].')';
+ echo '</a>';
+ echo '</span>';
+
+ echo '</th>';
+ echo '<th'.$colspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $spremenljivka['id'] . '\'); return false;">';
+ echo $spremenljivka['naslov'];
+ echo '('.$spremenljivka['variable'].')';
+ echo '</a>';
+ echo '</span>';
+ echo '</th>';
+ echo '</tr>';
+
+ echo '<tr>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ echo '<th class="sub" colspan="2">';
+ echo $variable['naslov'];
+ echo '('.$variable['variable'].')';
+ echo '</th>';
+ }
+ }
+ echo '</tr>';
+ echo '<tr>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ echo '<th class="sub">Povprečje'.$lang[''];
+ echo '</th>';
+ echo '<th class="sub red">Št. enot'.$lang[''];
+ echo '</th>';
+ }
+ }
+ echo '</tr>';
+
+ foreach ($frequencys AS $fkey => $fkeyFrequency) {
+
+ foreach ($options AS $oKey => $option) {
+ if ($displayAll || $means[$fkey][$oKey] != null) {
+ echo '<tr>';
+ echo '<td'.$break_percentRowSpan.' class="rsdl_bck_variable1">';
+ echo $forSpremenljivka['options'][$oKey];
+ echo '</td>';
+ $css = '';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($variable['other'] != 1) {
+ #povprečja
+ echo '<td'.$css.$break_percentRowSpan.'>';
+ echo $this->formatNumber($means[$fkey][$oKey][$sequence],$this->num_digit_average,'');
+ #echo $this->formatNumber($means[$fkey][$sequence],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ echo '</td>';
+ # enote
+ echo '<td class="red strong">';
+ echo (int)$frequencys[$fkey][$oKey][$sequence]['validCnt'];
+ #echo (int)$frequencys[$fkey][$sequence]['validCnt'];
+ echo '</td>';
+ #$totalMeans[$sequence] += ($this->getMeansFromKey($fkeyFrequency[$sequence])*(int)$frequencys[$fkey][$sequence]['validCnt']);
+ #$totalFreq[$sequence]+= (int)$frequencys[$fkey][$sequence]['validCnt'];
+ $totalMeans[$sequence] += ($means[$fkey][$oKey][$sequence]*(int)$frequencys[$fkey][$oKey][$sequence]['validCnt']);
+ $totalFreq[$sequence]+= (int)$frequencys[$fkey][$oKey][$sequence]['validCnt'];
+ }
+
+ }
+
+ }
+ echo '</tr>';
+ if ((int)$this->break_percent) {
+ echo '<tr>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['other'] != 1) {
+ $sequence = $variable['sequence'];
+ echo '<td class="">';
+ #echo (int)$frequencys[$fkey][$sequence]['validCnt'];
+ $percent = 0;
+ if ($frequencys[$fkey][$sequence]['validCnt'] > 0 ) {
+ $percent = 100;
+ }
+ echo $this->formatNumber($percent,$this->num_digit_percent,'%');
+ echo '</td>';
+ }
+ }
+
+ }
+ echo '</tr>';
+ }
+ }
+ }
+ }
+ #dodamo še skupno sumo in povprečje
+ echo '<tr>';
+ echo '<td class="rsdl_bck_variable1">';
+ echo $lang[''].'Skupaj';
+ echo '</td>';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+
+ $sequence = $variable['sequence'];
+ if ($variable['other'] != 1) {
+ #povprečja
+ echo '<td class="red strong">';
+ $totalMean = $totalFreq[$sequence] > 0 ? $totalMeans[$sequence] / $totalFreq[$sequence] : 0;
+ echo $this->formatNumber($totalMean ,$this->num_digit_average,'');
+ echo '</td>';
+ # enote
+ echo '<td class="red strong">';
+ echo (int)$totalFreq[$sequence];
+ echo '</td>';
+ }
+
+ }
+
+ }
+ echo '</tr>';
+ echo '</table>';
+
+
+ // Zvezdica za vkljucitev v porocilo
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $spremenljivka['grids'][0]['variables'][0]['sequence'].'-'.$spremenljivka['id'].'-undefined';
+
+ #xxxxx
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type=9, $sub_type=0, $spr1, $spr2);
+
+
+ } else if ($tip == 20){
+ # za multi number razdelimo na grupe - skupine
+ $rowspan = ' rowspan="3"';
+ $colspan = ' colspan="'.(2*count($spremenljivka['grids'][0]['variables'])).'"';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+
+ // Ce smo v porocilu po meri in ni prava tabela jo preskocimo
+ if(isset($spremenljivka['break_sub_table']['key']) && $spremenljivka['break_sub_table']['key'] != $gkey){
+ continue;
+ }
+
+ // Ce smo v porocilu po meri in je prava tabelo jo izpisemo brez naslova
+ if(!isset($spremenljivka['break_sub_table']['sequence'])){
+ echo '<br/><b>'.$lang['srv_break_table_for'];
+ echo $spremenljivka['naslov'].' (';
+ echo $spremenljivka['variable'].') = ';
+ echo $grid['naslov'];
+ echo ' ('.$grid['variable'].')';
+ echo '</b>';
+ }
+
+ echo '<table>';
+ #labele
+ echo '<tr>';
+ echo '<th'.$rowspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $forSpr . '\'); return false;">';
+ echo $forSpremenljivka['naslov'];
+ echo '('.$forSpremenljivka['variable'].')';
+ echo '</a>';
+ echo '</span>';
+ echo '</th>';
+
+ echo '<th'.$colspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $spremenljivka['id'] . '\'); return false;">';
+ echo $spremenljivka['naslov']. ' - ';
+ echo $grid['naslov'];
+ echo '('.$grid['variable'].')';
+ echo '</a>';
+ echo '</span>';
+ echo '</th>';
+ echo'</tr>';
+ #labele
+ echo '<tr>';
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ echo '<th class="sub" colspan="2">';
+ echo $variable['naslov'];
+ echo '('.$variable['variable'].')';
+ echo '</th>';
+ }
+ echo '</tr>';
+ echo '<tr>';
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ echo '<th class="sub">Povprečje'.$lang[''];
+ echo '</th>';
+ echo '<th class="sub red">Št. enot'.$lang[''];
+ echo '</th>';
+ }
+ echo '</tr>';
+ $cnt=0;
+ foreach ($frequencys AS $fkey => $fkeyFrequency) {
+ $cbxLabel = $forSpremenljivka['grids'][0]['variables'][$cnt]['naslov'];
+ $cnt++;
+ foreach ($forSpremenljivka['options'] AS $oKey => $option) {
+ if ($displayAll || $means[$fkey][$oKey] != null) {
+ # če je osnova checkbox vzamemo samo tam ko je 1
+ if(($forSpremenljivka['tip'] == 2 && $option == 1) || $forSpremenljivka['tip'] != 2 ) {
+ echo '<tr>';
+ echo '<td'.$break_percentRowSpan.' class="rsdl_bck_variable1">';
+ if ($forSpremenljivka['tip'] == 2) {
+ echo $cbxLabel;
+ } else {
+ echo $forSpremenljivka['options'][$oKey];
+ }
+
+ #echo ' ('.$oKey.')';
+ echo '</td>';
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ #povprečje
+ echo '<td>';
+ echo $this->formatNumber($means[$fkey][$oKey][$sequence],$this->num_digit_average,'');
+ echo '</td>';
+ # enote
+ echo '<td class="red strong">';
+ echo (int)$frequencys[$fkey][$oKey][$sequence]['validCnt'];
+ echo '</td>';
+ $totalMeans[$sequence] += ($means[$fkey][$oKey][$sequence]*(int)$frequencys[$fkey][$oKey][$sequence]['validCnt']);
+ $totalFreq[$sequence]+= (int)$frequencys[$fkey][$oKey][$sequence]['validCnt'];
+
+ }
+ echo '</tr>';
+ }
+ }
+ }
+ }
+ #dodamo še skupno sumo in povprečje
+ echo '<tr>';
+ echo '<td class="rsdl_bck_variable1">';
+ echo 'Skupaj';
+ echo '</td>';
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($variable['other'] != 1) {
+ #povprečja
+ echo '<td class="red strong">';
+ $totalMean = $totalFreq[$sequence] > 0 ? $totalMeans[$sequence] / $totalFreq[$sequence] : 0;
+ echo $this->formatNumber($totalMean ,$this->num_digit_average,'');
+ echo '</td>';
+ # enote
+ echo '<td class="red strong">';
+ echo (int)$totalFreq[$sequence];
+ echo '</td>';
+ }
+ }
+ echo '</tr>';
+ echo '</table>';
+
+
+ // Zvezdica za vkljucitev v porocilo
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $grid['variables'][0]['sequence'].'-'.$spremenljivka['id'].'-undefined';
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type=9, $sub_type=0, $spr1, $spr2);
+
+ echo '<br/>';
+ }
+
+ }
+ echo '</div>';
+ }
+
+ }
+
+ function displayBreakTableText($forSpr,$frequencys,$spremenljivka){
+ #text - 21:
+ #multi text - 19:
+ $keysCount = count($frequencys);
+ $sequences = explode('_',$spremenljivka['sequences']);
+ $forSpremenljivka = $this->_HEADERS[$forSpr];
+
+ $tip = $spremenljivka['tip'];
+ # izračunamo povprečja za posamezne sekvence
+ $texts = array();
+ $totalMeans = array();
+ $totalFreq = array();
+ $forSequences = array();
+ $cnt = array();
+ foreach ($frequencys AS $fkey => $fkeyFrequency) {
+ $forSequences[] = $fkey;
+ foreach ($forSpremenljivka['options'] AS $oKey => $option) {
+ foreach ($sequences AS $sequence) {
+ $txt = $this->getTextFromKey($fkeyFrequency[$oKey][$sequence]);
+ if ($txt) {
+ $cnt[$fkey]++;
+ $texts[$fkey][$oKey][$sequence] = $txt;
+ }
+ }
+ }
+ }
+
+ # če imamo več kot 20 kategorij,izpisujemo samo tiste ki imajo vrednosti
+ $displayAll = (count($forSpremenljivka['options']) > 20) ? false : true;
+
+ echo '<div id="'.$spremenljivka['id'].'" class="breakTableDiv">';
+ echo '<br/>';
+ # za multi text razdelimo na grupe - skupine
+ $rowspan = ' rowspan="2"';
+ $colspan = ' colspan="'.(count($spremenljivka['grids'][0]['variables'])).'"';
+ foreach ($spremenljivka['grids'] AS $gkey => $grid) {
+
+ // Ce smo v porocilu po meri in ni prava tabela jo preskocimo
+ if(isset($spremenljivka['break_sub_table']['sequence']) && $spremenljivka['break_sub_table']['key'] != $gkey){
+ continue;
+ }
+
+ // Ce smo v porocilu po meri in je prava tabelo jo izpisemo brez naslova
+ if(!isset($spremenljivka['break_sub_table']['sequence'])){
+ echo '<br/>';
+ if($tip != '21'){
+ echo '<b>';
+ echo $lang['srv_break_table_for'];
+ echo $spremenljivka['naslov'].' (';
+ echo $spremenljivka['variable'].') = ';
+ echo $grid['naslov'];
+ echo ' ('.$grid['variable'].')';
+ echo '</b>';
+ }
+ }
+
+ echo '<table>';
+ #labele
+ echo '<tr>';
+ echo '<th'.$rowspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $forSpr . '\'); return false;">';
+ echo $forSpremenljivka['naslov'];
+ echo '('.$forSpremenljivka['variable'].')';
+ echo '</a>';
+ echo '</span>';
+ echo '</th>';
+
+ echo '<th'.$colspan.'>';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $spremenljivka['id'] . '\'); return false;">';
+ echo $spremenljivka['naslov']. ' - ';
+ echo $grid['naslov'];
+ echo '('.$grid['variable'].')';
+ echo '</a>';
+ echo '</span>';
+ echo '</th>';
+ echo'</tr>';
+ #labele
+ echo '<tr>';
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ echo '<th class="sub" >';
+ echo $variable['naslov'];
+ echo '('.$variable['variable'].')';
+ echo '('.$variable['sequence'].')';
+ echo '</th>';
+ }
+ echo '</tr>';
+ $cntCbx= 0;
+ foreach ($forSequences AS $fKey => $forSequence) {
+ $cbxLabel = $forSpremenljivka['grids'][0]['variables'][$cntCbx]['naslov'];
+ $cntCbx++;
+ foreach ($forSpremenljivka['options'] AS $oKey => $option) {
+ if ($displayAll || $texts[$forSequence][$oKey] != null) {
+ if(($forSpremenljivka['tip'] == 2 && $option == 1) || $forSpremenljivka['tip'] != 2 ) {
+ echo '<tr>';
+ echo '<td'.$break_percentRowSpan.' class="rsdl_bck_variable1">';
+ if ($forSpremenljivka['tip'] == 2) {
+ echo $cbxLabel;
+ } else {
+ echo $forSpremenljivka['options'][$oKey];
+ }
+ echo '</td>';
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ #povprečje
+ echo '<td class="anl_at cll_clps" style="vertical-align:top;">';
+ if (count($texts[$forSequence][$oKey][$sequence]) > 0) {
+ $cnt=1;
+ $count = count($texts[$forSequence][$oKey][$sequence]);
+ foreach ($texts[$forSequence][$oKey][$sequence] AS $ky => $units) {
+ echo '<div class="'.($cnt<=$count && $cnt>1?'anl_bt_dot ':'').('').'"style="line-height: 150%; padding:3px;">';
+ echo $units['text'];
+ echo '</div>';
+ $cnt++;
+ }
+ }
+
+
+ #echo $this->formatNumber($texts[$oKey][$sequence],$this->num_digit_average,'');
+ echo '</td>';
+
+ }
+ echo '</tr>';
+ }
+ }
+ }
+ }
+ echo '</table>';
+
+
+ // Zvezdica za vkljucitev v porocilo
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $grid['variables'][0]['sequence'].'-'.$spremenljivka['id'].'-undefined';
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type=9, $sub_type=0, $spr1, $spr2);
+
+ echo '<br/>';
+ }
+
+ echo '</div>';
+
+ }
+
+ function displayCrosstabTable($forSpr,$frequencys,$spremenljivka){
+
+ #polovimo sekvence in spremenljivke
+ // Ce smo v creportu imamo nastavljeno prvo spremenljivko posebej (ne v sessionu)
+ if(isset($spremenljivka['break_sub_table']['sequence'])){
+ $spr1 = $spremenljivka['creport_first_spr']['spr'];
+ $seq1 = $spremenljivka['creport_first_spr']['seq'];
+ }
+ else{
+ $spr1 = $this->sessionData['break']['spr'];
+ $seq1 = $this->sessionData['break']['seq'];
+ }
+ $grd1 = 'undefined';
+ foreach ($this->_HEADERS[$spr1]['grids'] AS $gid => $grid) {
+ foreach ($grid['variables'] AS $vkey => $vrednost) {
+ if ($vrednost['sequence'] == $seq1) {
+ $grd1 = $gid;
+ }
+ }
+ }
+
+ $this->SurveyCrosstab->displayHi2 = false;
+ $this->SurveyCrosstab->fromBreak = true;
+ $this->SurveyCrosstab->showAverage = $this->break_percent;
+ if ($spremenljivka['tip'] == 2
+ || $spremenljivka['tip'] == 16
+ || $spremenljivka['tip'] == 4
+ || $spremenljivka['tip'] == 19
+ || $spremenljivka['tip'] == 21
+ || ($spremenljivka['tip'] == 6 && $spremenljivka['skala'] != 0)
+ || ($spremenljivka['tip'] == 1 && $spremenljivka['skala'] != 0)){
+ $this->SurveyCrosstab->showAverage = false;
+ }
+ $spr2 = $spremenljivka['id'];
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ // Ce smo v porocilu po meri in ni prava tabela jo preskocimo
+ if(isset($spremenljivka['break_sub_table']['sequence']) && $spremenljivka['break_sub_table']['key'] != $gid){
+ continue;
+ }
+
+ // Ce smo v porocilu po meri in je prava tabelo jo izpisemo brez naslova
+ if(!isset($spremenljivka['break_sub_table']['sequence']) && ($spremenljivka['tip'] == 16 || $spremenljivka['tip'] == 6) && $this->break_charts != 1){
+ echo '<br/><b>'.$lang['srv_break_table_for'];
+ echo $spremenljivka['naslov'].' (';
+ echo $spremenljivka['variable'].') = ';
+ echo $grid['naslov'];
+ if ($spremenljivka['tip'] != 6) {
+ echo ' ('.$grid['variable'].')';
+ }
+ echo '</b>';
+ }
+
+ $seq2 = $grid['variables'][0]['sequence'];
+ $grd2 = $gid;
+ $this->SurveyCrosstab->setColor(false);
+ # ali rišemo povprečje po stolpcih v zadnji vrstici
+ if ($spremenljivka['tip'] == 1 && $spremenljivka['skala'] == 0 ) {
+ $this->SurveyCrosstab->showBottomAverage (true);
+ }
+
+ if($this->break_charts == 1){
+ $this->SurveyCrosstab->setVariables($seq1,$spr1,'undefined'/*$grd1*/,$seq2,$spr2,$grd2);
+ $this->SurveyCrosstab->fromBreak = false;
+ $tableChart = new SurveyTableChart($this->sid, $this->SurveyCrosstab, 'break');
+ $tableChart->break_crosstab = 1;
+ $tableChart->display();
+ }
+ else{
+ $this->SurveyCrosstab->setVariables($seq1,$spr1,$grd1,$seq2,$spr2,$grd2);
+ $this->SurveyCrosstab->displayCrosstabsTable();
+ }
+
+ echo '<br/>';
+ }
+
+ }
+ function getMeansFromKey($frequencys) {
+ $sum = 0;
+ if (count($frequencys['valid']) > 0) {
+ foreach ($frequencys['valid'] AS $fkey => $tmp) {
+
+ $sum += (int)$fkey * (int)$tmp['cnt'];
+ }
+ }
+ $mean = (int)$frequencys['validCnt'] > 0 ? (int)$sum / (int)$frequencys['validCnt'] : 0;
+ return $mean;
+ }
+
+ function getTextFromKey($frequencys) {
+ $texts = array();
+ if (count($frequencys['valid']) > 0) {
+ foreach ($frequencys['valid'] AS $fkey => $tmp) {
+ $texts[] = $tmp;
+ }
+ }
+ return $texts;
+ }
+
+ function DisplayLink($hideAdvanced = true) {
+ global $lang;
+ if ($_GET['m'] == M_ANALYSIS_BREAK) {
+ $css = ' black';
+ } else {
+ $css = ' gray';
+ }
+
+ if ($hideAdvanced == false) {
+ echo '<li>';
+ echo '<span class="as_link'.$css.'" title="' . $lang['srv_break'] . '"><a class="gray" href="index.php?anketa='.$this->sid.'&a=analysis&m=break">' . $lang['srv_break'] . '</a></span>'."\n";
+ echo '</li>';
+ echo '<li class="space">&nbsp;</li>';
+ }
+ }
+
+
+ // Izvoz pdf in rtf
+ function displayExport ($spr, $seq) {
+
+ if ((int)$spr > 0 && (int)$seq > 0) {
+ $href_pdf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=break_izpis&anketa='.$this->sid);
+ $href_rtf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=break_izpis_rtf&anketa='.$this->sid);
+ $href_xls = makeEncodedIzvozUrlString('izvoz.php?b=export&m=break_izpis_xls&anketa='.$this->sid);
+ echo '<script>';
+ # nastavimopravilne linke
+ echo '$("#secondNavigation_links a#breakDoPdf").attr("href", "'.$href_pdf.'");';
+ echo '$("#secondNavigation_links a#breakDoRtf").attr("href", "'.$href_rtf.'");';
+ echo '$("#secondNavigation_links a#breakDoXls").attr("href", "'.$href_xls.'");';
+ # prikažemo linke
+ echo '$("#hover_export_icon").removeClass("hidden");';
+ echo '$("#secondNavigation_links a").removeClass("hidden");';
+ echo '</script>';
+ }
+ }
+
+ // Nastavitve na dnu
+ function displayBottomSettings(){
+ global $site_path;
+ global $lang;
+ global $global_user_id;
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $lan_print = ' title="'.$lang['PRN_Izpis'].'"';
+ $lan_pdf = ' title="'.$lang['PDF_Izpis'].'"';
+ $lan_rtf = ' title="'.$lang['RTF_Izpis'].'"';
+ $lan_xls = ' title="'.$lang['XLS_Izpis'].'"';
+
+ echo '<div class="analysis_bottom_settings printHide">';
+
+ echo '<a href="#" onClick="addCustomReportAllElementsAlert(9);" title="'.$lang['srv_custom_report_comments_add_hover'].'" class="'.(!$userAccess->checkUserAccess('analysis_analysis_creport') ? 'user_access_locked' : '').'" user-access="analysis_analysis_creport" style="margin-right: 40px;"><span class="spaceRight faicon comments_creport" ></span><span class="bold">'.$lang['srv_custom_report_comments_add'].'</span></a>';
+
+ echo '<a href="#" onClick="printAnaliza(\'Break\'); return false;"'.$lan_print.' class="srv_ico"><span class="faicon print icon-grey_dark_link"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=break_izpis&anketa=' . $this->sid) . '" target="_blank"'.$lan_pdf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon pdf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=break_izpis_rtf&anketa=' . $this->sid) . '" target="_blank"'.$lan_rtf.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon rtf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?b=export&m=break_izpis_xls&anketa=' . $this->sid) . '" target="_blank"'.$lan_xls.' class="srv_ico '.(!$userAccess->checkUserAccess('analysis_export') ? 'user_access_locked' : '').'" user-access="analysis_export"><span class="faicon xls black very_large"></span></a>';
+
+ echo '<a href="#" onclick="doArchiveBreak();" title="'.$lang['srv_analiza_arhiviraj_ttl'].'" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv black very_large"></span></a>';
+ echo '<a href="#" onclick="createArchiveBreakBeforeEmail();" title="'.$lang['srv_analiza_arhiviraj_email_ttl'] . '" class="'.(!$userAccess->checkUserAccess('archive') ? 'user_access_locked' : '').'" user-access="archive"><span class="faicon arhiv_mail black very_large"></span></a>';
+
+ echo '</div>';
+
+ // Javascript s katerim povozimo urlje za izvoze, ki niso na voljo v paketu
+ global $app_settings;
+ if($app_settings['commercial_packages'] == true){
+ echo '<script> userAccessExport(); </script>';
+ }
+ }
+
+ function setSessionPercent() {
+
+ if (isset($_POST['break_percent'])) {
+ $this->sessionData['break']['break_percent'] = ($_POST['break_percent'] == 'true') ? true : false;
+ $this->break_percent = $this->sessionData['break']['break_percent'];
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ $this->break_percent = isset($this->sessionData['break']['break_percent']) && (int)$this->sessionData['break']['break_percent'] == 1 ? true : false;
+ }
+
+ function setSessionCharts() {
+
+ if (isset($_POST['break_charts'])) {
+ $this->sessionData['break']['break_show_charts'] = ($_POST['break_charts'] == 1) ? 1 : 0;
+ $this->break_charts = $this->sessionData['break']['break_show_charts'];
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ $this->break_charts = isset($this->sessionData['break']['break_show_charts']) && (int)$this->sessionData['break']['break_show_charts'] == 1 ? 1 : 0;
+ }
+
+ function displayLinePercent() {
+ global $lang;
+ echo '<label><input id="break_percent" name="break_percent" onchange="change_break_percent();" type="checkbox" ' . ((int)$this->break_percent == 1 ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo $lang['srv_analiza_crosstab_odstotek_vrstice_short'].'</label>';
+ }
+
+ function displayLineCharts() {
+ global $lang;
+
+ echo '<span class="spaceLeft">';
+
+ echo ' <label for="break_charts_0"><input type="radio" value="0" name="break_charts" id="break_charts_0" '.((int)$this->break_charts == 0 ? ' checked="checked" ' : '').' onClick="change_break_charts(this.value)" />'.$lang['srv_tables'].'</label>';
+ echo ' <label for="break_charts_1"><input type="radio" value="1" name="break_charts" id="break_charts_1" '.((int)$this->break_charts == 1 ? ' checked="checked" ' : '').' onClick="change_break_charts(this.value)" />'.$lang['srv_charts'].'</label>';
+
+ echo '</span>';
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyChart.php b/admin/survey/classes/surveyAnalysis/class.SurveyChart.php
new file mode 100644
index 0000000..461468f
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyChart.php
@@ -0,0 +1,10829 @@
+<?php
+/**
+* @author Peter Hrvatin
+* @date Februar 2011
+*/
+
+define("SAA_FOLDER", "AnalysisArchive");
+
+class SurveyChart {
+
+ public static $anketa; # id ankete
+ public static $folder = ''; # pot do folderja
+ private static $headFileName = null; # pot do header fajla
+ private static $dataFileName = null; # pot do data fajla
+ private static $dataFileStatus = null; # status data datoteke
+ private static $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ public static $uid; # id userja
+
+ public static $inited = false; # ali smo razred inicializirali
+
+ public static $current_loop = 'undefined'; # v kateri zanki smo (ce imamo skupine)
+
+ public static $skin = '1ka'; # nastavitev skina za grafe
+ public static $numbering = 0; # stevilcenje vprasanj
+ public static $fontSize = 8; # velikost fonta v grafih
+ public static $quality = 1; # kvaliteta (sirina) slike (1 -> 800px, 2 -> 1600px)
+
+ public static $num_records = 10;
+ public static $numerusText = ''; // dodaten text pri numerusu (veljavni, navedbe)
+
+ public static $settings = array(); // nastavitve grafa
+
+ public static $settings_mode=0; // zavihek nastavitev (osnovno/napredno)
+
+ public static $returnChartAsHtml = false; # ali vrne rezultat analiz kot html ali ga izpiše
+ public static $isArchive = false; # nastavimo na true če smo v arhivu
+ public static $chartArchiveTime = ''; # unikatnost
+ public static $publicChart = false; # ali smo preko public povezave
+
+ private static $sessionData; // podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+ private static $survey = null; # podatki ankete
+
+ private static $baseImageUrl = "";
+
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ static function Init( $anketa = null ) {
+ global $global_user_id, $site_path, $site_url;
+
+ self::$folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ((int)$anketa > 0) { # če je poadan anketa ID
+
+ self::$anketa = $anketa;
+
+ self::$baseImageUrl = $site_url . 'admin/survey/';
+ #inicializiramo SurveyAnalasys
+ SurveyAnalysis::Init(self::$anketa);
+
+ //SurveyAnalysis::$setUpJSAnaliza = false;
+
+ #inicializiramo class za datoteke
+ self::$SDF = SurveyDataFile::get_instance();
+ self::$SDF->init($anketa);
+ self::$headFileName = self::$SDF->getHeaderFileName();
+ self::$dataFileName = self::$SDF->getDataFileName();
+ self::$dataFileStatus = self::$SDF->getStatus();
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA
+ || self::$dataFileStatus == FILE_STATUS_NO_FILE
+ || self::$dataFileStatus == FILE_STATUS_SRV_DELETED){
+
+ // Zakaj je treba da je tukaj exit?
+ //exit;
+ return false;
+ }
+
+ //polovimo podatke o nastavitvah trenutnega profila (missingi..)
+ SurveyAnalysis::$missingProfileData = SurveyMissingProfiles::getProfile(SurveyAnalysis::$currentMissingProfile);
+
+ #preberemo HEADERS iz datoteke
+ SurveyAnalysis::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ SurveyAnalysis::removeSystemVariables();
+
+ SurveyInfo :: getInstance()->SurveyInit(self::$anketa);
+ self::$survey = SurveyInfo::getInstance()->getSurveyRow();
+
+ }
+ else {
+ die("Napaka!");
+ }
+
+ if ( SurveyInfo::getInstance()->SurveyInit(self::$anketa))
+ {
+ self::$uid = $global_user_id;
+ SurveyUserSetting::getInstance()->Init(self::$anketa, self::$uid);
+ }
+
+ SurveyZankaProfiles :: Init(self::$anketa, $global_user_id);
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init(self::$anketa);
+ self::$sessionData = SurveyUserSession::getData('charts');
+
+ //$chartTableMore = SurveyDataSettingProfiles :: getSetting('chartTableMore');
+ //self::$num_records = ($chartTableMore == 0) ? 10 : 1000;
+ $result = SurveyDataSettingProfiles :: getSetting('numOpenAnswers');
+ self::$num_records = ($result > 0) ? $result : 30;
+
+ self::$skin = (SurveyUserSetting::getInstance()->getSettings('default_chart_profile_skin') == null ? '1ka' : SurveyUserSetting::getInstance()->getSettings('default_chart_profile_skin'));
+ self::$numbering = SurveyDataSettingProfiles :: getSetting('chartNumbering');
+ self::$fontSize = SurveyDataSettingProfiles :: getSetting('chartFontSize');
+
+ self::$quality = (isset(self::$sessionData['hq']) && self::$sessionData['hq'] == 1) ? 3 : 1;
+ }
+
+ /**
+ * Funkcija ki jo klicemo periodicno za vzdrzevanje cacha
+ *
+ * @param int $charts_num - stevilo grafov ki jih ustvarimo za vsako anketo
+ * @param int $expire_time - starejse grafe od $expire_time dni brisemo
+ */
+ static function chartCache($charts_num = 5, $expire_time = 10){
+
+ // loop cez vse ankete za katere urejamo cache
+ $sql = sisplet_query("SELECT id FROM srv_anketa WHERE edit_time >= NOW() - INTERVAL ".$expire_time." DAY");
+ while($row = mysqli_fetch_assoc($sql)){
+
+ echo $row['id'].'<br>';
+
+ self::Init($row['id']);
+ self::createCache($charts_num);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+ }
+
+ // Na koncu pobrisemo vse stare grafe - ki so bili ustvarjeni vec kot 3 mesece nazaj
+ self::clearCache($expire_time * 9);
+ }
+
+ // Pobrisemo stare (starejse od $expire_time v dnevih) slike grafov iz cache folderja
+ static function clearCache($expire_time = 14){
+
+ $folderPath = dirname(__FILE__).'/../../pChart/Cache/';
+ $fileTypes = '*';
+
+ // Pobrisemo file starejse od
+ $expire_time = $expire_time * 24 * 60 * 60;
+
+ foreach (glob($folderPath . $fileTypes) as $Filename) {
+
+ // preberemo cas dostopa do fila
+ //$FileCreationTime = fileatime($Filename);
+ // preberemo cas ustvarjanja fila
+ $FileCreationTime = filemtime($Filename);
+
+ // starost v dnevih
+ $FileAge = round( (time() - $FileCreationTime) / $expire_time );
+
+ if ($FileAge >= ($expire_time)){
+
+ // brisemo stare file
+ //echo 'Datoteka '.$Filename.' je starejša od '.$expire_time.' min in je bila zbrisana.<br />';
+ unlink($Filename);
+ }
+ }
+ }
+
+ // Zgeneriramo prvih $charts_num grafov v cache
+ static function createCache($charts_num = 5){
+ global $site_path;
+
+ # preberemo header
+ if (self::$headFileName !== null ) {
+
+ $vars_count = count(SurveyAnalysis::$_FILTRED_VARIABLES);
+ foreach (SurveyAnalysis::$_HEADERS AS $spid => $spremenljivka) {
+
+ # preverjamo ali je meta
+ if (($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], SurveyAnalysis::$_FILTRED_TYPES ))
+ && (!isset($_spid) || (isset($_spid) && $_spid == $spid)) && in_array($spremenljivka['tip'],array(1,2,3,6,7,8,16,17,18,20) )) {
+
+ # ali imamo sfiltrirano spremenljivko
+ if ( $vars_count == 0 || ($vars_count > 0 && isset(SurveyAnalysis::$_FILTRED_VARIABLES[$spid])) ) {
+
+ // defult nastavitve posameznega grafa
+ self::$settings = self::getDefaultSettings();
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, self::$settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0 in ni variabel v vprasanju preskocimo graf
+ if($DataSet != 0 && $DataSet != -1){
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, self::$settings, $DataSet->GetNumerus());
+
+ if($charts_num > 0){
+ # prikazujemo v odvisnosti od kategorije spremenljivke
+ switch ($spremenljivka['tip']) {
+ case 1: # radio
+ case 3: # dropdown
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 2: #checkbox
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 6: # multigrid
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 7: # število
+ case 8: # datum
+ case 22: # compute
+ case 25: # kvota
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 16: # multicheckbox
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createVerStructBars($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 17: # razvrščanje
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 20: # multi number
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createRadar($DataSet, $spremenljivka);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ case 18: # vsota
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+ $Test = self::createPie($DataSet, $spremenljivka, self::$settings['show_legend']);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+ $charts_num--;
+ break;
+
+ default: # vsi ostali
+ break;
+ }
+ }
+
+ // Dosezemo limit stevila grafov za generiranje
+ else
+ break;
+
+ }
+
+ }
+
+ } // end if $spremenljivka['tip'] != 'm'
+
+ } // end foreach self::$_HEADERS
+
+ } // end if else ($_headFileName == null)
+ }
+
+ static function display(){
+ global $site_path;
+ global $lang;
+
+ # zakeširamo vsebino, in jo nato po potrebi zapišpemo v html
+ if (self::$returnChartAsHtml != false) {
+ ob_start();
+ }
+
+ // prikazemo nastavitve
+ if (self::$isArchive != true && self::$publicChart != true) {
+ self::displayGlobalSettings();
+ echo "<br/>\n";
+ }
+
+ # preberemo header
+ if (self::$headFileName !== null ) {
+
+ echo '<div id="div_analiza_data" class="charts">';
+
+ if(self::$isArchive != true && self::$publicChart != true) {
+ SurveyAnalysis::$_LOOPS = SurveyZankaProfiles::getFiltersForLoops();
+ }
+
+ # če nimamo zank
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0){
+ self::$current_loop = 'undefined';
+ self::displayCharts();
+ }
+ else{
+ $loop_cnt = 0;
+ # če mamo zanke
+ foreach(SurveyAnalysis::$_LOOPS AS $loop) {
+ $loop_cnt++;
+ $loop['cnt'] = $loop_cnt;
+ SurveyAnalysis::$_CURRENT_LOOP = $loop;
+
+ self::$current_loop = $loop_cnt;
+
+ echo '<h2>'.$lang['srv_zanka_note'].$loop['text'].'</h2>';
+
+ self::displayCharts();
+ }
+ }
+
+ echo '</div>';
+
+ if (self::$isArchive != true && self::$publicChart != true) {
+ self::displayBottomSettings();
+ }
+
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData(self::$sessionData, 'charts');
+
+ } // end if else ($_headFileName == null)
+
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ return;
+ } else {
+ $result = ob_get_clean();
+ ob_flush(); flush();
+ return $result;
+ }
+
+ }
+
+ static function displayCharts(){
+ global $lang;
+ global $site_path;
+
+ # polovimo frekvence
+ SurveyAnalysis::getFrequencys();
+
+ $vars_count = count(SurveyAnalysis::$_FILTRED_VARIABLES);
+
+ foreach (SurveyAnalysis::$_HEADERS AS $spid => $spremenljivka) {
+ # preverjamo ali je meta
+ if (($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], SurveyAnalysis::$_FILTRED_TYPES ))
+ && (!isset($_spid) || (isset($_spid) && $_spid == $spid))
+ && $spremenljivka['tip'] != 5) {
+ # ali imamo sfiltrirano spremenljivko
+ if ($vars_count == 0 || ($vars_count > 0 && isset(SurveyAnalysis::$_FILTRED_VARIABLES[$spid]) ) ) {
+
+ // preberemo ze nastavljene nastavitve posameznega grafa iz sessiona
+ if(isset(self::$sessionData[$spid][self::$current_loop]) && self::$current_loop != 'undefined'){
+ self::$settings = self::$sessionData[$spid][self::$current_loop];
+ }
+ else if(isset(self::$sessionData[$spid]) && self::$current_loop == 'undefined'){
+ self::$settings = self::$sessionData[$spid];
+ }
+ // nastavimo default nastavitve za vsak graf
+ else{
+ self::$settings = self::getDefaultSettings();
+
+
+ // ce imamo numeric dropdown popravimo default graf na skupinski
+ if($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)){
+ self::$settings['type'] = 5;
+ }
+ else{
+ // Ce imamo radio tip in manj kot 5 variabel in numeric oz 2 variabli - po defaultu prikazemo piechart
+ $vars = (is_countable($spremenljivka['options'])) ? count($spremenljivka['options']) : 0;
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) && (($vars < 5 && $spremenljivka['skala'] == 1) || $vars < 3) ){
+ self::$settings['type'] = 2;
+ }
+
+ // Ce imamo radio tip in vec kot 20 variabel -> po defaultu ne prikazujemo praznih
+ $vars = (is_countable($spremenljivka['options'])) ? count($spremenljivka['options']) : 0;
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) && $vars > 20 ){
+ self::$settings['hideEmptyVar'] = 1;
+ }
+ }
+
+
+ // Ce imamo checkbox ga po defaultu uredimo po velikosti
+ if($spremenljivka['tip'] == 2){
+ self::$settings['sort'] = 1;
+ }
+ // Ce imamo checkbox in vec kot 20 variabel -> po defaultu ne prikazujemo praznih
+ $vars = (is_countable($spremenljivka['grids'][0]['variables'])) ? count($spremenljivka['grids'][0]['variables']) : 0;
+ if( $spremenljivka['tip'] == 2 && $vars > 20 ){
+ self::$settings['hideEmptyVar'] = 1;
+ }
+
+
+ // Ce imamo multigrid ali multicheckbox in vec kot 20 variabel -> po defaultu ne prikazujemo praznih
+ $vars = (is_countable($spremenljivka['grids'])) ? count($spremenljivka['grids']) : 0;
+ if( ($spremenljivka['tip'] == 6 || $spremenljivka['tip'] == 16) && $vars > 20 ){
+ self::$settings['hideEmptyVar'] = 1;
+ }
+
+ // Ce imamo semanticni diferencial po defaultu prikazemo vertikalno crto
+ $vars = (is_countable($spremenljivka['options'])) ? count($spremenljivka['options']) : 0;
+ if($spremenljivka['tip'] == 6 && $spremenljivka['enota'] == 1){
+ self::$settings['type'] = 6;
+ }
+ // Ce imamo mg tip in manj kot 4 gridov po defaultu prikazemo strukturne stolpce
+ elseif($spremenljivka['tip'] == 6 && $vars < 4 && $spremenljivka['enota'] != 3){
+ self::$settings['type'] = 2;
+ }
+
+ // Ce imamo MG vedno sortiramo po povprecijh razen ce imamo semanicni diferencial z 1 variablo
+ $vars = (is_countable($spremenljivka['grids'])) ? count($spremenljivka['grids']) : 0;
+ if($spremenljivka['tip'] == 6 && ($vars != 1 || $spremenljivka['enota'] != 1)){
+ self::$settings['sort'] = 1;
+ }
+ // Pri multigridu imamo default obrnjene gride/variable ???
+ /*if( $spremenljivka['tip'] == 6 ){
+ self::$settings['rotate'] = 1;
+ }*/
+
+
+ // pri number po defaultu prikazemo legendo
+ if($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22){
+ self::$settings['show_legend'] = 1;
+ }
+
+
+ // Ce imamo razvrscanje ga po defaultu uredimo po velikosti
+ if($spremenljivka['tip'] == 17){
+ self::$settings['sort'] = 1;
+ }
+
+
+ // Vsota ima po novem default hor. stolpce
+ if($spremenljivka['tip'] == 18)
+ self::$settings['type'] = 2;
+
+
+ // Ce imamo multinumber in samo en grid po defaultu prikazemo stolpce in zarotiramo grids/vars
+ $vars = $spremenljivka['grids']['0']['cnt_vars'];
+ if( $spremenljivka['tip'] == 20 && $vars == 1 ){
+ self::$settings['type'] = 1;
+ self::$settings['rotate'] = 1;
+ }
+ }
+
+ // Spremenimo default alignment vseh tabel ce imamo vklopljeno levo poravnavo
+ $chartTableAlign = SurveyDataSettingProfiles :: getSetting('chartTableAlign');
+ if($chartTableAlign == 1){
+ //popravimo tabele za other
+ self::$settings['otherType'] = 1;
+
+ //popravimo se vse ostale tabele
+ if(in_array($spremenljivka['tip'], array(19,21,4))){
+ self::$settings['show_legend'] = 1;
+ }
+ }
+ else{
+ //popravimo tabele za other
+ self::$settings['otherType'] = 0;
+
+ //popravimo se vse ostale tabele
+ if(in_array($spremenljivka['tip'], array(19,21,4))){
+ self::$settings['show_legend'] = 0;
+ }
+ }
+
+ # prikazujemo v odvisnosti od kategorije spremenljivke
+ switch ($spremenljivka['tip']) {
+ case 1: # radio
+ case 3: # dropdown
+ self::displayRadioChart($spid, self::$settings);
+ break;
+
+ case 2: #checkbox
+ self::displayCheckboxChart($spid, self::$settings);
+ break;
+
+ case 6: # multigrid
+ // dvojna tabela
+ if($spremenljivka['enota'] == 3)
+ self::displayDoubleMultigridChart($spid, self::$settings);
+ else
+ self::displayMultigridChart($spid, self::$settings);
+ break;
+
+ case 7: # število
+ case 22: # compute
+ self::displayNumberChart($spid, self::$settings);
+ break;
+
+ case 8: # datum
+ self::displayDateChart($spid, self::$settings);
+ break;
+
+ case 25: # kvota
+ break;
+
+ case 16: # multicheckbox
+ self::displayMulticheckboxChart($spid, self::$settings);
+ break;
+
+ case 17: # razvrščanje
+ self::displayRankingChart($spid, self::$settings);
+ break;
+
+ case 20: # multi number
+ self::displayMultinumberChart($spid, self::$settings);
+ break;
+
+ case 18: # vsota
+ self::displayVsotaChart($spid, self::$settings);
+ break;
+
+ case 4: # text
+ self::frequencyVertical($spid);
+ break;
+
+ case 5: # nagovor
+ /*if(self::$view == 0)
+ SurveyAnalysis::sumNagovor($spid,'sums');*/
+ break;
+
+ case 19: # multitext
+ self::sumMultiText($spid);
+ break;
+
+ case 21: # besedilo*
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ self::frequencyVertical($spid);
+ } else {
+ self::frequencyVertical($spid);
+ }
+ break;
+ case 27:
+ # heatmap
+ SurveyAnalysis::heatmapGraph($spid,'sums',true, true);
+ break;
+
+ default:
+ break;
+ }
+ //echo '</div>'.NEW_LINE;
+ }
+
+ } // end if $spremenljivka['tip'] != 'm'
+
+ } // end foreach self::$_HEADERS
+
+ }
+
+ static function displaySingle($spid){
+ global $site_path;
+ global $lang;
+
+ // Ce delamo arhiv iz custom reporta ne izvajamo ob_starta in ob_get_clean
+ $archiveFromCReport = (($_GET['a'] == 'submitArchiveAnaliza' || $_GET['a'] == 'createArchiveBeforeEmail') && $_POST['podstran'] == 'analysis_creport') ? true : true;
+
+ # zakeširamo vsebino, in jo nato po potrebi zapišpemo v html
+ if (self::$returnChartAsHtml != false && $archiveFromCReport == false) {
+ ob_start();
+ }
+
+ // prikazemo nastavitve
+ /*self::displaySettings();
+ echo "<br/>\n";
+ echo "<br/>\n";*/
+
+ # preberemo header
+ if (self::$headFileName !== null ) {
+
+ echo '<div id="div_analiza_data" class="charts">';
+
+ $vars_count = count(SurveyAnalysis::$_FILTRED_VARIABLES);
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ SurveyAnalysis::getFrequencys();
+
+ # preverjamo ali je meta
+ if (($spremenljivka['tip'] != 'm'
+ && in_array($spremenljivka['tip'], SurveyAnalysis::$_FILTRED_TYPES ))
+ && (!isset($_spid) || (isset($_spid) && $_spid == $spid))
+ && $spremenljivka['tip'] != 5) {
+ # ali imamo sfiltrirano spremenljivko
+ if ($vars_count == 0 || ($vars_count > 0 && isset(SurveyAnalysis::$_FILTRED_VARIABLES[$spid]) ) ) {
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'">';
+
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'"></div>';
+
+ // defult nastavitve posameznega grafa
+ if(isset(self::$sessionData[$spid])){
+ self::$settings = self::$sessionData[$spid];
+ }
+ else{
+
+ self::$settings = self::getDefaultSettings();
+
+ // Ce imamo radio tip in manj kot 5 variabel po defaultu prikazemo piechart
+ $vars = count($spremenljivka['options']);
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) && $vars < 5 && $spremenljivka['skala'] == 1){
+ self::$settings['type'] = 2;
+ }
+
+ // Ce imamo mg tip in manj kot 5 variabel po defaultu prikazemo en strukturni stolpec
+ /*$vars = $spremenljivka['cnt_all'];
+ if( ($spremenljivka['tip'] == 6) && $vars < 5 ){
+ self::$settings['type'] = 2;
+ }*/
+ // Ce imamo semanticni diferencial po defaultu prikazemo vertikalno crto
+ if($spremenljivka['tip'] == 6 && $spremenljivka['enota'] == 1){
+ self::$settings['type'] = 6;
+ }
+ // Ce imamo mg tip in manj kot 5 gridov po defaultu prikazemo strukturne stolpce
+ elseif($spremenljivka['tip'] == 6 && $vars < 5 && $spremenljivka['enota'] != 3){
+ self::$settings['type'] = 2;
+ }
+
+ // Vsota ima po novem default hor. stolpce
+ if($spremenljivka['tip'] == 18)
+ self::$settings['type'] = 2;
+
+ // Ce imamo multinumber in samo en grid po defaultu prikazemo stolpce in zarotiramo grids/vars
+ $vars = $spremenljivka['grids']['0']['cnt_vars'];
+ if( $spremenljivka['tip'] == 20 && $vars == 1 ){
+ self::$settings['type'] = 1;
+ self::$settings['rotate'] = 1;
+ }
+ }
+
+ // Spremenimo default alignment vseh tabel ce imamo vklopljeno levo poravnavo
+ $chartTableAlign = SurveyDataSettingProfiles :: getSetting('chartTableAlign');
+ if($chartTableAlign == 1){
+ //popravimo tabele za other
+ self::$settings['otherType'] = 1;
+
+ //popravimo se vse ostale tabele
+ if(in_array($spremenljivka['tip'], array(19,21,4))){
+ self::$settings['show_legend'] = 1;
+ }
+ }
+ else{
+ //popravimo tabele za other
+ self::$settings['otherType'] = 0;
+
+ //popravimo se vse ostale tabele
+ if(in_array($spremenljivka['tip'], array(19,21,4))){
+ self::$settings['show_legend'] = 0;
+ }
+ }
+
+ # prikazujemo v odvisnosti od kategorije spremenljivke
+ switch ($spremenljivka['tip']) {
+ case 1: # radio
+ case 3: # dropdown
+ self::displayRadioChart($spid, self::$settings);
+ break;
+ case 2: #checkbox
+ self::displayCheckboxChart($spid, self::$settings);
+ break;
+ case 6: # multigrid
+ // dvojna tabela
+ if($spremenljivka['enota'] == 3)
+ self::displayDoubleMultigridChart($spid, self::$settings);
+ else
+ self::displayMultigridChart($spid, self::$settings);
+ break;
+ case 7: # število
+ case 22: # compute
+ self::displayNumberChart($spid, self::$settings);
+ break;
+ case 8: # datum
+ self::displayDateChart($spid, self::$settings);
+ break;
+ case 25: # kvota
+ //self::displayNumberChart($spid, self::$settings);
+ break;
+ case 16: # multicheckbox
+ self::displayMulticheckboxChart($spid, self::$settings);
+ break;
+ case 17: # razvrščanje
+ self::displayRankingChart($spid, self::$settings);
+ break;
+ case 20: # multi number
+ self::displayMultinumberChart($spid, self::$settings);
+ //self::frequencyVertical($spid);
+ break;
+ case 18: # vsota
+ self::displayVsotaChart($spid, self::$settings);
+ break;
+ case 4: # text
+ //SurveyAnalysis::sumTextVertical($spid,'sums');
+ self::frequencyVertical($spid);
+ break;
+ case 5: # nagovor
+ /*if(self::$view == 0)
+ SurveyAnalysis::sumNagovor($spid,'sums');*/
+ break;
+ case 19: # multitext
+ //SurveyAnalysis::sumMultiText($spid,'sums');
+ //self::frequencyVertical($spid);
+ self::sumMultiText($spid);
+ break;
+ case 21: # besedilo*
+ if ($spremenljivka['cnt_all'] == 1) {
+ // če je enodimenzionalna prikažemo kot frekvence
+ // predvsem zaradi vprašanj tipa: language, email...
+ //SurveyAnalysis::sumTextVertical($spid,'sums');
+ self::frequencyVertical($spid);
+ } else {
+ //SurveyAnalysis::sumMultiText($spid,'sums');
+ self::frequencyVertical($spid);
+ }
+ break;
+ default:
+ break;
+ }
+ echo '</div>'.NEW_LINE;
+
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData(self::$sessionData, 'charts');
+ }
+
+ } // end if $spremenljivka['tip'] != 'm'
+
+ echo '</div>';
+
+ //self::displayBottomSettings();
+
+ } // end if else ($_headFileName == null)
+
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ return;
+ }
+ else {
+ if($archiveFromCReport == false){
+ $result = ob_get_clean();
+ ob_flush(); flush();
+ return $result;
+ }
+ }
+ }
+
+ /**
+ * Izrise graf za posamezno spremenljivko
+ */
+ static function displayRadioChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Ce smo ravnokar preklopili na pieChart vklopimo sortiranje
+ if(self::$current_loop != 'undefined'){
+ if((self::$sessionData[$spid][self::$current_loop]['type'] != 2 && $settings['type'] == 2) || (self::$sessionData[$spid][self::$current_loop]['type'] != 8 && $settings['type'] == 8)){
+ $settings['sort'] = 1;
+ self::$settings['sort'] = 1;
+ }
+ }
+ else{
+ if((self::$sessionData[$spid]['type'] != 2 && $settings['type'] == 2) || (self::$sessionData[$spid]['type'] != 8 && $settings['type'] == 8)){
+ $settings['sort'] = 1;
+ self::$settings['sort'] = 1;
+ }
+ }
+
+ // popravimo nastavitve za numeric dropdown
+ if(self::$current_loop != 'undefined'){
+ if($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)){
+ // Ce smo ravnokar preklopili na linijski - po skupinah imamo default vse intervale
+ if(self::$sessionData[$spid][self::$current_loop]['type'] != 7 && $settings['type'] == 7 ){
+ $settings['interval'] = -1;
+ self::$settings['interval'] = -1;
+ }
+ // Ce smo ravnokar preklopili na navaden - po skupinah imamo default 10 intervalov
+ if(self::$sessionData[$spid][self::$current_loop]['type'] < 5 && $settings['type'] > 4){
+ $settings['interval'] = 10;
+ self::$settings['interval'] = 10;
+ }
+ }
+ }
+ else{
+ if($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)){
+ // Ce smo ravnokar preklopili na linijski - po skupinah imamo default vse intervale
+ if(self::$sessionData[$spid]['type'] != 7 && $settings['type'] == 7 ){
+ $settings['interval'] = -1;
+ self::$settings['interval'] = -1;
+ }
+ // Ce smo ravnokar preklopili na navaden - po skupinah imamo default 10 intervalov
+ if(self::$sessionData[$spid]['type'] < 5 && $settings['type'] > 4){
+ $settings['interval'] = 10;
+ self::$settings['interval'] = 10;
+ }
+ }
+ }
+
+ // Popravimo pri preklopu na povprecje - prikazujemo notranje vrednosti in izklopimo prikaz povprecja
+ if(self::$sessionData[$spid]['type'] != 9 && $settings['type'] == 9){
+ $settings['barLabel'] = 1;
+ self::$settings['barLabel'] = 1;
+
+ $settings['show_avg'] = 0;
+ self::$settings['show_avg'] = 0;
+ }
+
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa - ali ce refreshamo grafe
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Horizontalni stolpci
+ case 0:
+ // Horizontalni stolpci - numeric dropdown
+ case 5:
+ // Horizontalen stolpec - povprecje
+ case 9:
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ break;
+
+ // Navpicni stolpci
+ case 1:
+ // Navpicni stolpci - numeric dropdown
+ case 6:
+ $Test = self::createVerBars($DataSet, $spremenljivka);
+ break;
+
+ // Pie chart
+ case 2:
+ $Test = self::createPie($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // 3D Pie chart
+ case 8:
+ $Test = self::create3DPie($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // Sestavljeni stolpec - horizontalen
+ case 3:
+ $Test = self::createHorStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Sestavljeni stolpec - vertikalen
+ case 4:
+ $Test = self::createVerStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Linijski graf - numeric dropdown
+ case 7:
+ case 22:
+ $Test = self::createLine($DataSet, $spremenljivka);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+
+ if(is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0){
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ static function displayCheckboxChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Popravimo pri preklopu na enote (kjer ne moremo imeti strukturnih stolpcev)
+ if( ($settings['type'] == 2 || $settings['type'] == 7 || $settings['type'] == 3 || $settings['type'] == 4) && $settings['base'] == 0 ){
+ $settings['type'] = 0;
+ }
+ // Popravimo pri preklopu na navedbe (kjer ne moremo imeti radarja in linijskega grafa)
+ if( ($settings['type'] == 5 || $settings['type'] == 6) && $settings['base'] == 1 ){
+ $settings['type'] = 0;
+ }
+
+ // Ce smo ravnokar preklopili na pieChart vklopimo sortiranje
+ if(self::$current_loop != 'undefined'){
+ if((self::$sessionData[$spid][self::$current_loop]['type'] != 2 && $settings['type'] == 2) || (self::$sessionData[$spid][self::$current_loop]['type'] != 7 && $settings['type'] == 7)){
+ $settings['sort'] = 1;
+ self::$settings['sort'] = 1;
+ }
+ }
+ else{
+ if((self::$sessionData[$spid]['type'] != 2 && $settings['type'] == 2) || (self::$sessionData[$spid]['type'] != 7 && $settings['type'] == 7)){
+ $settings['sort'] = 1;
+ self::$settings['sort'] = 1;
+ }
+ }
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Horizontalni stolpci
+ case 0:
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ break;
+
+ // Vodoravni stolpci
+ case 1:
+ $Test = self::createVerBars($DataSet, $spremenljivka);
+ break;
+
+ // Pie chart
+ case 2:
+ $Test = self::createPie($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // 3D Pie chart
+ case 7:
+ case 22:
+ $Test = self::create3DPie($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // Sestavljeni stolpec - horizontalen
+ case 3:
+ $Test = self::createHorStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Sestavljeni stolpec - vertikalen
+ case 4:
+ $Test = self::createVerStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Radar
+ case 5:
+ $Test = self::createRadar($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // Linijski graf
+ case 6:
+ $Test = self::createLine($DataSet, $spremenljivka);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ if($settings['base'] == 1)
+ echo '(r = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ else
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '<br /><span class="subtitle">'.$lang['srv_info_checkbox'];
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ $addHeight = ($settings['type'] == 2) ? 'style="height: 245px"' : '';
+
+ echo '<div class="chart_settings printHide iconHide" '.$addHeight.'>';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+
+ if(is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0){
+
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ static function displayNumberChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ if(self::$current_loop != 'undefined'){
+ // Ce smo ravnokar preklopili na linijski - po skupinah imamo default vse intervale
+ if(self::$sessionData[$spid][self::$current_loop]['type'] != 2 && $settings['type'] == 2){
+ $settings['interval'] = -1;
+ self::$settings['interval'] = -1;
+ }
+ // Ce smo ravnokar preklopili na navaden - po skupinah imamo default 10 intervalov
+ if(self::$sessionData[$spid][self::$current_loop]['type'] >= 2 && $settings['type'] < 2){
+ $settings['interval'] = 10;
+ self::$settings['interval'] = 10;
+ }
+ }
+ else{
+ // Ce smo ravnokar preklopili na linijski - po skupinah imamo default vse intervale
+ if(self::$sessionData[$spid]['type'] != 2 && $settings['type'] == 2){
+ $settings['interval'] = -1;
+ self::$settings['interval'] = -1;
+ }
+ // Ce smo ravnokar preklopili na navaden - po skupinah imamo default 10 intervalov
+ if(self::$sessionData[$spid]['type'] >= 2 && $settings['type'] < 2){
+ $settings['interval'] = 10;
+ self::$settings['interval'] = 10;
+ }
+ }
+
+ // Popravimo pri preklopu na povprecje - prikazujemo notranje vrednosti in izklopimo prikaz povprecja
+ if(self::$sessionData[$spid]['type'] != 9 && $settings['type'] == 9){
+ $settings['barLabel'] = 1;
+ self::$settings['barLabel'] = 1;
+
+ $settings['show_avg'] = 0;
+ self::$settings['show_avg'] = 0;
+ }
+
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Horizontalni stolpci - po skupinah ali navadno
+ case 0:
+ case 3:
+ // Horizontalen stolpec - povprecje
+ case 9:
+ $Test = self::createHorBars($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // Vertikalni stolpci - po skupinah ali navadno
+ case 1:
+ case 4:
+ $Test = self::createVerBars($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // Line chart - po skupinah
+ case 2:
+ $Test = self::createLine($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ echo '</div>';
+ }
+
+ static function displayDateChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Horizontalni stolpci - po skupinah ali navadno
+ case 0:
+ case 3:
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ break;
+
+ // Vertikalni stolpci - po skupinah ali navadno
+ case 1:
+ case 4:
+ $Test = self::createVerBars($DataSet, $spremenljivka);
+ break;
+
+ // Line chart
+ case 2:
+ $Test = self::createLine($DataSet, $spremenljivka);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ echo '</div>';
+ }
+
+ static function displayMultigridChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ //ce imamo nominalno spremenljivko ali ce je samo 1 variabla nimamo povprecij
+ if( ($spremenljivka['cnt_all'] == 1 || $spremenljivka['skala'] == 1) && ($settings['type'] == 0 || $settings['type'] == 5 || $settings['type'] == 6) ){
+ $settings['type'] = 2;
+ }
+
+ //ce imamo navadne stolpce (ne povprecij) - ugasnemo labele vrednosti na stolpcih
+ if( $settings['type'] == 3 || $settings['type'] == 4 ){
+ $settings['barLabel'] = 0;
+ self::$settings['barLabel'] = 0;
+ }
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Povprecja - horizontalni stolpci
+ case 0:
+ $Test = self::createHorBars($DataSet, $spremenljivka, $settings['show_legend'], $settings['noFixedScale']/*$fixedScale=1*/);
+ break;
+
+ // Povprecja - vertikalna crta
+ case 6:
+ $Test = self::createVerLine($DataSet, $spremenljivka, $settings['show_legend'], $settings['noFixedScale']);
+ break;
+
+ // Povprecja - radar
+ case 5:
+ $Test = self::createRadar($DataSet, $spremenljivka, $settings['show_legend'], $settings['noFixedScale']);
+ break;
+
+ // Sestavljeni stolpci - navpicni
+ case 1:
+ $Test = self::createVerStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Sestavljeni stolpci - vodoravni
+ case 2:
+ $Test = self::createHorStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Navpicni stolpci
+ case 3:
+ $Test = self::createVerBars($DataSet, $spremenljivka, 1);
+ break;
+
+ // Horizontalni stolpci
+ case 4:
+ $Test = self::createHorBars($DataSet, $spremenljivka, 1);
+ break;
+
+ // Nominalni radar
+ case 7:
+ case 22:
+ $Test = self::createRadar($DataSet, $spremenljivka, 1, $fixedScale=0);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+
+ if(is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0){
+
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ static function displayDoubleMultigridChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Horizontal chart
+ case 0:
+ $Test = self::createHorBars($DataSet, $spremenljivka, $legend=1, $settings['noFixedScale']);
+ break;
+
+ // Vertical chart
+ case 1:
+ $Test = self::createVerBars($DataSet, $spremenljivka, $legend=1, $settings['noFixedScale']);
+ break;
+
+ // Line chart
+ case 2:
+ $Test = self::createLine($DataSet, $spremenljivka, $legend=1, $settings['noFixedScale']);
+ break;
+
+ // Vertical line chart
+ case 3:
+ $Test = self::createVerLine($DataSet, $spremenljivka, $legend=1, $settings['noFixedScale']);
+ break;
+
+ // Radar chart
+ case 4:
+ $Test = self::createRadar($DataSet, $spremenljivka, $legend=1, $settings['noFixedScale']);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+
+ if(is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0){
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ static function displayMulticheckboxChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+
+ //Popravimo pri preklopu na enote (kjer ne moremo imeti strukturnih stolpcev)
+ if( ($settings['type'] == 2 || $settings['type'] == 3) && $settings['base'] == 0 ){
+ $settings['type'] = 0;
+ }
+ //Popravimo pri preklopu na navedbe (kjer ne moremo imeti radarja)
+ if( $settings['type'] == 4 && $settings['base'] == 1 ){
+ $settings['type'] = 0;
+ }
+
+ // Popravimo ce preklopimo iz veljavnih enot na navedbe
+ if($settings['base'] == 1 && $settings['value_type'] == 0){
+ $settings['value_type'] = 1;
+ }
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Povprecja
+ /*case 0:
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ break;*/
+
+ // Horizontalni stolpci
+ case 0:
+ $Test = self::createHorBars($DataSet, $spremenljivka, 1);
+ break;
+
+ // Navpicni stolpci
+ case 1:
+ $Test = self::createVerBars($DataSet, $spremenljivka, 1);
+ break;
+
+ // Sestavljeni stolpci - navpicni
+ case 2:
+ $Test = self::createVerStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Sestavljeni stolpci - vodoravni
+ case 3:
+ $Test = self::createHorStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Radar
+ case 4:
+ $Test = self::createRadar($DataSet, $spremenljivka, 1);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+
+ if($settings['base'] == 1)
+ echo '(r = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ else
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+
+ if(is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0){
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ static function displayVsotaChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Ce smo ravnokar preklopili (je session se prazen) na pieChart vklopimo sortiranje
+ if(self::$current_loop != 'undefined'){
+ if((self::$sessionData[$spid][self::$current_loop]['type'] != 0 && $settings['type'] == 0) || (self::$sessionData[$spid][self::$current_loop]['type'] != 5 && $settings['type'] == 5)){
+ $settings['sort'] = 1;
+ self::$settings['sort'] = 1;
+ }
+ }
+ else{
+ if((self::$sessionData[$spid]['type'] != 0 && $settings['type'] == 0) || (self::$sessionData[$spid]['type'] != 5 && $settings['type'] == 5)){
+ $settings['sort'] = 1;
+ self::$settings['sort'] = 1;
+ }
+ }
+
+ // Pri radarju ni sortiranja
+ if($settings['type'] == 4){
+ $settings['sort'] = 0;
+ self::$settings['sort'] = 0;
+ }
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Pie chart - povprecja
+ case 0:
+ $Test = self::createPie($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // 3D Pie chart - povprecja
+ case 5:
+ $Test = self::create3DPie($DataSet, $spremenljivka, $settings['show_legend']);
+ break;
+
+ // Line chart
+ case 1:
+ $Test = self::createLine($DataSet, $spremenljivka);
+ break;
+
+ // Horizontal bars
+ case 2:
+ $Test = self::createHorBars($DataSet, $spremenljivka);
+ break;
+
+ // Vertical bars
+ case 3:
+ $Test = self::createVerBars($DataSet, $spremenljivka);
+ break;
+
+ // Radar
+ case 4:
+ $Test = self::createRadar($DataSet, $spremenljivka);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ echo '</div>';
+ }
+
+ static function displayRankingChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ //$Cache->GetFromCache($ID,$DataSet->GetData());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Povprecja
+ case 0:
+ $Test = self::createHorBars($DataSet, $spremenljivka, $legend=0, $settings['noFixedScale']/*$fixedScale=1*/);
+ break;
+
+ // Sestavljeni stolpci - navpicni
+ case 1:
+ $Test = self::createHorStructBars($DataSet, $spremenljivka);
+ break;
+
+ // Sestavljeni stolpci - vodoravni
+ case 2:
+ $Test = self::createVerStructBars($DataSet, $spremenljivka);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ echo '</div>';
+ }
+
+ static function displayMultinumberChart($spid, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, $settings);
+
+ // nimamo nobenih podatkov in imamo vklopljeno opcijo da ne prikazujemo praznih grafov - vrnemo 0
+ if($DataSet == 0){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ // ni variabel v vprasanju preskocimo graf
+ if($DataSet == -1){
+ return;
+ }
+
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'_loop_'.self::$current_loop.'"></div>';
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = self::generateChartId($spid, $settings, $DataSet->GetNumerus());
+
+ // Ce se nimamo zgeneriranega grafa
+ $refresh = (isset($_GET['refresh'])) ? $_GET['refresh'] : $refresh;
+ if( (!$Cache->isInCache($ID, $DataSet->GetData())) || $refresh == 1 ){
+
+ switch($settings['type']){
+
+ // Povprecja - radar
+ case 0:
+ $Test = self::createRadar($DataSet, $spremenljivka, 1);
+ break;
+
+ // Povprecja - vertikalni stolpci
+ case 1:
+ $Test = self::createVerBars($DataSet, $spremenljivka, 1);
+ break;
+
+ // Povprecja - horizontalni stolpci
+ case 2:
+ $Test = self::createHorBars($DataSet, $spremenljivka, 1);
+ break;
+
+ // Povprecja - linijski graf
+ case 3:
+ $Test = self::createLine($DataSet, $spremenljivka, 1);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ if (self::$isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.self::$anketa.'_'.self::$chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+ $imgUrl = self::$baseImageUrl . $imgPath;
+
+ // zapisemo ime slike v session za izvoze
+ $settings['name'] = $imgName;
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title;
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 0){
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus()/*.self::$numerusText*/.')';
+ echo '</span>';
+ }
+ echo '</div>';
+
+ echo '<div class="chart_img" title="'.$lang['srv_chart_editirajspremenljivko'].'" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ self::displaySingleSettings($spid, $settings);
+ echo '</div>';
+
+ // ce imamo vklopljen nuimerus pod grafom
+ if(SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 3)
+ self::displayBottomChartInfo($DataSet, $spremenljivka);
+
+ if (self::$returnChartAsHtml == false) {
+ flush(); ob_flush();
+ }
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+
+ if(is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0){
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+
+ // Default nastavitve grafov
+ public static function getDefaultSettings(){
+
+ $colors = array_fill(0, 6, '');
+ $limits = array('advanced_settings' => 0);
+
+ $settings = array(
+ 'type' => 0, // tip grafa
+ 'sort' => 0, // sortiranje po velikosti (0->brez, 1->padajoce, 2->narascajoce)
+ // ali MG (0->brez, 1->kategorije (trenutno), 2->povprecje, 3->prva ketegorija)
+ 'value_type' => 0, // tip vrednosti (veljavni, frekvence, procenti...)
+ 'base' => 0, // checkbox / multicheckbox osnova (enote / navedbe)
+ 'show_legend' => 0, // prikaz legende
+ 'scale_limit' => 1, // zacni skalo z 0 / z najmanjso vrednostjo pri numericih ALI prikazi desno skalo pri semanticnem diferencialu
+ 'interval' => 10, // stevilo intervalov pri numericih
+ 'min' => '0', // minimalna vrednost po kateri delamo intervale pri numericih (max-min)/interval
+ 'max' => '', // maximalna vrednost po kateri delamo intervale pri numericih (max-min)/interval
+ 'open_up' => 0, // polodprt interval navzgor (ce so vrednosti nad max) pri numericih
+ 'open_down' => 0, // polodprt interval navzdol (ce so vrednosti pod min) pri numericih
+ 'limits' => $limits, // napredne meje number grafov (custom intervali) - ce je $limits['advanced_settings']==1
+ 'radar_type' => 0, // tip radarja (crte / liki)
+ 'radar_scale' => 0, // skala pri radarju (na osi / diagonalno)
+ '3d_pie' => 0, // tip kroznega grafa (navaden / 3d)
+ 'labelWidth' => 50, // sirina label (50% / 20%)
+ 'barLabel' => 1, // prikaz label v stolpicnih grafih
+ 'barLabelSmall' => 1, // prikaz label pod 5% v stolpicnih grafih (zraven stolpca)
+ 'rotate' => 0, // obrnjeni gridi in variable (pri vseh MG - multiradio, multinumber...)
+ 'colors' => $colors, // custom barve grafa
+ 'show_avg' => -1, // prikaz povprecja na grafu (samo pri ordinalnih radio)
+ 'show_numerus' => 1, // prikaz numerusa na grafu
+ 'otherType' => 0, // poravnava other tabel
+ 'otherFreq' => 0, // izpis frekvenc v other tabeli
+ 'hideEmptyVar' => 0, // ali izpuscamo prazne opcije brez odgovora (ce je nad 20 variabel -> default 1)
+ 'noFixedScale' => 0, // ce izklopimo skalo ki se zacne z 1 (samo pri multigrid povprecjih in ranking povprecjih) ALI prikazi polno skalo pri checkboxu (ce je 1)
+ );
+
+ return $settings;
+ }
+
+ // Zgeneriramo ID grafa za hash
+ public static function generateChartId($spid, $settings, $numerus){
+
+ // ce posebej prizgemo legendo pri pie chartu
+ if($settings['show_legend'] == 1 && $settings['type'] == 2)
+ $legend = '_legend';
+ else
+ $legend = '';
+
+ $ID = self::$anketa.'_chart_'.$spid.'_mv_'.SurveyAnalysis::$missingProfileData['display_mv_type'];
+
+ foreach ($settings AS $key => $val) {
+ if($key == 'colors'){
+
+ $ID .= '_colors';
+
+ foreach ($val AS $colKey => $color){
+ $ID .= '_'.$color;
+ }
+ }
+
+ elseif($key != 'name')
+ $ID .= '_'.$key.'_'.$val;
+ }
+
+ $ID .= '_skin_'.self::$skin;
+
+ $ID .= '_numerus_'.$numerus.'_numerusText_'.SurveyDataSettingProfiles :: getSetting('chartNumerusText');
+
+ $ID .= '_chartAvgText_'.SurveyDataSettingProfiles :: getSetting('chartAvgText');
+
+ $ID .= '_pieZeros_'.SurveyDataSettingProfiles :: getSetting('chartPieZeros');
+
+ $ID .= '_chartFontSize_'.SurveyDataSettingProfiles :: getSetting('chartFontSize');
+
+ $ID .= '_hq_'.self::$quality;
+
+ return $ID;
+ }
+
+ // nastavimo prave barve ustrezne skinu
+ public static function setChartColors($chart, $skin){
+
+ // Ce nimmo posebej nastavljenih barv
+ if(self::$settings['colors'][0] == ''){
+
+ // ce je nastavljen globalen custom skin
+ if(is_numeric($skin)){
+ $skin = self::getCustomSkin($skin);
+ $colors = explode('_', $skin['colors']);
+
+ $count = 0;
+ foreach($colors as $color){
+
+ $rgb = self::html2rgb($color);
+ $chart->setColorPalette($count,$rgb[0],$rgb[1],$rgb[2]);
+ $chart->setColorPalette($count+7,$rgb[0]+50,$rgb[1]+50,$rgb[2]+50);
+ $chart->setColorPalette($count+14,$rgb[0]+100,$rgb[1]+100,$rgb[2]+100);
+
+ $count++;
+ }
+ }
+
+ // imamo nastavljenega enega od default skinov
+ else{
+ switch ($skin){
+
+ // nov 1ka default skin
+ case '1ka':
+ default:
+ $chart->setColorPalette(0,30,136,229);
+ $chart->setColorPalette(1,255,166,8);
+ $chart->setColorPalette(2,72,229,194);
+ $chart->setColorPalette(3,242,87,87);
+ $chart->setColorPalette(4,117,70,68);
+ $chart->setColorPalette(5,248,202,0);
+ $chart->setColorPalette(6,255,112,166);
+
+ $chart->setColorPalette(7,63,81,180);
+ $chart->setColorPalette(8,76,174,80);
+ $chart->setColorPalette(9,204,219,57);
+ $chart->setColorPalette(10,255,235,59);
+ $chart->setColorPalette(11,0,149,135);
+ $chart->setColorPalette(12,121,85,72);
+ $chart->setColorPalette(13,157,157,157);
+ $chart->setColorPalette(14,96,125,138);
+ $chart->setColorPalette(15,155,39,175);
+ $chart->setColorPalette(16,103,58,182);
+ $chart->setColorPalette(17,255,255,103);
+ $chart->setColorPalette(18,255,249,100);
+ $chart->setColorPalette(19,100,255,255);
+ $chart->setColorPalette(20,255,100,255);
+ break;
+
+ // zivahen skin
+ case 'lively':
+ $chart->setColorPalette(0,224,9,13);
+ $chart->setColorPalette(1,4,23,227);
+ $chart->setColorPalette(2,0,255,8);
+ $chart->setColorPalette(3,255,247,3);
+ $chart->setColorPalette(4,255,149,0);
+ $chart->setColorPalette(5,0,251,255);
+ $chart->setColorPalette(6,166,0,255);
+
+ $chart->setColorPalette(7,255,59,63);
+ $chart->setColorPalette(8,54,73,255);
+ $chart->setColorPalette(9,50,255,58);
+ $chart->setColorPalette(10,255,255,53);
+ $chart->setColorPalette(11,255,199,35);
+ $chart->setColorPalette(12,50,255,255);
+ $chart->setColorPalette(13,216,50,255);
+ $chart->setColorPalette(14,255,109,113);
+ $chart->setColorPalette(15,104,123,255);
+ $chart->setColorPalette(16,100,255,108);
+ $chart->setColorPalette(17,255,255,103);
+ $chart->setColorPalette(18,255,249,100);
+ $chart->setColorPalette(19,100,255,255);
+ $chart->setColorPalette(20,255,100,255);
+ break;
+
+ // blag skin
+ case 'mild':
+ $chart->setColorPalette(0,188,224,46);
+ $chart->setColorPalette(1,224,100,46);
+ $chart->setColorPalette(2,224,214,46);
+ $chart->setColorPalette(3,46,151,224);
+ $chart->setColorPalette(4,176,46,224);
+ $chart->setColorPalette(5,224,46,117);
+ $chart->setColorPalette(6,92,224,46);
+
+ $chart->setColorPalette(7,238,255,96);
+ $chart->setColorPalette(8,255,150,96);
+ $chart->setColorPalette(9,255,255,96);
+ $chart->setColorPalette(10,96,201,255);
+ $chart->setColorPalette(11,226,96,255);
+ $chart->setColorPalette(12,255,96,167);
+ $chart->setColorPalette(13,142,255,96);
+ $chart->setColorPalette(14,255,255,146);
+ $chart->setColorPalette(15,255,200,146);
+ $chart->setColorPalette(16,255,255,146);
+ $chart->setColorPalette(17,146,251,255);
+ $chart->setColorPalette(18,255,146,255);
+ $chart->setColorPalette(19,255,146,217);
+ $chart->setColorPalette(20,192,255,146);
+ break;
+
+ // Office skin
+ case 'office':
+ $chart->setColorPalette(0,79,129,189);
+ $chart->setColorPalette(1,192,80,77);
+ $chart->setColorPalette(2,155,187,89);
+ $chart->setColorPalette(3,128,100,162);
+ $chart->setColorPalette(4,75,172,198);
+ $chart->setColorPalette(5,247,150,70);
+ $chart->setColorPalette(6,146,169,207);
+
+ $chart->setColorPalette(7,129,179,239);
+ $chart->setColorPalette(8,242,130,127);
+ $chart->setColorPalette(9,205,237,139);
+ $chart->setColorPalette(10,178,150,212);
+ $chart->setColorPalette(11,125,222,248);
+ $chart->setColorPalette(12,255,200,120);
+ $chart->setColorPalette(13,196,219,255);
+ $chart->setColorPalette(14,179,229,255);
+ $chart->setColorPalette(15,255,180,177);
+ $chart->setColorPalette(16,255,255,189);
+ $chart->setColorPalette(17,228,200,255);
+ $chart->setColorPalette(18,175,255,255);
+ $chart->setColorPalette(19,255,250,170);
+ $chart->setColorPalette(20,226,255,255);
+ break;
+
+ // Pastel skin
+ case 'pastel':
+ $chart->setColorPalette(0,121,159,11);
+ $chart->setColorPalette(1,215,161,37);
+ $chart->setColorPalette(2,146,100,190);
+ $chart->setColorPalette(3,24,132,132);
+ $chart->setColorPalette(4,76,198,139);
+ $chart->setColorPalette(5,138,136,35);
+ $chart->setColorPalette(6,108,153,210);
+
+ $chart->setColorPalette(7,171,209,61);
+ $chart->setColorPalette(8,255,211,87);
+ $chart->setColorPalette(9,196,150,240);
+ $chart->setColorPalette(10,74,182,182);
+ $chart->setColorPalette(11,126,255,189);
+ $chart->setColorPalette(12,188,186,85);
+ $chart->setColorPalette(13,158,203,255);
+ $chart->setColorPalette(14,221,255,111);
+ $chart->setColorPalette(15,255,255,137);
+ $chart->setColorPalette(16,246,200,255);
+ $chart->setColorPalette(17,124,232,255);
+ $chart->setColorPalette(18,176,255,239);
+ $chart->setColorPalette(19,238,236,135);
+ $chart->setColorPalette(20,208,253,255);
+ break;
+
+ // zelen skin
+ case 'green':
+ $chart->createColorGradientPalette(168,188,56,248,255,136,5);
+ $chart->setColorPalette(5,255,255,0);
+ $chart->setColorPalette(6,232,3,182);
+
+ $chart->setColorPalette(7,$chart->Palette['0']['R'],$chart->Palette['0']['G'],$chart->Palette['0']['B']);
+ $chart->setColorPalette(8,$chart->Palette['1']['R'],$chart->Palette['1']['G'],$chart->Palette['1']['B']);
+ $chart->setColorPalette(9,$chart->Palette['2']['R'],$chart->Palette['2']['G'],$chart->Palette['2']['B']);
+ $chart->setColorPalette(10,$chart->Palette['3']['R'],$chart->Palette['3']['G'],$chart->Palette['3']['B']);
+ $chart->setColorPalette(11,$chart->Palette['4']['R'],$chart->Palette['4']['G'],$chart->Palette['4']['B']);
+ $chart->setColorPalette(12,$chart->Palette['5']['R'],$chart->Palette['5']['G'],$chart->Palette['5']['B']);
+ $chart->setColorPalette(13,$chart->Palette['6']['R'],$chart->Palette['6']['G'],$chart->Palette['6']['B']);
+ $chart->setColorPalette(14,$chart->Palette['0']['R'],$chart->Palette['0']['G'],$chart->Palette['0']['B']);
+ $chart->setColorPalette(15,$chart->Palette['1']['R'],$chart->Palette['1']['G'],$chart->Palette['1']['B']);
+ $chart->setColorPalette(16,$chart->Palette['2']['R'],$chart->Palette['2']['G'],$chart->Palette['2']['B']);
+ $chart->setColorPalette(17,$chart->Palette['3']['R'],$chart->Palette['3']['G'],$chart->Palette['3']['B']);
+ $chart->setColorPalette(18,$chart->Palette['4']['R'],$chart->Palette['4']['G'],$chart->Palette['4']['B']);
+ $chart->setColorPalette(19,$chart->Palette['5']['R'],$chart->Palette['5']['G'],$chart->Palette['5']['B']);
+ $chart->setColorPalette(20,$chart->Palette['6']['R'],$chart->Palette['6']['G'],$chart->Palette['6']['B']);
+ break;
+
+ // moder skin
+ case 'blue':
+ //$chart->createColorGradientPalette(82,124,148,174,216,240,5);
+ $chart->setColorPalette(0,30,136,229);
+ $chart->setColorPalette(1,59,151,234);
+ $chart->setColorPalette(2,110,166,238);
+ $chart->setColorPalette(3,137,181,243);
+ $chart->setColorPalette(4,162,196,247);
+ $chart->setColorPalette(5,186,211,251);
+ $chart->setColorPalette(6,209,227,255);
+
+ $chart->setColorPalette(7,$chart->Palette['0']['R'],$chart->Palette['0']['G'],$chart->Palette['0']['B']);
+ $chart->setColorPalette(8,$chart->Palette['1']['R'],$chart->Palette['1']['G'],$chart->Palette['1']['B']);
+ $chart->setColorPalette(9,$chart->Palette['2']['R'],$chart->Palette['2']['G'],$chart->Palette['2']['B']);
+ $chart->setColorPalette(10,$chart->Palette['3']['R'],$chart->Palette['3']['G'],$chart->Palette['3']['B']);
+ $chart->setColorPalette(11,$chart->Palette['4']['R'],$chart->Palette['4']['G'],$chart->Palette['4']['B']);
+ $chart->setColorPalette(12,$chart->Palette['5']['R'],$chart->Palette['5']['G'],$chart->Palette['5']['B']);
+ $chart->setColorPalette(13,$chart->Palette['6']['R'],$chart->Palette['6']['G'],$chart->Palette['6']['B']);
+ $chart->setColorPalette(14,$chart->Palette['0']['R'],$chart->Palette['0']['G'],$chart->Palette['0']['B']);
+ $chart->setColorPalette(15,$chart->Palette['1']['R'],$chart->Palette['1']['G'],$chart->Palette['1']['B']);
+ $chart->setColorPalette(16,$chart->Palette['2']['R'],$chart->Palette['2']['G'],$chart->Palette['2']['B']);
+ $chart->setColorPalette(17,$chart->Palette['3']['R'],$chart->Palette['3']['G'],$chart->Palette['3']['B']);
+ $chart->setColorPalette(18,$chart->Palette['4']['R'],$chart->Palette['4']['G'],$chart->Palette['4']['B']);
+ $chart->setColorPalette(19,$chart->Palette['5']['R'],$chart->Palette['5']['G'],$chart->Palette['5']['B']);
+ $chart->setColorPalette(20,$chart->Palette['6']['R'],$chart->Palette['6']['G'],$chart->Palette['6']['B']);
+ break;
+
+ // rdeč skin
+ case 'red':
+ $chart->createColorGradientPalette(255,0,0,80,10,10,5);
+ $chart->setColorPalette(5,255,255,0);
+ $chart->setColorPalette(6,232,3,182);
+
+ $chart->setColorPalette(7,$chart->Palette['0']['R'],$chart->Palette['0']['G'],$chart->Palette['0']['B']);
+ $chart->setColorPalette(8,$chart->Palette['1']['R'],$chart->Palette['1']['G'],$chart->Palette['1']['B']);
+ $chart->setColorPalette(9,$chart->Palette['2']['R'],$chart->Palette['2']['G'],$chart->Palette['2']['B']);
+ $chart->setColorPalette(10,$chart->Palette['3']['R'],$chart->Palette['3']['G'],$chart->Palette['3']['B']);
+ $chart->setColorPalette(11,$chart->Palette['4']['R'],$chart->Palette['4']['G'],$chart->Palette['4']['B']);
+ $chart->setColorPalette(12,$chart->Palette['5']['R'],$chart->Palette['5']['G'],$chart->Palette['5']['B']);
+ $chart->setColorPalette(13,$chart->Palette['6']['R'],$chart->Palette['6']['G'],$chart->Palette['6']['B']);
+ $chart->setColorPalette(14,$chart->Palette['0']['R'],$chart->Palette['0']['G'],$chart->Palette['0']['B']);
+ $chart->setColorPalette(15,$chart->Palette['1']['R'],$chart->Palette['1']['G'],$chart->Palette['1']['B']);
+ $chart->setColorPalette(16,$chart->Palette['2']['R'],$chart->Palette['2']['G'],$chart->Palette['2']['B']);
+ $chart->setColorPalette(17,$chart->Palette['3']['R'],$chart->Palette['3']['G'],$chart->Palette['3']['B']);
+ $chart->setColorPalette(18,$chart->Palette['4']['R'],$chart->Palette['4']['G'],$chart->Palette['4']['B']);
+ $chart->setColorPalette(19,$chart->Palette['5']['R'],$chart->Palette['5']['G'],$chart->Palette['5']['B']);
+ $chart->setColorPalette(20,$chart->Palette['6']['R'],$chart->Palette['6']['G'],$chart->Palette['6']['B']);
+ break;
+
+ // skin za vec kot 5 moznosti
+ case 'multi':
+ $chart->setColorPalette(0,140,0,0);
+ $chart->setColorPalette(1,240,8,0);
+ $chart->setColorPalette(2,255,138,130);
+ $chart->setColorPalette(3,242,196,200);
+ $chart->setColorPalette(4,11,3,135);
+ $chart->setColorPalette(5,4,0,252);
+ $chart->setColorPalette(6,151,148,242);
+ $chart->setColorPalette(7,0,133,31);
+ $chart->setColorPalette(8,24,217,3);
+ $chart->setColorPalette(9,139,245,157);
+ $chart->setColorPalette(10,237,202,45);
+ $chart->setColorPalette(11,253,255,120);
+ $chart->setColorPalette(12,156,0,125);
+ $chart->setColorPalette(13,255,0,246);
+ $chart->setColorPalette(14,242,3,162);
+ $chart->setColorPalette(15,237,154,216);
+ $chart->setColorPalette(16,0,123,145);
+ $chart->setColorPalette(17,0,204,250);
+ $chart->setColorPalette(18,174,238,245);
+ $chart->setColorPalette(19,0,255,200);
+ $chart->setColorPalette(20,255,111,0);
+ $chart->setColorPalette(21,255,162,0);
+ $chart->setColorPalette(22,255,201,120);
+ $chart->setColorPalette(23,161,92,133);
+ $chart->setColorPalette(24,205,159,245);
+ $chart->setColorPalette(25,179,245,103);
+ $chart->setColorPalette(26,135,171,108);
+ $chart->setColorPalette(27,73,132,145);
+ $chart->setColorPalette(28,70,96,99);
+ $chart->setColorPalette(29,156,95,103);
+ break;
+ }
+ }
+ }
+
+ // Graf ima posebej nastavljen skin
+ else{
+ for($i=0; $i<7; $i++){
+
+ $color = self::$settings['colors'][$i];
+ $rgb = self::html2rgb($color);
+
+ $chart->setColorPalette($i,$rgb[0],$rgb[1],$rgb[2]);
+ $chart->setColorPalette($i+7,$rgb[0]+50,$rgb[1]+50,$rgb[2]+50);
+ $chart->setColorPalette($i+14,$rgb[0]+100,$rgb[1]+100,$rgb[2]+100);
+ }
+ }
+
+ return $chart;
+ }
+
+ public static function getDefaultColors($skin){
+
+ // ce je nastavljen globalen custom skin
+ if(is_numeric($skin)){
+ $skin = self::getCustomSkin($skin);
+ $default_colors = explode('_', $skin['colors']);
+ }
+
+ else{
+ switch($skin){
+ case '1ka':
+ $default_colors = array(0=>'#1e88e5', 1=>'#ffa608', 2=>'#48e5c2', 3=>'#f25757', 4=>'#754668', 5=>'#f8ca00', 6=>'#ff70a6');
+ break;
+ case 'lively':
+ $default_colors = array(0=>'#e9090d', 1=>'#0417e3', 2=>'#00ff08', 3=>'#fff703', 4=>'#ff9500', 5=>'#00fbff', 6=>'#a600ff');
+ break;
+ case 'mild':
+ $default_colors = array(0=>'#bce02e', 1=>'#e0642e', 2=>'#e0d62e', 3=>'#2e97e0', 4=>'#b02ee0', 5=>'#00fbff', 6=>'#5ce02e');
+ break;
+ case 'office':
+ $default_colors = array(0=>'#4f81bd', 1=>'#c0504d', 2=>'#9bbb59', 3=>'#8064a2', 4=>'#4bacc6', 5=>'#f79646', 6=>'#92a9cf');
+ break;
+ case 'pastel':
+ $default_colors = array(0=>'#799f0b', 1=>'#d7a125', 2=>'#9264be', 3=>'#188484', 4=>'#4cc68b', 5=>'#8a8823', 6=>'#6c99d2');
+ break;
+ case 'green':
+ $default_colors = array(0=>'#a8bc38', 1=>'#b8c948', 2=>'#c8d658', 3=>'#d8e468', 4=>'#e8e178', 5=>'#ffff00', 6=>'#e803b6');
+ break;
+ case 'blue':
+ $default_colors = array(0=>'#1e88e5', 1=>'#4f97ea', 2=>'#6ea6ee', 3=>'#89b5f3', 4=>'#a2c4f7', 5=>'#bad3fb', 6=>'#d1e3ff');
+ break;
+ case 'red':
+ $default_colors = array(0=>'#ff0000', 1=>'#dc0202', 2=>'#b90404', 3=>'#960606', 4=>'#730808', 5=>'#ffff00', 6=>'#e803b6');
+ break;
+ case 'multi':
+ $default_colors = array(0=>'#8c0000', 1=>'#f00800', 2=>'#ff8a82', 3=>'#f2c4c8', 4=>'#0b0387', 5=>'#0400fc', 6=>'#9794f2');
+ break;
+ }
+ }
+
+ return $default_colors;
+ }
+
+ public static function html2rgb($color){
+
+ if ($color[0] == '#')
+ $color = substr($color, 1);
+
+ if (strlen($color) == 6)
+ list($r, $g, $b) = array($color[0].$color[1],
+ $color[2].$color[3],
+ $color[4].$color[5]);
+ elseif (strlen($color) == 3)
+ list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
+ else
+ return false;
+
+ $r = hexdec($r);
+ $g = hexdec($g);
+ $b = hexdec($b);
+
+ return array($r, $g, $b);
+ }
+
+
+ // Napolnimo podatke za posamezen graf
+ public static function getDataSet($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ $dataArray = array();
+ $fullPercent = 0;
+ self::$numerusText = '';
+ $_answersOther = array();
+
+ $emptyData = true;
+
+ // napolnimo podatke za DROPDOWN, ki ima samo numeric variable
+ if($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)){
+
+ $dataArray = array();
+
+ $i=0;
+ $N = 0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+
+ $avg_count = 0;
+ $avg_sum = 0;
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21)))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ $N = SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $vAnswer['cnt'];
+
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+
+ $tempArray['key'] = $vkey;
+
+ // ce je znotraj nastavljenih mej
+ if( ($settings['max'] == '' || ($settings['open_up'] == 1 || (int)$vAnswer['text'] <= (int)$settings['max']))
+ && ($settings['min'] == '' || ($settings['open_down'] == 1 || (int)$vAnswer['text'] >= (int)$settings['min'])) ){
+
+ $avg_count += $vAnswer['cnt'];
+ $avg_sum += $vAnswer['cnt'] * (int)$vAnswer['text'];
+ }
+ else{
+ $N -= $vAnswer['cnt'];
+ }
+
+ // nastavimo da graf ni prazen
+ $emptyData = false;
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $vAnswer['text'] : $vAnswer['text_graf'];
+ $tempArray['variable'] = $text;
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+
+ //$N = ($settings['value_type'] == 0) ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ $N = ((int)$N > 0) ? $N : 0;
+ $DataSet->SetNumerus($N);
+
+ // nastavimo POVPRECJE
+ $avg = ($avg_count > 0) ? $avg_sum / $avg_count : 0;
+ $DataSet->SetAverage(round($avg, 1));
+
+
+ // Sortiramo podatke - ce imamo izpis vsakega vnosa posebej sortiramo po freq, ce pa po skupinah pa po key
+ if($settings['type'] > 4){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['key'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+ elseif($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ $max = (int)$dataArray[count($dataArray,0)-1]['variable'];
+ $min = (int)$dataArray[0]['variable'];
+ $stIntervalov = ((int)$settings['interval'] == 0 ? 10 : (int)$settings['interval']);
+
+
+ // Ce imamo napredno napredne intervale
+ if($settings['limits']['advanced_settings'] == 1){
+ $limits = $settings['limits'];
+
+ $max = $limits['interval_'. ($stIntervalov-1) ]['max'];
+ $min = $limits['interval_0']['min'];
+ }
+ // Ce imamo osnovne intervale
+ else{
+ // Nastavimo custom zgornjo mejo skale (razen v primeru ko ne ignoriramo vrednosti ki padejo ven in ce je max vnos vecji od nastavljenega max)
+ if($settings['max'] != '' /*&& ($settings['open_up'] == 0 || (int)$settings['max'] > $max)*/)
+ $max = (int)$settings['max'];
+ // Nastavimo custom spodnjo mejo skale (razen v primeru ko ne ignoriramo vrednosti ki padejo ven in ce je min vnos manjsi od nastavljenega min)
+ if($settings['min'] != '' /*&& ($settings['open_down'] == 0 || (int)$settings['min'] < $min)*/)
+ $min = (int)$settings['min'];
+
+ $stIntervalov = ($stIntervalov == -1 ? $max-$min : $stIntervalov);
+ $part = ($max-$min) / $stIntervalov;
+ $part = ($part < 1) ? 1 : round($part);
+ }
+
+
+ // Poberemo podatke v posamezne tabele - po intervalih oz normalno
+ if($settings['type'] > 4){
+
+ // Ce imamo polodprt intrerval navzdol
+ if($settings['open_down'] == 1){
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] < $min){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $count;
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $valid;
+ $vrednostiKey[] = $lang['srv_chart_less'].' '.$min;
+ $vrednostiVariable[] = $lang['srv_chart_less'].' '.$min;
+ }
+
+ // loop cez intervale - default 10
+ for($interval=0; $interval<$stIntervalov; $interval++){
+
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // Ce imamo napredno napredne intervale (custom dolocene)
+ if($settings['limits']['advanced_settings'] == 1){
+ $maxVal = $limits['interval_'.$interval]['max'];
+ $minVal = $limits['interval_'.$interval]['min'];
+ }
+ // Ce imamo osnovne intervale (racunamo sproti)
+ else{
+ $maxVal = ($interval < ($stIntervalov-1) ? $min + (($interval+1) * $part) : $max);
+ $minVal = ($interval > 0 ? $min + ($interval * $part) + 1 : $min);
+ }
+
+ // prekinemo ce zaradi zaokrozevanja pride do min > max
+ if($minVal > $maxVal)
+ break;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] <= $maxVal && $dataArray[$i]['variable'] >= $minVal && $dataArray[$i]['field'] == 0){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $count;
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $valid;
+
+ // Ce imamo napredne intervale (custom dolocene labele)
+ if($settings['limits']['advanced_settings'] == 1 && $limits['interval_'.$interval]['label'] != ''){
+ $vrednostiKey[] = $limits['interval_'.$interval]['label'];
+ $vrednostiVariable[] = $limits['interval_'.$interval]['label'];
+ }
+ elseif($minVal == $maxVal){
+ $vrednostiKey[] = $minVal;
+ $vrednostiVariable[] = $minVal;
+ }
+ else{
+ $vrednostiKey[] = $minVal.'-'.$maxVal;
+ $vrednostiVariable[] = $minVal.'-'.$maxVal;
+ }
+ }
+
+ // Ce imamo polodprt intrerval navzgor
+ if($settings['open_up'] == 1){
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] > $max){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $count;
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $valid;
+ $vrednostiKey[] = $lang['srv_chart_more'].' '.$max;
+ $vrednostiVariable[] = $lang['srv_chart_more'].' '.$max;
+ }
+ }
+
+ else{
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ if($dataArray[$i]['field'] == 0){
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $dataArray[$i]['percent'];
+ $vrednostiValid[] = $dataArray[$i]['valid'];
+ }
+ else{
+ $vrednosti[] = 0;
+ $vrednostiPercent[] = 0;
+ $vrednostiValid[] = 0;
+ }
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti');
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti');
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $var_title[0] = ($var_title[0] == '' ? 'Vrednosti' : $var_title[0]);
+ $DataSet->SetSerieName($var_title[0],'Vrednosti');
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+
+ if($settings['value_type'] > 0){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+ }
+
+ // napolnimo podatke za RADIO, DROPDOWN
+ elseif($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3){
+
+ $dataArray = array();
+
+ $i=0;
+ $N = 0;
+ $N_average = 0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ // Ce skrivamo prazne vrednosti
+ if($settings['hideEmptyVar'] == 1){
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $key => $valid) {
+ if ((int)$valid['cnt'] == 0) {
+ unset (SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$key]);
+ }
+ }
+ }
+
+ if (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21)))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $vAnswer['cnt'];
+
+ // nastavimo da graf ni prazen
+ if($vAnswer['cnt'] > 0)
+ $emptyData = false;
+
+ $N = ($settings['value_type'] == 0) ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+
+ $tempArray['key'] = $vkey;
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $vAnswer['text'] : $vAnswer['text_graf'];
+ $tempArray['variable'] = $text;
+
+ $fullPercent += $tempArray['percent'];
+
+ // ce imamo vklopljeno da izpuscamo 0 in prikazujemo pie chart spustimo nicelne vrednosti
+ if($_valid != 0 || SurveyDataSettingProfiles :: getSetting('chartPieZeros') == 1 || ($settings['type'] != 2 && $settings['type'] != 8))
+ $dataArray[] = $tempArray;
+
+ // Ce je ordinalen racunamo povprecje
+ if($spremenljivka['skala'] != 1){
+ $xi = (int)$vkey;
+ $fi = (int)$vAnswer['cnt'];
+
+ $sum_xi_fi += $xi * $fi;
+ $N_average += $fi;
+ }
+ }
+ }
+ }
+ }
+ // polnimo array za drugo
+ else{
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+
+ $N = ($settings['value_type'] == 0) ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+
+ $fullPercent += $tempArray['percent'];
+
+ // ce imamo vklopljeno da izpuscamo 0 in prikazujemo pie chart spustimo nicelne vrednosti
+ if($_invalid != 0 || SurveyDataSettingProfiles :: getSetting('chartPieZeros') == 1 || ($settings['type'] != 2 && $settings['type'] != 8))
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ $N = ((int)$N > 0) ? $N : 0;
+ $DataSet->SetNumerus($N);
+ self::$numerusText = ($settings['value_type'] == 0) ? ' ('.$lang['srv_analiza_frekvence_titleVeljavni'].')' : '';
+
+ //nastavimo povprecje ce je ordinalen
+ if($spremenljivka['skala'] != 1){
+ $avg = ($N_average > 0) ? $sum_xi_fi / $N_average : 0;
+ $DataSet->SetAverage(round($avg, 1));
+ }
+
+ // Sortiramo podatke ce je potrebno
+ if($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $dataArray[$i]['percent'];
+ $vrednostiValid[] = $dataArray[$i]['valid'];
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+
+
+ if(is_countable($vrednosti) && count($vrednosti) > 0){
+ if($settings['type'] < 3 || $settings['type'] == 8){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Frekvence','Vrednosti');
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+ }
+ // Graf povprecja
+ elseif($settings['type'] == 9){
+ $DataSet->AddPoint(round($avg, 1),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Frekvence','Vrednosti');
+ }
+ else{
+ for($i=0; $i<count($vrednosti); $i++){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti[$i],'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent[$i],'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid[$i],'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ $DataSet->SetSerieName($vrednostiVariable[$i],'Vrednosti_'.$i);
+ }
+
+ $DataSet->AddPoint('','Variable');
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->SetAbsciseLabelSerie('Variable');
+
+ if($settings['value_type'] != 1 && $settings['type'] != 9){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+ }
+
+ // napolnimo podatke za CHECKBOX
+ elseif($spremenljivka['tip'] == 2){
+ $dataArray = array();
+ $fullPercent = 0;
+
+ $i=0;
+ $nValid = 0;
+ $nAll = 0;
+ $nNavedbe = 0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if ($variable['text'] != true && $variable['other'] != true){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $vAnswer = (int)SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][1]['cnt'];
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = (int)SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][1]['cnt'];
+
+ // nastavimo da graf ni prazen
+ if($tempArray['freq'] > 0)
+ $emptyData = false;
+
+ $nValid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > $nValid) ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : $nValid;
+ $nAll = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+ $nNavedbe += (int)SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][1]['cnt'];
+
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $fullPercent += $tempArray['percent'];
+
+ // ce imamo vklopljeno da izpuscamo 0 spustimo nicelne vrednosti
+ if(($_valid != 0 || SurveyDataSettingProfiles :: getSetting('chartPieZeros') == 1 || ($settings['type'] != 2 && $settings['type'] != 7))
+ && ((int)SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']['1']['cnt'] > 0) || $settings['hideEmptyVar'] == 0)
+ $dataArray[] = $tempArray;
+ }
+ // polnimo array za drugo
+ else{
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = (int)$iAnswer['cnt'];
+
+ //$nValid = SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'];
+ $nAll = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+ $nNavedbe += (int)$iAnswer['cnt'];
+
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+
+ $fullPercent += $tempArray['percent'];
+
+ // ce imamo vklopljeno da izpuscamo 0 in prikazujemo pie chart spustimo nicelne vrednosti
+ if($_invalid != 0 || SurveyDataSettingProfiles :: getSetting('chartPieZeros') == 1 || ($settings['type'] != 2 && $settings['type'] != 7))
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ if($settings['base'] == 0){
+
+ //nastavimo numerus, ki se izpise pod legendo
+ if($settings['value_type'] == 0){
+ $numerus = $nValid;
+ self::$numerusText = ' ('.$lang['srv_analiza_frekvence_titleVeljavni'].')';
+ }
+ else
+ $numerus = $nAll;
+
+ $numerus = ((int)$numerus > 0) ? $numerus : 0;
+ $DataSet->SetNumerus($numerus);
+
+ //$valid = ($fullPercent * $dataArray[$i]['percent'] > 0) ? 100 / $fullPercent * $dataArray[$i]['percent'] : 0;
+ $valid = ($nValid > 0 ) ? $dataArray[$i]['freq'] * 100 / $nValid : 0;
+
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $dataArray[$i]['percent'];
+ $vrednostiValid[] = $valid;
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+
+
+ }
+ else{
+ //nastavimo numerus, ki se izpise pod legendo
+ $nNavedbe = ((int)$nNavedbe > 0) ? $nNavedbe : 0;
+ $DataSet->SetNumerus($nNavedbe);
+ self::$numerusText = ' ('.$lang['srv_analiza_opisne_arguments'].')';
+
+ $percent = ($fullPercent * $dataArray[$i]['percent'] > 0) ? 100 / $fullPercent * $dataArray[$i]['percent'] : 0;
+
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $percent;
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['type'] < 3 || $settings['type'] == 5 || $settings['type'] == 6 || $settings['type'] == 7){
+ if($settings['value_type'] == 1 || ($settings['value_type'] == 0 && $settings['base'] == 1)){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Frekvence','Vrednosti');
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+ }
+ else{
+ for($i=0; $i<count($vrednosti); $i++){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti[$i],'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent[$i],'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid[$i],'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ $DataSet->SetSerieName($vrednostiVariable[$i],'Vrednosti_'.$i);
+ }
+
+ $DataSet->AddPoint('','Variable');
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->SetAbsciseLabelSerie('Variable');
+
+ if(($settings['value_type'] == 0 && $settings['base'] == 0) || $settings['value_type'] == 2){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+ }
+
+ // napolnimo podatke za DVOJNI MULTIGRID
+ elseif($spremenljivka['tip'] == 6 && $spremenljivka['enota'] == 3){
+ $DataSet = new pData;
+ $dataArray = array();
+ $fullPercent = array();
+
+ $gridCount=0;
+ $sql = sisplet_query("SELECT count(*) AS count FROM srv_grid WHERE spr_id='$spid'");
+ $row = mysqli_fetch_array($sql);
+ $_variables_count = $row['count'];
+
+ $nArray = array();
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ // Prva podtabela
+ if($grid['part'] == 1){
+
+ # dodamo dodatne vrstice z albelami grida
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if ($variable['text'] != true && $variable['other'] != true){
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ $xi = $key;
+ $fi = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+ }
+ }
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ $nArray[] = $N;
+
+ $tempArray = array();
+
+ // nastavimo da graf ni prazen
+ if($N > 0)
+ $emptyData = false;
+
+ $avg = $avg < 1 ? 1 : $avg;
+ $tempArray['freq'] = $avg;
+ $tempArray['percent'] = $avg;
+ $tempArray['valid'] = $avg;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $dataArray[] = $tempArray;
+ }
+
+ // polnimo array za drugo
+ if ($variable['text'] == true || $variable['other'] == true){
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+ $tempArray['grid'] = $grid['variables'][0]['naslov'];
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $gridCount++;
+ }
+
+ else{
+ # dodamo dodatne vrstice z albelami grida
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if ($variable['text'] != true && $variable['other'] != true){
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ $xi = $key;
+ $fi = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+ }
+ }
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ $nArray[] = $N;
+
+ $tempArray = array();
+
+ // nastavimo da graf ni prazen
+ if($N > 0)
+ $emptyData = false;
+
+ $avg = $avg < 1 ? 1 : $avg;
+ $tempArray['freq'] = $avg;
+ $tempArray['percent'] = $avg;
+ $tempArray['valid'] = $avg;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $dataArray2[] = $tempArray;
+ }
+
+ // polnimo array za drugo
+ if ($variable['text'] == true || $variable['other'] == true){
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+ $tempArray['grid'] = $grid['variables'][0]['naslov'];
+
+ $dataArray2[] = $tempArray;
+ }
+ }
+ }
+ }
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if(count($spremenljivka['grids']) == 0)
+ return -1;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ rsort($nArray);
+ $numerus = ((int)$nArray[0] > 0) ? $nArray[0] : 0;
+ $DataSet->SetNumerus($numerus);
+ self::$numerusText = ($settings['value_type'] == 0) ? ' ('.$lang['srv_analiza_frekvence_titleVeljavni'].')' : '';
+
+ // Poberemo podatke v posamezne tabele
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $dataArray[$i]['percent'];
+ $vrednostiValid[] = $dataArray[$i]['valid'];
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+
+ for($i=0; $i<count($dataArray2,0); $i++){
+
+ $vrednosti2[] = $dataArray2[$i]['freq'];
+ $vrednostiPercent2[] = $dataArray2[$i]['percent'];
+ $vrednostiValid2[] = $dataArray2[$i]['valid'];
+
+ $vrednostiKey2[] = $dataArray2[$i]['key'];
+ $vrednostiVariable2[] = $dataArray2[$i]['variable'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ $DataSet->AddPoint($vrednosti2,'Vrednosti2');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti');
+ $DataSet->AddPoint($vrednostiPercent2,'Vrednosti2');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti');
+ $DataSet->AddPoint($vrednostiValid2,'Vrednosti2');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else{
+ $DataSet->AddPoint(array(0),'Vrednosti');
+ $DataSet->AddPoint(array(0),'Vrednosti2');
+ }
+
+ $title1 = ($spremenljivka['double'][1]['subtitle'] != '') ? $spremenljivka['double'][1]['subtitle'] : 'Tabela 1';
+ $title2 = ($spremenljivka['double'][2]['subtitle'] != '') ? $spremenljivka['double'][2]['subtitle'] : 'Tabela 2';
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName($title1,'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti2');
+ $DataSet->SetSerieName($title2,'Vrednosti2');
+
+
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ // napolnimo podatke za MULTIGRID
+ elseif($spremenljivka['tip'] == 6){
+ $DataSet = new pData;
+ $dataArray = array();
+ $fullPercent = array();
+
+ $gridCount=0;
+
+
+ // Prefiltriramo other, ki so manjkajoci
+ $_invalidAnswers = SurveyAnalysis :: getInvalidAnswers (2);
+ $noOthers = (isset($_invalidAnswers['-99'])) ? ' AND other!=-99' : '';
+ $noOthers .= (isset($_invalidAnswers['-98'])) ? ' AND other!=-98' : '';
+ $noOthers .= (isset($_invalidAnswers['-97'])) ? ' AND other!=-97' : '';
+
+ // Napolnimo vse gride, ki jih obravnavamo
+ $stolpci = array();
+ $sqlG = sisplet_query("SELECT * FROM srv_grid WHERE spr_id='$spid' ".$noOthers." ");
+ while($rowG = mysqli_fetch_array($sqlG)){
+ $stolpci[] = $rowG;
+ }
+
+ $_variables_count = count($stolpci);
+
+
+ # odstranimo še možne nepotrebne zapise za multigride
+ if($settings['hideEmptyVar'] == 1){
+ $allGrids = count($spremenljivka['grids']);
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $cntValidInGrid = 0;
+ # dodamo dodatne vrstice z labelami grida
+ if (count($grid['variables']) > 0 ) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ foreach(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $valid){
+ $cntValidInGrid+= (int)$valid['cnt'];
+ }
+ }
+ }
+ # preverjamo ali lahko prikazujemo podkategorije
+ if((int)$cntValidInGrid > 0) {
+ $gidsCanShow[$gid] = true;
+ } else {
+ $gidsCanShow[$gid] = false;
+ }
+ }
+ }
+ }
+
+
+ $nArray = array();
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ // Kontrola ce ne prikazujemo praznih variabel
+ if ((!is_array($gidsCanShow) && !isset($gidsCanShow[$gid]))
+ || (is_array($gidsCanShow) && isset($gidsCanShow[$gid]) && $gidsCanShow[$gid]== true)){
+
+ # dodamo dodatne vrstice z albelami grida
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if ($variable['text'] != true && $variable['other'] != true){
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ // Ce izrisujemo graf za povprecja
+ if($settings['type'] == 0 || $settings['type'] == 5 || $settings['type'] == 6){
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ $xi = $key;
+ $fi = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+ }
+ }
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ $nArray[] = $N;
+
+ $tempArray = array();
+
+ // nastavimo da graf ni prazen
+ if($N > 0)
+ $emptyData = false;
+
+ $avg = $avg < 1 ? 1 : $avg;
+ $tempArray['freq'] = $avg;
+ $tempArray['percent'] = $avg;
+ $tempArray['valid'] = $avg;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ // dodamo vrednosti na desni ce imamo vklopljen diferencial
+ if($spremenljivka['enota'] == 1){
+ $sqlV = sisplet_query("SELECT naslov2 FROM srv_vrednost WHERE spr_id='$spid' AND id='$variable[vr_id]'");
+ $rowV = mysqli_fetch_array($sqlV);
+ $tempArray['variable2'] = strip_tags($rowV['naslov2']);
+ }
+
+ $dataArray[] = $tempArray;
+ }
+
+ // izpisujemo navaden graf (ne povprecij)
+ else{
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ foreach ($stolpci as $key => $stolpec) {
+
+ $vkey = $stolpec['vrstni_red'];
+
+ // imamo OTHER grid (ne vem, zavrnil...)
+ if($stolpec['other'] != 0){
+
+ $vAnswer = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$stolpec['other']];
+
+ if($vAnswer != null){
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+ if($settings['value_type'] == 0){
+ $nArray[] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ else{
+ $nArray[] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+ }
+
+ // nastavimo da graf ni prazen
+ if($vAnswer['cnt'] > 0)
+ $emptyData = false;
+
+ $tempArray['freq'] = $vAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+ }
+
+ // ce missling (-99, -98...) nima nobene vrednosti potem ga ni v tabeli - zato ga rocno napolnimo
+ else{
+ $tempArray = array();
+
+ $nArray[] = 0;
+
+ $tempArray['freq'] = 0;
+ $tempArray['percent'] = 0;
+ $tempArray['valid'] = 0;
+ }
+
+ $tempArray['key'] = $vkey;
+
+ $text = $stolpec['other'].' '.$stolpec['naslov'];
+ $tempArray['variable'] = $text;
+
+ $textGrid = $spremenljivka['edit_graf'] == 0 ? $grid['variables'][0]['naslov'] : $grid['variables'][0]['naslov_graf'];
+ $tempArray['grid'] = $textGrid;
+
+ $dataArray[] = $tempArray;
+
+ $fullPercent[$gridCount] += $tempArray['percent'];
+ }
+
+ // imamo NAVADEN GRID
+ else{
+ $vAnswer = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$vkey];
+
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ // Za sortiranje po povprecju
+ $sum_xi_fi=0;
+ $N = 0;
+ if (count($spremenljivka['options']) > 0) {
+ foreach ( $spremenljivka['options'] as $key => $kategorija) {
+ $xi = $key;
+ $fi = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][$key]['cnt'];
+ $sum_xi_fi += $xi * $fi ;
+ $N += $fi;
+ }
+ }
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ $avg = $avg < 1 ? 1 : $avg;
+
+ $tempArray = array();
+
+ if($settings['value_type'] == 0){
+ $nArray[] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+ }
+ else{
+ $nArray[] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+ }
+
+ // nastavimo da graf ni prazen
+ if($vAnswer['cnt'] > 0)
+ $emptyData = false;
+
+ $tempArray['avg'] = $avg;
+ $tempArray['freq'] = $vAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+
+ $tempArray['key'] = $vkey;
+
+ $text = ($spremenljivka['edit_graf'] == 0) ? $vAnswer['text'] : $vAnswer['text_graf'];
+ $tempArray['variable'] = ($text == '') ? $vkey : $text;
+
+ $textGrid = $spremenljivka['edit_graf'] == 0 ? $grid['variables'][0]['naslov'] : $grid['variables'][0]['naslov_graf'];
+ $tempArray['grid'] = $textGrid;
+
+ // dodamo vrednosti na desni ce imamo vklopljen diferencial
+ if($spremenljivka['enota'] == 1){
+ $sqlV = sisplet_query("SELECT naslov2 FROM srv_vrednost WHERE spr_id='$spid' AND id='$variable[vr_id]'");
+ $rowV = mysqli_fetch_array($sqlV);
+ $tempArray['variable2'] = strip_tags($rowV['naslov2']);
+ }
+
+ $dataArray[] = $tempArray;
+
+ $fullPercent[$gridCount] += $tempArray['percent'];
+ }
+ }
+ }
+ }
+ }
+
+ // polnimo array za drugo
+ if ($variable['text'] == true || $variable['other'] == true){
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+ $tempArray['grid'] = $grid['variables'][0]['naslov'];
+
+ $dataArray[] = $tempArray;
+
+ $fullPercent[$gridCount] += $tempArray['percent'];
+ }
+ }
+ }
+
+ $gridCount++;
+ }
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if(count($spremenljivka['grids']) == 0)
+ return -1;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ rsort($nArray);
+ $numerus = ((int)$nArray[0] > 0) ? $nArray[0] : 0;
+ $DataSet->SetNumerus($numerus);
+ self::$numerusText = ($settings['value_type'] == 0) ? ' ('.$lang['srv_analiza_frekvence_titleVeljavni'].')' : '';
+
+ // Ce prikazujemo POVPRECJA napolnimo podatke samo na koncu
+ if($settings['type'] == 0 || $settings['type'] == 5 || $settings['type'] == 6){
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $dataArray[$i]['percent'];
+ $vrednostiValid[] = $dataArray[$i]['valid'];
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+
+ // se vrednosti na desni pri sem. diferencialu
+ if($spremenljivka['enota'] == 1)
+ $vrednostiVariable2[] = $dataArray[$i]['variable2'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Povprečja','Vrednosti');
+
+
+ // Pri povprecjih vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ // se vrednosti na desni pri sem. diferencialu
+ if($spremenljivka['enota'] == 1){
+ $DataSet->AddPoint($vrednostiVariable2,"Variable2");
+ $DataSet->SetRightLabelSerie("Variable2");
+ }
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ // Prikazujemo navadne podatke
+ else{
+
+ // Normalno obrnjen graf - gridi v stolpcih, variable v legendi (deli stolpcev)
+ if($settings['rotate'] != 1){
+
+ // Sortiramo podaatke ce je potrebno - Po kategorijah
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sort po povprecjih
+ elseif($settings['sort'] == 2){
+
+ $tmp = Array();
+
+ // preberemo povprecje iz vsake prve vrednosti vrstice
+ for($j=0; $j<$gridCount; $j++){
+ $offset = $j*$_variables_count;
+ $tmp[] = $dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sort po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsake vrstice
+ for($j=0; $j<$gridCount; $j++){
+ $offset = $j*$_variables_count;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+
+ for($i=0; $i<$_variables_count; $i++){
+
+ unset($vrednosti);
+ unset($vrednostiPercent);
+ unset($vrednostiValid);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+ unset($vrednostiGrid);
+ unset($vrednostiVariable2);
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$gridCount; $j++){
+
+ // ce sortiramo uporabimo sortirane kljuce
+ if($settings['sort'] == 1)
+ $offset = $sorted_keys[$i] + ($j*$_variables_count);
+
+ // sort po povprecjih
+ elseif($settings['sort'] == 2)
+ $offset = ($sorted_keys[$j]*$_variables_count) + $i;
+
+ // sort po prvi kategoriji
+ elseif($settings['sort'] == 3)
+ $offset = ($sorted_keys[$j]*$_variables_count) + $i;
+
+ else
+ $offset = $i + ($j*$_variables_count);
+
+
+ $vrednosti[] = $dataArray[$offset]['freq'];
+ $vrednostiPercent[] = $dataArray[$offset]['percent'];
+ $vrednostiValid[] = $dataArray[$offset]['valid'];
+
+ $vrednostiKey[] = $dataArray[$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$offset]['variable'];
+ $vrednostiGrid[] = $dataArray[$offset]['grid'];
+
+ // se vrednosti na desni pri sem. diferencialu
+ if($spremenljivka['enota'] == 1)
+ $vrednostiVariable2[] = $dataArray[$offset]['variable2'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ $DataSet->SetSerieName($vrednostiVariable[0],'Vrednosti_'.$i);
+ }
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiGrid,"Variable");
+
+ // se vrednosti na desni pri sem. diferencialu
+ if($spremenljivka['enota'] == 1){
+ $DataSet->AddPoint($vrednostiVariable2,"Variable2");
+ $DataSet->SetRightLabelSerie("Variable2");
+ }
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ // Obratno obrnjen graf - gridi v legendi (deli stolpca), variable v stolpcih - default ce imamo samo en grid
+ else{
+ // prej moramo napolniti imena serij (variabel)
+ for($i=0; $i<$gridCount; $i++){
+ $vrednostiGrid[] = $dataArray[$i*$_variables_count]['grid'];
+ }
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$gridCount; $j++){
+ $offset = $j*$_variables_count;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sort po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsake vrstice
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+
+ for($i=0; $i<$gridCount; $i++){
+
+ unset($vrednosti);
+ unset($vrednostiPercent);
+ unset($vrednostiValid);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+ unset($vrednostiVariable2);
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$_variables_count; $j++){
+
+ // ce sortiramo uporabimo sortirane kljuce
+ if($settings['sort'] == 1)
+ $offset = ($sorted_keys[$i]*$_variables_count) + $j;
+
+ // sort po prvi kategoriji
+ elseif($settings['sort'] == 3)
+ $offset = $sorted_keys[$j] + ($i*$_variables_count);
+
+ else
+ $offset = ($i*$_variables_count) + $j;
+
+
+ $vrednosti[] = $dataArray[$offset]['freq'];
+ $vrednostiPercent[] = $dataArray[$offset]['percent'];
+ $vrednostiValid[] = $dataArray[$offset]['valid'];
+
+ $vrednostiKey[] = $dataArray[$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$offset]['variable'];
+
+ // se vrednosti na desni pri sem. diferencialu
+ if($spremenljivka['enota'] == 1)
+ $vrednostiVariable2[] = $dataArray[$offset]['variable2'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednosti,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ if($settings['sort'] == 1)
+ $DataSet->SetSerieName($vrednostiGrid[$sorted_keys[$i]],'Vrednosti_'.$i);
+ else
+ $DataSet->SetSerieName($vrednostiGrid[$i],'Vrednosti_'.$i);
+ }
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+
+ // se vrednosti na desni pri sem. diferencialu
+ if($spremenljivka['enota'] == 1){
+ $DataSet->AddPoint($vrednostiVariable2,"Variable2");
+ $DataSet->SetRightLabelSerie("Variable2");
+ }
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+ }
+
+
+ if( $settings['value_type'] != 1 && $settings['type'] != 0 && $settings['type'] != 6 ){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+ }
+
+ // napolnimo podatke za NUMBER
+ elseif($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22){
+ $dataArray = array();
+
+ $has_decimal = false;
+
+ $i=0;
+ $N=0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+ $field = 0;
+
+ $avg_count = 0;
+ $avg_sum = 0;
+ $avg_count2 = 0;
+ $avg_sum2 = 0;
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+ $var_title[] = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if ($spremenljivka['tip'] == 22 || (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21))))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ if($field == 0)
+ $N = SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+
+ foreach ( SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $vAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+
+ $tempArray['key'] = $vkey;
+
+ if(floor($vkey) != $vkey)
+ $has_decimal = true;
+
+ // racunamo povprecje (za prvo variablo)
+ if($field == 0){
+
+ // ce je znotraj nastavljenih mej
+ if( ($settings['max'] == '' || ($settings['open_up'] == 1 || (int)$vAnswer['text'] <= (int)$settings['max']))
+ && ($settings['min'] == '' || ($settings['open_down'] == 1 || (int)$vAnswer['text'] >= (int)$settings['min'])) ){
+
+ $avg_count += $vAnswer['cnt'];
+ $avg_sum += $vAnswer['cnt'] * (int)$vAnswer['text'];
+ }
+ else{
+ $N--;
+ }
+ }
+ // racunamo povprecje (samo za drugo variablo)
+ if($field == 1){
+
+ // ce je znotraj nastavljenih mej
+ if( ($settings['max'] == '' || ($settings['open_up'] == 1 || (int)$vAnswer['text'] <= (int)$settings['max']))
+ && ($settings['min'] == '' || ($settings['open_down'] == 1 || (int)$vAnswer['text'] >= (int)$settings['min'])) ){
+
+ $avg_count2 += $vAnswer['cnt'];
+ $avg_sum2 += $vAnswer['cnt'] * (int)$vAnswer['text'];
+ }
+ else{
+ $N--;
+ }
+ }
+
+ // nastavimo da graf ni prazen
+ $emptyData = false;
+
+ $text = $vAnswer['text'];
+ $tempArray['variable'] = $text;
+
+ $tempArray['field'] = $field;
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+ }
+ $field++;
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ //$N = ($settings['value_type'] == 2) ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+
+ // nastavimo NUMERUS, ki se izpise pod legendo
+ $N = ((int)$N > 0) ? $N : 0;
+ $DataSet->SetNumerus($N);
+
+ // nastavimo POVPRECJE
+ $avg = ($avg_count > 0) ? $avg_sum / $avg_count : 0;
+ $DataSet->SetAverage(round($avg, 1));
+
+ // Povprecje za 2. variablo (rabimo pri grafu povprecja)
+ $avg2 = ($avg_count2 > 0) ? $avg_sum2 / $avg_count2 : 0;
+
+ // Sortiramo podatke - ce imamo izpis vsakega vnosa posebej sortiramo po freq, ce pa po skupinah pa po key
+ if($settings['type'] <= 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['key'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+ elseif($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ $max = (double)$dataArray[count($dataArray,0)-1]['variable'];
+ $min = (double)$dataArray[0]['variable'];
+ $stIntervalov = ((int)$settings['interval'] == 0 ? 10 : (int)$settings['interval']);
+
+
+ // Ce imamo napredno napredne intervale
+ if($settings['limits']['advanced_settings'] == 1){
+ $limits = $settings['limits'];
+
+ $max = $limits['interval_'. ($stIntervalov-1) ]['max'];
+ $min = $limits['interval_0']['min'];
+ }
+ // Ce imamo osnovne intervale
+ else{
+ // Nastavimo custom zgornjo mejo skale (razen v primeru ko ne ignoriramo vrednosti ki padejo ven in ce je max vnos vecji od nastavljenega max)
+ if($settings['max'] != '' /*&& ($settings['open_up'] == 0 || (int)$settings['max'] > $max)*/)
+ $max = (double)$settings['max'];
+ // Nastavimo custom spodnjo mejo skale (razen v primeru ko ne ignoriramo vrednosti ki padejo ven in ce je min vnos manjsi od nastavljenega min)
+ if($settings['min'] != '' /*&& ($settings['open_down'] == 0 || (int)$settings['min'] < $min)*/)
+ $min = (double)$settings['min'];
+
+
+ $stIntervalov = ($stIntervalov == -1 ? $max-$min : $stIntervalov);
+ $part = ($max-$min) / $stIntervalov;
+
+ if(!$has_decimal)
+ $part = ($part < 1) ? 1 : round($part);
+ }
+
+ // Poberemo podatke v posamezne tabele - po intervalih oz normalno
+ if($settings['type'] <= 2){
+
+ // Ce imamo polodprt intrerval navzdol
+ if($settings['open_down'] == 1){
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] < $min && $dataArray[$i]['field'] == 0){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $count;
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $valid;
+ $vrednostiKey[] = $lang['srv_chart_less'].' '.$min;
+ $vrednostiVariable[] = $lang['srv_chart_less'].' '.$min;
+ }
+
+ // loop cez intervale - default 10
+ for($interval=0; $interval<$stIntervalov; $interval++){
+
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // Ce imamo napredno napredne intervale (custom dolocene)
+ if($settings['limits']['advanced_settings'] == 1){
+ $maxVal = $limits['interval_'.$interval]['max'];
+ $minVal = $limits['interval_'.$interval]['min'];
+ }
+ // Ce imamo osnovne intervale (racunamo sproti)
+ else{
+ // Ce imamo decimalke
+ if($has_decimal){
+ $maxVal = ($interval < ($stIntervalov-1) ? $min-0.01 + (($interval+1) * $part) : $max);
+ $minVal = ($interval > 0 ? $min + ($interval * $part) : $min);
+ }
+ else{
+ $maxVal = ($interval < ($stIntervalov-1) ? $min + (($interval+1) * $part) : $max);
+ $minVal = ($interval > 0 ? $min + ($interval * $part) + 1 : $min);
+ }
+ }
+
+ // prekinemo ce zaradi zaokrozevanja pride do min > max
+ if($minVal > $maxVal)
+ break;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] <= $maxVal && $dataArray[$i]['variable'] >= $minVal && $dataArray[$i]['field'] == 0){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $count;
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $valid;
+
+ // Ce imamo napredne intervale (custom dolocene labele)
+ if($settings['limits']['advanced_settings'] == 1 && $limits['interval_'.$interval]['label'] != ''){
+ $vrednostiKey[] = $limits['interval_'.$interval]['label'];
+ $vrednostiVariable[] = $limits['interval_'.$interval]['label'];
+ }
+ elseif($minVal == $maxVal){
+ $vrednostiKey[] = $minVal;
+ $vrednostiVariable[] = $minVal;
+ }
+ else{
+ $vrednostiKey[] = $minVal.'-'.$maxVal;
+ $vrednostiVariable[] = $minVal.'-'.$maxVal;
+ }
+ }
+
+ // Ce imamo polodprt intrerval navzgor
+ if($settings['open_up'] == 1){
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] > $max && $dataArray[$i]['field'] == 0){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $count;
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $valid;
+ $vrednostiKey[] = $lang['srv_chart_more'].' '.$max;
+ $vrednostiVariable[] = $lang['srv_chart_more'].' '.$max;
+ }
+
+ //ponovimo ce imamo 2 polja
+ if($field == 2){
+
+ // Ce imamo polodprt intrerval navzdol
+ if($settings['open_down'] == 1){
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] < $min && $dataArray[$i]['field'] == 1){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti2[] = $count;
+ $vrednostiPercent2[] = $percent;
+ $vrednostiValid2[] = $valid;
+ }
+
+ // loop cez intervale - default 10
+ for($interval=0; $interval<$stIntervalov; $interval++){
+
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // Ce imamo napredno napredne intervale (custom dolocene)
+ if($settings['limits']['advanced_settings'] == 1){
+ $maxVal = $limits['interval_'.$interval]['max'];
+ $minVal = $limits['interval_'.$interval]['min'];
+ }
+ // Ce imamo osnovne intervale (racunamo sproti)
+ else{
+ // Ce imamo decimalke
+ if($has_decimal){
+ $maxVal = ($interval < ($stIntervalov-1) ? $min-0.01 + (($interval+1) * $part) : $max);
+ $minVal = ($interval > 0 ? $min + ($interval * $part) : $min);
+ }
+ else{
+ $maxVal = ($interval < ($stIntervalov-1) ? $min + (($interval+1) * $part) : $max);
+ $minVal = ($interval > 0 ? $min + ($interval * $part) + 1 : $min);
+ }
+ }
+
+ // prekinemo ce zaradi zaokrozevanja pride do min > max
+ if($minVal > $maxVal)
+ break;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] <= $maxVal && $dataArray[$i]['variable'] >= $minVal && $dataArray[$i]['field'] == 1){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti2[] = $count;
+ $vrednostiPercent2[] = $percent;
+ $vrednostiValid2[] = $valid;
+ }
+
+ // Ce imamo polodprt intrerval navzgor
+ if($settings['open_up'] == 1){
+ $count = 0;
+ $percent = 0;
+ $valid = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i]['variable'] > $max && $dataArray[$i]['field'] == 1){
+ $count += $dataArray[$i]['freq'];
+ $percent += $dataArray[$i]['percent'];
+ $valid += $dataArray[$i]['valid'];
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti2[] = $count;
+ $vrednostiPercent2[] = $percent;
+ $vrednostiValid2[] = $valid;
+ }
+ }
+ }
+
+ else{
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ if($dataArray[$i]['field'] == 0){
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiPercent[] = $dataArray[$i]['percent'];
+ $vrednostiValid[] = $dataArray[$i]['valid'];
+ }
+ else{
+ $vrednosti[] = 0;
+ $vrednostiPercent[] = 0;
+ $vrednostiValid[] = 0;
+ }
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+
+ //ponovimo ce imamo 2 polja
+ if($field == 2){
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ if($dataArray[$i]['field'] == 1){
+ $vrednosti2[] = $dataArray[$i]['freq'];
+ $vrednostiPercent2[] = $dataArray[$i]['percent'];
+ $vrednostiValid2[] = $dataArray[$i]['valid'];
+ }
+ else{
+ $vrednosti2[] = 0;
+ $vrednostiPercent2[] = 0;
+ $vrednostiValid2[] = 0;
+ }
+ }
+ }
+ }
+
+ if(count($vrednosti) > 0){
+
+ // Graf povprecja
+ if($settings['type'] == 9){
+ $DataSet->AddPoint(round($avg, 1),'Vrednosti');
+ if($field == 2)
+ $DataSet->AddPoint(round($avg2, 1),'Vrednosti2');
+ }
+ else{
+ if($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ if($field == 2)
+ $DataSet->AddPoint($vrednosti2,'Vrednosti2');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti');
+ if($field == 2)
+ $DataSet->AddPoint($vrednostiPercent2,'Vrednosti2');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti');
+ if($field == 2)
+ $DataSet->AddPoint($vrednostiValid2,'Vrednosti2');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $var_title[0] = ($var_title[0] == '' ? 'Vrednosti' : $var_title[0]);
+ $DataSet->SetSerieName($var_title[0],'Vrednosti');
+
+ if($field == 2){
+ $DataSet->AddSerie('Vrednosti2');
+ $var_title[1] = ($var_title[1] == '' ? 'Vrednosti 2' : $var_title[1]);
+ $DataSet->SetSerieName($var_title[1],'Vrednosti2');
+ }
+
+ // Vedno izpisemo cela imena variabel
+ if($settings['type'] != 9)
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+
+ if($settings['value_type'] > 0){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+ }
+
+ // napolnimo podatke za DATUM
+ elseif($spremenljivka['tip'] == 8){
+ $dataArray = array();
+
+ $i=0;
+ $N=0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+ $var_title[] = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21)))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ $N = SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+
+ foreach ( SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+
+ // ce je zunaj nastavljenih mej
+ if( ($settings['max'] != '' && ($settings['open_up'] == 0 && (int)$vAnswer['text'] > (int)$settings['max']))
+ || ($settings['min'] != '' && ($settings['open_down'] == 0 && (int)$vAnswer['text'] < (int)$settings['min'])) ){
+
+ $N--;
+ }
+
+ $date = strtotime($vkey);
+
+ $tempArray['day'] = date('j', $date);
+ $tempArray['month'] = date('n', $date);
+ $tempArray['year'] = date('Y', $date);
+
+ $tempArray['freq'] = $vAnswer['cnt'];
+
+ // nastavimo da graf ni prazen
+ $emptyData = false;
+
+ $text = $vAnswer['text'];
+ $tempArray['variable'] = $text;
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ //$N = ($settings['value_type'] == 2) ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+
+ $date = strtotime($ikey);
+
+ $tempArray['day'] = date('j', $date);
+ $tempArray['month'] = date('n', $date);
+ $tempArray['year'] = date('Y', $date);
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+ $tempArray['variable'] = $iAnswer['text'];
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ if($settings['value_type'] == 0)
+ $key = 'day';
+ elseif($settings['value_type'] == 1)
+ $key = 'month';
+ else
+ $key = 'year';
+
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ $N = ((int)$N > 0) ? $N : 0;
+ $DataSet->SetNumerus($N);
+
+ // Sortiramo podatke - ce imamo izpis vsakega vnosa posebej sortiramo po datumu, ce pa po skupinah pa po key
+ if($settings['type'] < 3){
+ if($settings['value_type'] == 0){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['day'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+ elseif($settings['value_type'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['month'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+ elseif($settings['value_type'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['year'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+ }
+ elseif($settings['sort'] == 1 ){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2 ){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['freq'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ $max = (int)$dataArray[count($dataArray,0)-1][$key];
+ $min = (int)$dataArray[0][$key];
+ $stIntervalov = ((int)$settings['interval'] == 0 ? 10 : (int)$settings['interval']);
+
+
+ // Ce imamo napredno napredne intervale
+ if($settings['limits']['advanced_settings'] == 1){
+ $limits = $settings['limits'];
+
+ $max = $limits['interval_'. ($stIntervalov-1) ]['max'];
+ $min = $limits['interval_0']['min'];
+ }
+ // Ce imamo osnovne intervale
+ else{
+ // Nastavimo custom zgornjo mejo skale (razen v primeru ko ne ignoriramo vrednosti ki padejo ven in ce je max vnos vecji od nastavljenega max)
+ if($settings['max'] != '' /*&& ($settings['open_up'] == 0 || (int)$settings['max'] > $max)*/)
+ $max = (int)$settings['max'];
+ // Nastavimo custom spodnjo mejo skale (razen v primeru ko ne ignoriramo vrednosti ki padejo ven in ce je min vnos manjsi od nastavljenega min)
+ if($settings['min'] != '' /*&& ($settings['open_down'] == 0 || (int)$settings['min'] < $min)*/)
+ $min = (int)$settings['min'];
+
+ $stIntervalov = ($stIntervalov == -1 ? $max-$min : $stIntervalov);
+ $part = round( ($max-$min) / $stIntervalov );
+ }
+
+ // Poberemo podatke v posamezne tabele - po intervalih oz normalno
+ if($settings['type'] < 3){
+
+ // Ce imamo polodprt intrerval navzdol
+ if($settings['open_down'] == 1){
+
+ $value = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i][$key] < $min){
+ $value ++;
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $value;
+ $vrednostiVariable[] = $lang['srv_chart_less'].' '.$min;
+ }
+
+ // loop cez intervale - default 10
+ for($interval=0; $interval<$stIntervalov; $interval++){
+
+ $value = 0;
+
+ // Ce imamo napredno napredne intervale (custom dolocene)
+ if($settings['limits']['advanced_settings'] == 1){
+ $maxVal = $limits['interval_'.$interval]['max'];
+ $minVal = $limits['interval_'.$interval]['min'];
+ }
+ // Ce imamo osnovne intervale (racunamo sproti)
+ else{
+ $maxVal = ($interval < ($stIntervalov-1) ? $min + (($interval+1) * $part) : $max);
+ $minVal = ($interval > 0 ? $min + ($interval * $part) + 1 : $min);
+ }
+
+ // prekinemo ce zaradi zaokrozevanja pride do min > max
+ if($minVal > $maxVal)
+ break;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i][$key] <= $maxVal && $dataArray[$i][$key] >= $minVal){
+ $value ++;
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $value;
+
+ // Ce imamo napredne intervale (custom dolocene labele)
+ if($settings['limits']['advanced_settings'] == 1 && $limits['interval_'.$interval]['label'] != ''){
+ $vrednostiVariable[] = $limits['interval_'.$interval]['label'];
+ }
+ elseif($minVal == $maxVal){
+ $vrednostiVariable[] = $minVal;
+ }
+ else{
+ $vrednostiVariable[] = $minVal.'-'.$maxVal;
+ }
+ }
+
+ // Ce imamo polodprt intrerval navzgor
+ if($settings['open_up'] == 1){
+
+ $value = 0;
+
+ // loop cez vse podatke
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ // ce pripada intervalu
+ if($dataArray[$i][$key] > $max){
+ $value ++;
+ }
+ }
+
+ // vnesemo podatke za interval
+ $vrednosti[] = $value;
+ $vrednostiVariable[] = $lang['srv_chart_more'].' '.$max;
+ }
+ }
+
+ else{
+ for($i=0; $i<count($dataArray,0); $i++){
+
+ $vrednosti[] = $dataArray[$i]['freq'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+ }
+
+ if(count($vrednosti) > 0){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $var_title[0] = ($var_title[0] == '' ? 'Vrednosti' : $var_title[0]);
+ $DataSet->SetSerieName($var_title[0],'Vrednosti');
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ // napolnimo podatke za MULTICHECKBOX
+ elseif($spremenljivka['tip'] == 16){
+ $DataSet = new pData;
+ $dataArray = array();
+ $fullPercent = array();
+
+
+ # odstranimo še možne nepotrebne zapise
+ if($settings['hideEmptyVar'] == 1){
+ $allGrids = count($spremenljivka['grids']);
+ if (count($spremenljivka['grids']) > 0) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $cntValidInGrid = 0;
+ # dodamo dodatne vrstice z labelami grida
+ if (count($grid['variables']) > 0 ) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ foreach(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $valid){
+ $cntValidInGrid+= (int)$valid['cnt'];
+ }
+ }
+ }
+ # preverjamo ali lahko prikazujemo podkategorije
+ if((int)$cntValidInGrid > 0) {
+ $gidsCanShow[$gid] = true;
+ } else {
+ $gidsCanShow[$gid] = false;
+ }
+ }
+ }
+ }
+
+
+ $gridCount=0;
+ $nValid = array();
+ $nAll = 0;
+ $nNavedbe = array();
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ // Kontrola ce ne prikazujemo praznih variabel
+ if ((!is_array($gidsCanShow) && !isset($gidsCanShow[$gid]))
+ || (is_array($gidsCanShow) && isset($gidsCanShow[$gid]) && $gidsCanShow[$gid]== true)){
+
+ # dodamo dodatne vrstice z albelami grida
+ $_variables_count=0;
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ if ($variable['text'] != true && $variable['other'] != true){
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $vAnswer = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][1]['cnt'];
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $tempArray = array();
+
+ $nValid[] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'];
+ $nAll = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+ $nNavedbe[$gid] += SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][1]['cnt'];
+
+ $tempArray['freq'] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'][1]['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_valid;
+
+ // nastavimo da graf ni prazen
+ if($vAnswer > 0)
+ $emptyData = false;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $textGrid = $spremenljivka['edit_graf'] == 0 ? $grid['naslov'] : $grid['naslov_graf'];
+ $tempArray['grid'] = $textGrid;
+
+ $dataArray[] = $tempArray;
+
+ $fullPercent[$gridCount] += $tempArray['percent'];
+ $fullPercentReverse[$_variables_count] += $tempArray['percent'];
+
+ $_variables_count++;
+ }
+
+ // polnimo array za drugo
+ if ($variable['text'] == true || $variable['other'] == true){
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $displayMV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ if ( (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0) && $displayMV) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $tempArray = array();
+
+ $tempArray['freq'] = $iAnswer['cnt'];
+ $tempArray['percent'] = $_percent;
+ $tempArray['valid'] = $_invalid;
+
+ $tempArray['key'] = $ikey;
+ $tempArray['variable'] = $iAnswer['text'];
+ $tempArray['grid'] = $grid['naslov'];
+
+ $fullPercent[$gridCount] += $tempArray['percent'];
+ $fullPercentReverse[$_variables_count] += $tempArray['percent'];
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $gridCount++;
+ }
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if(count($spremenljivka['grids']) == 0)
+ return -1;
+
+
+ // Normalno obrnjen graf - gridi v stolpcih, variable v legendi (deli stolpcev)
+ if($settings['rotate'] != 1){
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sort po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsake vrstice
+ for($j=0; $j<$gridCount; $j++){
+ $offset = $j*$_variables_count;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+
+ // Prikazujemo podatke
+ for($i=0; $i<$_variables_count; $i++){
+
+ unset($vrednosti);
+ unset($vrednostiPercent);
+ unset($vrednostiValid);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+ unset($vrednostiGrid);
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$gridCount; $j++){
+
+ // ce sortiramo uporabimo sortirane kljuce
+ if($settings['sort'] == 1)
+ $offset = $sorted_keys[$i] + ($j*$_variables_count);
+
+ // sort po prvi kategoriji
+ elseif($settings['sort'] == 3)
+ $offset = ($sorted_keys[$j]*$_variables_count) + $i;
+
+ else
+ $offset = $i + ($j*$_variables_count);
+
+
+ // Enote
+ if($settings['base'] != 1){
+ $vrednosti[] = $dataArray[$offset]['freq'];
+ $vrednostiPercent[] = $dataArray[$offset]['percent'];
+ $vrednostiValid[] = $dataArray[$offset]['valid'];
+
+ //nastavimo numerus, ki se izpise pod legendo
+ if($settings['value_type'] == 0){
+ rsort($nValid);
+ $numerus = ((int)$nValid[0] > 0) ? $nValid[0] : 0;
+ $DataSet->SetNumerus($numerus);
+ self::$numerusText = ' ('.$lang['srv_analiza_frekvence_titleVeljavni'].')';
+ }
+ else
+ $numerus = ((int)$nAll > 0) ? $nAll : 0;
+
+ $DataSet->SetNumerus($numerus);
+ }
+ // Navedbe
+ else{
+ $percent = ($fullPercent[$j] * $dataArray[$offset]['percent'] > 0) ? 100 / $fullPercent[$j] * $dataArray[$offset]['percent'] : 0;
+
+ $vrednosti[] = $dataArray[$offset]['freq'];
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $percent;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ rsort($nNavedbe);
+ $numerus = ((int)$nNavedbe[0] > 0) ? $nNavedbe[0] : 0;
+ $DataSet->SetNumerus($numerus);
+ self::$numerusText = ' ('.$lang['srv_analiza_opisne_arguments'].')';
+ }
+
+ $vrednostiKey[] = $dataArray[$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$offset]['variable'];
+ $vrednostiGrid[] = $dataArray[$offset]['grid'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednosti,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ $DataSet->SetSerieName($vrednostiVariable[0],'Vrednosti_'.$i);
+ }
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiGrid,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ // Obratno obrnjen graf - gridi v legendi (deli stolpca), variable v stolpcih - default ce imamo samo en grid
+ else{
+ // prej moramo napolniti imena serij (variabel)
+ for($i=0; $i<$gridCount; $i++){
+ $vrednostiGrid[] = $dataArray[$i*$_variables_count]['grid'];
+ }
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$gridCount; $j++){
+ $offset = $j*$_variables_count;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sort po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsake vrstice
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['valid'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+
+ for($i=0; $i<$gridCount; $i++){
+ unset($vrednosti);
+ unset($vrednostiPercent);
+ unset($vrednostiValid);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$_variables_count; $j++){
+
+ if($settings['sort'] == 1)
+ $offset = ($sorted_keys[$i]*$_variables_count) + $j;
+
+ // sort po prvi kategoriji
+ elseif($settings['sort'] == 3)
+ $offset = $sorted_keys[$j] + ($i*$_variables_count);
+
+ else
+ $offset = ($i*$_variables_count) + $j;
+
+ // Enote
+ if($settings['base'] != 1){
+ $vrednosti[] = $dataArray[$offset]['freq'];
+ $vrednostiPercent[] = $dataArray[$offset]['percent'];
+ $vrednostiValid[] = $dataArray[$offset]['valid'];
+
+ //nastavimo numerus, ki se izpise pod legendo
+ if($settings['value_type'] == 0){
+ rsort($nValid);
+ $numerus = ((int)$nValid[0] > 0) ? $nValid[0] : 0;
+ $DataSet->SetNumerus($numerus);
+ self::$numerusText = ' ('.$lang['srv_analiza_frekvence_titleVeljavni'].')';
+ }
+ else
+ $numerus = ((int)$nAll > 0) ? $nAll : 0;
+
+ $DataSet->SetNumerus($numerus);
+ }
+ // Navedbe
+ else{
+ $percent = ($fullPercentReverse[$j] * $dataArray[$offset]['percent'] > 0) ? 100 / $fullPercentReverse[$j] * $dataArray[$offset]['percent'] : 0;
+
+ $vrednosti[] = $dataArray[$offset]['freq'];
+ $vrednostiPercent[] = $percent;
+ $vrednostiValid[] = $percent;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ rsort($nNavedbe);
+ $numerus = ((int)$nNavedbe[0] > 0) ? $nNavedbe[0] : 0;
+ $DataSet->SetNumerus($numerus);
+ self::$numerusText = ' ('.$lang['srv_analiza_opisne_arguments'].')';
+ }
+
+ $vrednostiKey[] = $dataArray[$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$offset]['variable'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednosti,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednostiValid,'Vrednosti_'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ if($settings['sort'] == 1)
+ $DataSet->SetSerieName($vrednostiGrid[$sorted_keys[$i]],'Vrednosti_'.$i);
+ else
+ $DataSet->SetSerieName($vrednostiGrid[$i],'Vrednosti_'.$i);
+ }
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ if($settings['value_type'] == 1 || $settings['value_type'] == 0){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+ }
+
+ // napolnimo podatke za VSOTO
+ elseif($spremenljivka['tip'] == 18){
+ $dataArray = array();
+
+ $i=0;
+ $numerus=0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21)))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ # za povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ $min = null;
+ $max = null;
+ foreach ( SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+
+ $fi = $vAnswer['cnt'];
+ $sum_xi_fi += $vkey * $fi ;
+ $N += $fi;
+ $min = $min != null ? min($min,$vkey) : $vkey;
+ $max = max($max,$vkey);
+ }
+
+ #povprečje
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+
+ // nastavimo da graf ni prazen
+ if($avg > 0)
+ $emptyData = false;
+
+ $numerus = ($numerus > $N) ? $numerus : $N;
+
+ $tempArray = array();
+
+ $tempArray['avg'] = $avg;
+ $tempArray['max'] = $max;
+ $tempArray['min'] = $min;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ // ce imamo vklopljeno da izpuscamo 0 in prikazujemo pie chart spustimo nicelne vrednosti
+ if($avg != 0 || SurveyDataSettingProfiles :: getSetting('chartPieZeros') == 1 || ($settings['type'] != 0 && $settings['type'] != 5))
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ $numerus = ((int)$numerus > 0) ? $numerus : 0;
+ $DataSet->SetNumerus($numerus);
+
+ // Sortiramo podatke in jih razvrstimo po skupinah
+ if($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['avg'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['avg'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($i=0; $i<count($dataArray,0); $i++){
+ $vrednosti[] = $dataArray[$i]['avg'];
+ $vrednostiMax[] = $dataArray[$i]['max'];
+ $vrednostiMin[] = $dataArray[$i]['min'];
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+
+ if(is_countable($vrednosti) && count($vrednosti) > 0){
+ if($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiMax,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiMin,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Povprečja','Vrednosti');
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ if($settings['type'] != 2)
+ $DataSet->SetYAxisName($lang['srv_analiza_sums_average']);
+ }
+
+ // napolnimo podatke za RANKING
+ elseif($spremenljivka['tip'] == 17){
+ $dataArray = array();
+
+ $i=0;
+ $numerus=0;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+
+ $_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21)))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ $rankingArray = array();
+ $_variables_count=0;
+
+ # za povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ $min = null;
+ $max = null;
+ foreach ( SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+
+ $fi = $vAnswer['cnt'];
+ $sum_xi_fi += $vkey * $fi ;
+ $N += $fi;
+ $min = $min != null ? min($min,$vkey) : $vkey;
+ $max = max($max,$vkey);
+
+ $rankingArray[] = $vAnswer['cnt'];
+ $_variables_count++;
+ }
+
+ // nastavimo da graf ni prazen
+ if($N > 0)
+ $emptyData = false;
+
+ #povprečje
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+ $avg = $avg < 1 ? 1 : $avg;
+
+ if($settings['type'] == 0){
+ $numerus = ($numerus > $N) ? $numerus : $N;
+ }
+ else{
+ $numerus = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'];
+ }
+
+ $tempArray = array();
+
+ $tempArray['cnt'] = $N;
+ $tempArray['avg'] = $avg;
+ $tempArray['max'] = $max;
+ $tempArray['min'] = $min;
+
+ $tempArray['rankings'] = $rankingArray;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $dataArray[] = $tempArray;
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ $numerus = ((int)$numerus > 0) ? $numerus : 0;
+ $DataSet->SetNumerus($numerus);
+
+ // Sortiramo podatke in jih razvrstimo po skupinah
+ if($settings['sort'] == 1){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['avg'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_DESC, $dataArray);
+ }
+ elseif($settings['sort'] == 2){
+ $tmp = Array();
+ foreach($dataArray as &$data)
+ $tmp[] = &$data['avg'];
+ array_multisort($tmp, SORT_NUMERIC, SORT_ASC, $dataArray);
+ }
+
+ if($settings['type'] == 0){
+ // Poberemo podatke v posamezne tabele
+ for($i=0; $i<count($dataArray,0); $i++){
+ $vrednosti[] = $dataArray[$i]['avg'];
+ $vrednostiMax[] = $dataArray[$i]['max'];
+ $vrednostiMin[] = $dataArray[$i]['min'];
+
+ $vrednostiKey[] = $dataArray[$i]['key'];
+ $vrednostiVariable[] = $dataArray[$i]['variable'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednosti,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiMax,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiMin,'Vrednosti');
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Povprečja','Vrednosti');
+ }
+
+ //polnimo podatke po posameznih serijah
+ else{
+ // loop cez variable za posamezno serijo
+ for($i=0; $i<$_variables_count; $i++){
+
+ unset($vrednosti);
+ unset($vrednostiPercent);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ for($j=0; $j<count($dataArray,0); $j++){
+ $vrednosti[] = $dataArray[$j]['rankings'][$i];
+
+ if($dataArray[$j]['cnt'] > 0)
+ $percent = $dataArray[$j]['rankings'][$i] / $dataArray[$j]['cnt'] * 100;
+ else
+ $percent = 0;
+
+ $vrednostiPercent[] = $percent;
+
+ $vrednostiKey[] = $dataArray[$j]['key'];
+ $vrednostiVariable[] = $dataArray[$j]['variable'];
+ }
+
+ if(count($vrednosti) > 0){
+ if($settings['value_type'] == 0){
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_freq']);
+ }
+ elseif($settings['value_type'] == 1){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_percent']);
+ }
+ elseif($settings['value_type'] == 2){
+ $DataSet->AddPoint($vrednostiPercent,'Vrednosti'.$i);
+ //$DataSet->SetYAxisName($lang['srv_chart_valid']);
+ }
+ }
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$i);
+
+ $DataSet->AddSerie('Vrednosti'.$i);
+ $DataSet->SetSerieName($i+1,'Vrednosti'.$i);
+ }
+ }
+
+
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ if($settings['type'] > 1)
+ $DataSet->SetYAxisName("Povprečje");
+ }
+
+ // napolnimo podatke za MULTINUMBER
+ elseif($spremenljivka['tip'] == 20){
+ $dataArray = array();
+
+ $i=0;
+ $numerus=0;
+
+ $sql = sisplet_query("SELECT count(*) AS count FROM srv_grid WHERE spr_id='$spid'");
+ $row = mysqli_fetch_array($sql);
+ $_variables_count = $row['count'];
+
+ $vrednostiGrid = array();
+
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ $legendTitle = '';
+ $vrednostiGrid[] = $spremenljivka['edit_graf'] == 0 ? $grid['naslov'] : $grid['naslov_graf'];
+
+ //$_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $legendTitle = substr($variable['variable'],0,strpos($variable['variable'],'_'));
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if (($variable['text'] != true && $variable['other'] != true) || (in_array($spremenljivka['tip'],array(4,8,21)))){
+
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+
+ # za povprečje
+ $sum_xi_fi=0;
+ $N = 0;
+ $div=0;
+ $min = null;
+ $max = null;
+ foreach ( SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+
+ $fi = $vAnswer['cnt'];
+ $sum_xi_fi += $vkey * $fi ;
+ $N += $fi;
+ $min = $min != null ? min($min,$vkey) : $vkey;
+ $max = max($max,$vkey);
+ }
+
+ #povprečje
+ $avg = ($N > 0) ? $sum_xi_fi / $N : 0;
+
+ // nastavimo da graf ni prazen
+ if($avg > 0)
+ $emptyData = false;
+
+ $numerus = ($numerus > $N) ? $numerus : $N;
+
+ $tempArray = array();
+
+ $tempArray['avg'] = $avg;
+ $tempArray['max'] = $max;
+ $tempArray['min'] = $min;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $dataArray[] = $tempArray;
+ }
+
+ // ce missling (-99, -98...) nima nobene vrednosti potem ga ni v tabeli - zato ga rocno napolnimo
+ else{
+ $tempArray = array();
+
+ $tempArray['avg'] = 0;
+ $tempArray['max'] = 0;
+ $tempArray['min'] = 0;
+
+ $tempArray['key'] = $variable['variable'];
+
+ $text = $spremenljivka['edit_graf'] == 0 ? $variable['naslov'] : $variable['naslov_graf'];
+ $tempArray['variable'] = $text;
+
+ $dataArray[] = $tempArray;
+ }
+ }
+
+ // polnimo array za drugo
+ if ($variable['text'] == true || $variable['other'] == true){
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+
+ $i++;
+ }
+
+ // zascita pred praznimi vprasanji (brez variabel)
+ if($_variables_count == 0)
+ return -1;
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ //nastavimo numerus, ki se izpise pod legendo
+ $numerus = ((int)$numerus > 0) ? $numerus : 0;
+ $DataSet->SetNumerus($numerus);
+
+
+ // Normalno obrnjen graf - gridi v stolpcih, variable v legendi (deli stolpcev)
+ if($settings['rotate'] != 1 /*$_variables_count > 1*/){
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j*$_variables_count;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sortiramo podaatke po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ else{
+ for($j=0; $j<(count($spremenljivka['grids'])*$_variables_count); $j++){
+ $sorted_keys[] = $j;
+ }
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<count($spremenljivka['grids']); $j++){
+
+ unset($vrednosti);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ // odmik glede na sortirane po prvem gridu (sort po kategorijah ali brez)
+ if($settings['sort'] < 3){
+ $offset = $sorted_keys[$j] /*$j*/ * $_variables_count;
+
+ for($i=0; $i<$_variables_count; $i++){
+ $vrednosti[] = $dataArray[$i+$offset]['avg'];
+ $vrednostiMax[] = $dataArray[$i+$offset]['max'];
+ $vrednostiMin[] = $dataArray[$i+$offset]['min'];
+
+ $vrednostiKey[] = $dataArray[$i+$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$i+$offset]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$sorted_keys[$j]);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$sorted_keys[$j]);
+
+ $DataSet->AddSerie('Vrednosti'.$sorted_keys[$j]);
+ $DataSet->SetSerieName($vrednostiGrid[$sorted_keys[$j]],'Vrednosti'.$sorted_keys[$j]);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,'Variable'.$sorted_keys[$j]);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$sorted_keys[$j]);
+ }
+
+ // sort po prvi kategoriji
+ else{
+ for($i=0; $i<$_variables_count; $i++){
+ $vrednosti[] = $dataArray[$j*$_variables_count + $sorted_keys[$i]]['avg'];
+ $vrednostiMax[] = $dataArray[$j*$_variables_count + $sorted_keys[$i]]['max'];
+ $vrednostiMin[] = $dataArray[$j*$_variables_count + $sorted_keys[$i]]['min'];
+
+ $vrednostiKey[] = $dataArray[$j*$_variables_count + $sorted_keys[$i]]['key'];
+ $vrednostiVariable[] = $dataArray[$j*$_variables_count + $sorted_keys[$i]]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$j);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$j);
+
+ $DataSet->AddSerie('Vrednosti'.$j);
+ $DataSet->SetSerieName($vrednostiGrid[$j],'Vrednosti'.$j);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,'Variable'.$j);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$j);
+ }
+ }
+ }
+ // Obratno obrnjen graf - gridi v legendi (deli stolpca), variable v stolpcih - default ce imamo samo en grid
+ else{
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$_variables_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sortiramo podaatke po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<count($spremenljivka['grids']); $j++){
+ $offset = $j * $_variables_count;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ else{
+ for($j=0; $j<$_variables_count; $j++){
+ $sorted_keys[] = $j;
+ }
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$_variables_count; $j++){
+
+ // odmik glede na sortirane po prvem gridu (sort po kategorijah ali brez)
+ if($settings['sort'] < 3){
+ $offset = $sorted_keys[$j];
+
+ unset($vrednosti);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ for($i=0; $i<count($spremenljivka['grids']); $i++){
+
+ $vrednosti[] = $dataArray[$i*$_variables_count+$offset]['avg'];
+ $vrednostiMax[] = $dataArray[$i*$_variables_count+$offset]['max'];
+ $vrednostiMin[] = $dataArray[$i*$_variables_count+$offset]['min'];
+
+ $vrednostiKey[] = $dataArray[$i*$_variables_count+$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$i*$_variables_count+$offset]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$vrednostiKey[0]);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$vrednostiKey[0]);
+
+ $DataSet->AddSerie('Vrednosti'.$vrednostiKey[0]);
+ $DataSet->SetSerieName($vrednostiVariable[0],'Vrednosti'.$vrednostiKey[0]);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiGrid,'Variable'.$vrednostiKey[0]);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$vrednostiKey[0]);
+ }
+
+ // sort po prvi kategoriji
+ else{
+ $offset = $sorted_keys[$j];
+
+ unset($vrednosti);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ for($i=0; $i<count($spremenljivka['grids']); $i++){
+
+ $vrednosti[] = $dataArray[$sorted_keys[$i]*$_variables_count + $j]['avg'];
+ $vrednostiMax[] = $dataArray[$sorted_keys[$i]*$_variables_count + $j]['max'];
+ $vrednostiMin[] = $dataArray[$sorted_keys[$i]*$_variables_count + $j]['min'];
+
+ $vrednostiKey[] = $dataArray[$sorted_keys[$i]*$_variables_count + $j]['key'];
+ $vrednostiVariable[] = $dataArray[$sorted_keys[$i]*$_variables_count + $j]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$vrednostiKey[0]);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$vrednostiKey[0]);
+
+ $DataSet->AddSerie('Vrednosti'.$vrednostiKey[0]);
+ $DataSet->SetSerieName($vrednostiVariable[0],'Vrednosti'.$vrednostiKey[0]);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiGrid,'Variable'.$vrednostiKey[0]);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$vrednostiKey[0]);
+ }
+ }
+ }
+
+ //$DataSet->SetYAxisName($lang['srv_analiza_sums_average']);
+ }
+
+ // Nastavimo other vrednosti
+ $DataSet->SetOther($_answersOther);
+
+ // ce imamo prazno in de prikazujemo praznih grafov
+ $hideEmpty = SurveyDataSettingProfiles :: getSetting('hideEmpty');
+ if($emptyData && $hideEmpty == 1)
+ return 0;
+ else
+ return $DataSet;
+ }
+
+
+ // Preverimo ce ima dropdown samo numeric vrednosti -> potem ga obravnavamo kot tip number
+ static function checkDropdownNumeric($spid){
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ $check = true;
+
+ foreach ($spremenljivka['options'] AS $option) {
+ if(!is_numeric($option))
+ $check = false;
+ }
+
+ return $check;
+ }
+
+
+ // Funkcije za izris posameznih tipov grafov - vertikalni stolpci
+ static function createVerBars($DataSet, $spremenljivka, $show_legend=0, $fixedScale=0){
+
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+
+ $angle = 0;
+ $addHeight = 0;
+ $roundText = 15;
+ if($countGrids > 5){
+ $angle = 45;
+ $addHeight = 110;
+ $roundText = 25;
+ }
+ if($show_legend == 1)
+ $addHeight += 70;
+
+ // Initialise the graph
+ $Test = new pChart(self::$quality*800,self::$quality*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ $Test->setGraphArea(self::$quality*100,self::$quality*40,self::$quality*650,self::$quality*220);
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+ // Pri checkboxu lahko naredimo fiksno skalo
+ if($spremenljivka['tip'] == 2 && self::$settings['noFixedScale'] == 1){
+ // Frekvence
+ if(self::$settings['value_type'] == 1){
+ // Dobimo sum frekvenc
+ $sum = 0;
+ foreach($Data as $vrednost){
+ $sum += $vrednost['Vrednosti'];
+ }
+ $Test->setFixedScale(0, $sum);
+ }
+ // Odstotki
+ else
+ $Test->setFixedScale(0, 100);
+ }
+
+ // Pri dvojnem multigridu prikazemo skalo od 1 do stevila variabel
+ if($spremenljivka['tip'] == 6 && $spremenljivka['enota'] == 3){
+
+ $VMax = count($spremenljivka['options']);
+
+ // Zacnemo skalo z 1
+ if($fixedScale == 0){
+ $Divisions = $VMax-1;
+ $VMin = 1;
+ }
+ // Zacnemo skalo z 0
+ else{
+ $VMax--;
+ $Divisions = $VMax;
+ $VMin = 0;
+ }
+
+ $Test->setFixedScale($VMin, $VMax, $Divisions);
+ }
+
+ $Test->drawScale($Data,$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,$angle,0,TRUE,1,FALSE,$roundText);
+ $Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ // Draw the bar graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ $Test->drawBarGraph($Data,$DataSet->GetDataDescription(), false, 95, self::$settings['barLabel'], self::$settings['barLabelSmall']);
+
+ // Finish the graph
+ if($show_legend == 1)
+ //$Test->drawLegend(self::$quality*680,self::$quality*30,$DataSet->GetDataDescription(),255,255,255);
+ // pri vodoravnih strukturnih stolpcih izrisemo legendo na dnu
+ $Test->drawVerticalLegend(self::$quality*400,self::$quality*(190+$addHeight),$DataSet->GetDataDescription(),255,255,255);
+
+ //$Test->setFontProperties("Fonts/verdana.ttf",10);
+ //$Test->drawTitle(50,22,$spremenljivka['variable'].' - '.$spremenljivka['naslov'],50,50,50,585);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*210,self::$quality*795,self::$quality*220,$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $vars = isset($spremenljivka['options']) ? count($spremenljivka['options']) : 0;
+ // Prikaz povprecja na grafu (samo pri ordinalnem radiu)
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3)
+ && $spremenljivka['skala'] != 1
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*40,self::$quality*795,self::$quality*45,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*680,self::$quality*45,self::$quality*795,self::$quality*50,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+ // Prikaz povprecja za number
+ if( ($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22)
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*90,self::$quality*795,self::$quality*95,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*680,self::$quality*95,self::$quality*795,self::$quality*100,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - horizontalni stolpci
+ static function createHorBars($DataSet, $spremenljivka, $show_legend=0, $fixedScale=0){
+ global $lang;
+
+ // Nastavimo visino grafa (ce imamo vec kot 7 variabel/gridov)
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+ $addHeight = $countGrids > 5 ? ($countGrids-5)*30 : 0;
+
+ // Dodamo prostor na dnu za legendo pri multigrid povprecjih
+ $addLegendSpace = 0;
+ if($show_legend == 1 && $spremenljivka['tip'] == 6 && self::$settings['type'] == 0 && $spremenljivka['enota'] != 3)
+ $addLegendSpace = 70;
+
+
+ // Initialise the graph
+ $Test = new MyHorBar(self::$quality*800,self::$quality*(250+$addHeight+$addLegendSpace));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Sirina label
+ // Ce iamo povprecje ni labele
+ if(in_array($spremenljivka['tip'],array(1,3,7)) && self::$settings['type'] == 9){
+ $startX = 160;
+ $roundText = 35;
+ }
+ elseif(self::$settings['labelWidth'] == 20){
+ $startX = 225;
+ $roundText = 35;
+ }
+ elseif(self::$settings['labelWidth'] == 75){
+ $startX = 500;
+ $roundText = 80;
+ }
+ else{
+ $startX = 360;
+ $roundText = 60;
+ }
+
+ $Test->setGraphArea(self::$quality*$startX,self::$quality*50,self::$quality*650,self::$quality*(220+$addHeight));
+
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*(243+$addHeight+$addLegendSpace),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*(245+$addHeight+$addLegendSpace),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+ // Pri ordinalnih multigridih prikazemo skalo od 1 do stevila variabel (ce prikazujemo povprecja)
+ if( ($spremenljivka['tip'] == 6 && self::$settings['type'] == 0) || ($spremenljivka['tip'] == 17 && self::$settings['type'] == 0) ){
+
+ $VMax = count($spremenljivka['options']);
+
+ // Zacnemo skalo z 1
+ if($fixedScale == 0){
+ $Divisions = $VMax-1;
+ $VMin = 1;
+ }
+ // Zacnemo skalo z 0
+ else{
+ $VMax--;
+ $Divisions = $VMax;
+ $VMin = 0;
+ }
+
+ $Test->setFixedScale($VMin, $VMax, $Divisions);
+ }
+
+ // Pri checkboxu lahko naredimo fiksno skalo
+ if($spremenljivka['tip'] == 2 && self::$settings['noFixedScale'] == 1){
+ // Frekvence
+ if(self::$settings['value_type'] == 1){
+ // Dobimo sum frekvenc
+ $sum = 0;
+ foreach($DataSet->GetData() as $vrednost){
+ $sum += $vrednost['Vrednosti'];
+ }
+ $Test->setFixedScale(0, $sum);
+ }
+ // Odstotki
+ else
+ $Test->setFixedScale(0, 100);
+ }
+
+ // Pri povprecju (radio) poiscemo najvecjo vrednost
+ if(in_array($spremenljivka['tip'],array(1,3)) && self::$settings['type'] == 9){
+
+ $VMax = count($spremenljivka['options']);
+ foreach($DataSet->GetData() as $vrednost){
+ $VMax = ($VMax < $vrednost['Vrednosti']) ? $vrednost['Vrednosti'] : $VMax;
+ }
+
+ $VMin = 0;
+
+ $Test->setFixedScale($VMin, $VMax);
+ }
+ // Pri povprecju (numeric) poiscemo najvecjo vrednost
+ elseif(($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22) && self::$settings['type'] == 9){
+
+ $VMax = 1;
+ $sequences = explode('_', $spremenljivka['sequences']);
+ foreach($sequences as $sequence){
+ if (count(SurveyAnalysis::$_FREQUENCYS[$sequence]['valid']) > 0 ) {
+ foreach(SurveyAnalysis::$_FREQUENCYS[$sequence]['valid'] AS $vkey => $vAnswer) {
+ $VMax = ($VMax < (int)$vAnswer['text']) ? (int)$vAnswer['text'] : $VMax;
+ }
+ }
+ }
+
+ $VMin = 0;
+
+ $Test->setFixedScale($VMin, $VMax);
+ }
+
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,0,0,TRUE,1,FALSE,$roundText);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Draw the bar graph
+ $Test->drawHorBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(), self::$settings['barLabel'], self::$settings['barLabelSmall']);
+
+ // Finish the graph
+ if($show_legend == 1){
+ // posebna legenda pri povprecjih
+ if($spremenljivka['tip'] == 6 && self::$settings['type'] == 0 && $spremenljivka['enota'] != 3)
+ //$Test->drawAvgVerticalLegend(self::$quality*680,self::$quality*30,$spremenljivka['options'],255,255,255);
+ $Test->drawAvgVerticalLegend(self::$quality*400,self::$quality*(190+$addHeight+$addLegendSpace),$spremenljivka['options'],255,255,255);
+ else
+ $Test->drawLegend(self::$quality*680,self::$quality*30,$DataSet->GetDataDescription(),255,255,255);
+ }
+
+ if($spremenljivka['tip'] == 18 || $spremenljivka['tip'] == 20)
+ $Test->drawTitle(self::$quality*200,self::$quality*22,$lang['srv_analiza_sums_average'],0,0,0,self::$quality*680);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*(210+$addHeight),self::$quality*795,self::$quality*(220+$addHeight),$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $vars = isset($spremenljivka['options']) ? count($spremenljivka['options']) : 0;
+ // Prikaz povprecja na grafu (samo pri ordinalnem radiu)
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3)
+ && $spremenljivka['skala'] != 1
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*50,self::$quality*795,self::$quality*55,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*680,self::$quality*55,self::$quality*795,self::$quality*60,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+ // Prikaz povprecja za number
+ if( ($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22)
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*90,self::$quality*795,self::$quality*95,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*680,self::$quality*95,self::$quality*795,self::$quality*100,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - vertikalni sestavljeni stolpci
+ static function createVerStructBars($DataSet, $spremenljivka){
+
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+
+ $angle = 0;
+ $addHeight = 0;
+ $roundText = 15;
+ if($countGrids > 5){
+ $angle = 45;
+ $addHeight = 110;
+ $roundText = 30;
+ }
+
+ // Initialise the graph
+ $Test = new pChart(self::$quality*800,self::$quality*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Pri navadnem radio in checkbox vprasanju imamo samo en stolpec - zato so dimenzije drugacne
+ if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3)
+ $Test->setGraphArea(self::$quality*250,self::$quality*40,self::$quality*500,self::$quality*220);
+ else
+ $Test->setGraphArea(self::$quality*100,self::$quality*40,self::$quality*650,self::$quality*220);
+
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0,0,0,0,TRUE,$angle,0,TRUE,1,FALSE,$roundText);
+ $Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ // Draw the bar graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ $Test->drawStackedBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(), self::$settings['barLabel'], 95);
+
+ // Finish the graph
+ if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3)
+ $Test->drawLegend(self::$quality*580,self::$quality*30,$DataSet->GetDataDescription(),255,255,255,$Rs=-1,$Gs=-1,$Bs=-1,$Rt=0,$Gt=0,$Bt=0,$Border=false,$reverse=true);
+ else
+ $Test->drawLegend(self::$quality*680,self::$quality*30,$DataSet->GetDataDescription(),255,255,255,$Rs=-1,$Gs=-1,$Bs=-1,$Rt=0,$Gt=0,$Bt=0,$Border=false,$reverse=true);
+
+ $Test->setFontProperties("Fonts/verdana.ttf",self::$quality*10);
+ //$Test->drawTitle(50,22,$spremenljivka['variable'].' - '.$spremenljivka['naslov'],50,50,50,585);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3)
+ $Test->drawTextBox(self::$quality*540,self::$quality*210,self::$quality*645,self::$quality*220,$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ else
+ $Test->drawTextBox(self::$quality*680,self::$quality*210,self::$quality*795,self::$quality*220,$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $vars = count($spremenljivka['options']);
+ // Prikaz povprecja na grafu (samo pri ordinalnem radiu)
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3)
+ && $spremenljivka['skala'] != 1
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*350,self::$quality*25,self::$quality*400,self::$quality*30,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*350,self::$quality*30,self::$quality*400,self::$quality*35,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - horizontalni sestavljeni stolpci
+ static function createHorStructBars($DataSet, $spremenljivka){
+
+ // Nastavimo visino graffa (ce imamo vec kot 7 variabel/gridov)
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+ $addHeight = $countGrids > 5 ? ($countGrids-5)*30 : 0;
+
+ // Imamo semanticni dif. - izpisujemo labele na desni
+ $rightScale = ($spremenljivka['tip'] == 6 && $spremenljivka['enota'] == 1 && self::$settings['scale_limit'] == 1) ? true : false;
+
+ // Initialise the graph
+ $Test = new MyHorBar(self::$quality*800,self::$quality*(250+$addHeight+50));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Sirina label
+ if(self::$settings['labelWidth'] == 20){
+ $startX = 225;
+ $roundText = 35;
+ }
+ elseif(self::$settings['labelWidth'] == 75){
+ $startX = 500;
+ $roundText = 80;
+ }
+ else{
+ $startX = 360;
+ $roundText = 60;
+ }
+
+ // Pri navadnem radio in checkbox vprasanju imamo samo en stolpec - zato so dimenzije drugacne
+ if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3){
+ $Test->setGraphArea(self::$quality*200,self::$quality*50,self::$quality*630,self::$quality*220);
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*243,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*295,200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0,0,0,0,TRUE,0,0,TRUE);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+ }
+ // Semanticni diferencial s skalo na desni
+ elseif($rightScale){
+ $Test->setGraphArea(self::$quality*270,self::$quality*50,self::$quality*530,self::$quality*(220+$addHeight));
+ $Test->drawFilledRoundedRectangle(7,7,793,243+$addHeight,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*(295+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0/*SCALE_START0*/,0,0,0,TRUE,0,0,TRUE,1,$rightScale,$roundText=40);
+ $Test->drawHorGrid(4,false,230,230,230,50);
+ }
+ else{
+ $Test->setGraphArea(self::$quality*$startX,self::$quality*50,self::$quality*650,self::$quality*(220+$addHeight));
+ $Test->drawFilledRoundedRectangle(7,7,793,243+$addHeight,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*(295+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0,0,0,0,TRUE,0,0,TRUE,1,FALSE,$roundText);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+ }
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Draw the bar graph
+ $Test->drawStackedHorBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),self::$settings['barLabel'],95);
+
+ // Finish the graph
+ /*if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3)
+ $Test->drawLegend(560,30,$DataSet->GetDataDescription(),255,255,255);
+ else
+ $Test->drawLegend(680,30,$DataSet->GetDataDescription(),255,255,255);*/
+
+ // pri vodoravnih strukturnih stolpcih izrisemo legendo na dnu
+ $Test->drawVerticalLegend(self::$quality*400,self::$quality*(240+$addHeight),$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties("Fonts/verdana.ttf",self::$quality*10);
+ //$Test->drawTitle(50,22,$spremenljivka['variable'].' - '.$spremenljivka['naslov'],50,50,50,585);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ /*if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3)
+ $Test->drawTextBox(570,210+$addHeight,795,220+$addHeight,'n = '.$DataSet->GetNumerus().self::$numerusText,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ else*/
+ $Test->drawTextBox(self::$quality*680,self::$quality*(210+$addHeight),self::$quality*795,self::$quality*(220+$addHeight),$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $vars = count($spremenljivka['options']);
+ // Prikaz povprecja na grafu (samo pri ordinalnem radiu)
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3)
+ && $spremenljivka['skala'] != 1
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*50,self::$quality*795,self::$quality*55,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*680,self::$quality*55,self::$quality*795,self::$quality*60,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - krozni graf
+ static function createPie($DataSet, $spremenljivka, $show_legend=1){
+ global $lang;
+
+ // Initialise the graph
+ $Test = new pChart(self::$quality*800,self::$quality*280);
+
+ // Pri pie grafu uporabimo antialiasing
+ $Test->setAntialias(true, 20);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ //$Test->setGraphArea(50,40,685,220);
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*273,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*275,200,200,200);
+ //$Test->createColorGradientPalette(195,204,56,223,110,41,3);
+ //$Test->createColorGradientPalette(168,188,56,248,255,136,5);
+
+
+ // Pri vsoti ne izpisujemo procentov
+ if($spremenljivka['tip'] == 18 || ($spremenljivka['tip'] == 1 && self::$settings['type'] == 2 && self::$settings['value_type'] == 1))
+ $labels = (self::$settings['sort'] == 1) ? 'custom_sort' : 'custom';
+ else
+ $labels = (self::$settings['sort'] == 1) ? 'custom_percent_sort' : 'custom_percent';
+
+
+ // Izrisemo navaden krozni graf
+ $Test->drawFlatPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),self::$quality*390,self::$quality*145,self::$quality*95,$labels);
+
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ //$Test->drawLegend(700,30,$DataSet->GetDataDescription(),255,255,255);
+
+ if($show_legend == 1)
+ $Test->drawPieLegend(self::$quality*600,self::$quality*50,$DataSet->GetData(),$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*10);
+
+ if($spremenljivka['tip'] == 18)
+ $Test->drawTitle(self::$quality*180,self::$quality*30,$lang['srv_analiza_sums_average'],0,0,0,self::$quality*610);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ $Test->setAntialias(false, 0);
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*600,self::$quality*220,self::$quality*715,self::$quality*230,$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $vars = count($spremenljivka['options']);
+ // Prikaz povprecja na grafu (samo pri ordinalnem radiu)
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3)
+ && $spremenljivka['skala'] != 1
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*600,self::$quality*240,self::$quality*715,self::$quality*245,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*600,self::$quality*245,self::$quality*715,self::$quality*250,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - 3D krozni graf
+ static function create3DPie($DataSet, $spremenljivka, $show_legend=1){
+ global $lang;
+
+ // Initialise the graph
+ $Test = new pChart(self::$quality*800,self::$quality*280);
+
+ // Pri 3d pie grafu uporabimo antialiasing
+ $Test->setAntialias(true, 20);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ //$Test->setGraphArea(50,40,685,220);
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*273,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*275,200,200,200);
+ //$Test->createColorGradientPalette(195,204,56,223,110,41,3);
+ //$Test->createColorGradientPalette(168,188,56,248,255,136,5);
+
+
+ // Pri vsoti ne izpisujemo procentov
+ if($spremenljivka['tip'] == 18 || ($spremenljivka['tip'] == 1 && self::$settings['type'] == 2 && self::$settings['value_type'] == 1))
+ $labels = (self::$settings['sort'] == 1) ? 'custom_sort' : 'custom';
+ else
+ $labels = (self::$settings['sort'] == 1) ? 'custom_percent_sort' : 'custom_percent';
+
+
+ // Izrisemo 3d krozni graf
+ $Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),self::$quality*390,self::$quality*130,self::$quality*95,$labels,$EnhanceColors=true,$Skew=50,$SpliceHeight=self::$quality*20,$SpliceDistance=0,$Decimals=0);
+
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ //$Test->drawLegend(700,30,$DataSet->GetDataDescription(),255,255,255);
+
+ if($show_legend == 1)
+ $Test->drawPieLegend(self::$quality*600,self::$quality*50,$DataSet->GetData(),$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*10);
+
+ if($spremenljivka['tip'] == 18)
+ $Test->drawTitle(self::$quality*180,self::$quality*30,$lang['srv_analiza_sums_average'],0,0,0,self::$quality*610);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ $Test->setAntialias(false, 0);
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*600,self::$quality*220,self::$quality*715,self::$quality*230,$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $vars = count($spremenljivka['options']);
+ // Prikaz povprecja na grafu (samo pri ordinalnem radiu)
+ if( ($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3)
+ && $spremenljivka['skala'] != 1
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*600,self::$quality*240,self::$quality*715,self::$quality*245,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*600,self::$quality*245,self::$quality*715,self::$quality*250,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - linijski graf
+ //spremenljivka je lahko null za linijski graf analize editiranja (SurveyEditsAnalysis)
+ static function createLine($DataSet, $spremenljivka, $show_legend=0, $fixedScale=0){
+
+ // Initialise the graph
+ $Test = new pChart(self::$quality*800,self::$quality*280);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ if($spremenljivka != null && ($spremenljivka['tip'] == 6 && $fixedScale == 1 && $spremenljivka['enota'] != 3) || ($spremenljivka['tip'] == 6 && $fixedScale == 0 && $spremenljivka['enota'] == 3)){
+
+ $VMax = count($spremenljivka['options']);
+ $Divisions = $VMax-1;
+
+ $Test->setFixedScale($VMin=1, $VMax, $Divisions);
+ }
+
+ $count = count($DataSet->GetData());
+
+ // Ce imamo numeric vse vrednosti in jih je vec kot 20 omejimo max 20 label na X osi
+ $SkipLabels = 1;
+ if($spremenljivka != null && ($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22) && $count > 20)
+ $SkipLabels = $count / 20;
+
+ // Kot label na x osi
+ $angle = 0;
+ if($count > 6)
+ $angle = 45;
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ $Test->setGraphArea(self::$quality*100,self::$quality*40,self::$quality*650,self::$quality*220);
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*273,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*275,200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+ // Pri checkboxu lahko naredimo fiksno skalo
+ if($spremenljivka != null && $spremenljivka['tip'] == 2 && self::$settings['noFixedScale'] == 1){
+ // Frekvence
+ if(self::$settings['value_type'] == 1){
+ // Dobimo sum frekvenc
+ $sum = 0;
+ foreach($DataSet->GetData() as $vrednost){
+ $sum += $vrednost['Vrednosti'];
+ }
+ $Test->setFixedScale(0, $sum);
+ }
+ // Odstotki
+ else
+ $Test->setFixedScale(0, 100);
+ }
+
+ $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,$angle,0,TRUE, $SkipLabels);
+ if($count <= 20)
+ $Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ //$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ // Draw the bar graph
+ $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
+ if($count <= 20)
+ $Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),self::$quality*3,self::$quality*2,255,255,255);
+
+ if($show_legend == 1)
+ $Test->drawLegend(self::$quality*680,self::$quality*30,$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka != null && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16))) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*690,self::$quality*(210+$addHeight),self::$quality*795,self::$quality*(220+$addHeight),$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ // Prikaz povprecja za number
+ if($spremenljivka != null && ($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22)
+ && (self::$settings['show_avg'] == 1 || (self::$settings['show_avg'] == -1 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ){
+
+ $Test->drawTextBox(self::$quality*690,self::$quality*80,self::$quality*795,self::$quality*85,'x = '.$DataSet->GetAverage(),$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox(self::$quality*690,self::$quality*85,self::$quality*795,self::$quality*90,'&#8254;',$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - linijski graf
+ static function createVerLine($DataSet, $spremenljivka, $show_legend=0, $fixedScale=0){
+
+ // Nastavimo visino grafa (ce imamo vec kot 7 variabel/gridov)
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+ $addHeight = $countGrids > 5 ? ($countGrids-5)*30 : 0;
+
+ // Imamo semanticni dif. - izpisujemo labele na desni
+ $rightScale = ($spremenljivka['enota'] == 1 && self::$settings['scale_limit'] == 1) ? true : false;
+
+ // Initialise the graph
+ $Test = new MyHorBar(self::$quality*800,self::$quality*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ if($spremenljivka['tip'] == 6 && $fixedScale == 0){
+
+ $VMax = count($spremenljivka['options']);
+ $Divisions = $VMax-1;
+
+ $Test->setFixedScale($VMin=1, $VMax, $Divisions);
+ }
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ $Test->setGraphArea(self::$quality*270,self::$quality*50,self::$quality*530,self::$quality*(220+$addHeight));
+
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,0,0,TRUE,1,$rightScale,$roundText=40);
+ $Test->drawHorGrid(4,false,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Draw the line graph
+ $Test->drawVerLineGraph($DataSet->GetData(),$DataSet->GetDataDescription(), $insideValues=false);
+
+ // Finish the graph
+ if($show_legend == 1){
+ // posebna legenda pri povprecjih
+ if($spremenljivka['tip'] == 6 && self::$settings['type'] == 6)
+ $Test->drawAvgLegend(self::$quality*680,self::$quality*30,$spremenljivka['options'],255,255,255);
+ else
+ $Test->drawLegend(self::$quality*680,self::$quality*30,$DataSet->GetDataDescription(),255,255,255);
+ }
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ if($spremenljivka['tip'] == 18)
+ $Test->drawTitle(self::$quality*200,self::$quality*22,'Povprečje',150,150,150,self::$quality*585);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*680,self::$quality*(210+$addHeight),self::$quality*795,self::$quality*(220+$addHeight),$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - vertikalni stolpci
+ static function createRadar($DataSet, $spremenljivka, $show_legend=0, $fixedScale=0){
+
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+
+ // Initialise the graph
+ $Test = new pChart(self::$quality*800,self::$quality*350);
+
+ // Pri radarju uporabimo antialiasing
+ $Test->setAntialias(true, 20);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = self::setChartColors($Test, self::$skin);
+
+ $Test->setLineStyle(self::$quality,$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ $Test->setGraphArea(self::$quality*100,self::$quality*40,self::$quality*650,self::$quality*320);
+ $Test->drawFilledRoundedRectangle(self::$quality*7,self::$quality*7,self::$quality*793,self::$quality*343,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle(self::$quality*5,self::$quality*5,self::$quality*795,self::$quality*345,200,200,200);
+ //$Test->drawGraphArea(255,255,255,TRUE);
+ //$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,20,20,20,TRUE,$angle,0,TRUE,1,FALSE,$roundText);
+ //$Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+
+ // Pri ordinalnih multigridih prikazemo skalo od 1 do stevila variabel (ce prikazujemo povprecja)
+ if($spremenljivka['tip'] == 6 /*&& $spremenljivka['skala'] == 0*/ && $fixedScale == 0){
+
+ $VMax = count($spremenljivka['options']) - 1;
+ $Divisions = $VMax-1;
+
+ $Test->setFixedScale($VMin=1, $VMax, $Divisions);
+ }
+ else
+ $VMax = -1;
+
+
+ // Draw the radar
+ $Test->drawRadarAxis($DataSet->GetData(),$DataSet->GetDataDescription(),true,5,0,0,0,160,160,160,$VMax,self::$settings['radar_scale']);
+ // Tip radarja - navaden ali samo crte
+ if(self::$settings['radar_type'] == 1)
+ $Test->drawFilledRadar($DataSet->GetData(),$DataSet->GetDataDescription(),50,5,$VMax);
+ else{
+ $Test->setLineStyle($Width=(2*self::$quality),$DotSize=0);
+ $Test->drawRadar($DataSet->GetData(),$DataSet->GetDataDescription(),5,$VMax);
+ }
+
+ $Test->setAntialias(false, 0);
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ if($show_legend == 1){
+ // posebna legenda pri povprecjih
+ if($spremenljivka['tip'] == 6 && self::$settings['type'] == 5)
+ $Test->drawAvgLegend(self::$quality*680,self::$quality*30,$spremenljivka['options'],255,255,255);
+ else
+ $Test->drawLegend(self::$quality*680,self::$quality*30,$DataSet->GetDataDescription(),255,255,255);
+ }
+
+ $Test->setFontProperties("Fonts/verdana.ttf",self::$quality*10);
+ //$Test->drawTitle(50,22,$spremenljivka['variable'].' - '.$spremenljivka['naslov'],50,50,50,585);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',self::$quality*self::$fontSize);
+
+ // Prikaz numerusa na grafu
+ $char = (self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16)) ? 'r' : 'n';
+ if( self::$settings['show_numerus'] == 1 || (self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1) )
+ $numerus = $char.' = '.$DataSet->GetNumerus();
+ elseif( self::$settings['show_numerus'] == -1 && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 2 )
+ $numerus = $char.' = ' . $DataSet->GetNumerus() . self::$numerusText;
+ else
+ $numerus = '';
+
+ $Test->drawTextBox(self::$quality*600,self::$quality*220,self::$quality*715,self::$quality*230,$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+ return $Test;
+ }
+
+
+ // Nastavitve na vrhu
+ static function displayGlobalSettings(){
+ global $lang;
+ global $admin_type;
+ global $site_url;
+
+ self::$skin = SurveyUserSetting :: getInstance()->getSettings('default_chart_profile_skin');
+
+ //moznost osvezevanja grafov - ne uporabljamo zaenkrat
+ if($admin_type < 2 && false)
+ echo '<a href="'.$site_url.'?anketa='.self::$anketa.'&a=analysis&m=charts&refresh=1"><img src="img_0/random_off.png" title="Osveži grafe" /></a>';
+
+ // Izrisemo ostale filtre
+ SurveyAnalysis::DisplayFilters(self::$quality);
+
+ // prklop na vecjo resolucijo grafov (zaenkrat tukaj - kasneje v globalne nastavitve)
+ //self::displayHQSetting();
+
+
+ echo '<div id="displayFilterNotes">';
+ # če imamo filter zoom ga izpišemo
+ SurveyZoom::getConditionString();
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+ # če imamo filter ifov za inspect ga izpišemo
+ $SI = new SurveyInspect(self::$anketa);
+ $SI->getConditionString();
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile();
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString(true);
+
+ # če imamo rekodiranje
+ $SR = new SurveyRecoding(self::$anketa);
+ $SR -> getProfileString();
+
+ SurveyDataSettingProfiles :: getVariableTypeNote($doNewLine);
+ echo '</div>';
+ }
+
+ public static function displayHQSetting(){
+ global $lang;
+
+ echo '<div id="chart_hq_setting" class="analiza">';
+
+ echo '<ul>';
+ echo '<li>';
+ echo $lang['srv_chart_hq'].': ';
+ echo '<input type="checkbox" name="chart_hq" id="chart_hq" onClick="changeChartHq(this)" '.(self::$quality == 3 ? ' checked="checked"' : '').'>';
+ echo '</li>';
+
+ # nastavitev skina grafov
+ echo '<li>';
+ $SSH = new SurveyStaticHtml(self::$anketa);
+ $SSH -> displayLinkChart(false);
+ echo '</li>';
+
+ echo '</div>';
+ }
+
+ // Nastavitve na dnu
+ static function displayBottomSettings(){
+ global $site_path;
+ global $lang;
+
+ echo '<div class="chart_bottom_settings">';
+
+ echo '<a href="#" onClick="addCustomReportAllElementsAlert(4);" title="'.$lang['srv_custom_report_comments_add_hover'].'" style="margin-right: 40px;"><span class="spaceRight faicon comments_creport" ></span><span class="bold">'.$lang['srv_custom_report_comments_add'].'</span></a>';
+
+ echo '<a href="#" onClick="printAnaliza(\'Grafi\'); return false;" title="'.$lang['hour_print2'].'" class="srv_ico"><span class="faicon print icon-grey_dark_link"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts&anketa=' . self::$anketa) . '" target="_blank" title="'.$lang['PDF_Izpis'].'"><span class="faicon pdf black very_large" ></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts_rtf&anketa=' . self::$anketa) . '" target="_blank" title="'.$lang['RTF_Izpis'].'"><span class="faicon rtf black very_large"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts_ppt&anketa=' . self::$anketa) . '" target="_blank" title="'.$lang['PPT_Izpis'].'"><span class="faicon ppt black very_large"></span></a>';
+
+ echo '<a href="#" onclick="doArchiveAnaliza();" title="'.$lang['srv_analiza_arhiviraj_ttl'].'"><span class="faicon arhiv black very_large"></span></a>';
+ echo '<a href="#" onclick="createArchiveBeforeEmail();" title="'.$lang['srv_analiza_arhiviraj_email_ttl'] . '"><span class="faicon arhiv_mail black very_large"></span></a>';
+
+ echo '</div>';
+ }
+
+ // Pripis pod grafom (numerus, povprecje, spremenljivka...)
+ static function displayBottomChartInfo($DataSet, $spremenljivka){
+ global $site_path;
+ global $lang;
+
+ echo '<div class="chart_bottom_info">';
+ echo '<ul>';
+
+ // spremenljivka
+ echo '<li>'.$lang['srv_spremenljivka'].': <span class="strong">'.$spremenljivka['variable'].'</span> <span class="anl_ita">('.$lang['srv_vprasanje_tip_'.$spremenljivka['tip']].')</span></li>';
+
+ // numerus
+ if(self::$settings['base'] == 1 && ($spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 16))
+ echo '<li>,&nbsp; r = <span class="strong">'.$DataSet->GetNumerus().'</span> <span class="anl_ita">'.self::$numerusText.'</span></li>';
+ else
+ echo '<li>,&nbsp; n = <span class="strong">'.$DataSet->GetNumerus().'</span> <span class="anl_ita">'.self::$numerusText.'</span></li>';
+
+ // povprecje (ce je radio ali droipdown ordinalna)
+ if(($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 3) && $spremenljivka['skala'] != 1)
+ echo '<li>,&nbsp; <span style="text-decoration: overline;">x</span> = <span class="strong">'.$DataSet->GetAverage().'</span></li>';
+
+ echo '</ul>';
+ echo '</div>';
+ }
+
+
+ // Nastavitve posameznega grafa
+ static function displaySingleSettings($spid, $settings=0){
+ global $site_path;
+ global $lang;
+ if (self::$publicChart == true) {
+ return false;
+ }
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Ikone izvoza na vrhu posameznih nastavitev
+ self::displayExportIcons($spid);
+
+
+ echo '<div id="switch_left_'.$spid.'_loop_'.self::$current_loop.'" class="switch_left '.(self::$settings_mode == 1 ? ' non-active' : '').'" onClick="chartSwitchSettings(\''.$spid.'\', \'0\', \''.self::$current_loop.'\')">'.$lang['srv_chart_settings_basic'].'</div>';
+ //echo '<span id="switch_middle_'.$spid.'_loop_'.self::$current_loop.'" class="'.(self::$settings_mode == 1 ? 'rightHighlight' : 'leftHighlight').'"></span>';
+ echo '<div id="switch_right_'.$spid.'_loop_'.self::$current_loop.'" class="switch_right '.(self::$settings_mode == 0 ? ' non-active' : '').'" onClick="chartSwitchSettings(\''.$spid.'\', \'1\', \''.self::$current_loop.'\')">'.$lang['srv_chart_settings_advanced'].'</div>';
+
+
+ // OSNOVNE NASTAVITVE
+ echo '<div class="chart_settings_inner" id="chart_settings_basic_'.$spid.'_loop_'.self::$current_loop.'" '.(self::$settings_mode == 1 ? ' style="display:none;"' : '').'>';
+
+ //echo '<span class="title">'.$lang['srv_chart_settings'].'</span>';
+
+ switch($spremenljivka['tip']){
+ case 1:
+ case 3:
+ self::displayRadioSettings($spid, $settings);
+ break;
+
+ case 2:
+ self::displayCheckboxSettings($spid, $settings);
+ break;
+
+ case 6:
+ if($spremenljivka['enota'] == 3)
+ self::displayDoubleMultigridSettings($spid, $settings);
+ else
+ self::displayMultigridSettings($spid, $settings);
+ break;
+
+ case 7:
+ case 22:
+ self::displayNumberSettings($spid, $settings);
+ break;
+
+ case 8:
+ self::displayDateSettings($spid, $settings);
+ break;
+
+ case 16:
+ self::displayMulticheckboxSettings($spid, $settings);
+ break;
+
+ case 17:
+ self::displayRankingSettings($spid, $settings);
+ break;
+
+ case 18:
+ self::displayVsotaSettings($spid, $settings);
+ break;
+
+ case 20:
+ self::displayMultinumberSettings($spid, $settings);
+ break;
+
+ case 21:
+ case 4:
+ self::displayTableSettings($spid);
+ break;
+
+ case 19:
+ self::displayMultitextSettings($spid, $settings);
+ break;
+
+ default:
+ break;
+ }
+
+ // Preview vprasanja
+ //SurveyAnalysis::showVariable($spid, $spremenljivka['variable']);
+ echo '<div class="chart_setting" style="text-align: center; margin-top: 20px;">';
+ echo '<span style="margin-right: 6px; line-height: 6px; font-weight: 600; font-size: 11px;">';
+ //echo $lang['srv_vprasanje'].': ';
+ echo $spremenljivka['variable'];
+ echo '</span>';
+ //echo '<a href="/" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="preview_spremenljivka_analiza(\'' . $spid . '\'); return false;"><span class="sprites preview"></span></a>';
+ echo '<a href="#" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\''.$spid.'\'); return false;"><span class="faicon preview"></span></a> ';
+ //echo '</div>';
+
+ //echo '<div class="chart_setting" style="text-align: center;">';
+ SurveyAnalysis::showIcons($spid,$spremenljivka,$_from='charts');
+ echo '</div>';
+
+ echo '</div>';
+
+
+ // NAPREDNE NASTAVITVE
+ echo '<div class="chart_settings_inner" id="chart_settings_advanced_'.$spid.'_loop_'.self::$current_loop.'" '.(self::$settings_mode == 0 ? ' style="display:none;"' : '').'>';
+
+ switch($spremenljivka['tip']){
+ case 1:
+ case 3:
+ self::displayAdvancedRadioSettings($spid, $settings);
+ break;
+
+ case 2:
+ self::displayAdvancedCheckboxSettings($spid, $settings);
+ break;
+
+ case 6:
+ if($spremenljivka['enota'] == 3)
+ self::displayAdvancedDoubleMultigridSettings($spid, $settings);
+ else
+ self::displayAdvancedMultigridSettings($spid, $settings);
+ break;
+
+ case 7:
+ case 22:
+ self::displayAdvancedNumberSettings($spid, $settings);
+ break;
+
+ case 8:
+ self::displayAdvancedDateSettings($spid, $settings);
+ break;
+
+ case 16:
+ self::displayAdvancedMulticheckboxSettings($spid, $settings);
+ break;
+
+ case 17:
+ self::displayAdvancedRankingSettings($spid, $settings);
+ break;
+
+ case 18:
+ self::displayAdvancedVsotaSettings($spid, $settings);
+ break;
+
+ case 20:
+ self::displayAdvancedMultinumberSettings($spid, $settings);
+ break;
+
+ default:
+ break;
+ }
+
+ // Link na urejanje label
+ echo '<span class="edit" style="margin-top:15px;" onclick="chartAdvancedSettings(\''.$spid.'\', 1, \''.self::$current_loop.'\');">'.$lang['srv_chart_advancedLink_labels'].'</span>';
+ // Vprasajcek za pomoc
+ echo Help :: display('displaychart_settings_labels');
+
+ // Link na urejanje barv
+ echo '<span class="edit" onclick="chartAdvancedSettings(\''.$spid.'\', \'2\', \''.self::$current_loop.'\');">'.$lang['srv_chart_advancedLink_colors'].'</span>';
+ // Vprasajcek za pomoc
+ echo Help :: display('displaychart_settings_colors');
+
+ // Link na rekodiranje
+ echo '<span class="edit" onclick="chartAdvancedSettings(\''.$spid.'\', \'3\', \''.self::$current_loop.'\');">'.$lang['srv_chart_advancedLink_recoding'].'</span>';
+ // Vprasajcek za pomoc
+ echo Help :: display('displaychart_settings_recoding');
+
+ // Link na napredne number (radio dropdown numeric, number, date) nastavitve
+ if(($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)) || $spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 8 || $spremenljivka['tip'] == 22){
+ echo '<span class="edit" onclick="chartAdvancedSettings(\''.$spid.'\', \'4\', \''.self::$current_loop.'\');">'.$lang['srv_chart_advancedLink_limits'].'</span>';
+ // Vprasajcek za pomoc
+ //echo Help :: display('displaychart_settings_number');
+ }
+
+
+ echo '</div>';
+ }
+
+ // ikone na vrhu posameznih nastavitev (izvozi)
+ static function displayExportIcons($spid){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ $loop = (isset(SurveyAnalysis::$_CURRENT_LOOP)) ? SurveyAnalysis::$_CURRENT_LOOP['cnt'] : 'undefined';
+
+ // linki
+ echo '<div class="chart_setting_exportLinks">';
+
+ // Ikona za print
+ echo '<a href="#" onclick="showAnalizaSingleChartPopup(\''.$spid.'\',\''.M_ANALYSIS_CHARTS.'\'); return false;">';
+ echo '<span class="faicon print_small icon-grey_dark_link" title="' . $lang['PRN_Izpis'] . '"></span>';
+ echo '</a>';
+
+ // Izvoz posameznega grafa v PDF/RTF/PPT
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts&anketa='.self::$anketa.'&sprID='.$spid.'&loop='.$loop).'" target="_blank" title="'.$lang['PDF_Izpis'].'"><span class="faicon pdf"></span></a>';
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts_rtf&anketa='.self::$anketa.'&sprID='.$spid.'&loop='.$loop).'" target="_blank" title="'.$lang['RTF_Izpis'].'"><span class="faicon rtf"></span></a>';
+ // V PPT zaenkrat ne izvazamo tabel
+ if($spremenljivka['tip'] != 4 && $spremenljivka['tip'] != 19 && $spremenljivka['tip'] != 21)
+ echo '<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts_ppt&anketa='.self::$anketa.'&sprID='.$spid.'&loop='.$loop).'" target="_blank" title="'.$lang['PPT_Izpis'].'"><span class="faicon ppt"></span></a>';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za radio grafe (tip 1,3)
+ static function displayRadioSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Nastavitve numeric dropdowna - obravnavamo kot number
+ if($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)){
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 1, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="5" '.($settings['type']=='5'?' selected="selected"':'').'>'.$lang['srv_chart_group_horizontal'].'</option>';
+ echo ' <option value="6" '.($settings['type']=='6'?' selected="selected"':'').'>'.$lang['srv_chart_group_vertical'].'</option>';
+ echo ' <option value="7" '.($settings['type']=='7'?' selected="selected"':'').'>'.$lang['srv_chart_group_line'].'</option>';
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // tip izpisa vrednosti
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 1, \'value_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ if($settings['type'] < 5){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 1, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // stevilo intervalov
+ if($settings['type'] > 4){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_interval'].': <select id="chart_interval_'.$spid.'_loop_'.self::$current_loop.'" name="chart_interval" onchange="changeChart(\''.$spid.'\', 1, \'interval\', \''.self::$current_loop.'\');">';
+
+ for($i=3; $i<=10; $i++){
+ echo ' <option value="'.$i.'" '.($settings['interval']==$i ?' selected="selected"':'').'>'.$i.'</option>';
+ }
+ echo ' <option value="20" '.($settings['interval']=='20'?' selected="selected"':'').'>20</option>';
+ //echo ' <option value="50" '.($settings['interval']=='50'?' selected="selected"':'').'>50</option>';
+ //echo ' <option value="100" '.($settings['interval']=='100'?' selected="selected"':'').'>100</option>';
+ echo ' <option value="-1" '.($settings['interval']=='-1'?' selected="selected"':'').'>Vsi</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 0 || $settings['type'] == 1 || $settings['type'] == 3 || $settings['type'] == 4){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 1, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve radia in navadnega dropdowna
+ else{
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 1, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_pie'].'</option>';
+ echo ' <option value="8" '.($settings['type']=='8'?' selected="selected"':'').'>'.$lang['srv_chart_3Dpie'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_structure1_hor'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_structure1_ver'].'</option>';
+ if($spremenljivka['skala'] != 1)
+ echo ' <option value="9" '.($settings['type']=='9'?' selected="selected"':'').'>'.$lang['srv_chart_avg_single'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ if($settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 1, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // tip izpisa vrednosti
+ if($settings['type'] != 9){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 1, \'value_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ if($settings['type'] != 2 && $settings['type'] != 8)
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // prikaz legende
+ if($settings['type'] == 2 || $settings['type'] == 8){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_analiza_legenda'].': ';
+ echo '<input type="checkbox" id="chart_show_legend_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_legend" '.($settings['show_legend']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 1, \'show_legend\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 0 || $settings['type'] == 1 || $settings['type'] == 3 || $settings['type'] == 4 || $settings['type'] == 9){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 1, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+ }
+
+ // Nastavitve za radio grafe (tip 1,3) - NAPREDNO
+ static function displayAdvancedRadioSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 1, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // prikaz povprecja
+ if($spremenljivka['skala'] != 1 && $settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ $vars = count($spremenljivka['options']);
+ $checked = ($settings['show_avg']=='1' || ($settings['show_avg']=='-1' && $vars == 5 && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showAvg'].': ';
+ echo '<input type="checkbox" id="chart_show_avg_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_avg" '.$checked.' onchange="changeChart(\''.$spid.'\', 1, \'show_avg\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 1, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // 3D strukturni krog
+ /*if($settings['type'] == 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_3d_pie'].': ';
+ echo '<input type="checkbox" id="chart_3d_pie_'.$spid.'_loop_'.self::$current_loop.'" name="chart_3d_pie" '.($settings['3d_pie']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 1, \'3d_pie\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }*/
+
+ // Izpusti variable brez odgovora
+ if(($spremenljivka['tip'] != 3 || !self::checkDropdownNumeric($spid)) && $settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_hideEmtyVar'].': ';
+ echo '<input type="checkbox" id="chart_hideEmptyVar_'.$spid.'_loop_'.self::$current_loop.'" name="chart_hideEmptyVar" '.($settings['hideEmptyVar']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 1, \'hideEmptyVar\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label majhnih vrednosti zraven stolpcov
+ if($settings['barLabel'] == 1 && ($settings['type'] == 0 || $settings['type'] == 1)){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabelSmall'].': ';
+ echo '<input type="checkbox" id="chart_barLabelSmall_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabelSmall" '.($settings['barLabelSmall']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 1, \'barLabelSmall\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // Preklop med ordinalno in nominalno spremenljivko - ce imamo povprecja ne smemo preklopiti na nominalno
+ if($settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ $lestvica = SurveyAnalysis::getSpremenljivkaLegenda($spremenljivka,'skalaAsValue');
+
+ echo $lang['srv_skala'].': ';
+ // Vprasajcek za pomoc
+ echo Help :: display('srv_skala_edit');
+
+ echo '<span class="spaceLeft"></span>';
+ echo '<a onclick="chartAdvancedSettingsSkala(\''.$spid.'\', \'0\', \''.self::$current_loop.'\'); return false;" href="#" title="'.$lang['srv_skala_long_0'].'"><span '.($lestvica == 0 ? ' class="strong"' : '').'>'.$lang['srv_skala_short_0'].'</span></a>';
+ echo '<span class="blue"> / </span>';
+ echo '<a onclick="chartAdvancedSettingsSkala(\''.$spid.'\', \'1\', \''.self::$current_loop.'\'); return false;" href="#" title="'.$lang['srv_skala_long_1'].'"><span '.($lestvica == 1 ? ' class="strong"' : '').'>'.$lang['srv_skala_short_1'].'</span></a>';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za checkbox grafe (tip 2)
+ static function displayCheckboxSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // omejitev skale
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_base'].': <select id="chart_base_'.$spid.'_loop_'.self::$current_loop.'" name="chart_base" onchange="changeChart(\''.$spid.'\', 2, \'base\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['base']=='0'?' selected="selected"':'').'>'.$lang['srv_analiza_opisne_units'].'</option>';
+ echo ' <option value="1" '.($settings['base']=='1'?' selected="selected"':'').'>'.$lang['srv_analiza_opisne_arguments'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 2, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ if($settings['base'] != '0'){
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_pie'].'</option>';
+ echo ' <option value="7" '.($settings['type']=='7'?' selected="selected"':'').'>'.$lang['srv_chart_3Dpie'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_structure1_hor'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_structure1_ver'].'</option>';
+ }
+ else{
+ echo ' <option value="5" '.($settings['type']=='5'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+ echo ' <option value="6" '.($settings['type']=='6'?' selected="selected"':'').'>'.$lang['srv_chart_line'].'</option>';
+ }
+
+ echo '</select>';
+ echo '</div>';
+
+ // Tip radarja
+ if($settings['type'] == '5'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="chart_radar_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_type" onchange="changeChart(\''.$spid.'\', 2, \'radar_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == '5'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="chart_radar_scale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_scale" onchange="changeChart(\''.$spid.'\', 2, \'radar_scale\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // tip izpisa vrednosti
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 2, \'value_type\', \''.self::$current_loop.'\');" '.($settings['type'] == 2 ? 'disabled="disabled"' : '').'>';
+
+ if($settings['base'] != '1')
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ if($settings['type'] != 5){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 2, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // prikaz legende
+ if($settings['type'] == 2 || $settings['type'] == 7){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_analiza_legenda'].': ';
+ echo '<input type="checkbox" id="chart_show_legend_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_legend" '.($settings['show_legend']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 2, \'show_legend\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 0 || $settings['type'] == 1 || $settings['type'] == 3 || $settings['type'] == 4){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 2, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za checkbox grafe (tip 2)
+ static function displayAdvancedCheckboxSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 2, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 2, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // Izpusti variable brez odgovora
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_hideEmtyVar'].': ';
+ echo '<input type="checkbox" id="chart_hideEmptyVar_'.$spid.'_loop_'.self::$current_loop.'" name="chart_hideEmptyVar" '.($settings['hideEmptyVar']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 2, \'hideEmptyVar\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // prikaz polne skale
+ if($settings['type'] == 0 || $settings['type'] == 1 || $settings['type'] == 6){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_settings_fullScale'].': ';
+ echo '<input type="checkbox" id="chart_noFixedScale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_noFixedScale" '.($settings['noFixedScale']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 2, \'noFixedScale\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label majhnih vrednosti zraven stolpcov
+ if($settings['barLabel'] == 1 && ($settings['type'] == 0 || $settings['type'] == 1)){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabelSmall'].': ';
+ echo '<input type="checkbox" id="chart_barLabelSmall_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabelSmall" '.($settings['barLabelSmall']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 2, \'barLabelSmall\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // 3D strukturni krog
+ /*if($settings['type'] == 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_3d_pie'].': ';
+ echo '<input type="checkbox" id="chart_3d_pie_'.$spid.'_loop_'.self::$current_loop.'" name="chart_3d_pie" '.($settings['3d_pie']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 2, \'3d_pie\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }*/
+ }
+
+ // Nastavitve za number grafe (tip 7)
+ static function displayNumberSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 7, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_group_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_group_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_group_line'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="9" '.($settings['type']=='9'?' selected="selected"':'').'>'.$lang['srv_chart_avg_single'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // tip izpisa vrednosti
+ if($settings['type'] != 9){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 7, \'value_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // sortiranje
+ if($settings['type'] > 2 && $settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 7, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // stevilo intervalov
+ if($settings['type'] < 3){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_interval'].': <select id="chart_interval_'.$spid.'_loop_'.self::$current_loop.'" name="chart_interval" onchange="changeChart(\''.$spid.'\', 7, \'interval\', \''.self::$current_loop.'\');">';
+
+ for($i=3; $i<=10; $i++){
+ echo ' <option value="'.$i.'" '.($settings['interval']==$i ?' selected="selected"':'').'>'.$i.'</option>';
+ }
+ echo ' <option value="20" '.($settings['interval']=='20'?' selected="selected"':'').'>20</option>';
+ //echo ' <option value="50" '.($settings['interval']=='50'?' selected="selected"':'').'>50</option>';
+ //echo ' <option value="100" '.($settings['interval']=='100'?' selected="selected"':'').'>100</option>';
+ echo ' <option value="-1" '.($settings['interval']=='-1'?' selected="selected"':'').'>Vsi</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // prikaz legende
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_analiza_legenda'].': ';
+ echo '<input type="checkbox" id="chart_show_legend_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_legend" '.($settings['show_legend']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 7, \'show_legend\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // div z nastavitvami za zgornjo in spodnjo mejo
+ /*echo '<fieldset class="chart_num_limits"><legend>'.$lang['srv_chart_num_limit'].'</legend>';
+
+ // min
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_min'].': ';
+ echo '<input type="text" id="chart_min_'.$spid.'_loop_'.self::$current_loop.'" name="chart_min" value="'.$settings['min'].'" onBlur="changeChart(\''.$spid.'\', 7, \'min\', \''.self::$current_loop.'\');" onkeypress="checkNumber(this, 6, 0);" onkeyup="checkNumber(this, 6, 0);" />';
+
+ echo '</div>';
+
+ // polodprt interval navzdol
+ echo '<div class="chart_setting" style="text-align:right;">';
+
+ echo $lang['srv_chart_open_down'].': ';
+ echo '<input type="checkbox" id="chart_open_down_'.$spid.'_loop_'.self::$current_loop.'" name="chart_open_down" '.($settings['open_down']=='1'?' checked="checked"':'').' '.($settings['min']==''?' disabled="disabled"':'').' onchange="changeChart(\''.$spid.'\', 7, \'open_down\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // max
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_max'].': ';
+ echo '<input type="text" id="chart_max_'.$spid.'_loop_'.self::$current_loop.'" name="chart_max" value="'.$settings['max'].'" onBlur="changeChart(\''.$spid.'\', 7, \'max\', \''.self::$current_loop.'\');" onkeypress="checkNumber(this, 6, 0);" onkeyup="checkNumber(this, 6, 0);" />';
+
+ echo '</div>';
+
+ // polodprt interval navzgor
+ echo '<div class="chart_setting" style="text-align:right;">';
+
+ echo $lang['srv_chart_open_up'].': ';
+ echo '<input type="checkbox" id="chart_open_up_'.$spid.'_loop_'.self::$current_loop.'" name="chart_open_up" '.($settings['open_up']=='1'?' checked="checked"':'').' '.($settings['max']==''?' disabled="disabled"':'').' onchange="changeChart(\''.$spid.'\', 7, \'open_up\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ echo '</fieldset>';*/
+ }
+
+ // Nastavitve za number grafe (tip 7)
+ static function displayAdvancedNumberSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 7, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // prikaz povprecja
+ if($settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_avg']=='1' || ($settings['show_avg']=='-1' && SurveyDataSettingProfiles :: getSetting('chartAvgText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showAvg'].': ';
+ echo '<input type="checkbox" id="chart_show_avg_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_avg" '.$checked.' onchange="changeChart(\''.$spid.'\', 7, \'show_avg\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] != 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 7, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label majhnih vrednosti zraven stolpcov
+ if($settings['barLabel'] == 1 && $settings['type'] != 2 && $settings['type'] != 9){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabelSmall'].': ';
+ echo '<input type="checkbox" id="chart_barLabelSmall_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabelSmall" '.($settings['barLabelSmall']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 7, \'barLabelSmall\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 7, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za datum grafe (tip 8)
+ static function displayDateSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 8, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_group_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_group_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_line'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // tip izpisa vrednosti
+ if($settings['type'] < 3){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 8, \'value_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_day'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_month'].'</option>';
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_year'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // sortiranje
+ if($settings['type'] > 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 8, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // stevilo intervalov
+ if($settings['type'] < 3){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_interval'].': <select id="chart_interval_'.$spid.'_loop_'.self::$current_loop.'" name="chart_interval" onchange="changeChart(\''.$spid.'\', 8, \'interval\', \''.self::$current_loop.'\');">';
+
+ for($i=3; $i<=10; $i++){
+ echo ' <option value="'.$i.'" '.($settings['interval']==$i ?' selected="selected"':'').'>'.$i.'</option>';
+ }
+ echo ' <option value="20" '.($settings['interval']=='20'?' selected="selected"':'').'>20</option>';
+ //echo ' <option value="50" '.($settings['interval']=='50'?' selected="selected"':'').'>50</option>';
+ //echo ' <option value="100" '.($settings['interval']=='100'?' selected="selected"':'').'>100</option>';
+ echo ' <option value="-1" '.($settings['interval']=='-1'?' selected="selected"':'').'>Vsi</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // div z nastavitvami za zgornjo in spodnjo mejo
+ /*echo '<fieldset class="chart_num_limits"><legend>'.$lang['srv_chart_num_limit'].'</legend>';
+
+ // min
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_min'].': ';
+ echo '<input type="text" id="chart_min_'.$spid.'_loop_'.self::$current_loop.'" name="chart_min" value="'.$settings['min'].'" onBlur="changeChart(\''.$spid.'\', 8, \'min\', \''.self::$current_loop.'\');" onkeypress="checkNumber(this, 6, 0);" onkeyup="checkNumber(this, 6, 0);" />';
+
+ echo '</div>';
+
+ // polodprt interval navdol
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_open_down'].': ';
+ echo '<input type="checkbox" id="chart_open_down_'.$spid.'_loop_'.self::$current_loop.'" name="chart_open_down" '.($settings['open_down']=='1'?' checked="checked"':'').' '.($settings['min']==''?' disabled="disabled"':'').' onchange="changeChart(\''.$spid.'\', 8, \'open_down\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // max
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_max'].': ';
+ echo '<input type="text" id="chart_max_'.$spid.'_loop_'.self::$current_loop.'" name="chart_max" value="'.$settings['max'].'" onBlur="changeChart(\''.$spid.'\', 8, \'max\', \''.self::$current_loop.'\');" onkeypress="checkNumber(this, 6, 0);" onkeyup="checkNumber(this, 6, 0);" />';
+
+ echo '</div>';
+
+ // polodprt interval navgor
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_open_up'].': ';
+ echo '<input type="checkbox" id="chart_open_up_'.$spid.'_loop_'.self::$current_loop.'" name="chart_open_up" '.($settings['open_up']=='1'?' checked="checked"':'').' '.($settings['max']==''?' disabled="disabled"':'').' onchange="changeChart(\''.$spid.'\', 8, \'open_up\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ echo '</fieldset>';*/
+ }
+
+ // Nastavitve za datum grafe (tip 8)
+ static function displayAdvancedDateSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 8, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 8, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za multigrid grafe (tip 6)
+ static function displayMultigridSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 6, \'type\', \''.self::$current_loop.'\');">';
+
+ // Pri nominalnih ne prikazujemo povprecij
+ if($spremenljivka['skala'] != 1 && $spremenljivka['cnt_all'] != 1){
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_avg_hor'].'</option>';
+ echo ' <option value="5" '.($settings['type']=='5'?' selected="selected"':'').'>'.$lang['srv_chart_avg_radar'].'</option>';
+ echo ' <option value="6" '.($settings['type']=='6'?' selected="selected"':'').'>'.$lang['srv_chart_avg_line'].'</option>';
+ }
+ // Pri nominalnih pokazemo posebej radar
+ if($spremenljivka['skala'] == 1){
+ echo ' <option value="7" '.($settings['type']=='7'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+ }
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_structure_ver'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_structure_hor'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // Obrnjeni gridi in variable
+ if(($settings['type'] > 0 && $settings['type'] < 5) || $settings['type'] == 7){
+ echo '<div class="chart_setting">';
+ if($settings['rotate']=='1'){
+ echo $lang['srv_chart_rotate_grids'].' ';
+ //echo '<input type="checkbox" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" '.($settings['rotate']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');">';
+ echo '<span onclick="changeChart(\''.$spid.'\', 6, \'rotate\', \''.self::$current_loop.'\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" value="0">';
+ echo ' '.$lang['srv_chart_rotate_vars'].' ';
+ }
+ else{
+ echo $lang['srv_chart_rotate_vars'].' ';
+ //echo '<input type="checkbox" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" '.($settings['rotate']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');">';
+ echo '<span onclick="changeChart(\''.$spid.'\', 6, \'rotate\', \''.self::$current_loop.'\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" value="1">';
+ echo ' '.$lang['srv_chart_rotate_grids'];
+ }
+ echo '</div>';
+ }
+
+ // sortiranje - pri povprecjih sortiramo po velikosti (brez, narascajoce, padajoce)
+ if($settings['type'] == 0 || $settings['type'] == 5 || $settings['type'] == 6){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 6, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+ // sortiranje - pri navadnih grafih za gride (ne povprecja) sortiramo po povprecju, 1. kategoriji ali kategorijah
+ else{
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 6, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_category'].'</option>';
+ if($settings['rotate']=='0')
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_avg'].'</option>';
+ echo ' <option value="3" '.($settings['sort']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_sort_first'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // tip izpisa vrednosti
+ if(($settings['type'] > 0 && $settings['type'] < 5) || $settings['type'] == 7){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 6, \'value_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Tip radarja
+ if($settings['type'] == 5 || $settings['type'] == 7){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="chart_radar_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_type" onchange="changeChart(\''.$spid.'\', 6, \'radar_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == 5 || $settings['type'] == 7){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="chart_radar_scale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_scale" onchange="changeChart(\''.$spid.'\', 6, \'radar_scale\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // prikaz desne skale pri sem. diferencialu (ver. linijski graf ali hor. strukturni stolpci)
+ if($spremenljivka['enota'] == 1 && ($settings['type'] == 2 || $settings['type'] == 6)){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_right_scale'].': ';
+ echo '<input type="checkbox" id="chart_scale_limit_'.$spid.'_loop_'.self::$current_loop.'" name="chart_scale_limit" '.($settings['scale_limit']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 6, \'scale_limit\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz legende - opcija samo pri povprecjih (drugje je vedno vklopljena)
+ if($settings['type'] == 0 || $settings['type'] == 5 || $settings['type'] == 6){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_analiza_legenda'].': ';
+ echo '<input type="checkbox" id="chart_show_legend_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_legend" '.($settings['show_legend']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 6, \'show_legend\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 0 || $settings['type'] == 1 || $settings['type'] == 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 6, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za multigrid grafe (tip 6)
+ static function displayAdvancedMultigridSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 6, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 2 || $settings['type'] == 4){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 6, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // Izpusti variable brez odgovora
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_hideEmtyVar'].': ';
+ echo '<input type="checkbox" id="chart_hideEmptyVar_'.$spid.'_loop_'.self::$current_loop.'" name="chart_hideEmptyVar" '.($settings['hideEmptyVar']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 6, \'hideEmptyVar\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // prikaz label majhnih vrednosti zraven stolpcov
+ if($settings['barLabel'] == 1 && $settings['type'] == 0){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabelSmall'].': ';
+ echo '<input type="checkbox" id="chart_barLabelSmall_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabelSmall" '.($settings['barLabelSmall']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 6, \'barLabelSmall\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // zacni skalo z 0 (samo pri povprecju)
+ if($settings['type'] == 0 || $settings['type'] == 5 || $settings['type'] == 6){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_noFixedScale'].': ';
+ echo '<input type="checkbox" id="chart_noFixedScale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_noFixedScale" '.($settings['noFixedScale']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 6, \'noFixedScale\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // Preklop med ordinalno in nominalno spremenljivko
+ echo '<div class="chart_setting">';
+
+ $lestvica = SurveyAnalysis::getSpremenljivkaLegenda($spremenljivka,'skalaAsValue');
+
+ echo $lang['srv_skala'].': ';
+ // Vprasajcek za pomoc
+ echo Help :: display('srv_skala_edit');
+
+ echo '<span class="spaceLeft"></span>';
+ echo '<a onclick="chartAdvancedSettingsSkala(\''.$spid.'\', \'0\', \''.self::$current_loop.'\'); return false;" href="#" title="'.$lang['srv_skala_long_0'].'"><span '.($lestvica == 0 ? ' class="strong"' : '').'>'.$lang['srv_skala_short_0'].'</span></a>';
+ echo '<span class="blue"> / </span>';
+ echo '<a onclick="chartAdvancedSettingsSkala(\''.$spid.'\', \'1\', \''.self::$current_loop.'\'); return false;" href="#" title="'.$lang['srv_skala_long_1'].'"><span '.($lestvica == 1 ? ' class="strong"' : '').'>'.$lang['srv_skala_short_1'].'</span></a>';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za dvojne multigrid grafe (tip 6, enota 3)
+ static function displayDoubleMultigridSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 62, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_line_hor'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_line_ver'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+
+
+ echo '</select>';
+ echo '</div>';
+
+ // Tip radarja
+ if($settings['type'] == '4'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="chart_radar_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_type" onchange="changeChart(\''.$spid.'\', 62, \'radar_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == '4'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="chart_radar_scale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_scale" onchange="changeChart(\''.$spid.'\', 62, \'radar_scale\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 0 || $settings['type'] == 1){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 62, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za dvojne multigrid grafe (tip 6, enota 3)
+ static function displayAdvancedDoubleMultigridSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 62, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 0){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 62, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // zacni skalo z 0
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_noFixedScale'].': ';
+ echo '<input type="checkbox" id="chart_noFixedScale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_noFixedScale" '.($settings['noFixedScale']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 62, \'noFixedScale\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za multicheckbox grafe (tip 16)
+ static function displayMulticheckboxSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // omejitev skale
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_base'].': <select id="chart_base_'.$spid.'_loop_'.self::$current_loop.'" name="chart_base" onchange="changeChart(\''.$spid.'\', 16, \'base\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['base']=='0'?' selected="selected"':'').'>'.$lang['srv_analiza_opisne_units'].'</option>';
+ echo ' <option value="1" '.($settings['base']=='1'?' selected="selected"':'').'>'.$lang['srv_analiza_opisne_arguments'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 16, \'type\', \''.self::$current_loop.'\');">';
+
+ if($settings['base'] == '1'){
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_structure_ver'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_structure_hor'].'</option>';
+ }
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ if($settings['base'] == '0'){
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+ }
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 16, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_category'].'</option>';
+ echo ' <option value="3" '.($settings['sort']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_sort_first'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+
+ // Obrnjeni gridi in variable
+ echo '<div class="chart_setting">';
+
+ if($settings['rotate']=='1'){
+ echo $lang['srv_chart_rotate_grids'].' ';
+ //echo '<input type="checkbox" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" '.($settings['rotate']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');">';
+ echo '<span onclick="changeChart(\''.$spid.'\', 16, \'rotate\', \''.self::$current_loop.'\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" value="0">';
+ echo ' '.$lang['srv_chart_rotate_vars'].' ';
+ }
+ else{
+ echo $lang['srv_chart_rotate_vars'].' ';
+ //echo '<input type="checkbox" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" '.($settings['rotate']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');">';
+ echo '<span onclick="changeChart(\''.$spid.'\', 16, \'rotate\', \''.self::$current_loop.'\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" value="1">';
+ echo ' '.$lang['srv_chart_rotate_grids'];
+ }
+ echo '</div>';
+
+ // Tip radarja
+ if($settings['type'] == '4'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="chart_radar_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_type" onchange="changeChart(\''.$spid.'\', 16, \'radar_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == '4'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="chart_radar_scale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_scale" onchange="changeChart(\''.$spid.'\', 16, \'radar_scale\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // tip izpisa vrednosti
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 16, \'value_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+ echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ if($settings['base'] == '0')
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 2 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 16, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za multicheckbox grafe (tip 16)
+ static function displayAdvancedMulticheckboxSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 16, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 16, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // Izpusti variable brez odgovora
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_hideEmtyVar'].': ';
+ echo '<input type="checkbox" id="chart_hideEmptyVar_'.$spid.'_loop_'.self::$current_loop.'" name="chart_hideEmptyVar" '.($settings['hideEmptyVar']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 16, \'hideEmptyVar\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za vsoto (tip 18)
+ static function displayVsotaSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 18, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_pie'].'</option>';
+ echo ' <option value="5" '.($settings['type']=='5'?' selected="selected"':'').'>'.$lang['srv_chart_3Dpie'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_line'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // Tip radarja
+ if($settings['type'] == '4'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="chart_radar_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_type" onchange="changeChart(\''.$spid.'\', 18, \'radar_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == '4'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="chart_radar_scale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_scale" onchange="changeChart(\''.$spid.'\', 18, \'radar_scale\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // sortiranje
+ if($settings['type'] != '4'){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 18, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // prikaz legende
+ if($settings['type'] == 0 || $settings['type'] == 5){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_analiza_legenda'].': ';
+ echo '<input type="checkbox" id="chart_show_legend_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_legend" '.($settings['show_legend']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 18, \'show_legend\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // prikaz label v stolpcih
+ if($settings['type'] == 2 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 18, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za vsoto (tip 18)
+ static function displayAdvancedVsotaSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 18, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 18, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // prikaz label majhnih vrednosti zraven stolpcov
+ if($settings['barLabel'] == 1 && ($settings['type'] == 2 || $settings['type'] == 3)){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabelSmall'].': ';
+ echo '<input type="checkbox" id="chart_barLabelSmall_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabelSmall" '.($settings['barLabelSmall']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 18, \'barLabelSmall\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // 3D strukturni krog
+ /*if($settings['type'] == 0){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_3d_pie'].': ';
+ echo '<input type="checkbox" id="chart_3d_pie_'.$spid.'_loop_'.self::$current_loop.'" name="chart_3d_pie" '.($settings['3d_pie']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 18, \'3d_pie\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }*/
+ }
+
+ // Nastavitve za ranking grafe (tip 17)
+ static function displayRankingSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 17, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_avg'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_structure_hor'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_structure_ver'].'</option>';
+ //echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_structure'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 17, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_desc'].'</option>';
+ echo ' <option value="2" '.($settings['sort']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_sort_asc'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+
+ // tip izpisa vrednosti
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="chart_value_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_value_type" onchange="changeChart(\''.$spid.'\', 17, \'value_type\', \''.self::$current_loop.'\');" '.($settings['type'] == 0 ? 'disabled="disabled"' : '').'>';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+ //echo ' <option value="2" '.($settings['value_type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_valid'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // prikaz label v stolpcih
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="chart_barLabel_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 17, \'barLabel\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za ranking grafe (tip 17)
+ static function displayAdvancedRankingSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 17, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 0 || $settings['type'] == 1){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 17, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+ // prikaz label majhnih vrednosti zraven stolpcov
+ if($settings['barLabel'] == 1 && $settings['type'] == 0){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabelSmall'].': ';
+ echo '<input type="checkbox" id="chart_barLabelSmall_'.$spid.'_loop_'.self::$current_loop.'" name="chart_barLabelSmall" '.($settings['barLabelSmall']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 17, \'barLabelSmall\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // zacni skalo z 0 (samo pri povprecju)
+ if($settings['type'] == 0){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_noFixedScale'].': ';
+ echo '<input type="checkbox" id="chart_noFixedScale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_noFixedScale" '.($settings['noFixedScale']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 17, \'noFixedScale\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za multinumber (tip 20)
+ static function displayMultinumberSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 20, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_line'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="chart_sort_'.$spid.'_loop_'.self::$current_loop.'" name="chart_sort" onchange="changeChart(\''.$spid.'\', 20, \'sort\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_category'].'</option>';
+ echo ' <option value="3" '.($settings['sort']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_sort_first'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+
+ // Obrnjeni gridi in variable
+ echo '<div class="chart_setting">';
+
+ if($settings['rotate']=='1'){
+ echo $lang['srv_chart_rotate_grids'].' ';
+ //echo '<input type="checkbox" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" '.($settings['rotate']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');">';
+ echo '<span onclick="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" value="0">';
+ echo ' '.$lang['srv_chart_rotate_vars'].' ';
+ }
+ else{
+ echo $lang['srv_chart_rotate_vars'].' ';
+ //echo '<input type="checkbox" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" '.($settings['rotate']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');">';
+ echo '<span onclick="changeChart(\''.$spid.'\', 20, \'rotate\', \''.self::$current_loop.'\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="chart_rotate_'.$spid.'_loop_'.self::$current_loop.'" name="chart_rotate" value="1">';
+ echo ' '.$lang['srv_chart_rotate_grids'];
+ }
+ echo '</div>';
+
+ // Tip radarja
+ if($settings['type'] == '0'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="chart_radar_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_type" onchange="changeChart(\''.$spid.'\', 20, \'radar_type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == '0'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="chart_radar_scale_'.$spid.'_loop_'.self::$current_loop.'" name="chart_radar_scale" onchange="changeChart(\''.$spid.'\', 20, \'radar_scale\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za multinumber (tip 20)
+ static function displayAdvancedMultinumberSettings($spid, $settings){
+ global $site_path;
+ global $lang;
+
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1' || ($settings['show_numerus']=='-1' && SurveyDataSettingProfiles :: getSetting('chartNumerusText') == 1)) ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="chart_show_numerus_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_numerus" '.$checked.' onchange="changeChart(\''.$spid.'\', 20, \'show_numerus\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ // sirina label
+ if($settings['type'] == 2){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="chart_labelWidth_'.$spid.'_loop_'.self::$current_loop.'" name="chart_labelWidth" onchange="changeChart(\''.$spid.'\', 20, \'labelWidth\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="75" '.($settings['labelWidth']=='75'?' selected="selected"':'').'>75%</option>';
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za vse tabele
+ static function displayTableSettings($spid){
+ global $site_path;
+ global $lang;
+
+ // Tip tabele
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_table_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 21, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.(self::$settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_table_type_0'].'</option>';
+ echo ' <option value="1" '.(self::$settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_table_type_1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ //Poravnava texta
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_table_align'].': ';
+ echo '<input type="checkbox" id="chart_show_legend_'.$spid.'_loop_'.self::$current_loop.'" name="chart_show_legend" '.(self::$settings['show_legend']=='1'?' checked="checked"':'').' onchange="changeChart(\''.$spid.'\', 21, \'show_legend\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za vse multitext tabele
+ static function displayMultitextSettings($spid){
+ global $site_path;
+ global $lang;
+
+ // Tip tabele
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_table_type'].':<br /> <select style="width:140px;" id="chart_type_'.$spid.'_loop_'.self::$current_loop.'" name="chart_type" onchange="changeChart(\''.$spid.'\', 19, \'type\', \''.self::$current_loop.'\');">';
+
+ echo ' <option value="0" '.(self::$settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_table_type_0'].'</option>';
+ echo ' <option value="1" '.(self::$settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_table_type_1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Nastavitve za other tabele
+ static function displayOtherSettings($spid){
+ global $site_path;
+ global $lang;
+
+ echo '<div class="chart_settings_inner">';
+ echo '<span class="title">'.$lang['srv_chart_settings'].'</span>';
+
+ //Poravnava texta
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_table_align'].': ';
+ echo '<input type="checkbox" id="chart_other_otherType_'.$spid.'_loop_'.self::$current_loop.'" name="chart_other_otherType" '.(self::$settings['otherType']=='1'?' checked="checked"':'').' onchange="changeOther(\''.$spid.'\', \'otherType\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ //Prikaz frekvenc
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_table_freq'].': ';
+ echo '<input type="checkbox" id="chart_other_otherFreq_'.$spid.'_loop_'.self::$current_loop.'" name="chart_other_otherFreq" '.(self::$settings['otherFreq']=='1'?' checked="checked"':'').' onchange="changeOther(\''.$spid.'\', \'otherFreq\', \''.self::$current_loop.'\');">';
+
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+
+ // Napredne nastavitve za posamezen graf (popup)
+ static function displayAdvancedSettings($spid){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ echo '<h2>'.$spremenljivka['variable'].' - '.$spremenljivka['naslov'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="chartCloseAdvancedSettings(); return false;">✕</a></div>';
+
+ echo '<form method="post" name="chart_advanced_settings" onsubmit="chartSaveAdvancedSettings(\''.$spid.'\', \''.self::$current_loop.'\'); return false;">';
+
+ echo '<input type="hidden" name="anketa" value="'.self::$anketa.'" />';
+ echo '<input type="hidden" name="spid" value="'.$spid.'" />';
+ echo '<input type="hidden" name="loop" value="'.self::$current_loop.'" />';
+ echo '<input type="hidden" name="spr_type" value="'.$spremenljivka['tip'].'" />';
+
+ // urejanje label
+ echo '<div id="chartSettingsArea1" class="chartSettingsArea">';
+ self::displayAdvancedSettingsLabels($spid);
+ echo '</div>';
+
+ // urejanje barv
+ echo '<div id="chartSettingsArea2" class="chartSettingsArea" style="visibility: hidden;">';
+ self::displayAdvancedSettingsColors($spid);
+ echo '</div>';
+
+ // urejanje mej pri numericih
+ if(($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)) || $spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 8 || $spremenljivka['tip'] == 22){
+ echo '<div id="chartSettingsArea4" class="chartSettingsArea" style="visibility: hidden;">';
+ self::displayAdvancedSettingsLimits($spid, self::$settings['limits']['advanced_settings']);
+ echo '</div>';
+ }
+
+ /* REKODIRANJE */
+ echo '<div id="chartSettingsArea3" class="chartSettingsArea" style="visibility: hidden;">';
+ $spr_id=explode('_',$spid);
+
+ $vmv = new RecodeValues(self::$anketa,$spr_id[0]);
+ $vmv->DisplayMissingValuesForQuestion(false);
+ echo '</div>';
+
+ echo '</form>';
+
+
+ /* ZAVIHKI NA DESNI */
+ echo '<div id="chartTabs" class="chartSettingsTabs">';
+
+ echo '<ul>';
+ echo '<li id="chartTab1" class="chartTab active" onClick="chartTabAdvancedSettings(\'1\');">';
+ echo $lang['srv_chart_advanced_labels'];
+ echo '</li>';
+ echo '<li id="chartTab2" class="chartTab" onClick="chartTabAdvancedSettings(\'2\');">';
+ echo $lang['srv_chart_advanced_colors'];
+ echo '</li>';
+ echo '<li id="chartTab3" class="chartTab" onClick="chartTabAdvancedSettings(\'3\');">';
+ echo $lang['srv_chart_advanced_recoding'];
+ echo '</li>';
+ // Tab za meje numericov
+ if(($spremenljivka['tip'] == 3 && self::checkDropdownNumeric($spid)) || $spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 8 || $spremenljivka['tip'] == 22){
+ echo '<li id="chartTab4" class="chartTab" onClick="chartTabAdvancedSettings(\'4\');">';
+ echo $lang['srv_chart_advanced_limits'];
+ echo '</li>';
+ }
+ echo '</ul>';
+
+ echo '</div>';
+
+
+ /* GUMBI NA DNU */
+ echo '<div id="chartSettingsButtons" class="buttons_holder">';
+
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" onclick="chartCloseAdvancedSettings(); return false;"><span>'.$lang['srv_zapri'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" onclick="chartSaveAdvancedSettings(\''.$spid.'\', \''.self::$current_loop.'\'); return false;">'.$lang['srv_potrdi'].'</a>';
+ echo '</span>';
+
+ echo '</div>';
+ }
+
+ // Urejanje barv posameznega grafa
+ static function displayAdvancedSettingsColors($spid){
+ global $site_path;
+ global $lang;
+
+ echo '<script type="text/javascript" charset="utf-8">
+ $(document).ready(function() {
+ var f = $.farbtastic(\'#picker\');
+ var p = $(\'#picker\').css(\'opacity\', 0.25);
+ var selected;
+ $(\'.colorwell\')
+ .each(function () { f.linkTo(this); $(this).css(\'opacity\', 0.75); })
+ .focus(function() {
+ if (selected) {
+ $(selected).css(\'opacity\', 0.75).removeClass(\'colorwell-selected\');
+ }
+ f.linkTo(this);
+ p.css(\'opacity\', 1);
+ $(selected = this).css(\'opacity\', 1).addClass(\'colorwell-selected\');
+ });
+ });
+ </script>';
+
+
+ echo ' <div id="picker" style="float: right;"></div>';
+
+ $default_colors = self::getDefaultColors(self::$skin);
+
+ for($i=0; $i<7; $i++){
+ $name = 'color'.($i+1);
+ $value = (self::$settings['colors'][$i] != '') ? self::$settings['colors'][$i] : $default_colors[$i];
+
+ echo ' <div class="form-item"><label for="'.$name.'">'.$lang['srv_color'].' '.($i+1).': </label><input type="text" id="'.$name.'" name="'.$name.'" class="colorwell" value="'.$value.'" /></div>';
+ }
+
+ // reset na default barvo
+ echo '<br /><span class="as_link clr" onClick="chartAdvancedSettingsSetColor(\''.(is_numeric(self::$skin) ? implode("_",$default_colors) : self::$skin).'\')">'.$lang['srv_chart_advanced_default_color'].'</span>';
+
+ // nastavitev ene od palet
+ echo '<br /><span class="clr">'.$lang['srv_chart_advanced_skin'].': ';
+ echo '<select name="chart_advanced_color" id="chart_advanced_color" onChange="chartAdvancedSettingsSetColor(this.value)">';
+ echo ' <option' . (self::$skin == '1ka' ? ' selected="selected"' : '') . ' value="1ka">'.$lang['srv_chart_skin_1ka'].'</option>';
+ echo ' <option' . (self::$skin == 'lively' ? ' selected="selected"' : '') . ' value="lively">'.$lang['srv_chart_skin_0'].'</option>';
+ echo ' <option' . (self::$skin == 'mild' ? ' selected="selected"' : '') . ' value="mild">'.$lang['srv_chart_skin_1'].'</option>';
+ echo ' <option' . (self::$skin == 'office' ? ' selected="selected"' : '') . ' value="office">'.$lang['srv_chart_skin_6'].'</option>';
+ echo ' <option' . (self::$skin == 'pastel' ? ' selected="selected"' : '') . ' value="pastel">'.$lang['srv_chart_skin_7'].'</option>';
+ echo ' <option' . (self::$skin == 'green' ? ' selected="selected"' : '') . ' value="green">'.$lang['srv_chart_skin_2'].'</option>';
+ echo ' <option' . (self::$skin == 'blue' ? ' selected="selected"' : '') . ' value="blue">'.$lang['srv_chart_skin_3'].'</option>';
+ echo ' <option' . (self::$skin == 'red' ? ' selected="selected"' : '') . ' value="red">'.$lang['srv_chart_skin_4'].'</option>';
+ echo ' <option' . (self::$skin == 'multi' ? ' selected="selected"' : '') . ' value="multi">'.$lang['srv_chart_skin_5'].'</option>';
+
+ $customSkins = self::getCustomSkins();
+ foreach($customSkins as $customSkin){
+ echo ' <option' . (self::$skin == $customSkin['id'] ? ' selected="selected"' : '') . ' value="'.$customSkin['colors'].'">'.$customSkin['name'].'</option>';
+ }
+
+
+ echo '</select></span>';
+
+ }
+
+ // Urejanje label posameznega grafa
+ static function displayAdvancedSettingsLabels($spid){
+ global $site_path;
+ global $lang;
+
+ $row = Cache::srv_spremenljivka($spid);
+ $disabled = ($row['edit_graf'] == 0) ? ' disabled="disabled"' : '';
+
+
+ echo '<div><p>';
+ echo $lang['srv_chart_advanced_useLabels'].':';
+ echo '<label for="edit_graf_0"><input type="radio" value="0" name="edit_graf" id="edit_graf_0" '.(($row['edit_graf'] == 0) ? ' checked="checked" ' : '').' onClick="edit_labels(\'0\');" />';
+ echo $lang['no'].'</label>';
+ echo ' <label for="edit_graf_1"><input type="radio" value="1" name="edit_graf" id="edit_graf_1" '.(($row['edit_graf'] == 1) ? ' checked="checked" ' : '').' onClick="edit_labels(\'1\');" />';
+ echo $lang['yes'].'</label>';
+ echo '</p></div>';
+
+
+ echo '<div class="chart_editing">';
+
+ // Urejanje naslova spremenljivke
+ $text = $row['naslov_graf'] == '<p></p>' ? $row['naslov'] : $row['naslov_graf'];
+ if (strtolower(substr($text, 0, 3)) == '<p>' && strtolower(substr($text, -4)) == '</p>' && strrpos($text, '<p>') == 0) {
+ $text = substr($text, 3);
+ $text = substr($text, 0, -4);
+ }
+ echo '<p>';
+ echo '<textarea style="width:99%; height:50px;" name="naslov_graf" id="naslov_graf" class="chart_label" '.$disabled.'>'.$text.'</textarea>';
+ echo '</p>';
+
+
+ // Urejanje label za gride
+ if($row['tip'] == 6 || $row['tip'] == 16 || $row['tip'] == 19 || $row['tip'] == 20){
+
+ echo '<div class="grid_settings">';
+ echo '<input type="hidden" name="edit_grid_graf" value="1" />';
+
+ echo '<table id="grids" style="width:100%">';
+
+ echo '<tr>';
+ for ($i=1; $i<=$row['grids']; $i++) {
+ echo '<td>'.$i.'</td>';
+ }
+
+ //dodatne vrednosti (ne vem, zavrnil...)
+ if (count($already_set_mv) > 0 ) {
+ echo '<td></td>';
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ if (isset($already_set_mv[$mv_key])) {
+ echo '<td>'.$mv_key.'</td>';
+ }
+ }
+ }
+ }
+ echo '</tr>';
+
+ echo '<tr>';
+ for ($i=1; $i<=$row['grids']; $i++) {
+ $sql1 = sisplet_query("SELECT naslov, naslov_graf FROM srv_grid WHERE id='$i' AND spr_id='$spid'");
+ $row1 = mysqli_fetch_array($sql1);
+ $text = $row1['naslov_graf'] == '' ? $row1['naslov'] : $row1['naslov_graf'];
+ echo '<td><input type="text" maxlength="30" name="grid_graf_'.$i.'" id="grid_naslov_'.$i.'_graf" class="chart_label" value="'.$text.'" '.$disabled.' /></td>';
+ }
+
+ //dodatne vrednosti (ne vem, zavrnil...)
+ if (count($already_set_mv) > 0 ) {
+ echo '<td></td>';
+ if (count($missing_values) > 0) {
+ foreach ($missing_values AS $mv_key => $mv_text) {
+ if (isset($already_set_mv[$mv_key])) {
+ echo '<td><input type="text" maxlength="30" name="grid_'.$mv_key.'_graf" class="chart_label" value="'.$already_set_mv[$mv_key].'" '.$disabled.' /></td>';
+ }
+ }
+ }
+ }
+ echo '</tr>';
+
+ echo '</table>';
+ echo '</div>';
+ }
+
+
+ // Urejanje naslovov variabel
+ $sql1 = sisplet_query("SELECT id, variable, naslov, REPLACE(REPLACE(REPLACE(naslov_graf,'\n',' '),'\r',' '),'|',' ') as naslov_graf, other FROM srv_vrednost WHERE spr_id = '$spid' ORDER BY vrstni_red ASC");
+ if (!$sql1) echo mysqli_error($GLOBALS['connect_db']);
+
+ echo '<input type="hidden" name="edit_vrednost_graf" value="1" />';
+
+ echo '<div id="vrednosti_holder"><ul class="vrednost_sort">';
+ while ($row1 = mysqli_fetch_array($sql1)) {
+
+ $text = $row1['naslov_graf'] == '' ? $row1['naslov'] : $row1['naslov_graf'];
+
+ echo '<li id="vrednost_'.$vrednost.'" '.($row1['other'] == 1 ? 'class="li_other"' : '').'>';
+
+ echo '<textarea maxlength="30" name="vrednost_graf_'.$row1['id'].'" id="'.$row1['variable'].'_graf" class="vrednost_textarea chart_label" style="width:60%; height:15px;" '.$disabled.'>'.$text.'</textarea> ';
+ echo '['.$row1['variable'].']</span>';
+ if ($row1['other'] == 1) echo ' <input type="text" disabled style="width:40px" />';
+
+ echo '</li>';
+ }
+ echo '</ul></div>';
+
+ echo '<span class="red" style="font-size:11px;">'.$lang['srv_chart_advanced_labelsWarning'].'</span>';
+
+ echo '</div>';
+ }
+
+ // Urejanje mej za numericne tipe (radio dropdown number, number, date)
+ static function displayAdvancedSettingsLimits($spid, $mode=0){
+ global $site_path;
+ global $lang;
+
+ $spremenljivka = Cache::srv_spremenljivka($spid);
+ $limits = self::$settings['limits'];
+
+
+ // preklop med navadnimi mejami (zgornja/spodnja) in naprednimi (custom za vsak interval)
+ echo '<div class="chart_setting">';
+ echo '<span class="bold">'.$lang['srv_chart_num_limit_basic'].'<input type="radio" name="chart_number_limits_switch" value="0" '.($mode=='0'?' checked="checked"':'').' onClick="chartAdvancedSettingsLimitSwitch(\'0\');" /></span>';
+ echo '<span class="spaceLeft bold">'.$lang['srv_chart_num_limit_advanced'].'<input type="radio" name="chart_number_limits_switch" value="1" '.($mode=='1'?' checked="checked"':'').' onClick="chartAdvancedSettingsLimitSwitch(\'1\');" /></span>';
+ echo '</div>';
+
+
+ // OSNOVNE NASTAVITVE MEJ
+ echo '<div id="chart_number_limits_basic" '.($mode=='1'?' style="display:none;"':'').'>';
+
+ // stevilo intervalov
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_interval'].': <select id="chart_interval_'.$spid.'_loop_'.self::$current_loop.'" name="chart_interval">';
+
+ for($i=3; $i<=10; $i++){
+ echo ' <option value="'.$i.'" '.(self::$settings['interval']==$i ?' selected="selected"':'').'>'.$i.'</option>';
+ }
+ echo ' <option value="20" '.(self::$settings['interval']=='20'?' selected="selected"':'').'>20</option>';
+ echo ' <option value="-1" '.(self::$settings['interval']=='-1'?' selected="selected"':'').'>Vsi</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // Naslov "zgornja in spodnja meja"
+ echo '<div class="chart_setting">';
+ echo '<span class="bold">'.$lang['srv_chart_num_limit'].':</span>';
+ echo '</div>';
+
+ // min in polodprtost navzdol
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_min'].': ';
+ echo '<input type="text" id="chart_min_'.$spid.'_loop_'.self::$current_loop.'" name="chart_min" value="'.self::$settings['min'].'" onkeyup="checkNumber(this, 6, 2);" onkeypress="checkNumber(this, 6, 2);" />';
+
+ echo '<span style="padding-left:20px;">'.$lang['srv_chart_open_down'].': </span>';
+ echo '<input type="checkbox" id="chart_basic_open_down_'.$spid.'_loop_'.self::$current_loop.'" name="chart_basic_open_down" value="1" '.(self::$settings['open_down']=='1'?' checked="checked"':'').' />';
+
+ echo '</div>';
+
+ // max in polodprtost navzgor
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_max'].': ';
+ echo '<input type="text" id="chart_max_'.$spid.'_loop_'.self::$current_loop.'" name="chart_max" value="'.self::$settings['max'].'" onkeyup="checkNumber(this, 6, 2);" onkeypress="checkNumber(this, 6, 2);" />';
+
+ echo '<span style="padding-left:20px;">'.$lang['srv_chart_open_up'].': </span>';
+ echo '<input type="checkbox" id="chart_basic_open_up_'.$spid.'_loop_'.self::$current_loop.'" name="chart_basic_open_up" value="1" '.(self::$settings['open_up']=='1'?' checked="checked"':'').' />';
+
+ echo '</div>';
+ echo '</div>';
+
+
+ // NAPREDNE NASTAVITVE MEJ
+ echo '<div id="chart_number_limits_advanced" '.($mode=='0'?' style="display:none;"':'').'>';
+
+ // stevilo intervalov
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_interval'].': <select id="chart_interval_'.$spid.'_loop_'.self::$current_loop.'" name="chart_interval" onChange="chartAdvancedSettingsLimitInterval(this.value, \''.$spid.'\', \''.self::$current_loop.'\');">';
+
+ for($i=3; $i<=10; $i++){
+ echo ' <option value="'.$i.'" '.(self::$settings['interval']==$i ?' selected="selected"':'').'>'.$i.'</option>';
+ }
+ echo ' <option value="20" '.(self::$settings['interval']=='20'?' selected="selected"':'').'>20</option>';
+ echo ' <option value="-1" '.(self::$settings['interval']=='-1'?' selected="selected"':'').'>Vsi</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // Polodprtost navzdol
+ echo '<span style="padding-left:20px;">'.$lang['srv_chart_open_down'].': </span>';
+ echo '<input type="checkbox" id="chart_advanced_open_down_'.$spid.'_loop_'.self::$current_loop.'" name="chart_advanced_open_down" value="1" '.(self::$settings['open_down']=='1'?' checked="checked"':'').' />';
+
+ echo '<ul>';
+ for($i=0; $i<self::$settings['interval']; $i++){
+ echo '<li>';
+
+ echo '<span class="bold">'.$lang['interval'].' '. ($i+1) .': </span>';
+ echo '<span class="spaceLeft">'.$lang['srv_chart_num_limit_from'].' <input type="text" id="interval_'.$i.'_min_'.$spid.'_loop_'.self::$current_loop.'" name="interval_'.$i.'_min" value="'.$limits['interval_'.$i]['min'].'" class="advanced_interval" style="width:40px;" onBlur="chartAdvancedSettingsLimitLabel(\''.$i.'\', \''.$spid.'\', \''.self::$current_loop.'\'); chartAdvancedSettingsLimitCheck(\''.$i.'\', \''.$spid.'\', \''.self::$current_loop.'\');" onkeyup="checkNumber(this, 6, 2);" onkeypress="checkNumber(this, 6, 2);" /></span>';
+ echo '<span class="spaceLeft">'.$lang['srv_chart_num_limit_to'].' <input type="text" id="interval_'.$i.'_max_'.$spid.'_loop_'.self::$current_loop.'" name="interval_'.$i.'_max" value="'.$limits['interval_'.$i]['max'].'" class="advanced_interval" style="width:40px;" onBlur="chartAdvancedSettingsLimitLabel(\''.$i.'\', \''.$spid.'\', \''.self::$current_loop.'\'); chartAdvancedSettingsLimitCheck(\''.$i.'\', \''.$spid.'\', \''.self::$current_loop.'\');" onkeyup="checkNumber(this, 6, 2);" onkeypress="checkNumber(this, 6, 2);" /></span>';
+
+ // labela intervala
+ $label = ($limits['interval_'.$i]['label'] == '') ? $limits['interval_'.$i]['min'].'-'.$limits['interval_'.$i]['max'] : $limits['interval_'.$i]['label'];
+ echo '<span class="spaceLeft">'.$lang['srv_chart_num_limit_label'].': <input type="text" id="interval_'.$i.'_label_'.$spid.'_loop_'.self::$current_loop.'" name="interval_'.$i.'_label" value="'.$label.'" style="width:120px;" /></span>';
+
+ // Warningi, ce niso intervali v redu nastavljeni po velikosti
+ $show = ($limits['interval_'.$i]['min'] >= $limits['interval_'.$i]['max'] && $limits['interval_'.$i]['min'] != '' && $limits['interval_'.$i]['max'] != '') ? '' : ' style="display:none;"';
+ echo '<div id="chart_advanced_warning_1_interval_'.$i.'" class="chart_advanced_warning" '.$show.'>';
+ echo $lang['srv_chart_num_limit_warning1'];
+ echo '</div>';
+
+ $show = ($limits['interval_'.$i]['min'] <= $limits['interval_'. ($i-1) ]['max'] && $limits['interval_'.$i]['min'] != '' && $limits['interval_'. ($i-1) ]['max'] != '') ? '' : ' style="display:none;"';
+ echo '<div id="chart_advanced_warning_2_interval_'.$i.'" class="chart_advanced_warning" '.$show.'>';
+ echo $lang['srv_chart_num_limit_warning2'];
+ echo '</div>';
+
+ echo '</li>';
+ }
+ echo '</ul>';
+
+ // Polodprtost navzgor
+ echo '<span style="padding-left:20px;">'.$lang['srv_chart_open_up'].': </span>';
+ echo '<input type="checkbox" id="chart_advanced_open_up_'.$spid.'_loop_'.self::$current_loop.'" name="chart_advanced_open_up" value="1" '.(self::$settings['open_up']=='1'?' checked="checked"':'').' />';
+
+ echo '</div>';
+ }
+
+ // Izpis opozorila ce ni vnesenih podatkov in ne prikazujemo grafa
+ static function displayEmptyWarning($spid){
+
+ //$spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ // Naslov posameznega grafa
+ //echo '<div class="chart_title">Graf '.$spremenljivka['variable'].' nima veljavnih podatkov!</div>';
+ }
+
+ /** Izriše frekvence v vertikalni obliki
+ *
+ * @param unknown_type $spid
+ */
+ static function frequencyVertical($spid) {
+ global $lang;
+
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+ $inline_legenda = (SurveyAnalysis::$_HEADERS[$spid]['cnt_all'] == 1 || in_array($spremenljivka['tip'],array(1,8) ) ) ? false: true;
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = (self::$num_records == 0) ? 10 : self::$num_records;
+ //$num_show_records = SurveyAnalysis::getNumRecords();
+
+ // ce imamo prazno in ne prikazujemo praznih tabel
+ $hideEmpty = SurveyDataSettingProfiles :: getSetting('hideEmpty');
+ if($hideEmpty == 1){
+
+ $emptyData = true;
+
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_variables_count = count($grid['variables']);
+
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ if(SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0)
+ $emptyData = false;
+ }
+ }
+
+ if($emptyData){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+ }
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'"></div>';
+
+ echo '<div id="freq_'.$spid.'_loop_'.self::$current_loop.'" class="freq_chart_table">';
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title.'</div>';
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_br anl_bb" style="font-size: '.(self::$fontSize+3).'px !important; padding:0px; margin-top:5px !important; border-collapse: collapse; width: 800px;">';
+
+ if(self::$settings['type']==1){
+ echo '<tr>';
+ #odgovori
+ echo '<td class="anl_bl anl_br anl_bb anl_ac">'.$lang['srv_analiza_frekvence_titleAnswers'] . '</td>';
+ echo '<td class="anl_br anl_bb anl_ac anl_w70">'. $lang['srv_analiza_frekvence_titleFrekvenca'] .'</td>';
+
+ echo '</tr>';
+ // konec naslovne vrstice
+ }
+
+ $_answersOther = array();
+
+ # dodamo opcijo kje izrisujemo legendo
+ $options=array('inline_legenda' => $inline_legenda, 'isTextAnswer' => false, 'isOtherAnswer' => false, 'num_show_records' => $num_show_records);
+
+ # izpišemo vlejavne odgovore
+ $_current_grid = null;
+ if (count($spremenljivka['grids']) > 0)
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_variables_count = count($grid['variables']);
+
+ # dodamo dodatne vrstice z albelami grida
+ if ($_variables_count > 0 )
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ if (($variable['text'] != true && $variable['other'] != true)
+ || (in_array($spremenljivka['tip'],array(4,8,21,22,25)))){
+ # dodamo ime podvariable
+ //if ($_variables_count > 1 && in_array($spremenljivka['tip'],array(2,6,7,16,17,18,19,20,21))) {
+ if ($inline_legenda) {
+ # ali rišemo dvojno črto med grupami
+ if ( $_current_grid != $gid && $_current_grid !== null && $spremenljivka['tip'] != 6) {
+ $options['doubleTop'] = true;
+ $_current_grid = $gid;
+ } else {
+ $options['doubleTop'] = false;
+ $_current_grid = $gid;
+ }
+ self::outputSubVariablaVertical($spremenljivka,$variable,$grid,$spid,$options);
+ }
+ $counter = 0;
+ $_kumulativa = 0;
+
+
+ #po potrebi posortiramo podatke
+ if (($spremenljivka['tip'] == 7 || $spremenljivka['tip'] == 22) && is_array(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'])) {
+ ksort(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']);
+ }
+ //SurveyAnalysis::$_FREQUENCYS[$_sequence]
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+
+ if ($counter < $num_show_records) {
+ if ($vAnswer['cnt'] > 0 || true) { # izpisujemo samo tiste ki nisno 0
+ if (in_array($spremenljivka['tip'],array(4,7,8,19,20,21))) { // text, number, datum, mtext, mnumber, text*
+ $options['isTextAnswer'] = true;
+ } else {
+ $options['isTextAnswer'] = false;
+ }
+ $counter = self::outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_kumulativa,$options);
+ }
+ }
+ }
+ # izpišemo sumo veljavnih
+ if(self::$settings['type'] == 1)
+ $counter = self::outputSumaValidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ if (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0 && self::$settings['type'] == 1) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputInvalidAnswerVertical($counter,$ikey,$iAnswer,$_sequence,$spid,$options);
+ }
+ }
+ # izpišemo sumo veljavnih
+ $counter = self::outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,$options);
+ }
+ #izpišemo še skupno sumo
+ if(self::$settings['type'] == 1)
+ $counter = self::outputSumaVertical($counter,$_sequence,$spid,$options);
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</table>'.NEW_LINE;
+ echo '</div>';
+
+ // Izpisemo nastavitve za tabele
+ echo '<div class="chart_settings printHide iconHide" style="margin-top: 5px;">';
+ self::displaySingleSettings($spid);
+ echo '</div>';
+
+ # izpišemo še tekstovne odgovore za polja drugo
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ echo '<div id="chart_other_text_'.$spid.'_loop_'.self::$current_loop.'" class="chart_other_text">';
+ self::outputOtherAnswers($oAnswers);
+ echo '</div>';
+
+ echo '<div class="chart_settings other_settings printHide iconHide">';
+ self::displayOtherSettings($spid);
+ echo '</div>';
+ }
+ if (self::$returnChartAsHtml == false) {
+ ob_flush(); flush();
+ }
+ }
+
+ echo '</div>';
+ }
+
+ static function outputSubVariablaVertical($spremenljivka,$variable,$grid,$spid,$_options = array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ 'doubleTop' =>false, # ali imamo novo grupa in nardimo dvojni rob
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ $css_bck = 'anl_bck_freq_2 ';
+ echo '<tr'.($options['doubleTop'] ? ' class="anl_double_bt"' : '').'>';
+
+ echo '<td class="anl_bl anl_bt anl_bb anl_br anl_al anl_str">';
+ echo $variable['naslov'];
+ echo '</td>';
+
+ if(self::$settings['type'] == 1)
+ echo '<td class="anl_bb anl_br anl_w70">&nbsp;</td>';
+
+ echo '</tr>';
+ }
+
+ static function outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,&$_kumulativa,$_options=array()) {
+ global $lang;
+ # opcije
+
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ $cssBck = ($counter % 2 == 1) ? ' anl_bck_0_0' : '';
+
+ $_valid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_kumulativa += $_valid;
+
+ echo '<tr id="'.$spid.'_'.$_sequence.'_'.$counter.'" name="valid_row_'.$_sequence.'" >';
+ //echo '<td class="anl_bl anl_ac anl_br gray">&nbsp;</td>';
+
+ if($options['isOtherAnswer'] == 1){
+ // poravnava celice
+ $cellAlign = (self::$settings['otherType'] == 0) ? ' anl_al' : ' anl_ac';
+
+ echo '<td class="anl_bl anl_br '.$cellAlign.' '.$cssBck.'">'.$vkey;
+
+ if(self::$settings['otherFreq'] == 1){
+ echo '<td class="anl_ac anl_br '.$cssBck.'">';
+ echo (int)$vAnswer['cnt'];
+ echo '</td>';
+ }
+ }
+ elseif(self::$settings['type'] == 0){
+ // poravnava celice
+ $cellAlign = (self::$settings['show_legend'] == 0) ? ' anl_al' : ' anl_ac';
+
+ echo '<td class="anl_bl anl_br '.$cellAlign.' '.$cssBck.'">'.$vkey;
+ }
+ else{
+ // poravnava celice
+ $cellAlign = (self::$settings['show_legend'] == 0) ? ' style="float: none;"' : '';
+
+ echo '<td class="anl_bl anl_br '.$cssBck.'">';
+ echo '<div class="anl_user_text_more_charts" '.$cellAlign.'>'.$vkey.'</div>';
+ echo (($options['isTextAnswer'] == false && (string)$vkey != $vAnswer['text']) ? ' ('.$vAnswer['text'] .')' : '');
+ }
+
+ if ( $counter+1 == $options['num_show_records'] && $options['num_show_records'] < count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'])) {
+ echo '<div id="valid_row_togle_more_'.$_sequence.'" class="floatRight '.(self::$publicChart != true ? ' blue pointer' : '').' anl_more" onclick="showHidenTextTable(\''.$spid.'\', \''.$options['num_show_records'].'\', \''.self::$current_loop.'\');return false;">'.$lang['srv_anl_more'].'</div>'.NEW_LINE;
+ }
+ echo '</td>';
+
+ if(self::$settings['type'] == 1){
+ echo '<td class="anl_ac anl_br '.$cssBck.'">';
+ echo (int)$vAnswer['cnt'];
+ echo '</td>';
+ }
+
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaValidAnswerVertical($counter,$_sequence,$spid,$_options=array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ $cssBck = ($counter % 2 == 1) ? ' anl_bck_0_0' : '';
+
+ $_brez_MV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 0 ) ? TRUE : FALSE;
+ $_hide_minus = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2 ) ? TRUE : FALSE;
+ $value =((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 0 ) ? 0 : 1;
+
+ $_sufix = (SurveyAnalysis::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(SurveyAnalysis::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.SurveyAnalysis::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="anl_click_missing_tr_'.$_sequence.$_sufix.'" class="'.($_brez_MV ? 'anl_bb' : 'anl_dash_red_bb').'">';
+
+ echo '<td class="anl_bl anl_br anl_al anl_ita red '.$cssBck.'" >'.$lang['srv_anl_suma1'].'</td>';
+
+ echo '<td class="anl_ita red anl_br anl_ac '.$cssBck.'" >';
+
+ echo SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] > 0 ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] : 0;
+ echo '</td>';
+
+ $_percent = SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0
+ ? 100 * SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt']
+ : 0;
+
+ echo '</tr>';
+ return $counter;
+
+ }
+
+ static function outputInvalidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_options=array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ //$cssBck = ' '.SurveyAnalysis::$cssColors['text_' . ($counter & 1)];
+ $cssBck = ($counter % 2 == 1) ? ' anl_bck_0_0' : '';
+
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+ $_invalid = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ) ? 100*$vAnswer['cnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+
+ $_sufix = (SurveyAnalysis::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(SurveyAnalysis::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.SurveyAnalysis::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ $_Z_MV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 2) ? TRUE : FALSE;
+ echo '<tr name="missing_detail_'.$_sequence.$_sufix.'"'.($_Z_MV ? '': ' class="hidden"').'>';
+ //echo '<td class="anl_bl anl_br anl_ac gray" style="width:10px">&nbsp;</td>';
+ echo '<td class="anl_bl anl_br">';
+ echo '<div class="floatLeft"><div class="anl_tin2">'.'<span class="anl_user_text">' . $vkey . '</span>' . ' (' . $vAnswer['text'].')'.'</div></div>'.NEW_LINE;
+ echo '<div class="floatRight anl_detail_percent anl_w50 anl_ac anl_dash_bl">'.SurveyAnalysis::formatNumber($_invalid, 2, '%').'</div>'.NEW_LINE;
+ echo '<div class="floatRight anl_detail_percent anl_w30 anl_ac">'.$vAnswer['cnt'].'</div>'.NEW_LINE;
+ echo '</td>';
+
+ echo '<td class="anl_ac anl_br">';
+ echo (int)$vAnswer['cnt'];
+ echo '</td>';
+
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,$_options = array()) {
+ global $lang;
+ # opcije
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+ //$cssBck = ' '.SurveyAnalysis::$cssColors['text_' . ($counter & 1)];
+ $cssBck = ' '.SurveyAnalysis::$cssColors['text_1'];
+ $_percent = (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] > 0 ) ? 100*SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] / SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0;
+
+ $_brez_MV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+ $_hide_minus = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 1 || (int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+
+ $_sufix = (SurveyAnalysis::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(SurveyAnalysis::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.SurveyAnalysis::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="click_missing_1_'.$_sequence.$_sufix.'" class="anl_dash_red_bb'.($_brez_MV ?' hidden' : '').'">';
+
+ echo '<td class="anl_bl anl_br anl_ita red" >';
+ echo $lang['srv_analiza_manjkajocevrednosti'];
+ // podrobno za missinge
+ echo '<span id="single_missing_0'.$_sequence.$_sufix.'" class="printHide anl_ita anl_detail_percent'.($_hide_minus ? '' : ' hidden').'">&nbsp;&nbsp;';
+ echo '<a href="#single_missing_'.$_sequence.$_sufix.'" onclick="show_single_missing(\''.$_sequence.$_sufix.'\', 0);return false;" > ' ;
+ //echo $lang['srv_analiza_missingSpremenljivke'] ;
+ echo ' <span class="faicon plus_orange folder_plusminus"></span> </a>';
+ echo '</span>';
+ echo '<span id="single_missing_1'.$_sequence.$_sufix.'" class="printHide anl_ita anl_detail_percent'.($_hide_minus ? ' hidden' : '').'">&nbsp;&nbsp;';
+ echo '<a href="#single_missing_'.$_sequence.$_sufix.'" onclick="show_single_missing(\''.$_sequence.$_sufix.'\', 1);return false;" > ' ;
+ // echo $lang['srv_analiza_missingSpremenljivke'] ;
+ echo ' <span class="faicon minus_orange folder_plusminus"></span> </a>';
+ echo '</span>';
+
+ echo '<div id="single_missing_suma_'.$_sequence.$_sufix.'" class="floatRight anl_w50 anl_dash_bl anl_dash_bt anl_ac anl_detail_percent hidden">100.0%</div>'.NEW_LINE;
+ echo '<div id="single_missing_suma_freq_'.$_sequence.$_sufix.'" class="floatRight anl_w30 anl_dash_bt anl_ac anl_detail_percent hidden">'.SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'].'</div>'.NEW_LINE;
+ echo '</td>';
+
+ echo '<td class="anl_ac anl_br anl_detail_cnt anl_ita red">';
+ $answer['cnt'] = SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] > 0 ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalidCnt'] : 0;
+ echo (int)$answer['cnt'];
+ echo '</td>';
+
+ echo '</tr>';
+ $counter++;
+ return $counter;
+ }
+
+ static function outputSumaVertical($counter,$_sequence,$spid, $_options = array()) {
+ global $lang;
+ # opcije
+
+ $options = array( 'isTextAnswer' => false, # ali je tekstovni odgovor
+ 'isOtherAnswer' => false, # ali je odgovor Drugo
+ 'inline_legenda' => true, # ali je legenda inline ali v headerju
+ );
+ foreach ($_options as $_oKey => $_option) {
+ $options[$_oKey] = $_option;
+ }
+
+ $cssBck = ' anl_bck_text_0';
+ $_brez_MV = ((int)SurveyAnalysis::$missingProfileData['display_mv_type'] === 0) ? TRUE : FALSE;
+
+ $_sufix = (SurveyAnalysis::$podstran == M_ANALYSIS_SUMMARY_NEW ? '_NEW' : '');
+ # da deluje razpiranje manjkajočih tudi kadar imamo skupine
+ if (isset(SurveyAnalysis::$_CURRENT_LOOP['cnt'])) {
+ $_sufix = '_loop'.SurveyAnalysis::$_CURRENT_LOOP['cnt'].$_sufix;
+ }
+
+ echo '<tr id="click_missing_suma_'.$_sequence.$_sufix.'" class="'.($_brez_MV ? 'hidden' : '').'">';
+
+ //echo '<td class="anl_bl anl_ac anl_dash_bt anl_bb red anl_ita'.$cssBck.'">'.$lang['srv_anl_suma2'].'</td>';
+ echo '<td class="anl_bl anl_dash_bt anl_br anl_bb">&nbsp;</td>';
+
+ echo '<td class="anl_ac anl_dash_bt anl_br anl_bb anl_ita red" >' . (SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] ? SurveyAnalysis::$_FREQUENCYS[$_sequence]['allCnt'] : 0) . '</td>';
+
+ echo '</tr>';
+ }
+
+ /** izpišemo tabelo z tekstovnimi odgovori drugo
+ *
+ * @param $skey
+ * @param $oAnswers
+ * @param $spid
+ */
+ static function outputOtherAnswers($oAnswers) {
+ global $lang;
+ $spid = $oAnswers['spid'];
+ $_variable = SurveyAnalysis::$_HEADERS[$spid]['grids'][$oAnswers['gid']]['variables'][$oAnswers['vid']];
+ $_sequence = $_variable['sequence'];
+ $_frekvence = SurveyAnalysis::$_FREQUENCYS[$_variable['sequence']];
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $_variable['variable'].' - ' : '');
+ $title = SurveyAnalysis::$_HEADERS[$oAnswers['spid']]['variable'].' ('.$_variable['naslov'].' )';
+ echo '<div class="chart_title">'.$stevilcenje . $title.'</div>';
+
+
+ echo '<table class="anl_tbl anl_bt anl_br anl_bb" style="font-size: '.(self::$fontSize+3).'px !important; padding:0px; margin:0px; border-collapse: collapse;">' . NEW_LINE;
+
+ $counter = 0;
+ $_kumulativa = 0;
+ if (is_countable(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) && count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid']) > 0) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['valid'] AS $vkey => $vAnswer) {
+ if ($vAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputValidAnswerVertical($counter,$vkey,$vAnswer,$_sequence,$spid,$_kumulativa,array('isOtherAnswer'=>true));
+ }
+ }
+ # izpišemo sumo veljavnih
+ //$counter = self::outputSumaValidAnswerVertical($counter,$_sequence,$spid,array('isOtherAnswer'=>true));
+ }
+ if (count(SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'])> 0 ) {
+ foreach (SurveyAnalysis::$_FREQUENCYS[$_sequence]['invalid'] AS $ikey => $iAnswer) {
+ if ($iAnswer['cnt'] > 0 ) { # izpisujemo samo tiste ki nisno 0
+ $counter = self::outputInvalidAnswerVertical($counter,$ikey,$iAnswer,$_sequence,$spid,array('isOtherAnswer'=>true));
+ }
+ }
+ # izpišemo sumo veljavnih
+ //$counter = self::outputSumaInvalidAnswerVertical($counter,$_sequence,$spid,array('isOtherAnswer'=>true));
+ }
+ #izpišemo še skupno sumo
+ //$counter = self::outputSumaVertical($counter,$_sequence,$spid,array('isOtherAnswer'=>true));
+
+ echo '</table>'.NEW_LINE;
+ }
+
+ /** Izriše tekstovne odgovore kot tabelo z navedbami
+ *
+ * @param unknown_type $spid
+ */
+ static function sumMultiText($spid) {
+ global $lang;
+
+ $spremenljivka = SurveyAnalysis::$_HEADERS[$spid];
+
+ if(!is_countable(SurveyAnalysis::$_LOOPS) || count(SurveyAnalysis::$_LOOPS) == 0)
+ self::$sessionData[$spid] = $settings;
+ else
+ self::$sessionData[$spid][SurveyAnalysis::$_CURRENT_LOOP['cnt']] = $settings;
+
+ # koliko zapisov prikažemo naenkrat
+ $num_show_records = (self::$num_records == 0) ? 10 : self::$num_records;
+
+ $_answers = SurveyAnalysis::getAnswers($spremenljivka,$num_show_records);
+
+ // ce imamo prazno in de prikazujemo praznih tabel
+ $hideEmpty = SurveyDataSettingProfiles :: getSetting('hideEmpty');
+ if($_answers['validCnt'] == 0 && $hideEmpty == 1){
+ self::displayEmptyWarning($spid);
+ return;
+ }
+
+ echo '<div class="chart_holder" id="chart_'.$spid.'_loop_'.self::$current_loop.'">';
+ //div za pozicijo popupa
+ echo '<div id="'.$spid.'"></div>';
+
+ echo '<div id="freq_'.$spid.'_loop_'.self::$current_loop.'" class="freq_chart_table">';
+
+ // Naslov posameznega grafa
+ $stevilcenje = (self::$numbering == 1 ? $spremenljivka['variable'].' - ' : '');
+ $title = $spremenljivka['edit_graf'] == 0 ? $spremenljivka['naslov'] : $spremenljivka['naslov_graf'];
+ echo '<div class="chart_title">'.$stevilcenje . $title.'</div>';
+
+ # dodamo opcijo kje izrisujemo legendo
+ # če je besedilo * in je samo ena kategorija je inline legenda false
+
+ $_cols = $spremenljivka['cnt_all'] / $spremenljivka['cnt_grids'];
+
+ $_all_valid_answers_cnt = $_answers['validCnt'];
+ $_valid_answers = $_answers['valid'];
+
+ # tekst vprašanja
+ echo '<table class="anl_tbl anl_bt anl_bb" style="font-size: '.(self::$fontSize+3).'px !important; padding:0px; margin:0px; border-collapse: collapse;">' . NEW_LINE;
+
+ # naslovna vrstica
+ if(self::$settings['type']==1){
+ echo '<tr>';
+ #odgovori
+ echo '<td class="anl_br anl_bl anl_bb anl_ac">'.$lang['srv_analiza_opisne_subquestion'] . '</td>';
+
+ echo '<td class="anl_br anl_bb anl_ac" colspan="'.($_cols).'">'. $lang['srv_analiza_opisne_arguments'] .'</td>';
+
+ echo '</tr>';
+ }
+ // konec naslovne vrstice
+
+ $_answersOther = array();
+ $_grids_count = count($spremenljivka['grids']);
+ if ($_grids_count > 0) {
+ # naslovna vrstica
+ $_row = $spremenljivka['grids'][0];
+ echo '<tr>';
+ echo '<td class="anl_bl anl_br anl_bb">&nbsp;</td>';
+
+ if (count($_row['variables'])>0)
+ foreach ($_row['variables'] AS $rid => $_col ){
+ $_sequence = $_col['sequence']; # id kolone z podatki
+ if ($_col['other'] != true) {
+ echo '<td class="anl_br anl_bb anl_ac anl_str">';
+ // echo $_col['variable'];
+ echo $_col['naslov'];
+ echo '</td>';
+ } else {
+ $_answersOther[] = array('spid'=>$spid,'gid'=>$gid,'vid'=>$vid,'sequence'=>$_sequence);
+ }
+ }
+ echo '</tr>';
+ $last = 0;
+ //anl_bck_desc_2 anl_bl anl_br anl_variabla_sub
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ $_variables_count = count($grid['variables']);
+ echo '<tr class="anl_ac anl_bb">';
+ echo '<td class="anl_br anl_bl anl_ac anl_str">';
+ echo $grid['naslov'];
+ echo '</td>';
+
+ if ($_variables_count > 0) {
+ # preštejemo max vrstic na grupo
+ $_max_i = 0;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_sequence = $variable['sequence']; # id kolone z podatki
+ $_max_i = max($_max_i,min($num_show_records,SurveyAnalysis::$_FREQUENCYS[$_sequence]['validCnt']));
+ }
+
+ # za barvanje
+ $last = ($last & 1) ? 0 : 1 ;
+
+ foreach ($grid['variables'] AS $vid => $variable ){
+
+ $_sequence = $variable['sequence']; # id kolone z podatki
+
+ if ($variable['other'] != true) {
+
+ # tabela z navedbami
+ echo '<td class=" anl_at" style="padding: 0pt; margin: 0pt; border-collapse: collapse; vertical-align:top;" >';
+ echo '<table class="fullWidth anl_ac" style="padding:0; margin:0; border-collapse: collapse; vertical-align:top;">';
+
+ $index=0;
+ if (count($_valid_answers) > 0) {
+ foreach ($_valid_answers AS $answer) {
+
+ $cssBck = ($index % 2 == 1) ? ' anl_bck_0_0' : '';
+
+ $index++;
+ $_ans = $answer[$_sequence];
+ echo '<tr>';
+ echo '<td class="anl_br '.$cssBck.'">';
+ if ($_ans != null && $_ans != '') {
+ echo $_ans;
+ } else {
+ echo '&nbsp;';
+ }
+ echo '</td>';
+ echo '</tr>';
+ }
+ }
+ if ($_all_valid_answers_cnt > $index) {
+ $index++;
+ echo '<tr>';
+ echo '<td class="anl_br anl_user_text">';
+ echo '<div id="valid_row_togle_more_'.$vid.'" class="floatRight '.(self::$publicChart != true ? ' blue pointer' : '').' anl_more" onclick="showHidenTextTable(\''.$spid.'\', \''.$num_show_records.'\', \''.self::$current_loop.'\');return false;">'.$lang['srv_anl_more'].'</div>'.NEW_LINE;
+ echo '</td>';
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+ echo '</td>';
+ }
+ }
+ $last = $_max_i;
+ }
+ echo '</tr>';
+ }
+ }
+ echo '</table>'.NEW_LINE;
+ echo '</div>';
+
+ // Izpisemo nastavitve za tabele
+ echo '<div class="chart_settings printHide iconHide" style="margin-top: 5px;">';
+ self::displaySingleSettings($spid);
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+
+ /** Funkcije ki skrbijo za ajax del
+ *
+ */
+ public static function ajax() {
+ global $global_user_id;
+
+
+ if (isset ($_POST['anketa'])) {
+ $anketa = $_POST['anketa'];
+ self::$anketa = $_POST['anketa'];
+ }
+ if (isset ($_POST['spid']))
+ $spid = $_POST['spid'];
+ if (isset ($_POST['spr_type']))
+ $spr_type = $_POST['spr_type'];
+
+
+ // Ce imamo nastavljene loope (Skupine) - potem nastavimo trenuten loop v katerem se nahaja graf
+ self::$current_loop = (isset ($_POST['loop'])) ? $_POST['loop'] : 'undefined';
+ if(self::$current_loop != 'undefined'){
+ SurveyAnalysis::$_LOOPS = SurveyZankaProfiles::getFiltersForLoops();
+
+ $loop = SurveyAnalysis::$_LOOPS[ (int)self::$current_loop-1 ];
+ $loop['cnt'] = self::$current_loop;
+ SurveyAnalysis::$_CURRENT_LOOP = $loop;
+ }
+
+ SurveyAnalysis::$podstran = 'charts';
+ SurveyAnalysis::getFrequencys();
+
+ if (isset ($_POST['settings_mode']))
+ self::$settings_mode = $_POST['settings_mode'];
+
+
+ // dobimo vse nastavitve iz sessiona
+ if(self::$current_loop != 'undefined'){
+ if(isset(self::$sessionData[$spid][self::$current_loop]))
+ self::$settings = self::$sessionData[$spid][self::$current_loop];
+ else
+ self::$settings = self::getDefaultSettings();
+ }
+ else{
+ if(isset(self::$sessionData[$spid]))
+ self::$settings = self::$sessionData[$spid];
+ else
+ self::$settings = self::getDefaultSettings();
+ }
+
+
+
+ if (isset ($_POST['what']))
+ $what = $_POST['what'];
+ if (isset ($_POST['value']))
+ $value = $_POST['value'];
+
+ self::$settings[$what] = $value;
+
+
+ if (isset ($_POST['num_records'])){
+ $textAnswersMore = array('0'=>'10','10'=>'30','30'=>'300','300'=>'600','600'=>'900','900'=>'100000');
+ self::$num_records = $textAnswersMore[$_POST['num_records']];
+ }
+ if ($_GET['a'] == 'change_chart') {
+
+ switch ($spr_type) {
+ case 1: # radio
+ case 3: # dropdown
+ self::displayRadioChart($spid, self::$settings, $refresh=1);
+ break;
+ case 2: #checkbox
+ self::displayCheckboxChart($spid, self::$settings, $refresh=1);
+ break;
+ case 6: # multigrid
+ self::displayMultigridChart($spid, self::$settings, $refresh=1);
+ break;
+ case 62: # dvojni multigrid
+ self::displayDoubleMultigridChart($spid, self::$settings, $refresh=1);
+ break;
+ case 7: # število
+ case 22: # compute
+ self::displayNumberChart($spid, self::$settings, $refresh=1);
+ break;
+ case 8: # datum
+ self::displayDateChart($spid, self::$settings, $refresh=1);
+ break;
+ case 16: # multicheckbox
+ self::displayMulticheckboxChart($spid, self::$settings, $refresh=1);
+ break;
+ case 17: # razvrščanje
+ self::displayRankingChart($spid, self::$settings, $refresh=1);
+ break;
+ case 20: # multi number
+ self::displayMultinumberChart($spid, self::$settings, $refresh=1);
+ //self::frequencyVertical($spid);
+ break;
+ case 18: # vsota
+ self::displayVsotaChart($spid, self::$settings, $refresh=1);
+ break;
+ case 4: # text
+ case 5: # nagovor
+ case 21: # besedilo*
+ case 25: # kvota
+ self::frequencyVertical($spid);
+ break;
+ case 19: # multitext
+ self::sumMultiText($spid);
+ break;
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData(self::$sessionData, 'charts');
+ }
+
+ // nastavitve tabel za drugo
+ if($_GET['a'] == 'change_other'){
+
+ if(self::$current_loop != 'undefined'){
+ self::$sessionData[$spid][self::$current_loop][$what] = $value;
+ self::$settings = self::$sessionData[$spid][self::$current_loop];
+ }
+ else{
+ self::$sessionData[$spid][$what] = $value;
+ self::$settings = self::$sessionData[$spid];
+ }
+
+ // Napolnimo podatke za graf
+ $DataSet = self::getDataSet($spid, self::$settings);
+
+ $_answersOther = $DataSet->GetOther();
+ if (count($_answersOther) > 0 && SurveyAnalysis::$_FILTRED_OTHER) {
+ foreach ($_answersOther AS $oAnswers) {
+ self::outputOtherAnswers($oAnswers);
+ }
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData(self::$sessionData, 'charts');
+ }
+
+ // Brisanje cacha za grafe
+ if ($_GET['a'] == 'clear_cache') {
+
+ self::clearCache();
+ }
+
+ if ($_GET['a'] == 'show_spid_more_table') {
+
+ // tabela besedilo
+ if(SurveyAnalysis::$_HEADERS[$spid]['tip'] == 19)
+ self::sumMultiText($spid);
+
+ // navadno besedilo
+ else
+ self::frequencyVertical($spid);
+ }
+
+ if ($_GET['a'] == 'chart_advanced_settings') {
+ self::displayAdvancedSettings($spid);
+ }
+
+ if ($_GET['a'] == 'change_hq_settings') {
+
+ self::$sessionData['hq'] = $value;
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData(self::$sessionData, 'charts');
+ }
+
+ if ($_GET['a'] == 'chart_save_advanced_settings') {
+
+ # shranimo rekodiranje in po potrebi popravimo datoteko s podatki
+ if ((int)$spid > 0 && (int)self::$anketa > 0) {
+ # Shranimo zamenjave manjkajočih vrednosti pri posameznem vprašanu za analize
+ if (isset($_REQUEST['edit_recode_mv']) || isset($_REQUEST['edit_recode_number'])) {
+ $vmv = new RecodeValues(self::$anketa,$spid);
+ $dataChanged = $vmv->SetUpMissingValuesForQuestion();
+ //print_r("changed:".(int)$dataChanged );
+ if ($dataChanged == true ) {
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init(self::$anketa);
+ //print_r("new:".$createdNewFile);
+ self::$headFileName = $SDF->getHeaderFileName();
+ self::$dataFileName = $SDF->getDataFileName();
+ self::$dataFileStatus = $SDF->getStatus();
+ }
+ }
+ }
+
+ // headers, ki ga popravimo in prepisemo originalnega (zaradi refresha label)
+ $newHeaders = SurveyAnalysis::$_HEADERS;
+
+
+ // SHRANIMO BARVE
+ // preverimo najprej ce shranjujemo vrednosti, ki so enake kot izbran skin
+ $default = true;
+ $default_colors = self::getDefaultColors(self::$skin);
+ for($i=1; $i<8; $i++){
+ if($_POST['color'.$i] != $default_colors[$i-1]){
+ $default = false;
+ break;
+ }
+ }
+ for($i=1; $i<8; $i++){
+
+ // ce niso default vrednosti shranimo nastavljeno barvo
+ if($default == false)
+ $color = $_POST['color'.$i];
+ // ce so default vrednosti shranimo prazno
+ else
+ $color = '';
+
+ self::$settings['colors'][$i-1] = $color;
+ }
+
+
+ // SHRANIMO MEJE
+ if (isset($_POST['chart_interval'])) {
+
+ $limits = array();
+
+ $interval = $_POST['chart_interval'];
+ self::$settings['interval'] = $interval;
+
+ if (isset($_POST['chart_number_limits_switch']))
+ $limits['advanced_settings'] = $_POST['chart_number_limits_switch'];
+
+
+ // Shranjevanje osnovnih nastavitev mej pri number
+ if($limits['advanced_settings'] == 0){
+
+ // shranimo polodprtost
+ self::$settings['open_down'] = (isset($_POST['chart_basic_open_down']) && self::$settings['min'] != '' && $_POST['chart_basic_open_down'] == '1') ? 1: 0;
+ self::$settings['open_up'] = (isset($_POST['chart_basic_open_up']) && self::$settings['max'] != '' && $_POST['chart_basic_open_up'] == '1') ? 1 : 0;
+
+ if (isset($_POST['chart_min']))
+ self::$settings['min'] = $_POST['chart_min'];
+
+ if (isset($_POST['chart_max']))
+ self::$settings['max'] = $_POST['chart_max'];
+
+ self::$settings['limits'] = $limits;
+ }
+
+ // Shranjevanje naprednih nastavitev mej pri number
+ else{
+ for($i=0; $i<$interval; $i++){
+
+ // shranimo polodprtost
+ self::$settings['open_down'] = (isset($_POST['chart_advanced_open_down']) && $_POST['chart_advanced_open_down'] == '1') ? 1 : 0;
+ self::$settings['open_up'] = (isset($_POST['chart_advanced_open_up']) && $_POST['chart_advanced_open_up'] == '1') ? 1 : 0;
+
+ // Minimum posameznega intervala
+ if (isset($_POST['interval_'.$i.'_min']))
+ $limits['interval_'.$i]['min'] = $_POST['interval_'.$i.'_min'];
+
+ // Maximuma posameznega intervala
+ if (isset($_POST['interval_'.$i.'_max']))
+ $limits['interval_'.$i]['max'] = $_POST['interval_'.$i.'_max'];
+
+ // Labela posameznega intervala
+ if (isset($_POST['interval_'.$i.'_label']))
+ $limits['interval_'.$i]['label'] = $_POST['interval_'.$i.'_label'];
+ }
+
+
+ self::$settings['limits'] = $limits;
+ }
+ }
+
+
+ // SHRANIMO LABELE
+ if (isset($_POST['edit_graf'])) {
+ $edit_graf = $_POST['edit_graf'];
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET edit_graf='$edit_graf' WHERE id='$spid'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // popravimo upostevanje label v HEADER
+ $newHeaders[$spid]['edit_graf'] = $edit_graf;
+ }
+
+ // naslov spremenljivke za graf
+ if (isset($_POST['naslov_graf'])) {
+ $naslov = $_POST['naslov_graf'];
+ /*if (strtolower(substr($naslov, 0, 3)) != '<p>' && strtolower(substr($naslov, -4)) != '</p>' && strrpos($naslov, '<p>') === false) {
+ //$naslov = '<p>'.nl2br($naslov).'</p>';
+ $naslov = '<p>' . str_replace("\n", "</p>\n<p>", $naslov) . '</p>';
+ }*/
+
+ /*$purifier = New Purifier();
+ $naslov = $purifier->purify_DB($naslov);*/
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET naslov_graf='$naslov' WHERE id='$spid'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+ // popravimo naslov spremenljivke v HEADER
+ $newHeaders[$spid]['naslov_graf'] = $naslov;
+ }
+
+ // shrani dodatne naslove variabel za graf
+ if (isset($_POST['edit_vrednost_graf'])) {
+
+ $i = 1;
+ foreach ($_POST as $key => $v) {
+
+ if (substr($key, 0, 14) == 'vrednost_graf_') {
+ $vrednost = substr($key, 14);
+
+ $naslov = str_replace(array('\n', '\t', '\r'), '', $_POST['vrednost_graf_'.$vrednost]);
+
+ $s = sisplet_query("UPDATE srv_vrednost SET naslov_graf='".$naslov."' WHERE id = '$vrednost'");
+
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+
+ // Popravimo variable v HEADER
+ if($spr_type == 1 || $spr_type == 3){
+ $newHeaders[$spid]['options_graf'][$i] = $naslov;
+ }
+ elseif($spr_type == 6 ){
+ $newHeaders[$spid]['grids'][$i-1]['variables'][0]['naslov_graf'] = $naslov;
+ }
+ elseif($spr_type == 16 || $spr_type == 20){
+ $newHeaders[$spid]['grids'][$i-1]['naslov_graf'] = $naslov;
+ }
+ elseif($spr_type != 7 || $i < 3){
+ $newHeaders[$spid]['grids'][0]['variables'][$i-1]['naslov_graf'] = $naslov;
+ }
+
+ $i++;
+ }
+ }
+ }
+
+ // shrani dodatne naslove gridov za graf
+ if (isset($_POST['edit_grid_graf'])) {
+
+ $vrstni_red = 0;
+ foreach ($_POST as $key => $v) {
+ if (substr($key, 0, 10) == 'grid_graf_') {
+ $vrstni_red++;
+
+ $grid = substr($key, 10);
+ $naslov = $_POST['grid_graf_'.$grid];
+ $variable = $grid;
+ $id= $vrstni_red;
+
+ $other = '0';
+ # manjkoajoče vrednosti (ne vem, zavrnil ...
+ if (isset($_POST['missing_value_checkbox']) && is_array($_POST['missing_value_checkbox'])) {
+ if (in_array($grid, $_POST['missing_value_checkbox'])) {
+ # grid je manjkajoča vrednost
+ $other = $grid.'';
+ $id = $grid;
+ }
+ }
+ $s = sisplet_query("UPDATE srv_grid SET naslov_graf='$naslov' WHERE id='$id' AND spr_id='$spid'");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+
+
+ // Popravimo gride v HEADER
+ if($spr_type == 6 ){
+ $newHeaders[$spid]['options_graf'][$vrstni_red] = $naslov;
+ }
+ elseif($spr_type == 16 || $spr_type == 20){
+
+ foreach($newHeaders[$spid]['grids'] as $grdKey => $grdVal){
+ $newHeaders[$spid]['grids'][$grdKey]['variables'][$vrstni_red-1]['naslov_graf'] = $naslov;
+ }
+ }
+ }
+ }
+ }
+
+
+ // pobrisemo star header
+ if (file_exists(self::$headFileName))
+ unlink(self::$headFileName);
+
+ // shranimo popravljen headers v novo datoteko
+ file_put_contents(self::$headFileName, serialize($newHeaders));
+
+ SurveyAnalysis::$podstran = 'charts';
+ SurveyAnalysis::$_HEADERS = $newHeaders;
+ SurveyAnalysis::getFrequencys();
+
+
+ // Na novo zgeneriramo graf
+ switch ($spr_type) {
+ case 1: # radio
+ case 3: # dropdown
+ self::displayRadioChart($spid, self::$settings, $refresh=1);
+ break;
+ case 2: #checkbox
+ self::displayCheckboxChart($spid, self::$settings, $refresh=1);
+ break;
+ case 6: # multigrid
+ self::displayMultigridChart($spid, self::$settings, $refresh=1);
+ break;
+ case 62: # dvojni multigrid
+ self::displayDoubleMultigridChart($spid, self::$settings, $refresh=1);
+ break;
+ case 22: # compute
+ case 7: # število
+ self::displayNumberChart($spid, self::$settings, $refresh=1);
+ break;
+ case 8: # datum
+ self::displayDateChart($spid, self::$settings, $refresh=1);
+ break;
+ case 16: # multicheckbox
+ self::displayMulticheckboxChart($spid, self::$settings, $refresh=1);
+ break;
+ case 17: # razvrščanje
+ self::displayRankingChart($spid, self::$settings, $refresh=1);
+ break;
+ case 20: # multi number
+ self::displayMultinumberChart($spid, self::$settings, $refresh=1);
+ //self::frequencyVertical($spid);
+ break;
+ case 18: # vsota
+ self::displayVsotaChart($spid, self::$settings, $refresh=1);
+ break;
+ case 4: # text
+ case 5: # nagovor
+ case 21: # besedilo*
+ case 25: # kvota
+ self::frequencyVertical($spid);
+ break;
+ case 19: # multitext
+ self::sumMultiText($spid);
+ break;
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData(self::$sessionData, 'charts');
+ }
+
+ // spremenimo skalo spremenljivke (ordinalna/nominalna)
+ if ($_GET['a'] == 'chart_advanced_settings_skala') {
+
+ $spremenljivka = $_POST['spid'];
+ $skala = $_POST['skala'];
+
+ # popravimo skalo spremenljivke
+ # skala - 0 Ordinalna
+ # skala - 1 Nominalna
+ if ( isset($skala) && (int)$spremenljivka) {
+ $sql = sisplet_query("UPDATE srv_spremenljivka SET skala='".$skala."' WHERE id='$spremenljivka'");
+
+ # popravimo v header datoteki
+ SurveyAnalysis::$_HEADERS[$spremenljivka]['skala'] = $skala;
+ file_put_contents(self::$headFileName, serialize(SurveyAnalysis::$_HEADERS));
+ }
+ }
+
+ // Globalne nastavitve za vse grafe
+ if ($_GET['a'] == 'save_global_settings') {
+
+ SurveyUserSetting :: getInstance()->saveSettings('default_chart_profile_'.$what, $value);
+ }
+
+ // Odpremo okno za izbiro globalnega skina
+ if($_GET['a'] == 'analiza_show_chart_color') {
+
+ $skin = (SurveyUserSetting::getInstance()->getSettings('default_chart_profile_skin') == null ? '1ka' : SurveyUserSetting::getInstance()->getSettings('default_chart_profile_skin'));
+
+ self::displaySettingsProfiles($skin);
+ }
+
+ // Spreminjamo globalen skin
+ if($_GET['a'] == 'analiza_change_chart_color') {
+
+ //$skin = SurveyUserSetting :: getInstance()->getSettings('default_chart_profile_skin');
+ if (isset ($_POST['skin']))
+ $skin = $_POST['skin'];
+
+ self::displaySettingsProfiles($skin);
+ }
+
+ // Preimenujemo globalen skin
+ if($_GET['a'] == 'renameSkin') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+ if (isset ($_POST['name']))
+ $name = $_POST['name'];
+
+ $s = sisplet_query("UPDATE srv_chart_skin SET name='$name' WHERE id='$id'");
+
+ self::displaySettingsProfiles($id);
+ }
+
+ // Pobrisemo globalen skin
+ if($_GET['a'] == 'deleteSkin') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+
+ $s = sisplet_query("DELETE FROM srv_chart_skin WHERE id='$id'");
+
+ self::displaySettingsProfiles();
+ }
+
+ // Dodamo nov globalen skin
+ if($_GET['a'] == 'newSkin') {
+
+ if (isset ($_POST['name']))
+ $name = $_POST['name'];
+ if (isset ($_POST['colors']))
+ $colors = $_POST['colors'];
+
+ $s = sisplet_query("INSERT INTO srv_chart_skin (name, colors, usr_id) VALUES('$name', '$colors', '$global_user_id')");
+ $id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ self::displaySettingsProfiles($id);
+ }
+
+ // Popravimo obstojec custom skin
+ if($_GET['a'] == 'editSkin') {
+
+ if (isset ($_POST['id']))
+ $id = $_POST['id'];
+ if (isset ($_POST['colors']))
+ $colors = $_POST['colors'];
+
+ $s = sisplet_query("UPDATE srv_chart_skin SET colors='$colors' WHERE id='$id'");
+ }
+
+ // Preklop stevila intervalov pri mejah v naprednih nastavitvah
+ if($_GET['a'] == 'analiza_num_limit_interval') {
+
+ if (isset ($_POST['interval']))
+ self::$settings['interval'] = $_POST['interval'];
+
+ self::displayAdvancedSettingsLimits($spid, $mode=1);
+ }
+
+ echo '<script>charts_init();</script>';
+ }
+
+ static function setUpReturnAsHtml($returnAsHtml = false) {
+ self::$returnChartAsHtml = $returnAsHtml; # ali vrne rezultat analiz kot html ali ga izpiše
+ }
+
+ static function setUpIsForArchive($isArchive = false) {
+ #nastavimo timestamp, katerega dodamo imenu slike, za unikatnost
+ list($usec, $sec) = explode(" ", microtime());
+ self::$chartArchiveTime = $sec;
+ self::$isArchive = $isArchive; # nastavimo da smo v arhivu
+ return self::$chartArchiveTime;
+ }
+
+
+ static function displaySettingsProfiles($skin='1ka'){
+ global $site_path;
+ global $lang;
+
+
+ echo '<h2 style="margin-bottom:5px;">'.$lang['srv_chart_skin_long'].'</h2>';
+ echo '<span style="font-size: 12px; font-style: italic;">'.$lang['srv_chart_skin_info'].'</span><br/><br/>';
+
+ // Opozorilo na vrhu
+ if(!is_numeric($skin)){
+ echo '<div id="chart_skin_note">';
+ echo $lang['srv_chart_skin_warning'];
+ echo '</div>';
+ echo '<br class="clr" />'."\n";
+ }
+
+ echo '<script type="text/javascript" charset="utf-8">
+ $(document).ready(function() {
+ var f = $.farbtastic(\'#picker\');
+ var p = $(\'#picker\').css(\'opacity\', 0.25);
+ var selected;
+ $(\'.colorwell\')
+ .each(function () { f.linkTo(this); $(this).css(\'opacity\', 0.75); })
+ .focus(function() {
+ if (selected) {
+ $(selected).css(\'opacity\', 0.75).removeClass(\'colorwell-selected\');
+ }
+ f.linkTo(this);
+ p.css(\'opacity\', 1);
+ $(selected = this).css(\'opacity\', 1).addClass(\'colorwell-selected\');
+ });
+ });
+ </script>';
+
+
+ echo '<div id="chart_settings_profiles_left">';
+
+ // Prednastavljeni skini
+ echo '<span class="bold">'.$lang['srv_chart_skin_default'].':</span>';
+ echo '<span class="chart_profiles_holder" style="margin-bottom: 10px; height: 144px;">';
+ echo '<span id="chart_profiles" class="chart_profiles select">';
+
+ echo '<div class="option'.($skin == '1ka' ? ' active' : '').'" id="chart_profile_skin_1ka" value="1ka">'.$lang['srv_chart_skin_1ka'].'</div>';
+ echo '<div class="option'.($skin == 'lively' ? ' active' : '').'" id="chart_profile_skin_0" value="lively">'.$lang['srv_chart_skin_0'].'</div>';
+ echo '<div class="option'.($skin == 'mild' ? ' active' : '').'" id="chart_profile_skin_1" value="mild">'.$lang['srv_chart_skin_1'].'</div>';
+ echo '<div class="option'.($skin == 'office' ? ' active' : '').'" id="chart_profile_skin_6" value="office">'.$lang['srv_chart_skin_6'].'</div>';
+ echo '<div class="option'.($skin == 'pastel' ? ' active' : '').'" id="chart_profile_skin_7" value="pastel">'.$lang['srv_chart_skin_7'].'</div>';
+ echo '<div class="option'.($skin == 'green' ? ' active' : '').'" id="chart_profile_skin_2" value="green">'.$lang['srv_chart_skin_2'].'</div>';
+ echo '<div class="option'.($skin == 'blue' ? ' active' : '').'" id="chart_profile_skin_3" value="blue">'.$lang['srv_chart_skin_3'].'</div>';
+ echo '<div class="option'.($skin == 'red' ? ' active' : '').'" id="chart_profile_skin_4" value="red">'.$lang['srv_chart_skin_4'].'</div>';
+ echo '<div class="option'.($skin == 'multi' ? ' active' : '').'" id="chart_profile_skin_5" value="multi">'.$lang['srv_chart_skin_5'].'</div>';
+
+ echo '</span>';
+ echo '</span>';
+
+
+ // Custom kreirani skini
+ $custom_skins = self::getCustomSkins();
+
+ echo '<span class="bold">'.$lang['srv_chart_skin_custom'].':</span>';
+ echo '<span class="chart_profiles_holder">';
+ echo '<span id="chart_profiles_custom" class="chart_profiles select">';
+
+ foreach ($custom_skins as $custom_skin ){
+ echo '<div class="option'.($skin == $custom_skin['id'] ? ' active' : '').'" id="chart_profile_skin_'.$custom_skin['id'].'" value="'.$custom_skin['id'].'">'.$custom_skin['name'].'</div>';
+ }
+
+ echo '</span>';
+ echo '</span>';
+
+ // Ce je izbran custom skin imamo na dnu gumba brisi in preimenuj
+ if(is_numeric($skin)){
+ echo '<a href="#" onclick="chart_skin_action(\'show_rename\'); return false;">'.$lang['srv_rename_profile'].'</a><br/>'."\n";
+ echo '<a href="#" onclick="chart_skin_action(\'show_delete\'); return false;">'.$lang['srv_delete_profile'].'</a>'."\n";
+ }
+
+ echo '</div>';
+
+
+ echo '<div id="chart_settings_profiles_right">';
+
+ // ce je numeric je custom skin
+ if(is_numeric($skin)){
+
+ $custom_skin = self::getCustomSkin($skin);
+
+ $colors = explode('_', $custom_skin['colors']);
+ $default_colors = $colors;
+ }
+ else{
+ // preview za default skine
+ echo '<div id="div_chart_skin_previews">';
+ echo $lang['srv_chart_skin_preview'].':';
+ self::displayChartSkinPreview($skin);
+ echo '</div>';
+
+ $default_colors = self::getDefaultColors($skin);
+ }
+
+ // Izbira custom skina
+ echo '<div id="chart_custom_skin">';
+
+ echo ' <div id="picker" style="float: right;"></div>';
+
+
+ for($i=0; $i<7; $i++){
+ $name = 'color'.($i+1);
+ //$value = (self::$settings['colors'][$i] != '') ? self::$settings['colors'][$i] : $default_colors[$i];
+ $value = $default_colors[$i];
+
+ echo ' <div class="form-item"><label for="'.$name.'">'.$lang['srv_color'].' '.($i+1).': </label><input type="text" id="'.$name.'" name="'.$name.'" class="colorwell" value="'.$value.'" /></div>';
+ }
+
+ // reset na default barvo
+ echo '<br /><span class="as_link clr" onClick="chartAdvancedSettingsSetColor(\''.(is_numeric($skin) ? implode("_",$colors) : $skin).'\')">'.$lang['srv_chart_advanced_default_color'].'</span>';
+
+ echo '</div>';
+
+ echo '</div>';
+
+
+ // cover Div
+ echo '<div id="dsp_cover_div"></div>'."\n";
+
+ // div za kreacijo novega
+ echo '<div id="newChartSkin">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="newChartSkinName" name="newChartSkinName" type="text" value="" size="50" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="chart_skin_action(\'new\'); return false;"><span>'.$lang['srv_analiza_arhiviraj_save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="chart_skin_action(\'cancel_new\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameChartSkin">'.$lang['srv_missing_profile_name'].': '."\n";
+ echo '<input id="renameChartSkinName" name="renameChartSkinName" type="text" value="' . $custom_skin['name'] . '" size="50" />'."\n";
+ echo '<input id="renameChartSkinId" type="hidden" value="' . $custom_skin['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="chart_skin_action(\'rename\'); return false;"><span>'.$lang['srv_rename_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="chart_skin_action(\'cancel_rename\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteChartSkin">'.$lang['srv_missing_profile_delete_confirm'].': <b>' . $custom_skin['name'] . '</b>?'."\n";
+ echo '<input id="deleteChartSkinId" type="hidden" value="' . $custom_skin['id'] . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="chart_skin_action(\'delete\'); return false;"><span>'.$lang['srv_delete_profile_yes'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="chart_skin_action(\'cancel_delete\'); return false;"><span>'.$lang['srv_close_profile'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+
+ echo '<span class="clr"></span>';
+
+ echo '<div style="position:absolute; bottom:20px; right:20px;">';
+
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="save_chartColor(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_save_new_profile'].'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="chart_skin_action(\'show_new\'); return false;"><span>'.$lang['srv_save_new_profile'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="close_chartColor(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+
+ echo '</div>';
+ }
+
+ static function displayChartSkinPreview ($skin) {
+ global $lang;
+
+ echo '<div id="div_chart_skin_preview_1ka" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color1ka.png\'); '.($skin == '1ka' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_0" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color0.png\'); '.($skin == 'lively' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_1" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color1.png\'); '.($skin == 'mild' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_2" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color2.png\'); '.($skin == 'green' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_3" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color3.png\'); '.($skin == 'blue' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_4" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color4.png\'); '.($skin == 'red' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_5" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color5.png\'); '.($skin == 'multi' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_6" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color6.png\'); '.($skin == 'office' ? ' display:block;' : '').'">';
+ echo '</div>';
+
+ echo '<div id="div_chart_skin_preview_7" class="div_chart_skin_preview" style="background-image: url(\'pChart/preview/color7.png\'); '.($skin == 'pastel' ? ' display:block;' : '').'">';
+ echo '</div>';
+ }
+
+ static function getCustomSkins(){
+ global $global_user_id;
+
+ $skins = array();
+
+ $sql = sisplet_query("SELECT * FROM srv_chart_skin WHERE usr_id='$global_user_id'");
+ while($row = mysqli_fetch_array($sql)){
+ $skins[] = $row;
+ }
+
+ return $skins;
+ }
+
+ static function getCustomSkin($id){
+ global $global_user_id;
+
+ $sql = sisplet_query("SELECT * FROM srv_chart_skin WHERE usr_id='$global_user_id' AND id='$id'");
+ $skin = mysqli_fetch_array($sql);
+
+ return $skin;
+ }
+
+ static function displayPublicChart($properties = array()) {
+ global $lang;
+ global $site_url;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+
+ $anketa = self::$anketa;
+
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body style="margin:5px; padding:5px;" >';
+ echo '<h2>'.$lang['srv_publc_chart_title_for'] . self::$survey['naslov'].'</h2>';
+
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $anketa . '" />';
+ echo '<div id="analiza_data">';
+
+ # ponastavimo nastavitve- filter
+ self::Display();
+ echo '</div>';
+
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/printer.png" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+
+ echo '</body>';
+ echo '</html>';
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyCrosstabs.php b/admin/survey/classes/surveyAnalysis/class.SurveyCrosstabs.php
new file mode 100644
index 0000000..e0f4e85
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyCrosstabs.php
@@ -0,0 +1,2606 @@
+<?php
+/**
+ * @author Gorazd Veselič
+ * @date December 2010
+ *
+ */
+
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+# mejne vrednosti za barvanje residualov
+define("RESIDUAL_COLOR_LIMIT1", 1.00);
+define("RESIDUAL_COLOR_LIMIT2", 2.00);
+define("RESIDUAL_COLOR_LIMIT3", 3.00);
+define("AUTO_HIDE_ZERRO_VALUE", 20); # nad koliko kategorij skrivamo ničelne vrednosti
+
+@session_start();
+
+class SurveyCrosstabs {
+
+ public $sid; # id ankete
+ public $folder = ''; # pot do folderja
+
+ public $db_table; # katere tabele uporabljamo
+
+ public $inited = false; # ali smo razred inicializirali
+
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ # ali obstaja datoteka z podatki in ali je zadnja verzija
+ public $setUpJSAnaliza = true; # ali nastavimo __analiza = 1 v JS
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ public $currentMissingProfile = 1; # Kateri Missing profil je izbran
+ public $missingProfileData = null; # Nastavitve trenutno izbranega manjkajočega profila
+
+ public $_CURRENT_LOOP = null; # trenutni loop
+
+ # CHECKBOXI
+ public $crossChk0 = true; # checkbox frekvence
+ public $crossChk1 = false; # checkbox odstotek po vrsticah
+ public $crossChk2 = false; # checkbox odstotek po stolpcih
+ public $crossChk3 = false; # checkbox skupni odstotek
+
+ public $crossChkEC = false; # checkbox pričakovana frekvenca
+ public $crossChkRE = false; # checkbox rezidual
+ public $crossChkSR = false; # checkbox standardni rezidual
+ public $crossChkAR = false; # checkbox prilagojen rezidual
+ public $doColor = true; # checkbox Obarvaj celice
+ public $doValues = true; # checkbox Prikaži vrednosti
+
+ public $enableInspect = true; # checkbox enableInspect
+
+ public $variabla1 = array('0'=> array('seq'=>'0','spr'=>'undefined', 'grd'=>'undefined')); # array drugih variable, kamor shranimo spr, grid_id, in sequenco
+ public $variabla2 = array('0'=> array('seq'=>'0','spr'=>'undefined', 'grd'=>'undefined')); # array drugih variable, kamor shranimo spr, grid_id, in sequenco
+
+ public $crossNavVsEno = 1; # ali delamo po navedbah ali po enotah
+ public $displayHi2 = true; # ali prikazujemo hi^2
+ public $fromBreak = false; # ali delamo crosstab iz break-a
+ public $showAverage = true; # ali prikazujemo povprečja - v kombinaciji z from break
+ public $showBottomAverage = false; # ali prikazujemo povprečja - po stolpcih v zadnji vrstici
+ public $showChart = false; # ali prikazujemo graf pod tabelo
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ /* Variable so definirane v obliki:
+ * '37507_0_0_0' = x_y_z_w
+ * -> x => spr_id
+ * -> y => loop id
+ * -> z => grid_id
+ * -> y => variable id
+ *
+ */
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo crostabulacije (zakeširamo)
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ function Init( $anketa = null ) {
+ global $global_user_id, $site_path;
+
+ $this->folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ((int)$anketa > 0) { # če je poadan anketa ID
+ $this->sid = $anketa;
+
+ SurveyAnalysisHelper::getInstance()->Init($this->sid);
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->sid);
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileName = $this->SDF->getDataFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->sid);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyUserSetting::getInstance()->Init($this->sid, $global_user_id);
+
+ SurveyMissingProfiles :: Init($this->sid,$global_user_id);
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+ SurveyZankaProfiles :: Init($this->sid, $global_user_id);
+ SurveyTimeProfiles :: Init($this->sid, $global_user_id);
+
+ SurveyDataSettingProfiles :: Init($this->sid);
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->sid);
+ $this->sessionData = SurveyUserSession::getData();
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ # nastavimo uporabniške nastavitve
+ $this->readUserSettings();
+
+ } else {
+ die("Napaka!");
+ }
+ }
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter() {
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ if ($this->headFileName !== null && $this->headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) || ($_time_profile_awk != "" && $_time_profile_awk != null)) {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD) {
+
+ if (isset($this->_HEADERS['testdata'])) {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+ }
+
+
+ /** funkcija vrne seznam primern variabel za crostabe
+ *
+ */
+ function getVariableList() {
+ if (isset($this->variablesList) && is_array($this->variablesList) && count($this->variablesList) > 0) {
+ return $this->variablesList;
+ } else {
+ # pobrišemo array()
+ $this->variablesList = array();
+ # zloopamo skozi header in dodamo variable (potrebujemo posamezne sekvence)
+ foreach ($this->_HEADERS AS $skey => $spremenljivka) {
+ if ((int)$spremenljivka['hide_system'] == 1 && in_array($spremenljivka['variable'],array('email','ime','priimek','telefon','naziv','drugo'))) {
+ continue;
+ }
+
+ $tip = $spremenljivka['tip'];
+ if (is_numeric($tip)
+ # tekstovnih tipov ne dodajamo
+
+ && $tip != 4 #text
+ && $tip != 5 #label
+ #&& $tip != 7 #number
+ #&& $tip != 8 #datum
+ && $tip != 9 #SN-imena
+ #&& $tip != 18 #vsota
+ #&& $tip != 19 #multitext
+ #&& $tip != 20 #multinumber
+ #&& $tip != 21 #besedilo*
+ && $tip != 22 #compute
+ && $tip != 25 #kvota
+ ) {
+ $cnt_all = (int)$spremenljivka['cnt_all'];
+ # radio in select in checkbox
+ if ($cnt_all == '1' || $tip == 1 || $tip == 3 || $tip == 2) {
+ # pri tipu radio ali select dodamo tisto variablo ki ni polje "drugo"
+ if ($tip == 1 || $tip == 3 ) {
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][$vid]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+
+ }
+ }
+ }
+ }
+ } else {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+ } else if ($cnt_all > 1){
+ # imamo več skupin ali podskupin, zato zlopamo skozi gride in variable
+ if (count($spremenljivka['grids']) > 0 ) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # ali imamo en grid, ali več (tabele
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } else if($tip == 16||$tip == 18) {
+ # imamo multicheckbox
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>$gid,
+ 'sequence'=>$grid['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ } else {
+ # imamo več gridov - tabele
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>$sub);
+ }
+ if (count ($grid['variables']) > 0) {
+ $sub++;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>$sub);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ return $this->variablesList;
+ }
+ }
+
+
+ /** Prikazuje filtre
+ *
+ */
+ function DisplayFilters() {
+ if ($this->dataFileStatus == FILE_STATUS_SRV_DELETED || $this->dataFileStatus == FILE_STATUS_NO_DATA){
+ return false;
+ }
+
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->sid);
+ # izrišemo desne linke do posameznih nastavitev
+ $SSH -> displayAnalizaRightOptions(M_ANALYSIS_CROSSTAB);
+
+ if ($this->setUpJSAnaliza == true) {
+ echo '<script>
+ window.onload = function() {
+ __analiza = 1;
+ __tabele = 1;
+ }
+ </script>';
+ }
+ }
+
+ function DisplayLinks() {
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->sid);
+ $SSH -> displayAnalizaSubNavigation();
+ }
+
+ /** Prikazuje podatke analize
+ *
+ */
+ function Display() {
+ # preberemo prednastavljene variable iz seje, če obstajajo
+ $this->presetVariables();
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ global $lang;
+
+ # polovimo nastavtve missing profila
+ //$this->missingProfileData = SurveyMissingProfiles::getProfile($this->currentMissingProfile);
+
+ echo '<div id="crosstab_drobdowns">';
+ $resultIsCheckbox = $this->DisplayDropdows();
+ echo '</div>';
+ echo '<div id="div_crossCheck" class="floatLeft spaceLeft">' ;
+ $this->displayLinePercent();
+ $this->displayResidual();
+ $this->displayShowChart();
+ if ( $resultIsCheckbox['is_check']) {
+ echo '<div id="crossNavedbeVsENote">';
+ echo '<input type="radio" name="crossNavVsEno" id="crossNavVsEno0" vlaue="0" '.($this->crossNavVsEno == 0 ? ' checked="checked" ' : '' ).' onchange="change_crosstab(); return false;" autocomplete="off">'.
+ '<label for="crossNavVsEno0">'.$lang['srv_analiza_crosstab_navedbe'].'</label>';
+ echo '<input type="radio" name="crossNavVsEno" id="crossNavVsEno1" vlaue="1" '.($this->crossNavVsEno == 1? ' checked="checked" ' : '' ).' onchange="change_crosstab(); return false;" autocomplete="off">'.
+ '<label for="crossNavVsEno1">'.$lang['srv_analiza_crosstab_enote'].'</label>';
+ echo '</div>';
+ }
+ echo '</div>';
+
+
+ $this->displayExport();
+ $this->displayCrosstabCheckboxes();
+ echo '<div id="crosstab_table">';
+ $this->displayCrosstabsTables();
+ echo '</div>';
+ }
+
+ function DisplayDropdows() {
+ global $lang;
+ $variables = $this->getVariableList();
+ $multiple = true;
+
+ echo '<div id="crossLeftHolder" >';
+
+ # iz header datoteke preberemo spremenljivke
+ #js: $("#crosstab_variable_1, #crosstab_variable_2").live('click', function() {})
+ if (count($this->variabla1) > 0) {
+ $br=null;
+ echo $lang['srv_crosstab_label1'].'<br/>';
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<span class="pointer" id="crosstab_add_new" onclick="add_new_variable(\'1\');"><span class="faicon add small icon-as_link" title=""></span></span>';
+ }
+
+ foreach($this->variabla1 AS $_key => $variabla1) {
+ echo $_br;
+ echo '<span id="v1_'.$_key.'">';
+
+ echo '<select name="crosstab_variable_1" id="crosstab_variable_1" onchange="change_crosstab(); return false;" autocomplete="off">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $variabla1['seq'] == null || $variabla1['seq'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_izberi_prvo'] . '</option>';
+ }
+ foreach ($variables as $variable) {
+ echo '<option value="' . $variable['sequence'] . '" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($variabla1['seq'] > 0 &&$variabla1['seq'] == $variable['sequence']) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] . '</option>';
+
+ }
+
+ echo '</select>';
+ if (count($this->variabla1) > 1) {
+ echo '<span class="pointer" id="crosstab_remove" onclick="crs_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+ } else {
+ #echo '<span class="space_crosstab_new">&nbsp;</span>';
+ }
+
+ $_br = '<br/><span class="space_crosstab_new">&nbsp;</span>';
+ echo '</span>';
+ }
+ $_br = null;
+ }
+
+ echo '</div>';
+ echo '<div id="crossImgHolder">';
+ echo '<br/>';
+ if ($this->isSelectedBothVariables()) {
+ echo '<span class="faicon replace icon-as_link" title="'.$lang['srv_replace'].'" onclick="change_crosstab(\'rotate\');return false;" />';
+ } else {
+ echo '<span class="faicon replace icon-grey_normal" title="'.$lang['srv_replace'].'" />';
+ }
+ echo '</div>';
+
+ echo '<div id="crossRightHolder">';
+ echo $lang['srv_crosstab_label2'].'<br/>';
+ # za vsako novo spremenljivko 2 nardimo svoj select
+ if (count($this->variabla2) > 0) {
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<span class="pointer" id="crosstab_add_new" onclick="add_new_variable(\'2\');"><span class="faicon add small icon-as_link" title="'.'"></span></span>';
+ }
+
+ foreach($this->variabla2 AS $_key => $variabla2) {
+ echo $_br;
+ echo '<span id="v2_'.$_key.'">';
+
+ echo '<select name="crosstab_variable_2" id="crosstab_variable_2" onchange="change_crosstab(); return false;" autocomplete="off"'
+ . ((int)$this->variabla1['0']['seq'] > 0 ? '' : ' disabled="disabled" ')
+ .'>';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ((int)$this->variabla1['0']['seq'] == 0) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_najprej_prvo'] . '</option>';
+ } else {
+ # če druga variabla ni izbrana dodamo tekst za izbiro druge variable
+ if ($variabla2['seq'] == null || $variabla2['seq'] == 0) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_izberi_drugo'] . '</option>';
+ }
+ }
+
+ foreach ($variables as $variable) {
+ echo '<option value="' . $variable['sequence'] . '" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( $variabla2['seq'] > 0 && $variabla2['seq'] == $variable['sequence'] ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] .'</option>';
+
+ }
+ echo '</select>';
+ if (count($this->variabla2) > 1) {
+ echo '<span class="pointer" id="crosstab_remove" onclick="crs_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+ } else {
+ echo '<span class="space_crosstab_new">&nbsp;</span>';
+ }
+
+ $_br = '<br/><span class="space_crosstab_new">&nbsp;</span>';
+ echo '</span>';
+ }
+ }
+ echo '</div>';
+
+ # če je katera od variabel checkbox, ponudimo možnodt izbire ali po enotah ali po navedbah
+ $is_check = false;
+ if (count($this->variabla2) > 0) {
+ foreach ($this->variabla2 AS $key => $var) {
+ $spr_tip = $this->_HEADERS[$var['spr']]['tip'];
+ if ( $spr_tip == 2 || $spr_tip == 16 ) {
+ $is_check = true;
+ }
+ }
+ }
+ if (count($this->variabla1) > 0 && $is_check == false ) { # če še ni bil checkbox
+ foreach ($this->variabla1 AS $key => $var) {
+ $spr_tip = $this->_HEADERS[$var['spr']]['tip'];
+ if ( $spr_tip == 2 || $spr_tip == 16 ) {
+ $is_check = true;
+ }
+ }
+ }
+
+ return array("is_check" => $is_check);
+ }
+
+ function addNewVariable() {
+ global $lang;
+ $variables = $this->getVariableList();
+ $multiple = true;
+
+ $which = $_POST['which'];
+
+
+ if ($which == '1') {
+ echo '<br/>';
+ echo '<span class="space_crosstab_new">&nbsp;</span>';
+ echo '<select name="crosstab_variable_1" id="crosstab_variable_1" onchange="change_crosstab(); return false;" autocomplete="off">';
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $variabla1['seq'] == null || $variabla1['seq'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_izberi_more'] . '</option>';
+ }
+
+ foreach ($variables as $variable) {
+ echo '<option value="' . $variable['sequence'] . '" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] .$variable['sequence']. '</option>';
+
+ }
+ echo '</select>';
+ echo '<span class="pointer" id="crosstab_remove" onclick="crs_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+
+ } else {
+ echo '<br/>';
+ echo '<span class="space_crosstab_new">&nbsp;</span>';
+ echo '<select name="crosstab_variable_'.$which.'" id="crosstab_variable_'.$which.'" onchange="change_crosstab(); return false;" autocomplete="off"'
+ .'>';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_najprej_prvo'] . '</option>';
+ } else {
+ # če druga variabla ni izbrana dodamo tekst za izbiro druge variable
+ echo '<option value="0" selected="selected">'. $lang['srv_analiza_crosstab_izberi_more'] . '</option>';
+ }
+
+ foreach ($variables as $variable) {
+ echo '<option value="' . $variable['sequence'] . '" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] .$variable['sequence']. '</option>';
+
+ }
+ echo '</select>';
+ echo '<span class="pointer" id="crosstab_remove" onclick="crs_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+ }
+ }
+ /**
+ * @desc prikaze tabele za crosstab
+ */
+ function displayCrosstabCheckboxes () {
+ global $lang;
+
+ echo '<div id="div_color_residual_legend" '.($this->isSelectedBothVariables() && $this->doColor ? '' : ' class="hidden"').'>' ;
+
+ echo '<span id="span_color_residual_legend" class="floatLeft">';
+ echo '<span id="span_color_residual_legend1" class="floatLeft">';
+ echo '<span class="floatLeft">';
+ echo '<label>'.$lang['srv_analiza_crosstab_adjs_residual_short'].'</label>';
+ echo '</span>';
+ echo '<span class="floatLeft">';
+ echo '<table id="tbl_color_residual_legend" >';
+ echo '<tr>';
+ echo '<td style="width:15px !important; text-align: center !important; font-weight: bold !important;">-</td>';
+ echo '<td class="rsdl_bck6" title="'.$lang['srv_crosstab_residual_1'].'">&nbsp;</td>';
+ echo '<td class="rsdl_bck5" title="'.$lang['srv_crosstab_residual_2'].'">&nbsp;</td>';
+ echo '<td class="rsdl_bck4" title="'.$lang['srv_crosstab_residual_3'].'">&nbsp;</td>';
+ echo '<td class="rsdl_bck1" title="'.$lang['srv_crosstab_residual_4'].'">&nbsp;</td>';
+ echo '<td class="rsdl_bck2" title="'.$lang['srv_crosstab_residual_5'].'">&nbsp;</td>';
+ echo '<td class="rsdl_bck3" title="'.$lang['srv_crosstab_residual_6'].'">&nbsp;</td>';
+ echo '<td style="width:15px !important; text-align: center !important; font-weight: bold !important;">+</td>';
+ //echo '<td style="width:40px !important; text-align: center !important;"><span id="span_rsdl_legend_togle" class="as_link">'.$lang['srv_more'].'</span></td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</span>';
+ echo '<span class="floatLeft" style="padding-top:2px;">';
+ echo Help :: display('srv_crosstab_residual');
+ echo '</span>';
+
+ echo '</span>';
+
+ echo '<span id="span_color_residual_legend2" class="floatLeft displayNone">';
+ echo '<span class="floatLeft">';
+ echo '<label></label>';
+ echo '</span>';
+ echo '<span class="floatLeft">';
+ echo '<table id="tbl_color_residual" class="residual">';
+ echo '<tr><td>'.$lang['srv_analiza_crosstab_adjs_residual_long'].':&nbsp;&nbsp;&nbsp;&nbsp;</td><th>+</th><th>-</th></tr>';
+ echo '<tr><td class="anl_al">&nbsp;&nbsp;'.$lang['srv_crosstab_residual_3_0'].'</td><td class="rsdl_bck1 anl_dash_ba" title="'.$lang['srv_crosstab_residual_4'].'">&nbsp;</td><td class="rsdl_bck4 anl_dash_bt anl_dash_br anl_dash_bb" title="'.$lang['srv_crosstab_residual_3'].'">&nbsp;</td></tr>';
+ echo '<tr><td class="anl_al">&nbsp;&nbsp;'.$lang['srv_crosstab_residual_2_0'].'</td><td class="rsdl_bck2 anl_dash_bl anl_dash_bb" title="'.$lang['srv_crosstab_residual_5'].'">&nbsp;</td><td class="rsdl_bck5 anl_dash_br anl_dash_bb" title="'.$lang['srv_crosstab_residual_2'].'">&nbsp;</td></tr>';
+ echo '<tr><td class="anl_al">&nbsp;&nbsp;'.$lang['srv_crosstab_residual_1_0'].'</td><td class="rsdl_bck3 anl_dash_bl anl_dash_bb" title="'.$lang['srv_crosstab_residual_6'].'">&nbsp;</td><td class="rsdl_bck6 anl_dash_br anl_dash_bb" title="'.$lang['srv_crosstab_residual_1'].'">&nbsp;</td></tr>';
+ echo '</table>';
+ //echo '<span class="residual_link"><a href="http://www.1ka.si/db/19/308/Pogosta%20vprasanja/Kaj_pomenijo_residuali/?&p1=226&p2=735&p3=789&p4=0&p5=0&id=789&from1ka=1" target="_blank">'.$lang['srv_residual_link_faq'].'</a></span>';
+ echo '</span>';
+ echo '<span id="span_rsdl_legend_togle" class="floatLeft spaceLeft as_link">'.$lang['srv_less'].'</span>';
+ echo '<span class="floatLeft spaceLeft" style="padding-top:0px;">';
+ echo Help :: display('srv_crosstab_residual');
+ echo '</span>';
+
+ echo '</span>';
+
+
+ echo '<br />';
+ echo '<span id="span_color_residual_legend3" class="floatLeft '.($this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR == 4 ? '' : ' displayNone"').'" style="margin-top:10px; padding-left:18px;">';
+ echo '<span class="floatLeft">';
+ echo '<label>'.$lang['srv_analiza_crosstab_residuals'].'</label>';
+ echo '</span>';
+ echo '<span class="floatLeft">';
+ echo '<table id="tbl_color_residual_legend" >';
+ echo '<tr>';
+ echo '<td style="width:10px !important; text-align: center !important; font-weight: bold !important;"></td>';
+ echo '<td class="crossCheck_EC" title="'.$lang['srv_analiza_crosstab_expected_count'].'">&nbsp;</td>';
+ echo '<td class="crossCheck_RE" title="'.$lang['srv_analiza_crosstab_residual'].'">&nbsp;</td>';
+ echo '<td class="crossCheck_SR" title="'.$lang['srv_analiza_crosstab_stnd_residual'].'">&nbsp;</td>';
+ echo '<td class="crossCheck_AR" title="'.$lang['srv_analiza_crosstab_adjs_residual'].'">&nbsp;</td>';
+ echo '<td style="width:10px !important; text-align: center !important; font-weight: bold !important;"></td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</span>';
+ echo '<span class="floatLeft" style="padding-top:2px;">';
+ echo Help :: display('srv_crosstab_residual2');
+ echo '</span>';
+
+ echo '</span>';
+
+
+ echo '</span>';
+
+ echo '</div>';
+ echo '<br class="clr"/>';
+ }
+
+ public function displayCrosstabsTables() {
+
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile();
+
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString(true);
+
+ # če imamo rekodiranje
+ $SR = new SurveyRecoding($this->sid);
+ $SR -> getProfileString();
+
+ # preverimo ali imamo izbrano tretjo variablo
+ if ( $this->variabla_third == null || (int)$this->variabla_third == 0) {
+ # tretja variabla ni izbrana, nardimo navadne loope če obstajajo
+ $this->_LOOPS = SurveyZankaProfiles::getFiltersForLoops();
+ } else {
+ # tretja variabla je izbrana, zamenjamo loope z tretjo variablo
+ $this->_LOOPS = SurveyZankaProfiles::setLoopsForCrostabs($this->variabla_third);
+ }
+
+ if (count($this->_LOOPS) > 0) {
+ # če mamo zanke
+ foreach ( $this->_LOOPS AS $loop) {
+
+ $this->_CURRENT_LOOP = $loop;
+ echo '<h2>'.$lang['srv_zanka_note'].$loop['text'].'</h2>';
+ $this->displayCrosstabsTable();
+ echo '<br/>';
+ }
+ } else {
+ $this->displayCrosstabsTable();
+ }
+ }
+
+ public function displayCrosstabsTable() {
+ global $lang;
+ global $admin_type;
+
+ if ($this->getSelectedVariables(1) !== null && $this->getSelectedVariables(2) !== null) {
+ $variables1 = $this->getSelectedVariables(2);
+ $variables2 = $this->getSelectedVariables(1);
+ $counter = 0;
+ foreach ($variables1 AS $v_first) {
+ foreach ($variables2 AS $v_second) {
+
+ $crosstabs = null;
+ $crosstabs_value = null;
+
+ $crosstabs = $this->createCrostabulation($v_first, $v_second);
+
+ $crosstabs_value = $crosstabs['crosstab'];
+
+ # podatki spremenljivk
+ $spr1 = $this->_HEADERS[$v_first['spr']];
+ $spr2 = $this->_HEADERS[$v_second['spr']];
+
+ $grid1 = $spr1['grids'][$v_first['grd']];
+ $grid2 = $spr2['grids'][$v_second['grd']];
+
+ #število vratic in število kolon
+ $cols = count($crosstabs['options1']);
+ $rows = count($crosstabs['options2']);
+
+ # ali prikazujemo vrednosti variable pri spremenljivkah
+ $show_variables_values = $this->doValues;
+
+ # nastavitve oblike
+ if (($this->crossChk1 || $this->crossChk2 || $this->crossChk3) && ($this->crossChkEC || $this->crossChkRE || $this->crossChkSR || $this->crossChkAR)) {
+ # dodamo procente in residuale
+ $rowSpan = 3;
+ $numColumnPercent = $this->crossChk1 + $this->crossChk2 + $this->crossChk3;
+ $numColumnResidual = $this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR;
+ $tblColumn = max($numColumnPercent,$numColumnResidual);
+ } else if ($this->crossChk1 || $this->crossChk2 || $this->crossChk3) {
+ # imamo samo procente
+ $rowSpan = 2;
+ $numColumnPercent = $this->crossChk1 + $this->crossChk2 + $this->crossChk3;
+ $numColumnResidual = 1;
+ $tblColumn = $numColumnPercent;
+ } else if ($this->crossChkEC || $this->crossChkRE || $this->crossChkSR || $this->crossChkAR) {
+ # imamo samo residuale
+ $rowSpan = 2;
+ $numColumnPercent = 1;
+ $numColumnResidual = $this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR;
+ $tblColumn = $numColumnResidual;
+ } else {
+ #prikazujemo samo podatke
+ $rowSpan = 1;
+ $numColumnPercent = 1;
+ $numColumnResidual = 1;
+ $tblColumn = 1;
+ }
+
+ # za multicheckboxe popravimo naslov, na podtip
+ $sub_q1 = null;
+ $sub_q2 = null;
+ if ($spr1['tip'] == '6' || $spr1['tip'] == '7' || $spr1['tip'] == '16' || $spr1['tip'] == '17' || $spr1['tip'] == '18' || $spr1['tip'] == '19' || $spr1['tip'] == '20' || $spr1['tip'] == '21' ) {
+ foreach ($spr1['grids'] AS $grid) {
+ foreach ($grid['variables'] AS $variable) {
+ if ($variable['sequence'] == $v_first['seq']) {
+ $sub_q1 = '<span class="anl_variabla'.$sccFloat.'">';
+ $sub_q1 .= '<a href="/" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $v_first['spr'] . '\'); return false;">';
+ $sub_q1 .= strip_tags($spr1['naslov']);
+ if ($show_variables_values == true ) {
+ $sub_q1 .= '<span class="anl_variabla'.$sccFloat.'">';
+
+ $sub_q1 .= '&nbsp;('.strip_tags($spr1['variable']).')';
+
+ $sub_q1 .= '</span>';
+ }
+ if ($spr1['tip'] == '16') {
+ $sub_q1 .= '<br/>' . strip_tags($grid1['naslov']) . ($show_variables_values == true ? '&nbsp;(' . strip_tags($grid1['variable']) . ')' : '');
+ } else {
+ $sub_q1 .= '<br/>' . strip_tags($variable['naslov']) . ($show_variables_values == true ? '&nbsp;(' . strip_tags($variable['variable']) . ')' : '');
+ }
+ $sub_q1 .= '</a>';
+ $sub_q1 .= '</span>' . NEW_LINE;
+ }
+ }
+ }
+ }
+ if ($sub_q1 == null) {
+ $sub_q1 = '<span class="anl_variabla'.$sccFloat.'">';
+ $sub_q1 .= '<a href="/" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $v_first['spr'] . '\'); return false;">';
+ $sub_q1 .= strip_tags($spr1['naslov']);
+ $sub_q1 .= ($show_variables_values == true ? '&nbsp;('.strip_tags($spr1['variable']).')' : '');
+ $sub_q1 .= '</a>';
+ $sub_q1 .= '</span>' . NEW_LINE;
+ }
+ if ($spr2['tip'] == '6' || $spr2['tip'] == '7' || $spr2['tip'] == '16' || $spr2['tip'] == '17' || $spr2['tip'] == '18' || $spr2['tip'] == '19' || $spr2['tip'] == '20' || $spr2['tip'] == '21') {
+ foreach ($spr2['grids'] AS $grid) {
+ foreach ($grid['variables'] AS $variable) {
+ if ($variable['sequence'] == $v_second['seq']) {
+ $sub_q2 = '<span class="anl_variabla'.$sccFloat.'">';
+ $sub_q2 .= '<a href="/" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopupiza(\'' . $v_second['spr'] . '\'); return false;">';
+ $sub_q2 .= strip_tags($spr2['naslov']);
+ if ($show_variables_values == true) {
+ $sub_q2 .= '<span class="anl_variabla'.$sccFloat.'">';
+
+ $sub_q2 .= '&nbsp;('.strip_tags($spr2['variable']).')';
+
+ $sub_q2 .= '</span>';
+ }
+ if ($spr2['tip'] == '16') {
+ $sub_q2.= '<br/>' . strip_tags($grid2['naslov']) . ($show_variables_values == true ? '&nbsp;(' . strip_tags($grid2['variable']) . ')' : '');
+ } else {
+ $sub_q2.= '<br/>' . strip_tags($variable['naslov']) . ($show_variables_values == true ? '&nbsp;(' . strip_tags($variable['variable']) . ')' : '');
+ }
+ $sub_q2 .= '</a>';
+ $sub_q2 .= '</span>' . NEW_LINE;
+ }
+ }
+ }
+ }
+ if ($sub_q2 == null) {
+ $sub_q2 = '<span class="anl_variabla'.$sccFloat.'">';
+ $sub_q2 .= '<a href="/" title="' . $lang['srv_predogled_spremenljivka'] . '" onclick="showspremenljivkaSingleVarPopup(\'' . $v_second['spr'] . '\'); return false;">';
+ $sub_q2 .= strip_tags($spr2['naslov']);
+ $sub_q2 .= ($show_variables_values == true ? '&nbsp;('.strip_tags($spr2['variable']).')' : '');
+ $sub_q2 .= '</a>';
+ $sub_q2 .= '</span>' . NEW_LINE;
+ }
+ # izrišemo tabelo
+ # najprej izrišemo naslovne vrstice
+ #echo '<table class="anl_tbl_crosstab fullWidth fullHeight">';
+ echo $_br.'<br/>';
+# $_br = '<br/>';
+# echo '<div class="floatLeft">'.$sub_q1. '</div><div class="floatLeft spaceLeft spaceRight"> ==&gt; </div><div class="floatLeft">'. $sub_q2.'</div><br class="clr" />';
+
+ #Zadnja kolona: Če imamo vodoravno checkboxe in gledamo enote, potem kolono s summo malo razmaknemo
+ if ( $crosstabs['isCheckbox']['spr1'] == true && $this->crossNavVsEno == true) {
+ $addVerticalSpace = 1;
+ } else {
+ $addVerticalSpace = 0;
+ }
+
+ # hi2
+ if ($this->displayHi2 == true) {
+ echo '&#x3A7;<sup>2</sup> = ';
+ echo $this->formatNumber($crosstabs['hi2'], 3, '');
+ }
+
+ echo '<table class="anl_tbl_crosstab" style="padding:0px; margin:0px; margin-top:10px;"'
+ . ' sq1="'.$v_first['seq'].'" sp1="'.$v_first['spr'].'" gd1="'.$v_first['grd'].'" sq2="'.$v_second['seq'].'" sp2="'.$v_second['spr'].'" gd2="'.$v_second['grd'].'" >';
+
+ if ($this->fromBreak == false) {
+ echo '<colgroup>';
+ #echo '<col style="width:auto; min-width:150px;" />';
+ echo '<col style="width:auto; min-width:100px;" />';
+ if (count($crosstabs['options1']) > 0 ) {
+ $_width_percent = round(100 / count($crosstabs['options1'],2));
+ foreach ($crosstabs['options1'] as $ckey1 =>$crossVariabla) {
+ echo '<col style="width:'.$_width_percent.'%;" />';
+ }
+ }
+ if ($addVerticalSpace == 1) {
+ echo '<col style="width:10px;" />';
+ }
+ echo '<col style="width:auto;" />';
+ echo '</colgroup>';
+ }
+ echo '<tr>';
+ echo '<td class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll" rowspan="2" >';
+ #if ($cntY == 1) {
+ # ime variable
+ #echo '<td rowspan="' . $rows . '">';
+ echo $sub_q2;
+ #echo '</td>';
+ #}
+ echo '</td>';
+ echo '<td class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll" colspan="' . $cols . '" >';
+ echo $sub_q1;
+ echo '</td>';
+
+ echo '<td class="anl_bl">&nbsp;</td>';
+ if ($this->fromBreak == true && $this->showAverage == true) {
+ # če smo v break-u dodamo še povprečja
+ echo '<td class="">&nbsp;</td>';
+ }
+ echo '</tr>';
+ echo '<tr>';
+ $col_cnt=0;
+ if (count($crosstabs['options1']) > 0 ) {
+ foreach ($crosstabs['options1'] as $ckey1 =>$crossVariabla) {
+ $col_cnt++;
+ #ime variable
+ //$css_backX = 'rsdl_bck_variable'.($col_cnt & 1);
+ $css_backX = ' rsdl_bck_variable1';
+ echo '<td class="anl_bt anl_bl anl_ac'.$css_backX.' ctbCll" >';
+ echo $crossVariabla['naslov'];
+ # če ni tekstovni odgovor dodamo key
+ if ($crossVariabla['type'] != 't' && $show_variables_values == true) {
+ if ($crossVariabla['vr_id'] == null ) {
+ echo '<br/> ( '.$ckey1.' )';
+ } else {
+ echo '<br/> ( '.$crossVariabla['vr_id'].' )';
+ }
+ }
+ echo '</td>';
+ }
+ }
+ $col_cnt++;
+ //$css_backX = 'rsdl_bck_variable'.($col_cnt & 1);
+ if ($addVerticalSpace == 1) {
+ echo '<td class="anl_bl">&nbsp;</td>';
+ }
+ $css_backX = ' rsdl_bck_variable1';
+
+ echo '<td class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0'.$css_backX.' ctbCll">' . $lang['srv_analiza_crosstab_skupaj'] . '</td>';
+ if ($this->fromBreak == true && $this->showAverage == true) {
+ # če smo v break-u dodamo še povprečja
+ echo '<td class="anl_bl anl_bt anl_br anl_ac anl_ita anl_bck_text_0'.$css_backX.' ctbCll">' . $lang['srv_analiza_crosstab_average'] . '</td>';
+
+ }
+ echo '</tr>';
+
+ $cntY = 0;
+ if (count($crosstabs['options2']) > 0) {
+ foreach ($crosstabs['options2'] as $ckey2 =>$crossVariabla2) {
+ $cntY++;
+ echo '<tr>';
+
+
+ //$css_backY = 'rsdl_bck_variable'.($cntY & 1);
+ $css_backY = ' rsdl_bck_variable1';
+
+ echo '<td class="anl_bt anl_bl anl_ac'.$css_backY.' ctbCll">';
+
+ echo $crossVariabla2['naslov'];
+ # če ni tekstovni odgovor dodamo key
+ if ($crossVariabla2['type'] !== 't' && $show_variables_values == true ) {
+ if ($crossVariabla2['vr_id'] == null) {
+ echo '<br/> ( '.$ckey2.' )';
+ } else {
+ echo '<br/> ( '.$crossVariabla2['vr_id'].' )';
+ }
+
+ }
+ echo '</td>';
+
+ foreach ($crosstabs['options1'] as $ckey1 => $crossVariabla1) {
+ echo '<td class="ct_in_cell'.($this->enableInspect && ((int)$crosstabs_value[$ckey1][$ckey2] > 0) ? ' ct_inspect' : '').'" k1="'.$ckey1.'" k2="'.$ckey2.'" n1="'.$crossVariabla1['naslov'].'" n2="'.$crossVariabla2['naslov'].'" v1="'.$crossVariabla1['vr_id'].'" v2="'.$crossVariabla2['vr_id'].'">';
+ # celica z vebino
+ {
+ # prikazujemo eno ali več od: frekvenc, odstotkov, residualov
+ echo '<table class="ct_in_tbl">';
+ if ($this->crossChk0) {
+ # izpišemo frekvence crostabov
+ echo '<tr>';
+ echo '<td class="anl_ac '.($crosstabs['color'][$ckey1][$ckey2]).' ctbCll">';
+ echo ((int)$crosstabs_value[$ckey1][$ckey2] > 0) ? $crosstabs_value[$ckey1][$ckey2] : 0;
+ # .$crossTab[$crossVariabla1[cell_id]][$ckey2]
+ #
+
+ echo '</td>';
+ echo '</tr>';
+ }
+
+ if ($this->crossChk1 || $this->crossChk2 || $this->crossChk3) {
+ # sirina celice v %
+ if ( ($this->crossChk1 + $this->crossChk2 + $this->crossChk3) == 3 )
+ $css_width = ' ctb_w33p';
+ elseif (($this->crossChk1 + $this->crossChk2 + $this->crossChk3) == 2 )
+ $css_width = ' ctb_w50p';
+ else
+ $css_width = '';
+ $css_bt = ( $this->crossChk0 ) ? 'anl_dash_bt' : '';
+ # izpisemo procente
+ echo '<tr>';
+ echo '<td class="'.$css_bt.'">';
+
+ echo '<table class="anl_tbl_crosstab fullWidth fullHeight" style="padding:0px; margin:0px;">';
+ echo '<tr>';
+ $col=0;
+
+ if ($this->crossChk1) {
+ #procent vrstica
+ $col++;
+
+ $css_color = ($this->doColor == 'true') ? 'ctbChck_sp1' : 'ctbChck_sp0';
+ $css_br = $numColumnPercent > $col ? ' anl_dash_br' : '';
+ echo '<td class="'.$css_color.$css_br.$css_width.' ctbCll">';
+ echo $this->formatNumber($this->getCrossTabPercentage($crosstabs['sumaVrstica'][$ckey2], $crosstabs_value[$ckey1][$ckey2]), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk2) {
+ #procent stolpec
+ $col++;
+ $css_br = $numColumnPercent > $col ? ' anl_dash_br' : '';
+ $css_color = ($this->doColor == 'true') ? 'ctbChck_sp2' : 'ctbChck_sp0';
+ echo '<td class="'.$css_color.$css_br.$css_width.' ctbCll">';
+
+ echo $this->formatNumber($this->getCrossTabPercentage($crosstabs['sumaStolpec'][$ckey1], $crosstabs_value[$ckey1][$ckey2]), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk3) {
+ #procent skupni
+ $col++;
+ $css_br = $numColumnPercent > $col ? ' anl_dash_br' : '';
+ $css_color = ($this->doColor == 'true') ? 'ctbChck_sp3' : 'ctbChck_sp0';
+ echo '<td'.$css_br.$css_width.' class="'.$css_color.$css_br.' ctbCll">';
+
+ echo $this->formatNumber($this->getCrossTabPercentage($crosstabs['sumaSkupna'], $crosstabs_value[$ckey1][$ckey2]), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ echo '</tr>';
+ echo '</table>';
+
+ echo '</td>';
+ echo '</tr>';
+ }
+ # izpisemo residuale
+ if ($this->crossChkEC || $this->crossChkRE || $this->crossChkSR || $this->crossChkAR) {
+ # sirina celice v %
+ if ( ($this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR) == 4 )
+ $css_width = ' ctb_w25p';
+ elseif ( ($this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR) == 3 )
+ $css_width = ' ctb_w33p';
+ elseif ( ($this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR) == 2 )
+ $css_width = ' ctb_w50p';
+ else
+ $css_width = '';
+ $css_bt = ( $this->crossChk0 || ($this->crossChk1 && $this->crossChk2 && $this->crossChk3)) ? 'anl_dash_bt' : '';
+ echo '<tr>';
+
+ echo '<td class="'.$css_bt.'" style="padding:0px 0px;">';
+ echo '<table class="anl_tbl_crosstab fullWidth fullHeight" style="padding:0px; margin:0px;">';
+ echo '<tr>';
+ $col=0;
+
+ if ($this->crossChkEC) {
+ $col++;
+ $css_br = $numColumnResidual > $col ? ' anl_dash_br' : '';
+ $css_color = ($this->doColor == 'true') ? 'crossCheck_EC' : 'ctbChck_sp0';
+ echo '<td class="'.$css_color.$css_br.$css_width.' ctbCll">';
+ echo $this->formatNumber($crosstabs['exC'][$ckey1][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'), '');
+ echo '</td>';
+ }
+ if ($this->crossChkRE) {
+ $col++;
+ $css_br = $numColumnResidual > $col ? ' anl_dash_br' : '';
+ $css_color = ($this->doColor == 'true') ? 'crossCheck_RE' : 'ctbChck_sp0';
+ echo '<td class="'.$css_color.$css_br.$css_width.' ctbCll">';
+ echo $this->formatNumber($crosstabs['res'][$ckey1][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'), '');
+ echo '</td>';
+ }
+ if ($this->crossChkSR) {
+ $col++;
+ $css_br = $numColumnResidual > $col ? ' anl_dash_br' : '';
+ $css_color = ($this->doColor == 'true') ? 'crossCheck_SR' : 'ctbChck_sp0';
+ echo '<td class="'.$css_color.$css_br.$css_width.' ctbCll">';
+ echo $this->formatNumber($crosstabs['stR'][$ckey1][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'), '');
+ echo '</td>';
+ }
+ if ($this->crossChkAR) {
+ $col++;
+ $css_br = $numColumnResidual > $col ? ' anl_dash_br' : '';
+ $css_color = ($this->doColor == 'true') ? 'crossCheck_AR' : 'ctbChck_sp0';
+ echo '<td class="'.$css_color.$css_br.$css_width.' ctbCll">';
+ echo $this->formatNumber($crosstabs['adR'][$ckey1][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'), '');
+ echo '</td>';
+ }
+ echo '</tr>';
+ echo '</table>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ }
+ # konec celice z vsebino
+ echo '</td>';
+ }
+ # če mamo checkboxe in sumo malo razmaknemo
+ if ($addVerticalSpace == 1) {
+ echo '<td class="anl_bl">&nbsp;</td>';
+ }
+
+ // vedno rišemo zadnji stolpec.
+ echo '<td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 anl_bb" >';
+ echo '<table class="anl_tbl_crosstab fullWidth fullHeight" style="padding:0px; margin:0px;">';
+ if ($this->crossChk0) {
+ echo '<tr>';
+ echo '<td class="anl_ac ctbCll crostabSuma" colspan="' . ( $this->crossChk1 + $this->crossChk2 + $this->crossChk3 ).'">';
+ # suma po vrsticah
+ echo (int)$crosstabs['sumaVrstica'][$ckey2];
+ echo '</td>';
+ echo '</tr>';
+ }
+ if ($this->crossChk1 || $this->crossChk2 || $this->crossChk3) {
+ if (($this->crossChk1 + $this->crossChk2 + $this->crossChk3) == 3) {
+ $css_width = ' ctb_w33p';
+ } else if (($this->crossChk1 + $this->crossChk2 + $this->crossChk3) == 2) {
+ $css_width = ' ctb_w50p';
+ } else {
+ $css_width = '';
+ }
+ $css_bt = ( $this->crossChk0 ) ? ' anl_dash_bt' : '';
+ # suma po vrsticah v procentih
+ echo '<tr>';
+ if ($this->crossChk1) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp1' : 'ctbChck_sp0';
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.$css_width.'">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk2) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp2' : 'ctbChck_sp0';
+ $css_border = ($this->crossChk1 ? ' anl_dash_bl ' : '');
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.$css_border.$css_width.'">';
+ echo $this->formatNumber( ($crosstabs['sumaSkupna'] > 0 ? (100 * $crosstabs['sumaVrstica'][$ckey2] / $crosstabs['sumaSkupna']) : 0), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk3) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp3' : 'ctbChck_sp0';
+ $css_border = ($this->crossChk1 || $this->crossChk2 ? ' anl_dash_bl ' : '');
+ echo '<td class="anl_ac'.$css_color.$css_bt.$css_border.$css_width.' ctbCll">';
+ echo $this->formatNumber( ($crosstabs['sumaSkupna'] > 0 ? (100 * $crosstabs['sumaVrstica'][$ckey2] / $crosstabs['sumaSkupna']) : 0), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+ echo '</td>';
+ if ($this->fromBreak == true && $this->showAverage == true) {
+ # če smo v break dodamo še povprečja
+ echo '<td class="anl_ac anl_bl anl_bt anl_br anl_bb rsdl_bck_variable1" >';
+ echo $this->formatNumber( $crosstabs['avgVrstica'][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'), '');
+ echo '</td>';
+ }
+ echo '</tr>';
+ }
+ }
+ #Zadnja vrstica. Če imamo navpično checkboxe in gledamo enote, potem vrstico z summo malo razmaknemo
+ $cssBT = 'anl_bt';
+ if ( $crosstabs['isCheckbox']['spr2'] == true && $this->crossNavVsEno == true) {
+ echo '<tr>';
+ echo '<td class="'.$cssBT.'">&nbsp;</th>';
+ echo '<td class="'.$cssBT.'">&nbsp;</th>';
+ echo '<td class="'.$cssBT.'" colspan="'.count($crosstabs['options1']).'">&nbsp;</th>';
+ if ($addVerticalSpace == 1) {
+ echo '<td class="">&nbsp;</td>';
+ }
+
+ echo '<td class="'.$cssBT.'">&nbsp;</th>';
+ echo '</tr>';
+ $cssBT = '';
+ }
+
+ $cntY++;
+ echo '<tr>';
+ $css_backY = ' rsdl_bck_variable1';
+ echo '<td class="anl_bb anl_bt anl_bl anl_ac red anl_ita anl_bck_text_0'.$css_backY.' ctbCll">' . $lang['srv_analiza_crosstab_skupaj'] . '</td>';
+ // skupni sestevki po stolpcih
+ if (count($crosstabs['options1']) > 0)
+ foreach ($crosstabs['options1'] as $ckey1 => $crossVariabla1) {
+ echo '<td class="anl_ac anl_bb anl_bt anl_bl rsdl_bck0" >';
+ {
+ # prikazujemo eno od treh možnosti
+ echo '<table class="anl_tbl_crosstab fullWidth fullHeight" style="padding:0px; margin:0px;">';
+ if ($this->crossChk0) {
+ echo '<tr>';
+ echo '<td class="anl_ac ctbCll crostabSuma" colspan="'.($this->crossChk1 + $this->crossChk2 + $this->crossChk3).'">';
+ # suma po stolpcih
+ echo (int)$crosstabs['sumaStolpec'][$ckey1];
+ echo '</td>';
+ echo '</tr>';
+ }
+ if ($this->crossChk1 || $this->crossChk2 || $this->crossChk3) {
+ # suma po stolpcih v procentih
+ $css_bt = ($this->crossChk0) ? ' anl_dash_bt' : '';
+ echo '<tr>';
+ if ($this->crossChk1) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp1' : 'ctbChck_sp0';
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.'">';
+ echo $this->formatNumber( ($crosstabs['sumaSkupna'] > 0 ? (100 * $crosstabs['sumaStolpec'][$ckey1] / $crosstabs['sumaSkupna']) : 0), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk2) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp2' : 'ctbChck_sp0';
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.($this->crossChk1 ? ' anl_dash_bl' : '').'">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk3)
+ {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp3' : 'ctbChck_sp0';
+ echo '<td class="anl_ac'.$css_color.$css_bt.($this->crossChk2 ? ' anl_dash_bl' : '').' ctbCll">';
+ echo $this->formatNumber( ($crosstabs['sumaSkupna'] > 0 ? (100 * $crosstabs['sumaStolpec'][$ckey1] / $crosstabs['sumaSkupna']) : 0), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ echo '</tr>';
+ }
+ echo '</table>';
+ }
+ echo '</td>';
+ }
+ # če mamo checkboxe in sumo malo razmaknemo
+ if ($addVerticalSpace == 1) {
+ echo '<td class="anl_bl">&nbsp;</td>';
+ }
+
+ # zadnja celica z skupno sumo
+ echo '<td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0">';
+ {
+ echo '<table class="anl_tbl_crosstab fullWidth fullHeight" style="padding:0px; margin:0px;">';
+ if ($this->crossChk0) {
+ echo '<tr>';
+ echo '<td class="anl_ac ctbCll crostabSuma" colspan="'.($this->crossChk1 + $this->crossChk2 + $this->crossChk3).'">';
+ # skupna suma
+ echo (int)$crosstabs['sumaSkupna'];
+ echo '</td>';
+ echo '</tr>';
+ }
+ if ($this->crossChk1 || $this->crossChk2 || $this->crossChk3) {
+ # suma po stolpcih v procentih
+ $css_bt = ($this->crossChk0) ? ' anl_dash_bt' : '';
+ echo '<tr>';
+ if ($this->crossChk1) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp1' : 'ctbChck_sp0';
+ $css_border = ($this->crossChk2 || $this->crossChk3) ? ' anl_dash_br' : '';
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.$css_border.'">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk2) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp2' : 'ctbChck_sp0';
+ $css_border = ($this->crossChk3) ? ' anl_dash_br' : '';
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.$css_border.'">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ if ($this->crossChk3) {
+ $css_color = ($this->doColor == 'true') ? ' ctbChck_sp3' : 'ctbChck_sp0';
+ echo '<td class="anl_ac ctbCll'.$css_color.$css_bt.'">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td>';
+ }
+ echo '</tr>';
+ }
+ echo '</table>';
+ }
+ echo '</td>';
+ if ($this->fromBreak == true && $this->showAverage == true) {
+ # če smo v break dodamo še povprečja
+ echo '<td class="anl_bl anl_bt" >';
+ echo '&nbsp;';
+ echo '</td>';
+ }
+ echo '</tr>';
+ #xxx
+ #zadnja vrstica z povprečji - iz break
+ if ($this->showBottomAverage == true && $crosstabs['isCheckbox']['spr2'] == false) {
+ echo '<tr>';
+ $css_backY = ' rsdl_bck_variable1';
+ echo '<td class="anl_bb anl_bt anl_bl anl_br anl_ac anl_ita anl_bck_text_0'.$css_backY.' ctbCll">' . $lang['srv_analiza_crosstab_average'] . '</td>';
+ // skupni sestevki po stolpcih
+ if (count($crosstabs['options1']) > 0) {
+ foreach ($crosstabs['options1'] as $ckey1 => $crossVariabla1) {
+ echo '<td class="anl_ac anl_bb anl_bt anl_br rsdl_bck_variable1" >';
+ echo $this->formatNumber( $crosstabs['avgStolpec'][$ckey1], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'), '');
+ echo '</td>';
+ }
+ }
+ # če mamo checkboxe in sumo malo razmaknemo
+ if ($addVerticalSpace == 1) {
+ echo '<td>&nbsp;</td>';
+ }
+
+ # zadnja celica z skupno sumo
+ echo '<td>&nbsp;</td>';
+ if ($this->fromBreak == true && $this->showAverage == true) {
+ # če smo v break dodamo še povprečja
+ echo '<td>&nbsp;</td>';
+ }
+ echo '</tr>';
+ }
+ echo '</table>';
+
+ // Zvezdica za vkljucitev v porocilo
+ $spr2 = $v_first['seq'].'-'.$v_first['spr'].'-'.$v_first['grd'];
+ $spr1 = $v_second['seq'].'-'.$v_second['spr'].'-'.$v_second['grd'];
+
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type=5, $sub_type=0, $spr1, $spr2);
+ #SurveyAnalysis::addCustomReportElement($type=5, $sub_type=0, $spr1, $spr2);
+
+ // Izrisemo graf za tabelo
+ if($this->showChart && !$this->fromBreak){
+ $tableChart = new SurveyTableChart($this->sid, $this, 'crosstab', $counter);
+ $tableChart->display();
+ }
+
+ $counter++;
+ }
+ }
+ } else {
+ # crostab variables not set
+ echo $lang['srv_crosstab_note0'];
+ #print_r("Crosstab variables not set!");
+ }
+ }
+
+ /**
+ * @desc prikaze izvoz za PDF/RTF
+ */
+ function displayExport () {
+ # z javascriptom prikažemo ikonce za arhiviranje, emaijlanje arhivov, pdf, rtf, excel...
+ if ($this->isSelectedBothVariables()) {
+ $data1 = '';
+ $data2 = '';
+
+ foreach($this->variabla1 as $var1){
+ $data1 .= implode(',', array_values($var1)).',';
+ }
+ $data1 = substr($data1, 0, -1);
+
+ foreach($this->variabla2 as $var2){
+ $data2 .= implode(',', array_values($var2)).',';
+ }
+ $data2 = substr($data2, 0, -1);
+
+ $href_print = makeEncodedIzvozUrlString('izvoz.php?b=export&m=crosstabs_izpis&anketa=' . $this->sid . '&data1='.$data1.'&data2='.$data2);
+ $href_pdf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=crosstabs_izpis&anketa=' . $this->sid . '&data1='.$data1.'&data2='.$data2);
+ $href_rtf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=crosstabs_izpis_rtf&anketa=' . $this->sid . '&data1='.$data1.'&data2='.$data2);
+ $href_xls = makeEncodedIzvozUrlString('izvoz.php?b=export&m=crosstabs_izpis_xls&anketa=' . $this->sid . '&data1='.$data1.'&data2='.$data2);
+ echo '<script>';
+ # nastavimopravilne linke
+ echo '$("#secondNavigation_links a#crosstabDoPdf").attr("href", "'.$href_pdf.'");';
+ echo '$("#secondNavigation_links a#crosstabDoRtf").attr("href", "'.$href_rtf.'");';
+ echo '$("#secondNavigation_links a#crosstabDoXls").attr("href", "'.$href_xls.'");';
+ # prikažemo linke
+ echo '$("#hover_export_icon").removeClass("hidden");';
+ echo '$("#secondNavigation_links a").removeClass("hidden");';
+ echo '</script>';
+
+ }
+
+ }
+
+ /** kadar kličemo iz Break, ali pri radio grupi dodamo še povprečje po stolpcih
+ *
+ * @param unknown_type $showBottomAverage
+ */
+ function showBottomAverage ($showBottomAverage = false) {
+ $this->showBottomAverage = $showBottomAverage ;
+ }
+ /**
+ * @desc nastavimo spremenljivke/variable za prikaz pdf/rtf
+ */
+ function setVariables($seq1, $spr1, $grd1, $seq2, $spr2, $grd2){
+
+ $this->variabla1[0]['seq'] = $seq1;
+ $this->variabla1[0]['spr'] = $spr1;
+ $this->variabla1[0]['grd'] = $grd1;
+
+ $this->variabla2[0]['seq'] = $seq2;
+ $this->variabla2[0]['spr'] = $spr2;
+ $this->variabla2[0]['grd'] = $grd2;
+ }
+
+
+ public function createCrostabulation($v_first, $v_second) {
+ global $site_path;
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ($this->dataFileName != '' && file_exists($this->dataFileName)) {
+
+ $spr1 = $this->_HEADERS[$v_first['spr']];
+ $spr2 = $this->_HEADERS[$v_second['spr']];
+
+ $grid1 = $spr1['grids'][$v_first['grd']];
+ $grid2 = $spr2['grids'][$v_second['grd']];
+
+ $sequence1 = $v_first['seq'];
+ $sequence2 = $v_second['seq'];
+
+ # za checkboxe gledamo samo odgovore ki so bili 1 in za vse opcije
+ $sekvences1 = array();
+ $sekvences2 = array();
+ $spr_1_checkbox = false;
+ $spr_2_checkbox = false;
+ if ($spr1['tip'] == 2 || $spr1['tip'] == 16) {
+ $spr_1_checkbox = true;
+ if ($spr1['tip'] == 2) {
+ if (count($spr1['grids'][0]['variables']) > 0)
+ foreach ($spr1['grids'][0]['variables'] AS $_vkey =>$_variable) {
+ if ((int)$_variable['text'] != 1) {
+ $sekvences1[] = $_variable['sequence'];
+ }
+ } else {
+ $sekvences1 = explode('_',$spr1['sequences']);
+ }
+ }
+ if ($spr1['tip'] == 16) {
+
+ foreach ($grid1['variables'] AS $_variables) {
+
+ $sekvences1[] = $_variables['sequence'];
+ }
+
+ #$sekvences1 = explode('_',$this->_HEADERS[$v_first['spr']]['sequences']);
+ }
+ } else {
+ $sekvences1[] = $sequence1;
+ }
+
+ if ($spr2['tip'] == 2 || $spr2['tip'] == 16) {
+ $spr_2_checkbox = true;
+ if ($spr2['tip'] == 2 ) {
+ if (count($this->_HEADERS[$v_second['spr']]['grids'][0]['variables']) > 0)
+ foreach ($this->_HEADERS[$v_second['spr']]['grids'][0]['variables'] AS $_vkey =>$_variable) {
+ if ((int)$_variable['text'] != 1) {
+ $sekvences2[] = $_variable['sequence'];
+ }
+
+ } else {
+ $sekvences2 = explode('_',$this->_HEADERS[$v_second['spr']]['sequences']);
+ }
+
+ }
+ if ($spr2['tip'] == 16) {
+ foreach ($grid2['variables'] AS $_variables) {
+ $sekvences2[] = $_variables['sequence'];
+ }
+ #$sekvences2 = explode('_',$this->_HEADERS[$v_second['spr']]['sequences']);
+ }
+ } else {
+ $sekvences2[] = $sequence2;
+ }
+ # pogoji so že dodani v _CURRENT_STATUS_FILTER
+
+ # dodamo filter za loop-e
+ if (isset($this->_CURRENT_LOOP['filter']) && $this->_CURRENT_LOOP['filter'] != '') {
+ $status_filter = $this->_CURRENT_STATUS_FILTER.' && '.$this->_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+ }
+
+
+ # dodamo status filter za vse sekvence checkbox-a da so == 1
+ if ($additional_status_filter != null) {
+ $status_filter .= $additional_status_filter;
+ }
+
+ # odstranimo vse zapise, kjer katerakoli od variabel vsebuje missing
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_pageMissing_answers = $this->getInvalidAnswers (MISSING_TYPE_CROSSTAB);
+
+ # polovimo obe sequenci
+ $tmp_file = $folder . 'tmp_crosstab_'.$this->sid.'.TMP';
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+ if (count($sekvences1)>0)
+ foreach ($sekvences1 AS $sequence1) {
+ if (count($sekvences2)>0)
+ foreach ($sekvences2 AS $sequence2) {
+ #skreira variable: $crosstab, $cvar1, $cvar2
+
+ $additional_filter = '';
+ if ($spr_1_checkbox == true) {
+ $_seq_1_text = ''.$sequence1;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter = ' && ($'.$sequence1.' == 1)';
+ } else {
+ $_seq_1_text = '$'.$sequence1;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key1 => $missing1) {
+ $additional_filter .= ' && ($'.$sequence1.' != '.$m_key1.')';
+ }
+ }
+
+ if ($spr_2_checkbox == true) {
+ $_seq_2_text = ''.$sequence2;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter .= ' && ($'.$sequence2.' == 1)';
+ } else {
+ $_seq_2_text = '$'.$sequence2;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key2 => $missing2) {
+ $additional_filter .= ' && ($'.$sequence2.' != '.$m_key2.')';
+ }
+ }
+
+ if (IS_WINDOWS) {
+ #$command = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$_status_filter.' { print \"$crosstab[\x27\",$'.$sequence1.',\"\x27][\x27\",$'.$sequence2.',\"\x27]++; $options1[\x27\",$'.$sequence1.',\"\x27]++; $options2[\x27\",$'.$sequence2.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$additional_filter.' { print \"$crosstab[\x27\",'.$_seq_1_text.',\"\x27][\x27\",'.$_seq_2_text.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ #$command = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$_status_filter.' { print "$crosstab[\x27",$'.$sequence1.',"\x27][\x27",$'.$sequence2.',"\x27]++; $options1[\x27",$'.$sequence1.',"\x27]++; $options2[\x27",$'.$sequence2.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ $command = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$additional_filter.' { print "$crosstab[\x27",'.$_seq_1_text.',"\x27][\x27",'.$_seq_2_text.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out = shell_exec($command);
+ }
+
+ }
+
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ #ker z awk ne gre nardit tolower zaradi šumnikov, nardimo ročno v loopu
+ $caseInsensitiveCrosstab = array();
+ if (count($crosstab) > 0) {
+ foreach ($crosstab as $fkey => $fvalue) {
+ $fkey = mb_strtolower($fkey,'UTF-8');
+ if (count($fvalue) > 0) {
+ foreach ($fvalue as $skey => $svalue) {
+ $skey = mb_strtolower($skey,'UTF-8');
+ $caseInsensitiveCrosstab[$fkey][$skey] += $svalue;
+ }
+ }
+ }
+ }
+ $crosstab = $caseInsensitiveCrosstab;
+ # poiščemo pripadajočo spremenljivko
+ $var_options1 = $this->_HEADERS[$v_first['spr']]['options'];
+ $var_options2 = $this->_HEADERS[$v_second['spr']]['options'];
+
+ # inicializacija
+ $_all_options1 = array();
+ $_all_options2 = array();
+ $sumaStolpec = array();
+ $sumaVrstica = array();
+ $sumaSkupna = 0;
+
+ # najprej poiščemo (združimo) vse opcije ki so definirane kot opcije spremenljivke in vse ki so v crosstabih
+ if (count($var_options1) > 0 && $spr_1_checkbox !== true ) {
+ foreach ($var_options1 as $okey => $opt) {
+ $_all_options1[$okey] = array('naslov'=>$opt, 'cnt'=>$options1[$okey], 'type'=>'o');
+ }
+ }
+ if (count($var_options2) > 0 && $spr_2_checkbox !== true) {
+ foreach ($var_options2 as $okey => $opt) {
+ $_all_options2[$okey] = array('naslov'=>$opt, 'cnt'=>$options2[$okey], 'type'=>'o');
+ }
+ }
+ # za checkboxe dodamo posebej vse opcije
+ if ($spr_1_checkbox == true ) {
+ if ($spr1['tip'] == 2 ) {
+ $grid1 =$this->_HEADERS[$v_first['spr']]['grids']['0'];
+ }
+
+ foreach ($grid1['variables'] As $vkey => $variable) {
+ if ($variable['other'] != 1) {
+ $_all_options1[$variable['sequence']] = array('naslov'=>$variable['naslov'], 'cnt'=>0, 'type'=>'o', 'vr_id'=> $variable['variable']);
+ }
+ }
+ }
+
+ if ($spr_2_checkbox == true ) {
+ if ($spr2['tip'] == 2 ) {
+ $grid2 =$this->_HEADERS[$v_second['spr']]['grids']['0'];
+ }
+
+ foreach ($grid2['variables'] As $vkey => $variable) {
+ if ($variable['other'] != 1) {
+ $_all_options2[$variable['sequence']] = array('naslov'=>$variable['naslov'], 'cnt'=>0, 'type'=>'o', 'vr_id'=> $variable['variable']);
+ }
+ }
+ }
+
+ # dodamo odgovore iz baze ki niso missingi
+ if (count($crosstab) > 0 ) {
+ foreach ($crosstab AS $_kvar1=>$_var1) {
+ # missingov ne dodajamo še zdaj, da ohranimo pravilen vrstni red
+ if (!isset($_allMissing_answers[$_kvar1]) && !isset($_all_options1[$_kvar1])) {
+ $_all_options1[$_kvar1] = array('naslov'=>$_kvar1, 'cnt'=>($_all_options1[$_kvar1]['cnt']+1), 'type'=>'t');
+ }
+
+ foreach ($_var1 AS $_kvar2=>$_var2) {
+ if (!isset($_allMissing_answers[$_kvar1]) || (isset($_allMissing_answers[$_kvar1]) && isset($_pageMissing_answers[$_kvar1]))) {
+ $sumaStolpec[$_kvar1] += $_var2;
+ }
+ if (!isset($_allMissing_answers[$_kvar2]) || (isset($_allMissing_answers[$_kvar2]) && isset($_pageMissing_answers[$_kvar2]))) {
+ $sumaVrstica[$_kvar2] += $_var2;
+ }
+ # missingov ne dodajamo še zdaj, da ohranimo pravilen vrstni red
+ if (!isset($_allMissing_answers[$_kvar2]) && !isset($_all_options2[$_kvar2])) {
+ $_all_options2[$_kvar2] = array('naslov'=>$_kvar2, 'cnt'=>($_all_options1[$_kvar2]['cnt']+1), 'type'=>'t');
+ }
+
+ }
+ }
+ }
+ /*
+ # dodamo še missinge, samo tiste ki so izbrani z profilom
+ if (count($_pageMissing_answers) > 0 ) {
+ foreach ($_pageMissing_answers as $mkey => $missing ) {
+ if ( $spr_1_checkbox !== true) {
+ $_all_options1[$mkey] = array('naslov'=>$missing['text'], 'cnt'=>(int)$options1[$mkey], 'type'=>'m');
+ }
+ if ( $spr_2_checkbox !== true ) {
+ $_all_options2[$mkey] = array('naslov'=>$missing['text'], 'cnt'=>(int)$options2[$mkey], 'type'=>'m');
+ }
+ }
+ }
+ */
+ # dodamo še missinge, samo tiste ki so izbrani z profilom
+ foreach ($_allMissing_answers AS $miskey => $_missing) {
+ if (!isset($_pageMissing_answers[$miskey])) {
+ if ( $spr_1_checkbox !== true) {
+ $_all_options1[$miskey] = array('naslov'=>$_missing, 'cnt'=>(int)$options1[$miskey], 'type'=>'m');
+ }
+ if ( $spr_2_checkbox !== true ) {
+ $_all_options2[$miskey] = array('naslov'=>$_missing, 'cnt'=>(int)$options2[$miskey], 'type'=>'m');
+ }
+ }
+ }
+ $sumaSkupna = max(array_sum($sumaStolpec), array_sum($sumaVrstica));
+
+ # če lovimo po enotah, moramo skupne enote za vsako kolono(vrstico) izračunati posebej - POPRAVLJENO KER TO MORA VERJETNO NAREDIT SAMO CE STA OBE SPR CHECKBOXA??
+ //if ($this->crossNavVsEno == 1) {
+ if ($spr_1_checkbox == true && $spr_2_checkbox == true && $this->crossNavVsEno == 1) {
+ $sumaSkupna = 0;
+ $sumaStolpec = array();
+ $sumaVrstica = array();
+
+ # sestavimo filtre za posamezno variablo da ni missing
+ if (count($sekvences1)>0) {
+ $spr1_addFilter = '';
+
+ foreach ($sekvences1 AS $sequence1) {
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key1 => $missing1) {
+ $spr1_addFilter .= ' && ($'.$sequence1.' != '.$m_key1.')';
+ }
+ }
+ }
+ if (count($sekvences2)>0) {
+ $spr2_addFilter = '';
+
+ foreach ($sekvences2 AS $sequence2) {
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key2 => $missing2) {
+ $spr2_addFilter .= ' && ($'.$sequence2.' != '.$m_key2.')';
+ }
+ }
+ }
+
+ # polovimo obe sequenci
+ $tmp_file = $folder . 'tmp_crosstab_'.$this->sid.'.TMP';
+
+
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+
+ fclose($file_handler);
+
+ # preštejemo vse veljavne enote (nobena vrednost ne sme bit missing)
+
+
+ if (IS_WINDOWS) {
+ $command_all = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$spr1_addFilter.$spr2_addFilter.' { print \"$sumaSkupna++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command_all = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$spr1_addFilter. $spr2_addFilter.' { print "$sumaSkupna++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out_all = shell_exec($command_all);
+
+
+ #za vsako variablo polovimo število enot
+ #najprej za stolpce
+ if (count($sekvences1)>0) {
+ foreach ($sekvences1 AS $sequence1) {
+ if ($spr_1_checkbox == true) {
+ $_seq_1_text = ''.$sequence1;
+ # pri checkboxih lovimo samo tiste ki so 1
+ $chckbox_filter1 = ' && ($'.$sequence1.' == 1)';
+ } else {
+ $_seq_1_text = '$'.$sequence1;
+ }
+
+ if (IS_WINDOWS) {
+ $command_1 = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$chckbox_filter1.$spr2_addFilter.' { print \"$sumaStolpec[\x27\",'.$_seq_1_text.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command_1 = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$chckbox_filter1.$spr2_addFilter.' { print "$sumaStolpec[\x27",'.$_seq_1_text.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+ $out = shell_exec($command_1);
+ }
+ }
+ #nato še za vrstice
+ if (count($sekvences2)>0) {
+ foreach ($sekvences2 AS $sequence2) {
+ if ($spr_2_checkbox == true) {
+ $_seq_2_text = ''.$sequence2;
+ # pri checkboxih lovimo samo tiste ki so 1
+ $chckbox_filter2 = ' && ($'.$sequence2.' == 1)';
+ } else {
+ $_seq_2_text = '$'.$sequence2;
+ }
+
+ if (IS_WINDOWS) {
+ $command_2 = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$chckbox_filter2.$spr1_addFilter.' { print \"$sumaVrstica[\x27\",'.$_seq_2_text.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command_2 = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$chckbox_filter2.$spr1_addFilter.' { print "$sumaVrstica[\x27",'.$_seq_2_text.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+ $out = shell_exec($command_2);
+ }
+ }
+
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+ }
+
+ $CSS_COLOR0 = ' rsdl_bck0';
+ $CSS_COLOR1 = ' rsdl_bck1';
+ $CSS_COLOR2 = ' rsdl_bck2';
+ $CSS_COLOR3 = ' rsdl_bck3';
+ $CSS_COLOR4 = ' rsdl_bck4';
+ $CSS_COLOR5 = ' rsdl_bck5';
+ $CSS_COLOR6 = ' rsdl_bck6';
+
+ # izracunamo se pricakovano vrednost, in residuale
+ # exC - expected count (pricakovana vrednost)
+ $exC = array();
+ # res - residual
+ $res = array();
+ # stR - standardized residual
+ $stR = array();
+ # adR - adjusted residual
+ $adR = array();
+ #color - array kjer shranjujemo barvo celice v odvisnosti od adjusted residuala
+ $color = array();
+ #pocprečje vrstice
+ $sum_avgi = array();
+ #pocprečje stolpca
+ $sum_avgj = array();
+
+ $_w = 0;
+ $_fij = 0;
+ $_ri = 0;
+ $_cj = 0;
+ $_exC = 0;
+ $_res = 0;
+ $_stR = 0;
+ $_ri_div_w = 0;
+ $_cj_div_w = 0;
+ $_sqrt_part = 0;
+ $_adR = 0;
+ $_limit = 0;
+
+ $cnt1 = count($_all_options1);
+ $cnt2 = count($_all_options2);
+
+ # gremo skozi vsako celico
+ if ($cnt1 > 0 && $cnt2) {
+ foreach ($_all_options1 as $ckey1 => $crossVariabla1) {
+ if($sumaStolpec[$ckey1]!=null) {
+ foreach ($_all_options2 as $ckey2 => $crossVariabla2) {
+ if($sumaVrstica[$ckey2]!=null) {
+ # skupna suma
+ $_w = $sumaSkupna;
+ #frekvenca celice
+ $_fij = $crosstab[$ckey1][$ckey2];
+ #suma vrstice
+ $_ri = $sumaVrstica[$ckey2];
+ #suma stolpca
+ $_cj = $sumaStolpec[$ckey1];
+
+ # povprečje vrstice
+ $sum_avgi[$ckey2] += ((int)$_ri != 0) ? ((int)$_fij * (int)$ckey1 / (int)$_ri) : 0;
+
+ # povprečje stolpcev
+ $sum_avgj[$ckey1] += ((int)$_cj != 0) ? ((int)$_fij * (int)$ckey2 / (int)$_cj) : 0;
+
+ # exC - expected count (pricakovana vrednost
+ $_exC = ($_w > 0 ) ? (( $_ri * $_cj) / $_w) : 0;
+ $exC[$ckey1][$ckey2] = $_exC;
+ # res - residual
+ $_res = $_fij - $_exC;
+ $res[$ckey1][$ckey2] = $_res;
+ # stR - standardized residual
+ $_stR = ($_exC != 0) ? $_res / sqrt($_exC) : 0;
+ $stR[$ckey1][$ckey2] = $_stR;
+ # adR - adjusted residual
+ $_ri_div_w = ($_w != 0) ? ($_ri / $_w) : 0;
+ $_cj_div_w = ($_w != 0) ? ($_cj / $_w) : 0;
+ $_sqrt_part = $_exC * (1 - $_ri_div_w ) * (1 - $_cj_div_w );
+ $_adR = ($_sqrt_part != 0) ? $_res / sqrt($_sqrt_part ) : 0;
+
+ $adR[$ckey1][$ckey2] = $_adR;
+ #privzeto je belo
+ $color[$ckey1][$ckey2] = $CSS_COLOR0;
+ # katera vrednost nam je limit (prilagojen residual)
+ $_limit = $_adR;
+ if ($this->doColor == 'true') {
+ # če imamo barvanje residualov še pobarvamo v odvisnosti od prilagojenega residuala
+ if (abs($_limit) >= RESIDUAL_COLOR_LIMIT1)
+ $color[$ckey1][$ckey2] = $_limit > 0 ? $CSS_COLOR1 : $CSS_COLOR4;
+ if (abs($_limit) >= RESIDUAL_COLOR_LIMIT2)
+ $color[$ckey1][$ckey2] = $_limit > 0 ? $CSS_COLOR2 : $CSS_COLOR5;
+ if (abs($_limit) >= RESIDUAL_COLOR_LIMIT3)
+ $color[$ckey1][$ckey2] = $_limit > 0 ? $CSS_COLOR3 : $CSS_COLOR6;
+ }
+ } else {
+ if ($cnt2 > AUTO_HIDE_ZERRO_VALUE) {
+ unset($_all_options2[$ckey2]);
+ }
+ }
+ }
+ } else {
+ if ($cnt1 > AUTO_HIDE_ZERRO_VALUE) {
+ unset($_all_options1[$ckey1]);
+ }
+ }
+ }
+ }
+
+ # izračunamo še hi^2
+ $hi2 = 0;
+ if ($cnt1 > 0 && $cnt2)
+ foreach ($_all_options1 as $ckey1 => $crossVariabla1) {
+ foreach ($_all_options2 as $ckey2 => $crossVariabla2) {
+ $fr = (float)$crosstab[$ckey1][$ckey2];
+ $exp = (float)$exC[$ckey1][$ckey2];
+ if ($exp != 0) {
+ $hi2 += pow(($fr - $exp),2) / $exp;
+ }
+ #dejanska frekvenca
+
+ }
+ }
+ return(array(
+ 'crosstab' => $crosstab, # krostabulacije - frekvence
+ 'options1' => $_all_options1, # vse opcije za variablo 1
+ 'options2' => $_all_options2, # vse opcije za variablo 2
+ 'exC' => $exC, # pričakovana vrednost
+ 'res' => $res, # res - residual
+ 'stR' => $stR, # stR - standardized residual
+ 'adR' => $adR, # adR - adjusted residual
+ 'color' => $color, #color - array kjer shranjujemo barvo celice v odvisnosti od adjusted residuala
+ 'sumaStolpec'=> $sumaStolpec, #
+ 'sumaVrstica'=> $sumaVrstica, #
+ 'sumaSkupna' => $sumaSkupna, #
+ 'avgVrstica' => $sum_avgi, # povprečje vrstice
+ 'avgStolpec' => $sum_avgj, # povprečje stolpca
+ 'hi2' => $hi2, # hi kvadrat
+ 'isCheckbox' => array('spr1'=>(boolean)$spr_1_checkbox,'spr2'=>(boolean)$spr_2_checkbox)
+ ));
+
+ }
+
+
+ }
+
+
+
+ /** Sestavi array nepravilnih odgovorov
+ *
+ */
+ function getInvalidAnswers($type) {
+ $result = array();
+ $missingValuesForAnalysis = SurveyMissingProfiles :: GetMissingValuesForAnalysis($type);
+
+ foreach ($missingValuesForAnalysis AS $k => $answer) {
+ $result[$k] = array('text'=>$answer,'cnt'=>0);
+ }
+ return $result;
+ }
+
+ /** Naredimo formatiran izpis
+ *
+ * @param $value
+ * @param $digit
+ * @param $sufix
+ */
+
+ static function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands) . $sufix;
+
+ return $result;
+ }
+
+ function getCrossTabPercentage ($sum, $value) {
+ $result = 0;
+ if ($value ) {
+ $result = (int)$sum == 0 ? 0 : $value / $sum * 100;
+ }
+
+ return $result;
+ }
+
+ function setSessionPercent() {
+
+ if (isset($_POST['crossChk1'])) {
+ $this->sessionData['crosstabs']['crossChk1'] = ($_POST['crossChk1'] == 'true');
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function setSessionColor() {
+
+ if (isset($_POST['doColor'])) {
+ $this->sessionData['crosstabs']['doColor'] = ($_POST['doColor'] == 'true');
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function setShowChart() {
+
+ if (isset($_POST['showChart'])) {
+ $this->sessionData['crosstab_charts']['showChart'] = $_POST['showChart'] == 'true';
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ public function setColor($doColor = true) {
+ if ($doColor == true) {
+ $this->doColor = true;
+ } else {
+ $this->doColor = false;
+ }
+ }
+
+ /** Funkcije ki skrbijo za ajax del
+ *
+ */
+ public function ajax() {
+ if ( isset($_POST['sequence1']) && count($_POST['sequence1']) > 0 ) {
+ $i=0;
+ if ( count($_POST['sequence1']) > 0 ){
+ foreach ($_POST['sequence1'] AS $_seq1) {
+ $this->variabla1[$i]['seq'] = $_seq1;
+ $i++;
+ }
+ }
+ }
+
+ if ( isset($_POST['spr1']) && count($_POST['spr1']) > 0 ) {
+ $i=0;
+ if ( count($_POST['spr1']) > 0 ){
+ foreach ($_POST['spr1'] AS $_spr1) {
+ $this->variabla1[$i]['spr'] = $_spr1;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['grid1']) && count($_POST['grid1']) > 0 ) {
+ $i=0;
+ if ( count($_POST['grid1']) > 0 ){
+ foreach ($_POST['grid1'] AS $_grd1) {
+ $this->variabla1[$i]['grd'] = $_grd1;
+ $i++;
+ }
+ }
+ }
+
+ if ( isset($_POST['sequence2']) && count($_POST['sequence2']) > 0 ) {
+ $i=0;
+ if ( count($_POST['sequence2']) > 0 ){
+ foreach ($_POST['sequence2'] AS $_seq2) {
+ $this->variabla2[$i]['seq'] = $_seq2;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['spr2']) && count($_POST['spr2']) > 0 ) {
+ $i=0;
+ if ( count($_POST['spr2']) > 0 ){
+ foreach ($_POST['spr2'] AS $_spr2) {
+ $this->variabla2[$i]['spr'] = $_spr2;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['grid2']) && count($_POST['grid2']) > 0 ) {
+ $i=0;
+ if ( count($_POST['grid2']) > 0 ){
+ foreach ($_POST['grid2'] AS $_grd2) {
+ $this->variabla2[$i]['grd'] = $_grd2;
+ $i++;
+ }
+ }
+ }
+
+ # variable shranimo v sejo, da jih obdržimo tudi če spreminjamo nastavitve ali razne filtre analiz
+ if (isset($this->variabla1) && count($this->variabla1) > 0) {
+ $this->sessionData['crosstabs']['crosstab_variables']['variabla1'] = $this->variabla1;
+ }
+ if (isset($this->variabla2) && count($this->variabla2) > 0) {
+ $this->sessionData['crosstabs']['crosstab_variables']['variabla2'] = $this->variabla2;
+ }
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ if (isset($_POST['crossNavVsEno']) && $_POST['crossNavVsEno'] != '' ) {
+ $this->crossNavVsEno = $_POST['crossNavVsEno'] !== 'undefined' ? $_POST['crossNavVsEno'] : 0;
+ }
+
+
+ $this->readUserSettings();
+ switch ($_GET['a']) {
+ case 'changeDropdown':
+ $this->DisplayDropdows();
+ break;
+ case 'change':
+ $this->Display();
+ break;
+ case 'change_cb':
+ $this->displayCrosstabsTables();
+ break;
+ case 'change_cb_percent':
+ $this->setSessionPercent();
+ break;
+ case 'change_cb_color':
+ $this->setSessionColor();
+ break;
+ case 'add_new_variable':
+ $this->addNewVariable();
+ break;
+ case 'prepareInspect':
+ $this->prepareInspect();
+ break;
+ case 'changeSessionInspect':
+ $this->changeSessionInspect();
+ break;
+ case 'change_show_chart':
+ $this->setShowChart();
+ break;
+ default:
+ print_r("<pre>");
+ print_r($_GET);
+ print_r($_POST);
+ print_r("</pre>");
+ break;
+ }
+
+ }
+
+ function readUserSettings() {
+ @session_start();
+ $sdsp = SurveyDataSettingProfiles :: getSetting();
+
+ $this->crossChk0 = $sdsp['crossChk0'] == '1' ? true : false;
+
+ # če smo checkbox za odstotke po vrsticah nastavili preko seje (posebej) prevzamemo vrednost
+ if (isset($this->sessionData['crosstabs']['crossChk1'])) {
+ $this->crossChk1 = $this->sessionData['crosstabs']['crossChk1'];
+ } else {
+ # če ne preberemo iz profila
+ $this->crossChk1 = $sdsp['crossChk1'] == '1' ? true : false;
+ }
+
+ # če smo checkbox za barvanje nastavili preko seje (posebej) prevzamemo vrednost
+ if (isset($this->sessionData['crosstabs']['doColor'])) {
+ $this->doColor = $this->sessionData['crosstabs']['doColor'];
+ } else {
+ # če ne preberemo iz profila
+ $this->doColor = $sdsp['doColor'] == '1' ? true : false;
+ }
+
+ # če smo radio enableInspect
+ if ($sdsp['enableInspect'] == '1' || (isset($_SESSION['enableInspect']) && $_SESSION['enableInspect'] == true)) {
+ $this->enableInspect = true;
+ } else {
+ # če ne preberemo iz profila
+ $this->enableInspect = false;
+ }
+
+ $this->doValues = $sdsp['doValues'] == '1' ? true : false;
+
+ $this->crossChk2 = $sdsp['crossChk2'] == '1' ? true : false;
+ $this->crossChk3 = $sdsp['crossChk3'] == '1' ? true : false;
+ $this->crossChkEC = $sdsp['crossChkEC'] == '1' ? true : false;
+ $this->crossChkRE = $sdsp['crossChkRE'] == '1' ? true : false;
+ $this->crossChkSR = $sdsp['crossChkSR'] == '1' ? true : false;
+ $this->crossChkAR = $sdsp['crossChkAR'] == '1' ? true : false;
+
+ $this->showChart = isset($this->sessionData['crosstab_charts']['showChart']) ? $this->sessionData['crosstab_charts']['showChart'] : false;
+ }
+
+ function isSelectedBothVariables() {
+ $selected1 = false;
+ $selected2 = false;
+ if (count($this->variabla1)) {
+ foreach ($this->variabla1 AS $var1) {
+ if ((int)$var1['seq'] > 0) {
+ $selected1 = true;
+ }
+ }
+ }
+ if (count($this->variabla2)) {
+ foreach ($this->variabla2 AS $var2) {
+ if ((int)$var2['seq'] > 0) {
+ $selected2 = true;
+ }
+ }
+ }
+
+ return ($selected1 && $selected2);
+ }
+
+ function getSelectedVariables($which = 1) {
+ $selected = array();
+ if ($which == 1) {
+ if (count($this->variabla1) > 0 ) {
+ foreach ($this->variabla1 AS $var1) {
+ if ((int)$var1['seq'] > 0) {
+ $selected[] = $var1;
+ }
+ }
+ }
+ } else {
+ if (count($this->variabla2) > 0 ) {
+ foreach ($this->variabla2 AS $var2) {
+ if ((int)$var2['seq'] > 0) {
+ $selected[] = $var2;
+ }
+ }
+ }
+ }
+
+ return count($selected) > 0 ? $selected : null;
+ }
+
+ function prepareInspect() {
+
+ global $global_user_id, $lang;
+
+ # nastavimo v sejo od kod smo prišli v inspect:
+ @session_start();
+ if ((isset($_POST['from_podstran']) && trim($_POST['from_podstran']) != '')) {
+ $_SESSION['inspectFromPodstran'][$this->sid] = $_POST['from_podstran'];
+ } else {
+ unset($_SESSION['inspectFromPodstran'][$this->sid]);
+ }
+ @session_commit();
+
+ # naredimo filter po spremenljivkah
+ $variables = $_POST['sp1'].','.$_POST['sp2'];
+ if (SurveyDataSettingProfiles :: getSetting('enableInspect')) {
+ $_add_vars = $_SESSION['dataSetting_profile'][$this->sid]['InspectListVars'];
+ if (isset($_add_vars) && is_array($_add_vars) && count($_add_vars) > 0) {
+ foreach ($_add_vars AS $add_var) {
+ $variables .= ','.$add_var.'_0';
+ }
+ }
+ }
+ $svp = new SurveyVariablesProfiles();
+ $svp -> Init($this->sid,$global_user_id);
+ $svp-> setProfileInspect($variables);
+
+ $_spr1 = $this->_HEADERS[$_POST['sp1']];
+ $_spr2 = $this->_HEADERS[$_POST['sp2']];
+
+ # nastaviti moramo dva filtra - pogojev in spremenljivk
+ $spr1 = explode('_',$_POST['sp1']);
+ $spr1 = $spr1[0];
+ $spr2 = explode('_',$_POST['sp2']);
+ $spr2 = $spr2[0];
+
+
+ # if id za inspect shranimo v nastavitev ankete SurveyUserSetting -> inspect_if_id (če ne obstaja skreiramo novega)
+ # dodamo tudi kot profil pogojev (če ne obstaja skreiramo novega)
+
+ #preverimo ali obstaja zapis v SurveyUserSetting->inspect_if_id
+ $if_id = (int)SurveyUserSetting :: getInstance()->getSettings('inspect_if_id');
+ # preverimo dejanski obstoj ifa (srv_if) če ne skreiramo novega
+ if ((int)$if_id > 0) {
+ $chks1 = "SELECT * FROM srv_if WHERE id='$if_id'";
+ $chkq1 = sisplet_query($chks1);
+ # dodamo še k profilu če ne obstaja
+ if (mysqli_num_rows($chkq1) == 0) {
+ $if_id = null;
+ SurveyUserSetting :: getInstance()->removeSettings('inspect_if_id');
+ }
+ }
+
+ if ( (int)$if_id == 0 || $if_id == null) {
+ # if še ne obstaja, skreiramo novga
+ $sql = sisplet_query("INSERT INTO srv_if (id) VALUES ('')");
+ # if (!$sql) echo '<br> -1';
+
+ $if_id = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+ # shranimo pogoj kot privzet pogoj z ainspect
+ SurveyUserSetting :: getInstance()->saveSettings('inspect_if_id',(int)$if_id);
+ }
+
+
+ if ((int)$if_id > 0) {
+ # dodamo ifa za obe variabli
+
+ # ne brišemo starih pogojev, da omogočimo gnezdenje
+ #$delStr = "DELETE FROM srv_condition WHERE if_id = '$if_id'";
+ #sisplet_query($delStr);
+
+ # poiščemo vrednosti za oba vprašanja
+ $condition1 = $this->createSubCondition(1,$if_id,$spr1,$_spr1);
+ $condition2 = $this->createSubCondition(2,$if_id,$spr2,$_spr2);
+
+ sisplet_query("COMMIT");
+
+ # pogoj dodamo še v srv_condition_profile vendar ga ne nastavimo kot privzetega
+ $chk_if_str = "SELECT * FROM srv_condition_profiles WHERE sid='".$this->sid."' AND uid = '".$global_user_id."' AND type='inspect'";
+ $chk_if_qry = sisplet_query($chk_if_str);
+ $_tmp_name = $lang['srv_inspect_temp_profile'];
+ if (mysqli_num_rows($chk_if_qry) > 0) {
+ # if že obstaja popravimo morebitne podatke
+ $str = "UPDATE srv_condition_profiles SET name = '$_tmp_name', if_id='$if_id'";
+ $sql = sisplet_query($str);
+ } else {
+ #vstavimo nov profil pogojev - inspect
+ $str = "INSERT INTO srv_condition_profiles (sid, uid, name, if_id, type ) VALUES ('".$this->sid."', '".$global_user_id."', '$_tmp_name', '$if_id', 'inspect')"
+ . " ON DUPLICATE KEY UPDATE name='$_tmp_name', if_id='$if_id'";
+ $sql = sisplet_query($str);
+ }
+ sisplet_query("COMMIT");
+ }
+
+ if (isset($_SESSION['inspect_goto'])) {
+ $inspect_goto = (int)$_SESSION['inspect_goto'];
+ } else {
+ $inspect_goto = (int)0;
+ }
+ $inspect_goto_array = array( 0 => '&a=analysis&m=sumarnik',
+ 1 => '&a=data&m=quick_edit',
+ 2 => '&a=data');
+
+ echo $inspect_goto_array[$inspect_goto];
+ return ($inspect_goto_array[$inspect_goto]);
+ }
+
+ function createSubCondition($vrstn_red,$if_id,$sid,$spr) {
+ $tip = $spr['tip'];
+
+ # 1. Radio
+ # 3. Dropdown
+ # 2. Select - checkbox
+ if ($tip == '1' || $tip == '3' || $tip == '2') {
+ #radio in dropdown
+ if ($tip == '1' || $tip == '3') {
+ #s pomočjo k preberemo vrstni red
+ $sql_string = "SELECT id FROM srv_vrednost WHERE spr_id='$sid' AND variable = '".$_POST['k'.$vrstn_red]."'";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) == 1 ) {
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ $vred_id = $sql_row['id'];
+ }
+ }
+ #select
+ if ($tip == '2' ) {
+ $vred_id=null;
+ # če je čekbox poiščemo vred_id za sekvenco k
+ foreach ($spr[grids] as $gkey=>$grid) {
+ foreach ($grid[variables] as $vkey=>$variable) {
+ if ($variable['sequence'] == $_POST['k'.$vrstn_red]) {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+ }
+ if ($vred_id != null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red) VALUES ('$if_id', '$sid', '$vrstn_red')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red'";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ((int)$vred_id > 0 || (int)$cond_id > 0) {
+ $istr = "INSERT INTO srv_condition_vre (cond_id, vre_id) VALUES ('$cond_id', '$vred_id')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+ return $cond_id;
+ }
+ }
+
+ # 7. Number
+ if ($tip == '7' ) {
+ $text=$_POST['k'.$vrstn_red];
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ $seq = $_POST['sq'.$vrstn_red];
+ $vrstn_red = $vrstn_red-1;
+ foreach ($spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $seq) {
+ $grid_id = $vkey;
+ }
+ }
+ }
+ if ($grid_id !== null) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, grd_id, text) VALUES ('$if_id', '$sid', '$vrstn_red', '$grid_id', '$text')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red', grd_id='$grid_id', text='$text'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ return $cond_id;
+ }
+ }
+ # 21. besedilo
+ # 18. vsota
+ if ($tip == '21' || $tip == '18') {
+
+ $text=$_POST['k'.$vrstn_red];
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ $seq = $_POST['sq'.$vrstn_red];
+
+ foreach ($spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $seq) {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id, text) VALUES ('$if_id', '$sid', '$vrstn_red', '$vred_id', '$text')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red', vre_id='$vred_id', text='$text'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ return $cond_id;
+ }
+ }
+ # 16. multi checkbox
+ if ($tip == '16' ) {
+ $vred_id=null;
+
+ # sekvenca je podana pod k
+ $seq = $_POST['k'.$vrstn_red];
+
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ foreach ($spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $seq) {
+ $vred_id = $variable['vr_id'];
+ $grid_id = $variable['gr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id) VALUES ('$if_id', '$sid', '$vrstn_red', '$vred_id')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red', vre_id='$vred_id'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ #dodamo še v srv_grid
+ if ($cond_id > 0 && $grid_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$grid_id."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } else {
+ echo '<br>-5 :: ';
+ }
+ return $cond_id;
+ }
+ }
+ # 6. multi radio
+ if ($tip == '6' ) {
+ $vred_id=null;
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ $seq = $_POST['sq'.$vrstn_red];
+ foreach ($spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $seq) {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id) VALUES ('$if_id', '$sid', '$vrstn_red', '$vred_id')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red', vre_id='$vred_id'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ #dodamo še v srv_grid
+ if ($cond_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$_POST['k'.$vrstn_red]."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } else {
+ echo '<br>-5 :: ';
+ }
+ return $cond_id;
+ }
+ }
+ # 17. razvrščanje ranking
+ if ($tip == '17' ) {
+
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ $seq = $_POST['sq'.$vrstn_red];
+
+ foreach ($spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $seq) {
+ $vred_id = $variable['vr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id) VALUES ('$if_id', '$sid', '$vrstn_red', '$vred_id')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red', vre_id='$vred_id'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ $grid_id = $_POST['k'.$vrstn_red];
+ #dodamo še v srv_grid
+ if ($cond_id > 0 && $grid_id > 0) {
+ $istr = "INSERT INTO srv_condition_grid (cond_id, grd_id) VALUES ('$cond_id', '".$grid_id."')";
+ $sql = sisplet_query($istr);
+ if (!$sql) {
+ echo '<br>-4 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ } else {
+ echo '<br>-5 :: ';
+ }
+ return $cond_id;
+ }
+ }
+ # 19. multi text
+ # 20. multi number
+ if ($tip == '19' || $tip == '20') {
+ $text=$_POST['k'.$vrstn_red];
+ #pogledamo za katero vrednost iščemo s pomočjo sekvence
+ $seq = $_POST['sq'.$vrstn_red];
+
+ foreach ($spr['grids'] AS $gkey=> $grid) {
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ if ($variable['sequence'] == $seq) {
+ $vred_id = $variable['vr_id'];
+ $grid_id = $variable['gr_id'];
+ }
+ }
+ }
+
+ if ($vred_id !== null && (int)$vred_id > 0 && $grid_id > 0) {
+ $istr = "INSERT INTO srv_condition (if_id, spr_id, vrstni_red, vre_id, grd_id, text) VALUES ('$if_id', '$sid', '$vrstn_red', '$vred_id', '$grid_id', '$text')"
+ . " ON DUPLICATE KEY UPDATE spr_id='$sid', vrstni_red = '$vrstn_red', grd_id='$grid_id', text='$text'";
+ $sql = sisplet_query($istr);
+
+ if (!$sql) {
+ echo '<br>-3 :: '.$istr;
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+ $cond_id = mysqli_insert_id($GLOBALS['connect_db']);
+ return $cond_id;
+ }
+ }
+
+ return null;
+ }
+
+ function changeSessionInspect() {
+ @session_start();
+ #Zamenjamo sejo
+ if (isset($_SESSION['enableInspect']) && $_SESSION['enableInspect'] == true) {
+ unset($_SESSION['enableInspect']);
+ } else {
+ $_SESSION['enableInspect'] = true;
+ }
+ @session_commit();
+
+ #nastavimo inspect
+ $sdsp = SurveyDataSettingProfiles :: getSetting();
+ if ($sdsp['enableInspect'] == '1' || (isset($_SESSION['enableInspect']) && $_SESSION['enableInspect'] == true)) {
+ $this->enableInspect = true;
+ } else {
+ # če ne preberemo iz profila
+ $this->enableInspect = false;
+ }
+
+ $this->displaySessionInspectCheckbox();
+ }
+ function displaySessionInspectCheckbox() {
+ global $lang;
+ echo '<input type="checkbox" id="session_inspect" '.($this->enableInspect == true ? ' checked="checekd"' : '').' onClick="changeSessionInspect();">'.$lang['srv_inspect_setting'];
+ echo Help :: display('srv_crosstab_inspect');
+ }
+
+
+ function displayLinePercent() {
+ global $lang;
+
+ echo '<input id="crossCheck1" name="crossCheck1" onchange="change_crosstab_percent();" type="checkbox" ' . ($this->crossChk1 == true ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo '<label for="crossCheck1" id="spn_residual_sp1" class="ctbChck_sp1">' . $lang['srv_analiza_crosstab_odstotek_vrstice_short'].'</label>';
+ echo '<input id="crossDoColor" name="crossDoColor" onchange="change_crosstab_color();" type="checkbox" ' . ($this->doColor == true ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo '<label for="crossDoColor" id="spn_residual_sp1" class="ctbChck_sp1">' . $lang['srv_analiza_crosstab_color'].'</label>';
+ }
+
+ function displayResidual(){
+ global $lang;
+
+ $selected = ($this->crossChkEC + $this->crossChkRE + $this->crossChkSR + $this->crossChkAR == 4) ? true : false;
+
+ echo '<input id="crossResiduals" name="crossResiduals" onchange="saveResidualProfileSetting(\''.SurveyDataSettingProfiles::getCurentProfileId().'\', this.checked); return false;" type="checkbox" ' . ($selected ? ' checked="checked" ' : '') . ' autocomplete="off"/>';
+ echo '<label for="crossResiduals" id="crossResiduals" class="show_residual">' . $lang['srv_analiza_crosstab_residuals'].'</label>';
+ }
+
+ function displayShowChart() {
+ global $lang;
+
+ echo '<input id="showChart" name="showChart" onchange="showTableChart(\'crosstab\');" type="checkbox" ' . ($this->showChart == true ? ' checked="checked" ' : '') . ' />';
+ echo '<label for="showChart" id="showChart" class="showChart">'.$lang['srv_show_charts'].'</label>';
+ }
+
+ function presetVariables() {
+ # preberemo prednastavljene variable iz seje, če obstajajo
+ if (isset($this->sessionData['crosstabs']['crosstab_variables']['variabla1']) && count($this->sessionData['crosstabs']['crosstab_variables']['variabla1']) > 0) {
+ $this->variabla1 = $this->sessionData['crosstabs']['crosstab_variables']['variabla1'];
+ }
+ if (isset($this->sessionData['crosstabs']['crosstab_variables']['variabla2']) && count($this->sessionData['crosstabs']['crosstab_variables']['variabla2']) > 0) {
+ $this->variabla2 = $this->sessionData['crosstabs']['crosstab_variables']['variabla2'];
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyEditsAnalysis.php b/admin/survey/classes/surveyAnalysis/class.SurveyEditsAnalysis.php
new file mode 100644
index 0000000..b1b7b5f
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyEditsAnalysis.php
@@ -0,0 +1,984 @@
+<?php
+/**
+ * Analize urejanja
+ *
+ * Author: Uroš Podkrižnik
+ * Created: 14.4.2017
+ */
+
+define('GRAPH_REDUCE', '1.22'); # količnik za koliko zmanjšamo širino grafa da ne prebije
+
+class SurveyEditsAnalysis{
+
+ private $anketa; # id ankete
+ private $db_table; # katere tabele uporabljamo
+
+
+ function __construct($anketa){
+ if ((int)$anketa > 0){
+
+ $this->anketa = $anketa;
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+ }
+ else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+
+ function displayTable(){
+ global $lang;
+
+ // Legenda statusov
+ $statuses = array(
+ -1 => $lang['srv_vsi'],
+ 0 => $lang['srv_urejanje'],
+ 1 => $lang['import_data'],
+ 2 => $lang['export_analisys'],
+ 3 => $lang['srv_reporti'],
+ 4 => $lang['srv_podatki'],
+ 5 => $lang['srv_inv_nav_email'],
+ 20 => $lang['srv_hierarchy'], // Splošni podatki o hierarhiji
+ 21 => $lang['srv_hierarchy_structure'], // Grajenje hierarhije
+ 22 => $lang['srv_hierarchy_users'], // Urejanje uporabnikov
+ );
+
+ //se ponovi v funkciji ajax_drawContinuEditsTable
+ if ($_GET['seansa'] > 0)
+ $seansa = $_GET['seansa'];
+ else
+ $seansa = '30';
+ if (isset ($_GET['time']))
+ $time = $_GET['time'];
+ else
+ $time = '1 month';
+ if (isset ($_GET['status']))
+ $status = $_GET['status'];
+ else
+ $status = 0;
+ if (isset ($_GET['from']))
+ $from = $_GET['from'];
+ else
+ $from = '';
+ if (isset ($_GET['to']))
+ $to = $_GET['to'];
+ else
+ $to = '';
+
+ echo '<form id="diagnostics_form" action="index.php" method="get">';
+
+ echo '<input type="hidden" name="a" value="edits_analysis" />';
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'" />';
+
+ echo ''.$lang['srv_edits_analysis_seansa'].' <select name="seansa" onchange="this.form.submit();">';
+ echo '<option value="5"' . ($seansa == '5' ? ' selected' : '') . '>'.$lang['srv_edits_analysis_seansa_5min'].'</option>';
+ echo '<option value="10"' . ($seansa == '10' ? ' selected' : '') . '>'.$lang['srv_edits_analysis_seansa_10min'].'</option>';
+ echo '<option value="30"' . ($seansa == '30' ? ' selected' : '') . '>'.$lang['srv_edits_analysis_seansa_30min'].'</option>';
+ echo '<option value="60"' . ($seansa == '60' ? ' selected' : '') . '>'.$lang['srv_edits_analysis_seansa_1h'].'</option>';
+ echo '</select> ';
+
+ echo ''.$lang['status'].' <select name="status" id="edits_analysis_status" onchange="this.form.submit();">';
+ echo '<option value="-1"' . ($status == -1 ? ' selected' : '') . '>'.$statuses[-1].'</option>';
+ echo '<option value="0"' . ($status == 0 ? ' selected' : '') . '>'.$statuses[0].'</option>';
+ echo '<option value="1"' . ($status == 1 ? ' selected' : '') . '>'.$statuses[1].'</option>';
+ echo '<option value="2"' . ($status == 2 ? ' selected' : '') . '>'.$statuses[2].'</option>';
+ echo '<option value="3"' . ($status == 3 ? ' selected' : '') . '>'.$statuses[3].'</option>';
+ echo '<option value="4"' . ($status == 4 ? ' selected' : '') . '>'.$statuses[4].'</option>';
+ echo '<option value="5"' . ($status == 5 ? ' selected' : '') . '>'.$statuses[5].'</option>';
+ /*echo '<option value="20"' . ($status == 20 ? ' selected' : '') . '>'.$statuses[20].'</option>';
+ echo '<option value="21"' . ($status == 21 ? ' selected' : '') . '>'.$statuses[21].'</option>';
+ echo '<option value="22"' . ($status == 22 ? ' selected' : '') . '>'.$statuses[22].'</option>';*/
+ echo '</select> '.$lang['srv_diagnostics_in'].' ';
+
+ echo '<select id="diagnostics_date_selected" name="time" onchange="diagnosticsChooseDate();">';
+ /*echo '<option value="10 minute"' . ($time == '10 minute' ? ' selected' : '') . '>'.$lang['srv_diagnostics_10 minute'].'</option>';
+ echo '<option value="30 minute"' . ($time == '30 minute' ? ' selected' : '') . '>'.$lang['srv_diagnostics_30 minute'].'</option>';*/
+ echo '<option value="lifetime"' . ($time == 'lifetime' ? ' selected' : '') . '>'.$lang['srv_edits_analysis_period_lifetime'].'</option>';
+ echo '<option value="1 hour"' . ($time == '1 hour' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 hour'].'</option>';
+ echo '<option value="6 hour"' . ($time == '6 hour' ? ' selected' : '') . '>'.$lang['srv_diagnostics_6 hour'].'</option>';
+ echo '<option value="12 hour"' . ($time == '12 hour' ? ' selected' : '') . '>'.$lang['srv_diagnostics_12 hour'].'</option>';
+ echo '<option value="1 day"' . ($time == '1 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 day'].'</option>';
+ echo '<option value="2 day"' . ($time == '2 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_2 day'].'</option>';
+ echo '<option value="5 day"' . ($time == '5 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_5 day'].'</option>';
+ echo '<option value="7 day"' . ($time == '7 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_7 day'].'</option>';
+ echo '<option value="14 day"' . ($time == '14 day' ? ' selected' : '') . '>'.$lang['srv_diagnostics_14 day'].'</option>';
+ echo '<option value="1 month"' . ($time == '1 month' ? ' selected' : '') . '>'.$lang['srv_diagnostics_1 month'].'</option>';
+ echo '<option value="3 month"' . ($time == '3 month' ? ' selected' : '') . '>'.$lang['srv_diagnostics_3 month'].'</option>';
+ echo '<option value="6 month"' . ($time == '6 month' ? ' selected' : '') . '>'.$lang['srv_diagnostics_6 month'].'</option>';
+ echo '<option id="option_99date" value="99date"' . ($time == '99date' ? ' selected' : '') . '>'.$lang['srv_diagnostics_choose_date'].'</option>';
+ echo '</select> ';
+
+ // Datum - od
+ echo ''.$lang['srv_diagnostics_orfrom'].' <input type="text" id="from" name="from" value="' . $from . '" '. ($time != '99date' ? ' disabled' : '') .' />';
+ echo ' <span class="faicon calendar_icon icon-as_link" onclick="changeSelectOption()" id="from_img"></span>';
+
+ // Datum - do
+ echo ' '.$lang['srv_diagnostics_to'].' <input type="text" id="to" name="to" value="' . $to . '" '. ($time != '99date' ? ' disabled' : '') .'/>';
+ echo ' <span class="faicon calendar_icon icon-as_link" onclick="changeSelectOption()" id="to_img"></span>';
+
+ echo '<input type="submit" class="spaceLeft pointer" value="'.$lang['hour_show'].'" />';
+
+ echo '</form><div>';
+
+ //create iterval - SQL where statement
+ $interval = $this->createInterval($time, $from, $to);
+ //get object of all edits data
+ $data = $this->getData($status, $interval);
+
+ if(sizeof($data) == 0)
+ $this->echoNoData();
+ else{
+ echo '<div id="edits_analysis_time_tables">';
+ echo '<div>';
+ $sum_data = $this->drawTimeEdits($data['timeEdits'], $seansa*60, $status);
+ echo '</div>';
+ $this->GraphData($this->graphQuery($status, $interval));
+ echo '</div>';
+
+ echo '<table class="dashboard" id="edits_analysis_info">';
+ echo '<tr>';
+
+ //draw edits counter and sums of editors
+ $this->drawCountEdits($sum_data);
+
+ //draw continuous editing box
+ $continu_data = $this->continuEditsQuery($status, $interval);
+ $this->drawContinuEdits($continu_data, $sum_data);
+
+ echo '</tr>';
+ echo '</table>';
+
+ //prestavi vse tabele na konec, da bo info na vrhu
+ echo'<script>var myElement = document.getElementById("edits_analysis_time_tables");'
+ . 'myElement.parentNode.appendChild(myElement);</script>';
+
+
+ }
+ echo '</div>';
+ }
+
+ function GraphData($data){
+ global $lang, $site_url;
+
+ //error_log(json_encode($data));
+ //$DataSetJson = json_decode('{"Data":[{"Vrednosti":5,"Vrednosti2":2,"Name":0,"Variable":"0-1000"},{"Vrednosti":20,"Vrednosti2":15,"Name":1,"Variable":"1001-5000"},{"Vrednosti":20,"Vrednosti2":20,"Name":2,"Variable":"5001-10000"},{"Vrednosti":0,"Vrednosti2":8,"Name":3,"Variable":"10001-50000"}],'
+ // . '"DataDescription":{"Position":"Variable","Format":{"X":"number","Y":"number"},"Unit":{"X":null,"Y":null},"Values":["Vrednosti", "Vrednosti2"],"Description":{"Vrednosti":"prvi-prvi-prvi-prvi-prvi", "Vrednosti2":"drugi-drugi-drugi-drugi-drugi"}},"numerus":45,"average":4721,"Other":[]}');
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ $vrednosti = array();
+ $vrednostiVariable = array();
+ $avg_count = 0;
+ $avg_sum = 0;
+
+ /*foreach ($DataSetJson->Data as $value){
+ $vrednosti[] = $value->Vrednosti;
+ $vrednosti2[] = $value->Vrednosti2;
+ $avg_sum+=$value->Vrednosti;
+ $vrednostiVariable[] = $value->Variable;
+ $avg_count++;
+ }*/
+
+ $start_date = new DateTime($data['first_date']);
+ $temp_date = $start_date;
+ $end_date = new DateTime($data['last_date']);
+
+ $diff = $this->differDateTimeInDays($start_date, $end_date);
+ $DayFormat = '';
+ $DayIncrease = 'month';
+ if($diff < 32){
+ $DayFormat = '-d';
+ $DayIncrease = 'day';
+ }
+ else
+ $temp_date->setDate($start_date->format('Y'), $start_date->format('m'), 1);
+
+ while ($temp_date <= $end_date){
+ foreach($data['edits'] as $user=>$value){
+ $datestring = $temp_date->format('Y-m'.$DayFormat);
+ $cnt = isset($value[$datestring]) ? $value[$datestring] : 0;
+ $vrednosti[$user][] = $cnt;
+
+ $avg_sum+=$cnt;
+ }
+
+ $vrednostiVariable[] = $datestring;
+ $avg_count++;
+ $temp_date->modify('+1 '.$DayIncrease);
+ }
+
+ foreach($data['edits'] as $user=>$value){
+ $DataSet->AddPoint($vrednosti[$user],$user);
+ $DataSet->AddSerie($user);
+ $DataSet->SetSerieName($user,$user);
+ }
+
+ // nastavimo NUMERUS, ki se izpise pod legendo
+ $numerus = $avg_sum;
+ $DataSet->SetNumerus($numerus);
+
+ // nastavimo POVPRECJE
+ $avg = ($avg_count > 0) ? $avg_sum / $avg_count : 0;
+ $DataSet->SetAverage(round($avg, 1));
+
+
+ $DataSet->AddPoint($vrednostiVariable,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ //$DataSet->SetYAxisUnit("null");
+ $DataSet->SetYAxisFormat("number");
+
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+ $ID = self::generateChartId($DataSet->GetNumerus());
+
+ echo '<div style="margin-top:-2.5em;">';
+ echo '<div class="chart_holder" style="margin: auto !important; width: auto !important;" id="chart_edits_'.$this->anketa.'">';
+ echo '<div class="chart_title" style="width: auto !important">'. $lang['srv_edits_analysis_graph'];
+ echo '<span class="numerus">';
+ echo '(n = '.$DataSet->GetNumerus().')';
+ echo '</span>';
+ echo '</div>';
+
+ if(!$Cache->isInCache($ID, $DataSet->GetData())){
+ $graph = SurveyChart::createLine($DataSet, null, 1);
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$graph);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+ $imgPath = 'pChart/Cache/'.$imgName;
+
+ $imgUrl = $site_url . 'admin/survey/' . $imgPath;
+
+ echo '<div class="chart_img" style="float: none !important" title="'.$lang['srv_edits_analysis_graph'].'">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgUrl.'?'.time().'" />';
+ echo '</div></div></div>';
+ }
+
+ /**
+ * Run querry for action times
+ * @param type $status - int of status
+ * @param type $interval - where clause for time interval
+ * @return type array of results from DB
+ */
+ function graphQuery($status, $interval){
+ $sql2 = "SELECT min(DATE_FORMAT(st.datetime, '%Y-%m-%d')) as first_date, max(DATE_FORMAT(st.datetime, '%Y-%m-%d')) as last_date"
+ . " FROM srv_tracking$this->db_table st, users u WHERE st.ank_id='$this->anketa' AND u.id = st.user ".
+ ($status != -1 ? "AND st.status=$status " : "") ."$interval ";
+ $output2=sisplet_query($sql2, 'obj');
+
+ $diff = $this->differDateTimeInDays(new DateTime($output2->first_date), new DateTime($output2->last_date));
+ $queryDayFormat = '';
+ $queryDayGroup = '';
+ if($diff < 32){
+ $queryDayFormat = '-%d';
+ $queryDayGroup = ', DAY(st.datetime)';
+ }
+
+ $sql = "SELECT count(*) as cnt, u.email, u.id, DATE_FORMAT(st.datetime, '%Y-%m$queryDayFormat') as date"
+ . " FROM srv_tracking$this->db_table st, users u WHERE st.ank_id='$this->anketa' AND u.id = st.user ".
+ ($status != -1 ? "AND st.status=$status " : "") ."$interval "
+ . "GROUP BY u.email, YEAR(st.datetime), MONTH(st.datetime)$queryDayGroup "
+ . "ORDER BY u.email, date ASC";
+ $output=sisplet_query($sql, 'array');
+
+ $data = array('edits'=>array(), 'first_date'=>$output2->first_date, 'last_date'=>$output2->last_date);
+ foreach($output as $row){
+ $data['edits'][$row['email']][$row['date']]=$row['cnt'];
+ }
+ return $data;
+ }
+
+ private function differDateTimeInDays($start_date, $end_date){
+ return $end_date->diff($start_date)->format("%a");
+ }
+
+ // Zgeneriramo ID grafa za hash
+ private function generateChartId($numerus){
+ $ID = $this->anketa.'_chart_'.$numerus.'edits_analysis';
+ return $ID;
+ }
+
+ /**
+ * Get data to show in table
+ *
+ * @param type $status - status or type of edits
+ * @param type $interval - where statement including interval for SQL
+ * @return type
+ */
+ function getData($status, $interval){
+ $data = array();
+
+ $data_temp = $this->timeEditsQuery($status, $interval);
+
+ if(sizeof($data_temp) == 0)
+ return array();
+ else
+ $data['timeEdits'] = $data_temp;
+
+ return $data;
+ }
+
+ /**
+ * Create interval for SQL query from criteria
+ *
+ * @param type $time - time selected from dropdown
+ * @param type $from - from calendat
+ * @param type $to - to calendar
+ * @return type - string WHERE statement
+ */
+ function createInterval($time, $from, $to){
+ if($time == 'lifetime' || ($time == '99date' && $from == '' && $to == ''))
+ $interval = "";
+ else if ($from == '' && $to == '')
+ $interval = "AND st.datetime > NOW() - INTERVAL $time";
+ else if ($to == '')
+ $interval = "AND '$from' <= st.datetime";
+ else if ($from == '')
+ $interval = "AND st.datetime <= '$to'";
+ else
+ $interval = "AND '$from' <= st.datetime AND st.datetime <= '$to'";
+
+ return $interval;
+ }
+
+ /**
+ * Run querry for action times
+ * @param type $status - int of status
+ * @param type $interval - where clause for time interval
+ * @return type array of results from DB
+ */
+ function timeEditsQuery($status, $interval){
+ $sql = "SELECT u.email, u.id, st.datetime". ($status == 0 ? ", st.get, st.post" : "") . ($status == -1 ? ", st.status" : "")
+ . " FROM srv_tracking$this->db_table st, users u WHERE st.ank_id='$this->anketa' AND u.id = st.user ".
+ ($status != -1 ? "AND st.status=$status " : "") ."$interval ORDER BY u.email, st.datetime DESC";
+ return sisplet_query($sql, 'array');
+ }
+
+ /**
+ * Draw box of number of edit actions
+ * @global type $lang
+ * @param type $data - object data of sums
+ */
+ function drawCountEdits($data){
+ global $lang;
+
+ echo '<td>';
+ $sum_akcij = 0;
+ $sum_time = 0;
+ $sum_seans = 0;
+
+ echo '<div class="dashboard_cell" name="div_edits_analysis_counter" id="div_edits_analysis_counter" >'."\n";
+ echo '<span class="floatLeft dashboard_title">'.$lang['srv_edits_analysis_counter'];
+ echo '</span>';
+
+ echo '<br class="clr"/><br/>';
+
+ echo '<span class="dashboard_status_span">' . $lang['srv_edits_analysis_counter_editors'] .' :</span>' . sizeof($data).'<br/><br/>';
+ echo '<table id="tbl_answ_state">';
+ echo '<tr class="anl_dash_bb "><th><strong>'.$lang['srv_edits_analysis_counter_editor'].'</strong></th>'
+ . '<td><strong>'.$lang['srv_edits_analysis_time_time'].'</strong></td>'
+ . '<td><strong>'.$lang['srv_edits_analysis_num_sessions'].'</strong></td>'
+ . '<td><strong>'.$lang['srv_edits_analysis_time_actions'].'</strong></td></tr>';
+
+ foreach ($data as $key => $value) {
+ $this->echoCountEditsRow($key, $this->calculateTimeFromSeconds($value['time_sum']), $value['st_akcij_sum'], $value['st_seans_sum'], $value['user_id']);
+ $sum_akcij += $value['st_akcij_sum'];
+ $sum_time += $value['time_sum'];
+ $sum_seans += $value['st_seans_sum'];
+ }
+
+ // vsota vlejavnih
+ $this->echoCounterEditsFootRow($sum_time, $sum_akcij, $sum_seans);
+ echo '</table>';
+ echo '</div>';
+ echo '</td>';
+ }
+
+ /**
+ * Run querry for continuous editing
+ * @param type $status - int of status
+ * @param type $interval - where clause for time interval
+ * @param type $interval_criteria - criteria for interval - continued 'day' or 'hour'
+ * @return type array of results from DB
+ */
+ function continuEditsQuery($status, $interval, $interval_criteria = 'day', $user_criteria = 'all'){
+ $interval_criteria = ($interval_criteria == 'day') ? '' : ' %H';
+
+ $sqlString = "SELECT DATE_FORMAT(st.datetime, '%Y-%m-%d$interval_criteria') AS formatdate, count(*) as cnt FROM srv_tracking$this->db_table st WHERE ank_id = '$this->anketa' ".
+ ($status != -1 ? "AND st.status=$status " : "")."".
+ ($user_criteria != 'all' ? "AND st.user=$user_criteria " : "")."$interval GROUP BY formatdate ORDER BY formatdate desc";
+
+ return sisplet_query($sqlString, 'array');
+ }
+
+ /**
+ * Draw box of continuous editing
+ * @global type $lang
+ * @param type $data - object data of continued editing
+ * @param type $sum_data - object data of sums
+ * @param type $interval_criteria - criteria for interval - continued 'day' or 'hour'
+ */
+ function drawContinuEdits($data, $sum_data, $interval_criteria = 'day'){
+ global $lang;
+
+ echo '<td>';
+ echo '<div class="dashboard_cell" name="div_edits_analysis_countinu" id="div_edits_analysis_countinu" >'."\n";
+ echo '<span class="floatLeft dashboard_title">'.$lang['srv_edits_analysis_countinu'];
+ echo '</span>';
+
+ echo '<br class="clr"/><br/>';
+
+ //user/s
+ echo '<span id="span_timelineDropDownType">';
+ echo $lang['srv_edits_analysis_counter_editor'].': ';
+ echo '<select id="edits_analysis_continu_user" name="edits_analysis_continu_user" onchange="editsAnalysisContinuousEditing();">';
+ echo '<option value="all" selected>'.$lang['srv_edits_analysis_counter_all'].'</option>';
+ foreach ($sum_data as $email => $row) {
+ echo '<option value="'.$row['user_id'].'">'.$email.'</option>';
+ }
+ echo '</select> ';
+ echo '</span>';
+
+ // Oblika
+ echo '<span>';
+ echo '<label>'.$lang['srv_statistic_period'].'</label>:'."\n";
+ echo '<select id="edits_analysis_continu_period" name="edits_analysis_continu_period" size="1" autocomplete="off" onchange="editsAnalysisContinuousEditing();">'."\n";
+ echo '<option value="hour" '.(($interval_criteria == "hour") ? "selected" : "").'>'.$lang['srv_statistic_period_hour_period'].'</option>';
+ echo '<option value="day" '.(($interval_criteria == "day") ? "selected" : "").'>'.$lang['srv_statistic_period_day_period'].'</option>';
+ echo '</select>'."\n";
+ echo '</span>';
+
+ //data table
+ echo '<div name="edits_analysis_continu_table" id="edits_analysis_continu_table" >'."\n";
+ //draw table
+ $this->drawContinuEditsTable($data, $interval_criteria);
+ echo '</div>';
+ }
+
+ /**
+ * Draw table with bars od continued editing
+ * @param type $data - object data of continued editing
+ * @param type $interval_criteria - criteria for interval - continued 'day' or 'hour'
+ */
+ function drawContinuEditsTable($data, $interval_criteria = 'day'){
+ $maxValue = 0;
+
+ $interval_seconds = ($interval_criteria == 'day') ? 86400 : 3600;
+ $interval_crit = ($interval_criteria == 'day') ? '' : ' H';
+
+ echo '<table class="survey_referals_tbl">'."\n";
+ if ($data) {
+ $temp_time = null;
+ //units
+ $zapored = 0;
+ $results = array();
+
+ foreach ($data as $row) {
+ if($temp_time == null)
+ $temp_time = DateTime::createFromFormat('Y-m-d'.$interval_crit, $row['formatdate']);
+ else{
+ //calculate seconds between actions (rounded on 3600 or 86400)
+ $interval = $this->calculateTimeBetweenActions($temp_time, DateTime::createFromFormat('Y-m-d'.$interval_crit, $row['formatdate']));
+
+ //if interval between actions are 1 unit (1 hour or 1 day), add it to continued editing session
+ if($interval/$interval_seconds-$zapored < 2){
+ $zapored++;
+ //set maxValue, needed for width of bars
+ $maxValue = max($maxValue, $zapored);
+ }
+ //interval is more than 1 unit apart, not in continued editing session
+ else{
+ //if there is continued editing session until previous action, store it to array - ignore otherwise
+ if($zapored > 0)
+ array_push($results, array('time' => $temp_time, 'zapored' => $zapored));
+
+ //restart all
+ $temp_time = DateTime::createFromFormat('Y-m-d'.$interval_crit, $row['formatdate']);
+ $zapored = 0;
+ }
+ }
+ }
+ //if there is continued editing session in last actions, store it to array - ignore otherwise
+ if($zapored > 0)
+ //$this->drawContinuRow($temp_time, $zapored, $maxValue, $value);
+ array_push($results, array('time' => $temp_time, 'zapored' => $zapored));
+
+ if(!$results)
+ $this->echoNoData();
+ else{
+ //reduce bars a little
+ $maxValue *= GRAPH_REDUCE;//najvecje stevilo
+ //draw all data and bars
+ foreach ($results as $row) {
+ $this->drawContinuRow($row['time'], $row['zapored'], $maxValue, $interval_criteria);
+ }
+ }
+ } else
+ $this->echoNoData();
+
+ echo '</table>'."\n";
+ }
+
+ /**
+ * Draws a row with bar of continuous editing
+ * @param type $temp_time - the last edit
+ * @param type $zapored - hour of continuoed editing
+ * @param type $maxValue - max value of bars
+ * @param type $interval_criteria - criteria for interval - continued 'day' or 'hour'
+ */
+ function drawContinuRow($temp_time, $zapored, $maxValue, $interval_criteria){
+ $time_last = clone $temp_time;
+ //edit DateTime get starting of continued editting session by subtracting units
+ $temp_time->modify('- '.$zapored.' '.$interval_criteria);
+
+ //if hour criteria
+ if($interval_criteria == 'hour'){
+ //add 1 hour because of from to view
+ $time_last->modify('+ 1 '.$interval_criteria);
+ $s_time = $temp_time->format('Y-m-d H:00') .' - '. $time_last->format('H:00');
+ }
+ else if($interval_criteria == 'day')
+ $s_time = $temp_time->format('Y-m-d') .' - '. $time_last->format('Y-m-d');
+
+ //echo data
+ echo '<tr>'."\n";
+ echo '<td style="width:90px;">' . $s_time . '</td>'."\n";
+ $width = ($maxValue && $zapored) ? (round($zapored / $maxValue * 100, 0)) : "0";
+ echo '<td style=""><div class="graph_db" style="text-align:right; float:left; width:'.$width.'%">&nbsp;</div><span style="display:block; margin:auto; margin-left:5px; width:20px; float:left">'.($zapored+1).'</span></td>'."\n";
+ echo '</tr>'."\n";
+ }
+
+ /**
+ * Draw box of editing times
+ * @param type $data - $data['timeEdits']
+ * @param type $seansa - cas nastavljene dolzine seanse v min
+ * @param type $status - code of status criteria
+ * @return Object - object of editors e.g. {admin:{time_sum:500, st_akcij_sum:30, st_seans_sum:5}, ...}
+ */
+ function drawTimeEdits($data, $seansa, $status){
+ global $lang;
+
+ $sum_data = array();
+
+ $datetime_last = null;
+ $datetime_start = null;
+ $st_akcij = 0;
+ $st_akcij_sum = 0;
+ $st_seans_sum = 0;
+ $time_sum = 0;
+ $user_temp = null;
+ $user_id = 0;
+ $row_id = 0;
+ $action_type = null;
+ $action_type_sum = null;
+ $statuses = null;
+
+ if($status == -1){
+ $statuses = array(
+ 0 => array("name"=>$lang['srv_urejanje'], "sum"=>0),
+ 1 => array("name"=>$lang['import_data'], "sum"=>0),
+ 2 => array("name"=>$lang['export_analisys'], "sum"=>0),
+ 3 => array("name"=>$lang['srv_reporti'], "sum"=>0),
+ 4 => array("name"=>$lang['srv_podatki'], "sum"=>0),
+ 5 => array("name"=>$lang['srv_inv_nav_email'], "sum"=>0),
+ //20 => array("name"=>$lang['srv_hierarchy'], "sum"=>0),// Splošni podatki o hierarhiji
+ //21 => array("name"=>$lang['srv_hierarchy_structure'], "sum"=>0),// Grajenje hierarhije
+ //22 => array("name"=>$lang['srv_hierarchy_users'], "sum"=>0),// Urejanje uporabnikov
+ );
+ $action_type = $statuses;
+ $action_type_sum = $statuses;
+ }
+ else if($status == 0){
+ $statuses = array();
+ $action_type = array();
+ $action_type_sum = array();
+ }
+
+ echo '<h2>'.$lang["srv_edits_analysis_editing_details"].'</h2>';
+
+ foreach ($data as $rowGrupa) {
+
+ //$post = $this->convertToJSON($rowGrupa['post']);
+ $akcija = null;
+ if($status == -1)
+ $akcija = $rowGrupa['status'];
+ else if($status == 0){
+ $get = $this->convertToJSON($rowGrupa['get']);
+ $akcija = $get['a'];
+ }
+
+ //zacetek risanja
+ if(!isset($user_temp)){
+ $user_temp = $rowGrupa['email'];
+ $user_id = $rowGrupa['id'];
+ echo '<table class="text_analysis_table floatLeft" border="1">'; //border zaradi printa - css na strani ga povozi
+ $this->echoTimeTalbeHeader($user_temp, $status, $user_id);
+ }
+
+ //naslednji editor
+ else if($user_temp != $rowGrupa['email']){
+ //izrisi se zadnjo vrstico prejsnjega urejevalca
+ $time_sum += $this -> drawTimeEditsRow($datetime_start, $datetime_last, $st_akcij, $action_type, $user_id.'_'.$row_id);
+ $this -> echoTimeEditsFootRow($time_sum, $st_akcij_sum, $action_type_sum, $user_id.'_sum');
+ $sum_data[$user_temp]['time_sum']=$time_sum;
+ $sum_data[$user_temp]['st_akcij_sum']=$st_akcij_sum;
+ $sum_data[$user_temp]['st_seans_sum']=$st_seans_sum;
+ $sum_data[$user_temp]['user_id']=$user_id;
+ $action_type_sum = $statuses;
+
+ //nova tabela - nov urejevalec
+ $user_temp = $rowGrupa['email'];
+ $user_id = $rowGrupa['id'];
+ $this->echoTimeTalbeHeader($user_temp, $status, $user_id);
+
+ //ponastavi spremenljivke
+ $datetime_last = null;
+ $datetime_start = null;
+ $st_akcij = 0;
+ $st_akcij_sum = 0;
+ $st_seans_sum = 0;
+ $time_sum = 0;
+ }
+
+ //izpis vrstic
+ //nov start seanse
+ if(!isset($datetime_start)){
+ $datetime_start = new DateTime($rowGrupa['datetime']);
+ $st_akcij++;
+ $st_seans_sum++;
+ $action_type = $statuses;
+ }
+ //se ni druge akcije
+ else if(!isset($datetime_last)){
+ $temp_time = new DateTime($rowGrupa['datetime']);
+ $interval = $this->calculateTimeBetweenActions($datetime_start, $temp_time);
+
+ //ce je akcija od starta v kriteriju seanse, jo dodaj k seansi
+ if($interval <= $seansa){
+ $datetime_last = clone $temp_time;
+ $st_akcij++;
+ }
+ //akcija je izven kriterija seanse, izpisi samo to akcijo
+ else{
+ $datetime_last = clone $datetime_start;
+ $datetime_last->add(new DateInterval('PT5S'));
+ $time_sum += $this -> drawTimeEditsRow($datetime_start, $datetime_last, $st_akcij, $action_type, $user_id.'_'.$row_id);
+ $st_akcij = 1;
+ $st_seans_sum++;
+ $datetime_start = clone $temp_time;
+ $datetime_last = null;
+ $action_type = $statuses;
+ }
+ }
+ //seasna ze ima vsaj dve akciji
+ else{
+ $temp_time = new DateTime($rowGrupa['datetime']);
+ $interval = $this->calculateTimeBetweenActions($datetime_last, $temp_time);
+
+ //ce je akcija od prejsnje v kriteriju seanse, jo dodaj k seansi
+ if($interval <= $seansa){
+ $datetime_last = clone $temp_time;
+ $st_akcij++;
+ }
+ //akcija je izven kriterija seanse, izpisi vse prejsnje akcije
+ else{
+ $time_sum += $this -> drawTimeEditsRow($datetime_start, $datetime_last, $st_akcij, $action_type, $user_id.'_'.$row_id);
+ $st_akcij = 1;
+ $st_seans_sum++;
+ $datetime_start = clone $temp_time;
+ $datetime_last = null;
+ $action_type = $statuses;
+ }
+ }
+ $st_akcij_sum++;
+ $row_id++;
+ if($status == -1){
+ $action_type[$akcija]['sum'] ++;
+ $action_type_sum[$akcija]['sum'] ++;
+ }
+ else if($status == 0){
+ $action_type[$akcija] = isset($action_type[$akcija]) ? $action_type[$akcija]+1 : 1;
+ $action_type_sum[$akcija] = isset($action_type_sum[$akcija]) ? $action_type_sum[$akcija]+1 : 1;
+ }
+ }
+
+ //izrisi se zadnjo vrstico, ki jo ni foreach ter footer
+ if($datetime_last == null){
+ $datetime_last = clone $datetime_start;
+ $datetime_last->add(new DateInterval('PT5S'));
+ }
+ $time_sum += $this -> drawTimeEditsRow($datetime_start, $datetime_last, $st_akcij, $action_type, $user_id.'_'.$row_id);
+ $this -> echoTimeEditsFootRow($time_sum, $st_akcij_sum, $action_type_sum, $user_id.'_sum');
+ $sum_data[$user_temp]['time_sum']=$time_sum;
+ $sum_data[$user_temp]['st_akcij_sum']=$st_akcij_sum;
+ $sum_data[$user_temp]['st_seans_sum']=$st_seans_sum;
+ $sum_data[$user_temp]['user_id']=$user_id;
+
+ echo '</table>';
+
+ return $sum_data;
+ }
+
+ /**
+ * Izrisi header tabele za cas urejanja vsakega urejevalca
+ * @param type $user_temp - email of user
+ * @param type $status - status from criteria
+ * @param type $user_num - int sequence nuber of user (unique, for this site, no need to be ID)
+ */
+ function echoTimeTalbeHeader($user_temp, $status, $user_num){
+ global $lang;
+
+ echo '<tr id="edits_analysis_user_'.$user_num.'"><th colspan="100"><strong>'.$user_temp.'</strong></th></tr>';
+ echo '<tr><th>'.$lang['srv_edits_analysis_time_span'].'</th><th>'.$lang['srv_edits_analysis_time_time'].
+ '</th><th>'.$lang['srv_edits_analysis_time_actions'].'</th>'.($status < 1 ? '<th>'.$lang['srv_edits_analysis_action_type'].'</th>' : '').'</tr>';
+ }
+
+ /**
+ * Nastavi in kasneje izrise vrstico urejanja
+ *
+ * @param type $datetime_start - datetime start of editing
+ * @param type $datetime_last - datetime end of editing
+ * @param type $st_akcij - num ob actions during editing
+ * @param type $action_type - string of type of action
+ * @param type $row_id - int sequence nuber of row (unique, for this site, no need to be ID)
+ * @return type int - calculated second of editing session
+ */
+ function drawTimeEditsRow($datetime_start, $datetime_last, $st_akcij, $action_type = null, $row_id = null){
+ $seconds = 0;
+
+ //create string of actions type
+ $action_type_string = ($action_type != null) ? $this -> createActionsTypeString($action_type, $row_id) : null;
+
+ if(isset($datetime_last)){
+ $seconds = $this->calculateTimeBetweenActions($datetime_start, $datetime_last);
+ $this -> echoTimeEditsRow($datetime_last->format('Y-m-d H:i:s') .' - '. $datetime_start->format('Y-m-d H:i:s'),
+ $this->calculateTimeFromSeconds($seconds), $st_akcij, $action_type_string);
+ }
+ //ce je samo ena akcija
+ else
+ $this -> echoTimeEditsRow($datetime_start->format('Y-m-d H:i:s'), 0 ,1, $action_type_string);
+
+ return $seconds;
+ }
+
+ /**
+ * Create/convert array of action types to string for table cell
+ * @param type $action_type - array of action types
+ * @param type $row_id - int sequence nuber of row (unique user int and row in table)
+ * @return string - converter array to string to put it in table cell
+ */
+ function createActionsTypeString($action_type, $row_id){
+ $action_type_string = '';
+ //urejanje - ali drug specificen status
+ if(!isset($action_type[0]['sum'])){
+ global $lang;
+ $i = 0;
+ foreach ($action_type as $key => $at){
+ if($i == 3)
+ $action_type_string .= '<div class="srv_edits_analysis_'.$row_id.' as_link" onclick="$(\'.srv_edits_analysis_'.$row_id.'\').toggle();">'.$lang['srv_more'].'</div>';
+ if($i < 3)
+ $action_type_string .= '<div>'.$key.' ('.$at.')'.'</div>';
+ else
+ $action_type_string .= '<div class="srv_edits_analysis_'.$row_id.' displayNone">'.$key.' ('.$at.')'.'</div>';
+ $i++;
+ }
+ if($i > 3)
+ $action_type_string .= '<div class="srv_edits_analysis_'.$row_id.' as_link displayNone" onclick="$(\'.srv_edits_analysis_'.$row_id.'\').toggle();">'.$lang['srv_less'].'</div>';
+ }
+ //vsi statusi
+ else{
+ foreach ($action_type as $at){
+ if($at['sum'] > 0){
+ if($action_type_string != '')
+ $action_type_string .= '</br>';
+ $action_type_string .= $at['name'].' ('.$at['sum'].')';
+ }
+ }
+ }
+ return $action_type_string;
+ }
+
+ /**
+ * Izrise vrstico urejanja
+ * @param type $datetime - string from to editing
+ * @param type $cas_seanse - editing time
+ * @param type $st_akcij - num of editing actions
+ * @param type $action_type - string of type of action
+ */
+ function echoTimeEditsRow($datetime, $cas_seanse, $st_akcij, $action_type = null){
+ //casovni razpon urejanja
+ echo '<tr><td>'.$datetime.'</td>';
+ //cas urejanja
+ echo '<td>'.$cas_seanse.'</td>';
+ //stevilo akcij
+ echo '<td>'.$st_akcij.'</td>';
+ if($action_type != null)
+ //vrsta akcij
+ echo '<td>'.$action_type.'</td>';
+ echo '</tr>';
+ }
+
+ /**
+ * Izrise vrstico editor info
+ * @param type $user - string of editor
+ * @param type $time_sum - editing time
+ * @param type $st_akcij - num of sum editing actions
+ * @param type $st_seans_sum - num of sessions
+ * @param type $user_num - int sequence nuber of user (unique user int and row in table)
+ */
+ function echoCountEditsRow($user, $time_sum, $st_akcij, $st_seans_sum, $user_num){
+ //casovni razpon urejanja
+ echo '<tr><th><a href="#edits_analysis_user_'.$user_num.'">'.$user.'</a></th>';
+ //cas urejanja
+ echo '<td>'.$time_sum.'</td>';
+ //stevilo seans
+ echo '<td>'.$st_seans_sum.'</td>';
+ //stevilo akcij
+ echo '<td>'.$st_akcij.'</td>';
+ echo '</tr>';
+ }
+
+ /**
+ * Izrise total/footer vrstico urejanja
+ * @param type $time - seconds of editing
+ * @param type $st_akcij - num of editing actions
+ * @param type $action_type - string of type of actions
+ * @param type $row_id - int sequence nuber of user (unique, for this site, no need to be ID)
+ */
+ function echoTimeEditsFootRow($time, $st_akcij, $action_type = null, $row_id = 0){
+ global $lang;
+
+ //casovni razpon urejanja
+ echo '<tr class="colored"><td>'.$lang['srv_edits_analysis_time_total'].'</td>';
+ //cas urejanja
+ echo '<td>'.$this->calculateTimeFromSeconds($time).'</td>';
+ //stevilo akcij
+ echo '<td>'.$st_akcij.'</td>';
+ if($action_type != null)
+ //vrsta akcij
+ echo '<td>'.$this->createActionsTypeString($action_type, $row_id).'</td>';
+ echo '</tr>';
+ }
+
+ /**
+ * Izrise total/footer vrstico urejanja
+ * @param type $time - seconds of editing
+ * @param type $st_akcij - num of editing actions
+ * @param type $st_seans_sum - num of sessions
+ */
+ function echoCounterEditsFootRow($time, $st_akcij, $st_seans_sum){
+ global $lang;
+
+ //casovni razpon urejanja
+ echo '<tr class="anl_dash_bt full strong"><th>'.$lang['srv_edits_analysis_time_total'].'</th>';
+ //cas urejanja
+ echo '<td>'.$this->calculateTimeFromSeconds($time).'</td>';
+ //stevilo seans
+ echo '<td>'.$st_seans_sum.'</td>';
+ //stevilo akcij
+ echo '<td>'.$st_akcij.'</td>';
+ echo '</tr>';
+ }
+
+ /**
+ * Calculate
+ * @param type $datetime_start - datetime start of editing
+ * @param type $datetime_last - datetime end of editing
+ * @return type - float in time in minutes between actions
+ */
+ function calculateTimeBetweenActions($datetime_start, $datetime_last){
+ return abs($datetime_last ->getTimestamp() - $datetime_start->getTimestamp());
+ }
+
+ /**
+ * Get readable time from seconds
+ * @param type $seconds - time in seconds
+ * @return type string - readable time
+ */
+ function calculateTimeFromSeconds($seconds){
+ $hours = floor($seconds / 3600);
+ $mins = floor($seconds / 60 % 60);
+ $secs = floor($seconds % 60);
+
+ return sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
+ }
+
+ /**
+ * Convert false JSON (with keys without quotes and no stat and end braces)
+ * from DB to valid JSON
+ * @param type $toJSON string to convert to JSON (with keys without
+ * quotes and no stat and end braces)
+ * @return type valid converted JSON
+ */
+ function convertToJSON($toJSON){
+ $toJSON = preg_replace('/("(.*?)"|(\w+))(\s*:\s*(".*?"|.))/s', '"$2$3"$4', $toJSON);
+ $toJSON = '{'.$toJSON.'}';
+ return json_decode($toJSON, true);
+ }
+
+ /**
+ * Echo 'no data in DB'
+ */
+ function echoNoData(){
+ global $lang;
+ echo '<p><b>'.$lang['srv_edits_analysis_no_data'].'</b></p>'."\n";
+ }
+
+ function ajax_drawContinuEditsTable(){
+ if (isset ($_POST['user']))
+ $user = $_POST['user'];
+ else
+ $user = 'all';
+ if (isset ($_POST['period']))
+ $period = $_POST['period'];
+ else
+ $period = 'day';
+ if (isset($_POST['time']))
+ $time = $_POST['time'];
+ else
+ $time = '1 month';
+ if (isset ($_POST['status']))
+ $status = $_POST['status'];
+ else
+ $status = 0;
+ if (isset ($_POST['from']))
+ $from = $_POST['from'];
+ else
+ $from = '';
+ if (isset ($_POST['to']))
+ $to = $_POST['to'];
+ else
+ $to = '';
+
+ //create iterval - SQL where statement
+ $interval = $this->createInterval($time, $from, $to);
+
+ //get data
+ $data = $this->continuEditsQuery($status, $interval, $period, $user);
+
+ //draw table
+ $this->drawContinuEditsTable($data, $period);
+ }
+
+ function getList($status, $interval){
+ $sql = "SELECT st.datetime, u.email, st.post, st.get FROM srv_tracking$this->db_table st, users u WHERE st.ank_id='$this->anketa' AND u.id = st.user ". ($status != -1 ? "AND st.status=$status " : "") ."$interval";
+
+ // Loop cez vse vrednosti v vprasanjih na straneh v anketi
+ $sqlGrupa = sisplet_query($sql);
+
+ $vrstic = 0;
+ while($rowGrupa = mysqli_fetch_array($sqlGrupa)){
+ $vrstic++;
+ }
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyMeans.php b/admin/survey/classes/surveyAnalysis/class.SurveyMeans.php
new file mode 100644
index 0000000..f2155cf
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyMeans.php
@@ -0,0 +1,1369 @@
+<?php
+/** Class ki skrbi za povprečja - meanse
+ * December 2011
+ *
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+
+class SurveyMeans{
+
+ private $sid; # id ankete
+ private $db_table; # katere tabele uporabljamo
+ private $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ public $variabla1 = array('0'=> array('seq'=>'0','spr'=>'undefined', 'grd'=>'undefined')); # array drugih variable, kamor shranimo spr, grid_id, in sequenco
+ public $variabla2 = array('0'=> array('seq'=>'0','spr'=>'undefined', 'grd'=>'undefined')); # array drugih variable, kamor shranimo spr, grid_id, in sequenco
+
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo meanse (zakeširamo)
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ public $doValues = true; # checkbox Prikaži vrednosti
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ public function __construct($sid) {
+ if ((int)$sid > 0) {
+ $this->sid = $sid;
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->sid);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyUserSetting::getInstance()->Init($this->sid, $global_user_id);
+
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyMissingProfiles :: Init($this->sid,$global_user_id);
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+ SurveyZankaProfiles :: Init($this->sid, $global_user_id);
+ SurveyTimeProfiles :: Init($this->sid, $global_user_id);
+ SurveyVariablesProfiles :: Init($this->sid);
+
+ SurveyDataSettingProfiles :: Init($this->sid);
+
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->sid);
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileName = $this->SDF->getDataFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->sid);
+ $this->sessionData = SurveyUserSession::getData();
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_NO_FILE || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ Common::noDataAlert();
+ exit();
+ }
+
+ if ($this->headFileName !== null && $this->headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ # nastavimo uporabniške nastavitve
+ $this->readUserSettings();
+
+ } else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter() {
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) || ($_time_profile_awk != "" && $_time_profile_awk != null)) {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD) {
+
+ if (isset($this->_HEADERS['testdata'])) {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+ }
+
+ function readUserSettings() {
+ $sdsp = SurveyDataSettingProfiles :: getSetting();
+ $this->doValues = $sdsp['doValues'] == '1' ? true : false;
+ }
+
+ /** Prikazuje filtre
+ *
+ */
+ function DisplayFilters() {
+ if ($this->dataFileStatus == FILE_STATUS_SRV_DELETED || $this->dataFileStatus == FILE_STATUS_NO_DATA){
+ return false;
+ }
+
+ global $lang;
+ if ($this->setUpJSAnaliza == true) {
+ echo '<script>
+ window.onload = function() {
+ __analiza = 1;
+ __tabele = 1;
+ }
+ </script>';
+ }
+
+ /*echo '<div id="dataOnlyValid">';
+ SurveyStatusProfiles::displayOnlyValidCheckbox();
+ echo '</div>';*/
+
+
+ # izrišemo desne linke do posameznih nastavitev
+ $SSH -> displayAnalizaRightOptions(M_ANALYSIS_MEANS);
+ }
+
+ function DisplayLinks() {
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->sid);
+ $SSH -> displayAnalizaSubNavigation();
+ }
+
+ function ajax() {
+ #nastavimo variable če so postane
+ $this->setPostVars();
+ # izvedemo akcijo
+ switch ($_GET['a']) {
+ case 'changeDropdown':
+ $this->displayDropdowns();
+ break;
+ case 'change':
+ $this->displayData();
+ break;
+ case 'add_new_variable':
+ $this->addNewVariable();
+ break;
+ case 'changeMeansSubSetting':
+ $this->changeMeansSubSetting();
+ break;
+ case 'changeMeansShowChart':
+ $this->changeMeansShowChart();
+ break;
+ default:
+ print_r("<pre>");
+ print_r($_GET);
+ print_r($_POST);
+ break;
+ }
+
+ }
+
+ function Display() {
+ global $lang;
+
+ # ali imamo testne podatke
+ if ($this->_HAS_TEST_DATA) {
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml($this->sid);
+ $SSH -> displayTestDataBar(true);
+ }
+
+ # preberemo prednastavljene variable iz seje, če obstajajo
+ $this->presetVariables();
+
+ //$this->DisplayLinks();
+ //$this->DisplayFilters();
+
+ echo '<div id="div_means_dropdowns">';
+ $this->displayDropdowns();
+ echo '</div>'; #id="div_means_dropdowns"
+
+ echo '<div id="div_means_data">';
+ $this->displayData();
+ echo '</div>'; #id="div_means_data"
+ }
+
+ function displayDropdowns() {
+ global $lang;
+ $variables1 = $this->getVariableList(1);
+ $variables2 = $this->getVariableList(2);
+
+ echo '<div id="meansLeftDropdowns" >';
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<span class="pointer space_means_new" >&nbsp;</span>';
+ }
+ echo $lang['srv_means_label1'];
+ echo '<br />';
+ # iz header datoteke preberemo spremenljivke
+ #js: $("#means_variable_1, #means_variable_2").live('click', function() {})
+ if (count($this->variabla1) > 0) {
+ $br=null;
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<span class="pointer" id="means_add_new" onclick="means_add_new_variable(\'1\');"><span class="faicon add small icon-as_link" title=""></span></span>';
+ }
+
+ foreach($this->variabla1 AS $_key => $variabla1) {
+ echo $_br;
+ echo '<span id="v1_'.$_key.'">';
+
+ echo '<select name="means_variable_1" id="means_variable_1" onchange="change_means(); return false;" autocomplete="off">';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $variabla1['seq'] == null || $variabla1['seq'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_means_izberi_prvo'].'</option>';
+ }
+ foreach ($variables1 as $variable) {
+ echo '<option value="'.$variable['sequence'].'" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( ($variabla1['seq'] > 0 &&$variabla1['seq'] == $variable['sequence']) ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'].'</option>';
+
+ }
+
+ echo '</select>';
+ if (count($this->variabla1) > 1) {
+ echo '<span class="pointer" id="means_remove" onclick="means_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+ } else {
+ #echo '<span class="space_means_new">&nbsp;</span>';
+ }
+
+ $_br = '<br/><span class="space_means_new">&nbsp;</span>';
+ echo '</span>';
+ }
+ $_br = null;
+ }
+
+ echo '</div>';
+
+ echo '<div id="meansRightDropdowns">';
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<span class="pointer space_means_new" >&nbsp;</span>';
+ }
+ echo $lang['srv_means_label2'];
+ echo '<br />';
+
+
+ # za vsako novo spremenljivko 2 nardimo svoj select
+ if (count($this->variabla2) > 0) {
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<span class="pointer" id="means_add_new" onclick="means_add_new_variable(\'2\');"><span class="faicon add small icon-as_link" title="'.'"></span></span>';
+ }
+
+ foreach($this->variabla2 AS $_key => $variabla2) {
+ echo $_br;
+ echo '<span id="v2_'.$_key.'">';
+ echo '<select name="means_variable_2" id="means_variable_2" onchange="change_means(); return false;" autocomplete="off"'
+ . ((int)$this->variabla1['0']['seq'] > 0 ? '' : ' disabled="disabled" ')
+ .'>';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ((int)$this->variabla1['0']['seq'] == 0) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_means_najprej_prvo'].'</option>';
+ } else {
+ # če druga variabla ni izbrana dodamo tekst za izbiro druge variable
+ if ($variabla2['seq'] == null || $variabla2['seq'] == 0) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_means_izberi_drugo'].'</option>';
+ }
+ }
+
+ foreach ($variables2 as $variable) {
+ echo '<option value="'.$variable['sequence'].'" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( $variabla2['seq'] > 0 && $variabla2['seq'] == $variable['sequence'] ? ' selected="selected" ' : '')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] .'</option>';
+
+ }
+ echo '</select>';
+ if (count($this->variabla2) > 1) {
+ echo '<span class="pointer" id="means_remove" onclick="means_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+ } else {
+ echo '<span class="space_means_new">&nbsp;</span>';
+ }
+
+ $_br = '<br/><span class="space_means_new">&nbsp;</span>';
+ echo '</span>';
+ }
+ }
+ echo '</div>';
+
+ echo '<span id="meansSubSetting" class="floatLeft spaceLeft">';
+ if (count($this->variabla2) > 1) {
+ echo '<label><input id="chkMeansSeperate" type="checkbox" onchange="changeMeansSubSetting();" '.($this->sessionData['means']['meansSeperateTables']==true?' checked="checked"':'' ).'> '.$lang['srv_means_setting_1'].'</label>';
+
+ echo '<br /><span id="spanMeansJoinPercentage"'.($this->sessionData['means']['meansSeperateTables']!=true?'':' class="displayNone"').'><label><input id="chkMeansJoinPercentage" type="checkbox" onchange="changeMeansSubSetting();" '.($this->sessionData['means']['meansJoinPercentage']==true?' checked="checked"':'' ).'> '.$lang['srv_means_setting_2'].'</label></span>';
+ }
+ echo '<br /><label><input id="showChart" type="checkbox" onchange="showTableChart(\'mean\');" '.($this->sessionData['mean_charts']['showChart']==true?' checked="checked"':'' ).'> '.$lang['srv_show_charts'].'</label>';
+ echo '</span>';
+
+ echo '<br class="clr"/>';
+
+ // Ikone za izvoz (so tukaj da se refreshajo ob ajax klicu)
+ $this->displayExport();
+ }
+
+ function displayData() {
+ global $lang;
+ global $admin_type;
+
+ $br='';
+ $means = array();
+
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile(false);
+
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString($doNewLine , true);
+
+ # če imamo rekodiranje
+ $SR = new SurveyRecoding($this->sid);
+ $SR -> getProfileString();
+
+ if ($this->getSelectedVariables(1) !== null && $this->getSelectedVariables(2) !== null) {
+ $variables1 = $this->getSelectedVariables(2);
+ $variables2 = $this->getSelectedVariables(1);
+ $c1=0;
+ $c2=0;
+
+ # odvisno ok checkboxa prikazujemo druge variable v isti tabeli ali v svoji
+ if ($this->sessionData['means']['meansSeperateTables'] == true ) {
+ #prikazujemo ločeno
+ if (is_array($variables2) && count($variables2) > 0) {
+ foreach ($variables2 AS $v_second) {
+ if (is_array($variables1) && count($variables1) > 0) {
+ foreach ($variables1 AS $v_first) {
+ $_means = $this->createMeans($v_first, $v_second);
+ if ($_means != null) {
+ $means[$c1][0] = $_means;
+ }
+ $c1++;
+ }
+ }
+ }
+ }
+ } else {
+ #prikazujemo v isti tabeli
+ if (is_array($variables2) && count($variables2) > 0) {
+ foreach ($variables2 AS $v_second) {
+ if (is_array($variables1) && count($variables1) > 0) {
+ foreach ($variables1 AS $v_first) {
+ $_means = $this->createMeans($v_first, $v_second);
+ if ($_means != null) {
+ $means[$c1][$c2] = $_means;
+ }
+ $c2++;
+ }
+ }
+ $c1++;
+ $c2=0;
+ }
+ }
+ }
+
+ if (is_array($means) && count($means) > 0) {
+ $counter=0;
+ foreach ($means AS $mean_sub_grup) {
+ echo($br);
+ $this->displayMeansTable($mean_sub_grup);
+ $br='<br />';
+
+ // Zvezdica za vkljucitev v porocilo
+ $spr2 = $mean_sub_grup[0]['v1']['seq'].'-'.$mean_sub_grup[0]['v1']['spr'].'-'.$mean_sub_grup[0]['v1']['grd'];
+ $spr1 = $mean_sub_grup[0]['v2']['seq'].'-'.$mean_sub_grup[0]['v2']['spr'].'-'.$mean_sub_grup[0]['v2']['grd'];
+ SurveyAnalysis::Init($this->sid);
+ SurveyAnalysis::addCustomReportElement($type=6, $sub_type=0, $spr1, $spr2);
+
+ // Izrisemo graf za tabelo - zaenkrat samo admin
+ if($this->sessionData['mean_charts']['showChart'] && $_GET['m'] != 'analysis_creport'){
+ $tableChart = new SurveyTableChart($this->sid, $this, 'mean', $counter);
+ $tableChart->display();
+ }
+
+ $counter++;
+ }
+ }
+
+ } else {
+ # dropdowni niso izbrani
+ }
+ }
+
+ // Izvoz pdf in rtf
+ function displayExport () {
+
+ if ($this->isSelectedBothVariables()) {
+ $vars1 = $this->getSelectedVariables(1);
+ $vars2 = $this->getSelectedVariables(2);
+
+ $data1 = '';
+ $data2 = '';
+
+ foreach($vars1 as $var1){
+ $data1 .= implode(',', array_values($var1)).',';
+ }
+ $data1 = substr($data1, 0, -1);
+
+ foreach($vars2 as $var2){
+ $data2 .= implode(',', array_values($var2)).',';
+ }
+ $data2 = substr($data2, 0, -1);
+
+
+ $href_pdf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=mean_izpis&anketa=' . $this->sid);
+ $href_rtf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=mean_izpis_rtf&anketa=' . $this->sid);
+ $href_xls = makeEncodedIzvozUrlString('izvoz.php?b=export&m=mean_izpis_xls&anketa=' . $this->sid);
+ echo '<script>';
+ # nastavimopravilne linke
+ echo '$("#secondNavigation_links a#meansDoPdf").attr("href", "'.$href_pdf.'");';
+ echo '$("#secondNavigation_links a#meansDoRtf").attr("href", "'.$href_rtf.'");';
+ echo '$("#secondNavigation_links a#meansDoXls").attr("href", "'.$href_xls.'");';
+ # prikažemo linke
+ echo '$("#hover_export_icon").removeClass("hidden");';
+ echo '$("#secondNavigation_links a").removeClass("hidden");';
+ echo '</script>';
+ }
+ }
+
+ function setPostVars() {
+ if ( isset($_POST['sequence1']) && count($_POST['sequence1']) > 0 ) {
+ $i=0;
+ if (is_array($_POST['sequence1']) && count($_POST['sequence1']) > 0 ){
+ foreach ($_POST['sequence1'] AS $_seq1) {
+ $this->variabla1[$i]['seq'] = $_seq1;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['spr1']) && count($_POST['spr1']) > 0 ) {
+ $i=0;
+ if (is_array($_POST['spr1']) && count($_POST['spr1']) > 0 ){
+ foreach ($_POST['spr1'] AS $_spr1) {
+ $this->variabla1[$i]['spr'] = $_spr1;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['grid1']) && count($_POST['grid1']) > 0 ) {
+ $i=0;
+ if ( is_array($_POST['grid1']) &&count($_POST['grid1']) > 0 ){
+ foreach ($_POST['grid1'] AS $_grd1) {
+ $this->variabla1[$i]['grd'] = $_grd1;
+ $i++;
+ }
+ }
+ }
+
+ if ( isset($_POST['sequence2']) && count($_POST['sequence2']) > 0 ) {
+ $i=0;
+
+ if (is_array($_POST['sequence2']) && count($_POST['sequence2']) > 0 ){
+
+ foreach ($_POST['sequence2'] AS $_seq2) {
+ $this->variabla2[$i]['seq'] = $_seq2;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['spr2']) && count($_POST['spr2']) > 0 ) {
+ $i=0;
+ if ( is_array($_POST['spr2']) && count($_POST['spr2']) > 0 ){
+ foreach ($_POST['spr2'] AS $_spr2) {
+ $this->variabla2[$i]['spr'] = $_spr2;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['grid2']) && is_array($_POST['grid2']) && count($_POST['grid2']) > 0 ) {
+ $i=0;
+ if ( count($_POST['grid2']) > 0 ){
+ foreach ($_POST['grid2'] AS $_grd2) {
+ $this->variabla2[$i]['grd'] = $_grd2;
+ $i++;
+ }
+ }
+ }
+
+ # variable shranimo v sejo, da jih obdržimo tudi če spreminjamo nastavitve ali razne filtre analiz
+ if (isset($this->variabla1) && count($this->variabla1) > 0) {
+ $this->sessionData['means']['means_variables']['variabla1'] = $this->variabla1;
+ }
+ if (isset($this->variabla2) && count($this->variabla2) > 0) {
+ $this->sessionData['means']['means_variables']['variabla2'] = $this->variabla2;
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ /** funkcija vrne seznam primern variabel za meanse
+ *
+ */
+ function getVariableList($dropdown) {
+ if (isset($this->variablesList[$dropdown]) && is_array($this->variablesList[$dropdown]) && count($this->variablesList[$dropdown]) > 0) {
+ return $this->variablesList[$dropdown];
+ } else {
+ # pobrišemo array()
+ $this->variablesList = array();
+ # zloopamo skozi header in dodamo variable (potrebujemo posamezne sekvence)
+ foreach ($this->_HEADERS AS $skey => $spremenljivka) {
+ if ((int)$spremenljivka['hide_system'] == 1 && in_array($spremenljivka['variable'],array('email','ime','priimek','telefon','naziv','drugo'))) {
+ continue;
+ }
+
+ $tip = $spremenljivka['tip'];
+
+
+ $skala = (int)$spremenljivka['skala'];
+ # pri drugi, analizirani variabli morajo biti numerične ali ordinalne, v ostalem pa nič)
+ # skala - 0 Ordinalna
+ # skala - 1 Nominalna
+ $_dropdown_condition = $dropdown == 1
+ || ($dropdown == 2
+ && ($skala == 0 # ordinalna
+ || $tip == 7 # number
+ || $tip == 18 # vsota
+ || $tip == 20)) # multi number
+ ? true : false;
+
+
+ if (is_numeric($tip)
+ # tekstovnih tipov ne dodajamo
+
+ && $tip != 4 #text
+ && $tip != 5 #label
+ #&& $tip != 7 #number
+ #&& $tip != 8 #datum
+ && $tip != 9 #SN-imena
+ #&& $tip != 18 #vsota
+ #&& $tip != 19 #multitext
+ #&& $tip != 20 #multinumber
+ #&& $tip != 21 #besedilo*
+ && $tip != 22 #compute
+ && $tip != 25 #kvota
+ && $_dropdown_condition # ali ustreza pogoju za meanse
+ ) {
+
+ $cnt_all = (int)$spremenljivka['cnt_all'];
+ # radio in select in checkbox
+ if ($cnt_all == '1' || $tip == 1 || $tip == 3 || $tip == 2) {
+
+
+ # pri tipu radio ali select dodamo tisto variablo ki ni polje "drugo"
+ if (($tip == 1 || $tip == 3 )) {
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][$vid]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+
+ }
+ }
+ }
+ }
+ } else if ($skala == 1 || true) { # ta pogoj skala == 1 je malo sumljiv. ne vem več zakaj je tako
+
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+ } else if ($cnt_all > 1){
+
+ # imamo več skupin ali podskupin, zato zlopamo skozi gride in variable
+ if (count($spremenljivka['grids']) > 0 ) {
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # ali imamo en grid, ali več (tabele
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } else if($tip == 16||$tip == 18) {
+ # imamo multicheckbox
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>$gid,
+ 'sequence'=>$grid['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ } else {
+ # imamo več gridov - tabele
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>$sub);
+ }
+ if (count ($grid['variables']) > 0) {
+ $sub++;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[$dropdown][] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>$sub);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ return $this->variablesList[$dropdown];
+ }
+ }
+
+ function isSelectedBothVariables() {
+ $selected1 = false;
+ $selected2 = false;
+ if (count($this->variabla1)) {
+ foreach ($this->variabla1 AS $var1) {
+ if ((int)$var1['seq'] > 0) {
+ $selected1 = true;
+ }
+ }
+ }
+ if (count($this->variabla2)) {
+ foreach ($this->variabla2 AS $var2) {
+ if ((int)$var2['seq'] > 0) {
+ $selected2 = true;
+ }
+ }
+ }
+
+ return ($selected1 && $selected2);
+ }
+
+
+ function getSelectedVariables($which = 1) {
+ $selected = array();
+ if ($which == 1) {
+ if (count($this->variabla1) > 0 ) {
+ foreach ($this->variabla1 AS $var1) {
+ if ((int)$var1['seq'] > 0) {
+ $selected[] = $var1;
+ }
+ }
+ }
+ } else {
+ if (count($this->variabla2) > 0 ) {
+ foreach ($this->variabla2 AS $var2) {
+ if ((int)$var2['seq'] > 0) {
+ $selected[] = $var2;
+ }
+ }
+ }
+ }
+
+ return count($selected) > 0 ? $selected : null;
+ }
+
+ public function createMeans($v_first, $v_second) {
+ global $site_path;
+ $folder = $site_path.EXPORT_FOLDER.'/';
+
+ if ($this->dataFileName != '' && file_exists($this->dataFileName)) {
+
+ $spr1 = $this->_HEADERS[$v_first['spr']];
+ $spr2 = $this->_HEADERS[$v_second['spr']];
+
+ $grid1 = $spr1['grids'][$v_first['grd']];
+ $grid2 = $spr2['grids'][$v_second['grd']];
+
+ $sequence1 = $v_first['seq'];
+ $sequence2 = $v_second['seq'];
+
+ # za checkboxe gledamo samo odgovore ki so bili 1 in za vse opcije
+ $sekvences1 = array();
+ $sekvences2 = array();
+ $spr_1_checkbox = false;
+ $spr_2_checkbox = false;
+
+ if ($spr1['tip'] == 2 || $spr1['tip'] == 16) {
+ $spr_1_checkbox = true;
+ if ($spr1['tip'] == 2) {
+ $sekvences1 = explode('_',$spr1['sequences']);
+ }
+ if ($spr1['tip'] == 16) {
+
+ foreach ($grid1['variables'] AS $_variables) {
+ $sekvences1[] = $_variables['sequence'];
+ }
+ }
+ } else {
+ $sekvences1[] = $sequence1;
+ }
+
+ if ($spr2['tip'] == 2 || $spr2['tip'] == 16) {
+ $spr_2_checkbox = true;
+ if ($spr2['tip'] == 2 ) {
+ $sekvences2 = explode('_',$this->_HEADERS[$v_second['spr']]['sequences']);
+ }
+ if ($spr2['tip'] == 16) {
+ foreach ($grid2['variables'] AS $_variables) {
+ $sekvences2[] = $_variables['sequence'];
+ }
+ }
+ } else {
+ $sekvences2[] = $sequence2;
+ }
+
+ # pogoji so že dodani v _CURRENT_STATUS_FILTER
+
+ # dodamo filter za loop-e
+ if (isset($this->_CURRENT_LOOP['filter']) && $this->_CURRENT_LOOP['filter'] != '') {
+ $status_filter = $this->_CURRENT_STATUS_FILTER.' && '.$this->_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+ }
+
+
+ # dodamo status filter za vse sekvence checkbox-a da so == 1
+ if ($additional_status_filter != null) {
+ $status_filter .= $additional_status_filter;
+ }
+
+ # odstranimo vse zapise, kjer katerakoli od variabel vsebuje missing
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_pageMissing_answers = $this->getInvalidAnswers (MISSING_TYPE_CROSSTAB);
+ # polovimo obe sequenci
+ $tmp_file = $folder.'tmp_means_'.$this->sid.'.tmp';
+
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+ if (count($sekvences1)>0)
+ foreach ($sekvences1 AS $sequence1) {
+ if (count($sekvences2)>0)
+ foreach ($sekvences2 AS $sequence2) {
+ #skreira variable: $meansArray
+
+ $additional_filter = '';
+ if ($spr_1_checkbox == true) {
+ $_seq_1_text = ''.$sequence1;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter = ' && ($'.$sequence1.' == 1)';
+ } else {
+ $_seq_1_text = '$'.$sequence1;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key1 => $missing1) {
+ $additional_filter .= ' && ($'.$sequence1.' != '.$m_key1.')';
+ }
+ }
+
+ if ($spr_2_checkbox == true) {
+ $_seq_2_text = ''.$sequence2;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter .= ' && ($'.$sequence2.' == 1)';
+ } else {
+ $_seq_2_text = '$'.$sequence2;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key2 => $missing2) {
+ $additional_filter .= ' && ($'.$sequence2.' != '.$m_key2.')';
+ }
+ }
+
+ if (IS_WINDOWS) {
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$additional_filter.' { print \"$meansArray[\x27\",'.$_seq_2_text.',\"\x27][\x27\",'.$_seq_1_text.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$additional_filter.' { print "$meansArray[\x27",'.$_seq_2_text.',"\x27][\x27",'.$_seq_1_text.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out = shell_exec($command);
+ }
+
+ }
+
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ # izračunamo povprečja
+ $means = array();
+ $_tmp_sumaMeans = 0;
+ if(is_array($meansArray) && count($meansArray) > 0) {
+ foreach ($meansArray AS $f_key => $first) {
+ $tmp_sum = 0;
+ $tmp_cnt = 0;
+ foreach ($first AS $s_key => $second) {
+ # preverimo da je vse numeric
+ if (is_numeric($s_key) && is_numeric($second)) {
+ $tmp_sum = $tmp_sum + ($s_key*$second);
+ $tmp_cnt = $tmp_cnt + $second;
+
+ }
+ }
+ $_tmp_sumaMeans += $tmp_sum;
+ $key = $f_key;
+ if ($tmp_cnt != 0) {
+ $means[$key] = bcdiv($tmp_sum, $tmp_cnt, 3);
+ } else {
+ $means[$key] = bcdiv(0,1, 3);
+ }
+ }
+ }
+ # inicializacija
+ $_all_options = array();
+ $sumaVrstica = array();
+ $sumaSkupna = 0;
+ $sumaMeans = 0;
+
+ # poiščemo pripadajočo spremenljivko
+ $var_options = $this->_HEADERS[$v_second['spr']]['options'];
+
+
+ # najprej poiščemo (združimo) vse opcije ki so definirane kot opcije spremenljivke in vse ki so v meansih
+ if (count($var_options) > 0 && $spr_2_checkbox !== true) {
+ foreach ($var_options as $okey => $opt) {
+ $_all_options[$okey] = array('naslov'=>$opt, 'type'=>'o');
+ }
+ }
+
+ # za checkboxe dodamo posebej vse opcije
+ if ($spr_2_checkbox == true ) {
+ if ($spr2['tip'] == 2 ) {
+ $grid2 =$this->_HEADERS[$v_second['spr']]['grids']['0'];
+ }
+
+ foreach ($grid2['variables'] As $vkey => $variable) {
+ if ($variable['other'] != 1) {
+ $_all_options[$variable['sequence']] = array('naslov'=>$variable['naslov'], 'type'=>'o', 'vr_id'=> $variable['variable']);
+ }
+ }
+ }
+
+ # dodamo odgovore iz baze ki niso missingi
+ if (count($meansArray) > 0 ) {
+ foreach ($meansArray AS $_kvar1=>$_var1) {
+ # missingov ne dodajamo še zdaj, da ohranimo pravilen vrstni red
+ foreach ($_var1 AS $_kvar2=>$_var2) {
+ if (!isset($_allMissing_answers[$_kvar1]) || (isset($_allMissing_answers[$_kvar1]) && isset($_pageMissing_answers[$_kvar1]))) {
+ $sumaVrstica[$_kvar1] += $_var2;
+ }
+ }
+ # missingov ne dodajamo še zdaj, da ohranimo pravilen vrstni red
+ if (!isset($_allMissing_answers[$_kvar1]) && !isset($_all_options[$_kvar1])) {
+ $_all_options[$_kvar1] = array('naslov'=>$_kvar1, 'type'=>'t');
+ }
+
+ }
+ }
+ # dodamo še missinge, samo tiste ki so izbrani z profilom
+ foreach ($_allMissing_answers AS $miskey => $_missing) {
+ if (!isset($_pageMissing_answers[$miskey])) {
+ if ( $spr_2_checkbox !== true ) {
+ $_all_options[$miskey] = array('naslov'=>$_missing, 'type'=>'m');
+ }
+ }
+ }
+ $sumaSkupna = array_sum($sumaVrstica);
+ $sumaMeans = ($sumaSkupna > 0) ? $_tmp_sumaMeans / $sumaSkupna : 0;
+
+ # če lovimo po enotah, moramo skupne enote za vsako kolono(vrstico) izračunati posebej
+ if ($this->crossNavVsEno == 1) {
+ $sumaSkupna = 0;
+ $sumaVrstica = array();
+
+ # sestavimo filtre za posamezno variablo da ni missing
+ if (count($sekvences1)>0) {
+ $spr1_addFilter = '';
+
+ foreach ($sekvences1 AS $sequence1) {
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key1 => $missing1) {
+ $spr1_addFilter .= ' && ($'.$sequence1.' != '.$m_key1.')';
+ }
+ }
+ }
+ if (count($sekvences2)>0) {
+ $spr2_addFilter = '';
+
+ foreach ($sekvences2 AS $sequence2) {
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key2 => $missing2) {
+ $spr2_addFilter .= ' && ($'.$sequence2.' != '.$m_key2.')';
+ }
+ }
+ }
+
+ # polovimo obe sequenci
+ $tmp_file = $folder.'tmp_means_'.$this->sid.'.TMP';
+
+
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+
+ fclose($file_handler);
+
+ # preštejemo vse veljavne enote (nobena vrednost ne sme bit missing)
+ if (IS_WINDOWS) {
+ $command_all = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$spr1_addFilter.$spr2_addFilter.' { print \"$sumaSkupna++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command_all = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$spr1_addFilter. $spr2_addFilter.' { print "$sumaSkupna++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out_all = shell_exec($command_all);
+
+
+ #za vsako variablo polovimo število enot
+ #najprej za stolpce
+ if (count($sekvences1)>0) {
+ foreach ($sekvences1 AS $sequence1) {
+ if ($spr_1_checkbox == true) {
+ $_seq_1_text = ''.$sequence1;
+ # pri checkboxih lovimo samo tiste ki so 1
+ $chckbox_filter1 = ' && ($'.$sequence1.' == 1)';
+ } else {
+ $_seq_1_text = '$'.$sequence1;
+ }
+
+ if (IS_WINDOWS) {
+ $command_1 = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$chckbox_filter1.$spr2_addFilter.' { print \"$sumaVrstica[\x27\",'.$_seq_1_text.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command_1 = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$chckbox_filter1.$spr2_addFilter.' { print "$sumaVrstica[\x27",'.$_seq_1_text.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+ $out = shell_exec($command_1);
+ }
+ }
+ }
+
+
+
+ $meansArr['v1'] = $v_first; # prva variabla
+ $meansArr['v2'] = $v_second; # druga variabla
+ $meansArr['result'] = $means; # povprečja
+ $meansArr['options'] = $_all_options; # vse opcije za variablo 2
+ $meansArr['sumaVrstica'] = $sumaVrstica; #
+ $meansArr['sumaSkupna'] = $sumaSkupna; #
+ $meansArr['sumaMeans'] = $sumaMeans; #
+ return $meansArr;
+ }
+ }
+
+ function displayMeansTable($_means) {
+ global $lang;
+
+ #število vratic in število kolon
+ $cols = count($_means);
+ # preberemo kr iz prvega loopa
+ $rows = count($_means[0]['options']);
+
+ # ali prikazujemo vrednosti variable pri spremenljivkah
+ $show_variables_values = $this->doValues;
+
+ $showSingleUnits = $this->sessionData['means']['meansJoinPercentage']==true && $this->sessionData['means']['meansSeperateTables'] == false;
+
+ # izrišemo tabelo
+ echo '<table class="anl_tbl_crosstab fullWidth" style="margin-top:10px;">';
+ echo '<colgroup>';
+ echo '<col style="width:auto; min-width:30px;" />';
+ echo '<col style="width:auto; min-width:30px; " />';
+ for ($i = 0; $i < $cols; $i++) {
+ echo '<col style="width:auto; min-width:30px;" />';
+ if ($showSingleUnits == false) {
+ echo '<col style="width:auto; min-width:30px;" />';
+ }
+ }
+ if ($showSingleUnits == true) {
+ echo '<col style="width:auto; min-width:30px;" />';
+ }
+ echo '</colgroup>';
+
+ echo '<tr>';
+ #echo '<td>xx&nbsp;</td>';
+ # ime variable
+ # teksti labele:
+ $label2 = $this->getSpremenljivkaTitle($_means[0]['v2']);
+ if ($showSingleUnits == false) {
+ $span = ' colspan="2"';
+ }
+ echo '<td class="anl_bt anl_bl anl_ac rsdl_bck_title ctbCll" rowspan="2">';
+ echo $label2;
+ echo '</td>';
+
+ for ($i = 0; $i < $cols; $i++) {
+ echo '<td class="anl_bt anl_bl anl_br anl_ac rsdl_bck_title ctbCll"'.$span.'>';
+ $label1 = $this->getSpremenljivkaTitle($_means[$i]['v1']);
+ echo $label1;
+ echo '</td>';
+ }
+ if ($showSingleUnits == true) {
+ echo '<td class="anl_bl ">&nbsp;</td>';
+ }
+ echo '</tr>';
+ echo '<tr>';
+
+ for ($i = 0; $i < $cols; $i++) {
+ #Povprečje
+ echo '<td class="anl_bt anl_bl anl_br anl_ac rsdl_bck_variable1 ctbCll" >';
+ echo $lang['srv_means_label'];
+ echo '</td>';
+ #enote
+ if ($showSingleUnits == false) {
+ echo '<td class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">'.$lang['srv_means_label4'].'</td>';
+ }
+ }
+ if ($showSingleUnits == true) {
+ echo '<td class="anl_bl anl_bt anl_br anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">'.$lang['srv_means_label4'].'</td>';
+ }
+
+ echo '</tr>';
+
+ if (count($_means[0]['options']) > 0) {
+
+ foreach ($_means[0]['options'] as $ckey2 =>$crossVariabla2) {
+ $units_per_row = 0;
+ echo '<tr>';
+ echo '<td class="anl_bt anl_bl anl_ac rsdl_bck_variable1 ctbCll">';
+ echo $crossVariabla2['naslov'];
+ # če ni tekstovni odgovor dodamo key
+ if ($crossVariabla2['type'] !== 't' ) {
+ if ($show_variables_values == true) {
+ if ($crossVariabla2['vr_id'] == null) {
+ echo '&nbsp;( '.$ckey2.' )';
+ } else {
+ echo '&nbsp;( '.$crossVariabla2['vr_id'].' )';
+ }
+ }
+ }
+ echo '</td>';
+ # celice z vsebino
+ for ($i = 0; $i < $cols; $i++) {
+ echo '<td class="ct_in_cell anl_br'.'" k1="'.$ckey1.'" k2="'.$ckey2.'" n1="'.$crossVariabla1['naslov'].'" n2="'.$crossVariabla2['naslov'].'" v1="'.$crossVariabla1['vr_id'].'" v2="'.$crossVariabla2['vr_id'].'">';
+ echo $this->formatNumber($_means[$i]['result'][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'));
+ echo '</td>';
+ if ($showSingleUnits == false) {
+ echo '<td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 crostabSuma">';
+ echo (int)$_means[$i]['sumaVrstica'][$ckey2];
+ echo '</td>';
+ } else {
+ $units_per_row = max($units_per_row,(int)$_means[$i]['sumaVrstica'][$ckey2]);
+ }
+ }
+ if ($showSingleUnits == true) {
+ echo '<td class="anl_ac anl_bl anl_bt anl_br rsdl_bck0 crostabSuma">';
+ echo $units_per_row;
+ echo '</tr>';
+ }
+ echo '</tr>';
+ $max_units += $units_per_row;
+ }
+ }
+ echo '<tr>';
+ echo '<td class="anl_bb anl_bt anl_bl anl_ac red anl_ita anl_bck_text_0 rsdl_bck_variable1 ctbCll">'.$lang['srv_means_label3'].'</td>';
+ for ($i = 0; $i < $cols; $i++) {
+ echo '<td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">';
+
+ echo $this->formatNumber($_means[$i]['sumaMeans'], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'));
+ echo '</td>';
+ if ($showSingleUnits == false) {
+ echo '<td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">';
+ echo (int)$_means[$i]['sumaSkupna'];
+ echo '</td>';
+ }
+ }
+ if ($showSingleUnits == true) {
+ echo '<td class="anl_ac anl_bt anl_bl anl_br anl_bb rsdl_bck0 crostabSuma">';
+ echo $max_units;
+ echo '</tr>';
+ }
+
+ echo '</tr>';
+ echo '</table>';
+ }
+
+ /** Sestavi array nepravilnih odgovorov
+ *
+ */
+ function getInvalidAnswers($type) {
+ $result = array();
+ $missingValuesForAnalysis = SurveyMissingProfiles :: GetMissingValuesForAnalysis($type);
+
+ foreach ($missingValuesForAnalysis AS $k => $answer) {
+ $result[$k] = array('text'=>$answer,'cnt'=>0);
+ }
+ return $result;
+ }
+
+
+
+ /** Naredimo formatiran izpis
+ *
+ * @param $value
+ * @param $digit
+ * @param $sufix
+ */
+
+ static function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands).$sufix;
+
+ return $result;
+ }
+
+ function addNewVariable() {
+ global $lang;
+ $which = $_POST['which'];
+ $variables = $this->getVariableList($which);
+ $multiple = true;
+
+
+ if ($which == '1') {
+ echo '<br/>';
+ echo '<span class="space_means_new">&nbsp;</span>';
+ echo '<select name="means_variable_'.$which.'" id="means_variable_'.$which.'" onchange="change_means(); return false;" autocomplete="off"'
+ .'>';
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ( $variabla1['seq'] == null || $variabla1['seq'] == 0 ) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_izberi_more'].'</option>';
+ }
+
+ foreach ($variables as $variable) {
+ echo '<option value="'.$variable['sequence'].'" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] . '</option>';
+
+ }
+ echo '</select>';
+ echo '<span class="pointer" id="means_remove" onclick="means_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+
+ } else {
+ # which = 2
+ echo '<br/>';
+ echo '<span class="space_means_new">&nbsp;</span>';
+ echo '<select name="means_variable_'.$which.'" id="means_variable_'.$which.'" onchange="change_means(); return false;" autocomplete="off"'
+ .'>';
+
+ # ce prva variabla ni izbrana, dodamo tekst za izbiro prve variable
+ if ((int)$this->variabla1['0']['seq'] > 0) {
+ echo '<option value="0" selected="selected" >'. $lang['srv_analiza_crosstab_najprej_prvo'].'</option>';
+ } else {
+ # če druga variabla ni izbrana dodamo tekst za izbiro druge variable
+ echo '<option value="0" selected="selected">'. $lang['srv_analiza_crosstab_izberi_more'].'</option>';
+ }
+
+ foreach ($variables as $variable) {
+ echo '<option value="'.$variable['sequence'].'" spr_id="'.$variable['spr_id'].'" '
+ . ( isset($variable['grd_id']) ? ' grd_id="'.$variable['grd_id'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] . '</option>';
+
+ }
+ echo '</select>';
+ echo '<span class="pointer" id="means_remove" onclick="means_remove_variable(this);"><span class="faicon delete_circle icon-orange_link" title=""></span></span>';
+ }
+ }
+
+ function getSpremenljivkaTitle($v_first) {
+ global $lang;
+ # podatki spremenljivk
+ $spremenljivka_id = $v_first['spr'];
+ $grid_id = $v_first['grd'];
+ $sekvenca = $v_first['seq'];
+
+ $spremenljivka = $this->_HEADERS[$spremenljivka_id];
+ $grid = $spremenljivka['grids'][$grid_id];
+
+
+ # za multicheckboxe popravimo naslov, na podtip
+ $labela = null;
+ if ($spremenljivka['tip'] == '6' || $spremenljivka['tip'] == '7' || $spremenljivka['tip'] == '16' || $spremenljivka['tip'] == '17' || $spremenljivka['tip'] == '18' || $spremenljivka['tip'] == '19' || $spremenljivka['tip'] == '20' || $spremenljivka['tip'] == '21' ) {
+ foreach ($spremenljivka['grids'] AS $grids) {
+ foreach ($grids['variables'] AS $variable) {
+ if ($variable['sequence'] == $sekvenca) {
+ $labela .= '<span class="anl_variabla">';
+ $labela .= '<a href="/" title="'.$lang['srv_predogled_spremenljivka'].'" onclick="showspremenljivkaSingleVarPopup(\''.$spremenljivka_id.'\'); return false;">';
+ $labela .= strip_tags($spremenljivka['naslov']);
+ if ($show_variables_values == true) {
+ $labela .= '&nbsp;('.strip_tags($spremenljivka['variable']).')';
+ }
+ $labela .= '</a>';
+ $labela .= '</span>';
+
+ if ($spremenljivka['tip'] == '16') {
+ if (strip_tags($grid['naslov']) != $lang['srv_new_text']) {
+ $labela .= '<br/>'.strip_tags($grid['naslov']);
+ }
+ $labela .= '&nbsp;('.strip_tags($grid['variable']).')' ;
+ } else {
+ if (strip_tags($variable['naslov']) != $lang['srv_new_text']) {
+ $labela .= '<br/>'.strip_tags($variable['naslov']);
+ }
+ if ($show_variables_values == true) {
+ $labela .= '&nbsp;('.strip_tags($variable['variable']).')';
+ }
+ }
+
+ }
+ }
+ }
+ }
+ if ($labela == null) {
+ $labela = '<span class="anl_variabla">';
+ $labela .= '<a href="/" title="'.$lang['srv_predogled_spremenljivka'].'" onclick="showspremenljivkaSingleVarPopup(\''.$spremenljivka_id.'\'); return false;">';
+ $labela .= strip_tags($spremenljivka['naslov']);
+ if ($show_variables_values == true) {
+ $labela .= '&nbsp;('.strip_tags($spremenljivka['variable']).')';
+ }
+ $labela .= '</a>';
+ $labela .= '</span>'.NEW_LINE;
+ }
+ return $labela;
+ }
+
+ function changeMeansSubSetting() {
+ $this->sessionData['means']['meansSeperateTables'] = ($_POST['chkMeansSeperate'] == 1);
+ $this->sessionData['means']['meansJoinPercentage'] = ($_POST['chkMeansJoinPercentage'] == 1);
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function changeMeansShowChart() {
+ $this->sessionData['mean_charts']['showChart'] = ($_POST['showChart'] == 'true');
+ $this->sessionData['means']['meansSeperateTables'] = ($_POST['showChart'] == 'true') ? true : $this->sessionData['means']['meansSeperateTables'];
+ $this->sessionData['means']['meansJoinPercentage'] = ($_POST['showChart'] == 'true') ? true : $this->sessionData['means']['meansJoinPercentage'];
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function presetVariables() {
+ # preberemo prednastavljene variable iz seje, če obstajajo
+ if (isset($this->sessionData['means']['means_variables']['variabla1']) && count($this->sessionData['means']['means_variables']['variabla1']) > 0) {
+ $this->variabla1 = $this->sessionData['means']['means_variables']['variabla1'];
+ }
+ if (isset($this->sessionData['means']['means_variables']['variabla2']) && count($this->sessionData['means']['means_variables']['variabla2']) > 0) {
+ $this->variabla2 = $this->sessionData['means']['means_variables']['variabla2'];
+ }
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyMultiCrosstabs.php b/admin/survey/classes/surveyAnalysis/class.SurveyMultiCrosstabs.php
new file mode 100644
index 0000000..67664da
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyMultiCrosstabs.php
@@ -0,0 +1,2489 @@
+<?php
+
+define("AUTO_HIDE_ZERRO_VALUE", 20); # nad koliko kategorij skrivamo ničelne vrednosti
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+define("R_FOLDER", "admin/survey/R");
+
+class SurveyMultiCrosstabs {
+
+ public $ank_id; # id ankete
+
+ public $table_id = 0; # id tabele, ki jo trenutno izrisujemo
+ public $table_settings = array(); # nastavitve za tabelo
+
+ public $db_table; # katere tabele uporabljamo
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ public $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ public $_CURRENT_STATUS_FILTER = ''; # filter po statusih, privzeto izvažamo 6 in 5
+ public $currentMissingProfile = 1; # Kateri Missing profil je izbran
+ public $missingProfileData = null; # Nastavitve trenutno izbranega manjkajočega profila
+
+ public $_CURRENT_LOOP = null; # trenutni loop
+
+ /* Variable so definirane v obliki:
+ * '37507_0_0_0' = x_y_z_w
+ * -> x => spr_id
+ * -> y => loop id
+ * -> z => grid_id
+ * -> y => variable id
+ *
+ */
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo crostabulacije (zakeširamo)
+
+ public $selectedVars = null; # Seznam izbranih variabel v tabeli
+ public $crosstabData = null; # Izracunani podatki za izbrane spremenljivke
+ public $crosstabClass = null; # Instanca crosstab razreda (za racunanje)
+
+ public $colSpan = 0; # Celoten span stolpcev (stevilo vseh childov)
+ public $rowSpan = 0; # Celoten span vrstic (stevilo vseh childov)
+ public $colLevel2 = false; # Ali imamo v stolpcih kaksen 2. nivo
+ public $rowLevel2 = false; # Ali imamo v vrsticah kaksen 2. nivo
+ public $fullColSpan = 0; # Celoten span stolpcev (stevilo vseh childov) z sumami (ce jih imamo)
+
+ public $isCheckbox = false; # Ce je kaksen checkbox v tabeli - potem imamo opcijo navedbe/enote
+
+
+ /**
+ * Inicializacija
+ *
+ * @param int $anketa
+ */
+ public function __construct( $anketa = null ) {
+ global $global_user_id, $site_path, $lang;
+
+ // če je podan ID ankete
+ if ((int)$anketa > 0) {
+
+ $this->ank_id = $anketa;
+
+ // Poskrbimo za datoteko s podatki
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->ank_id);
+ $SDF->prepareFiles();
+
+ $this->headFileName = $SDF->getHeaderFileName();
+ $this->dataFileName = $SDF->getDataFileName();
+ $this->dataFileStatus = $SDF->getStatus();
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->ank_id);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+
+ $this->_CURRENT_STATUS_FILTER = STATUS_FIELD.' ~ /6|5/';
+
+ SurveyStatusProfiles::Init($this->ank_id);
+ SurveyMissingProfiles :: Init($this->ank_id, $global_user_id);
+
+ SurveyConditionProfiles :: Init($this->ank_id, $global_user_id);
+ SurveyZankaProfiles :: Init($this->ank_id, $global_user_id);
+ SurveyTimeProfiles :: Init($this->ank_id, $global_user_id);
+ SurveyDataSettingProfiles :: Init($this->ank_id);
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ SurveyUserSetting::getInstance()->Init($this->ank_id, $global_user_id);
+
+ # Ce ne obstaja nobena tabela jo ustvarimo
+ $sql = sisplet_query("SELECT id FROM srv_mc_table WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+ if(mysqli_num_rows($sql) == 0){
+ $name = $lang['srv_table'].' 1';
+ sisplet_query("INSERT INTO srv_mc_table (ank_id, usr_id, time_created, name) VALUES('$this->ank_id', '$global_user_id', NOW(), '$name')");
+ $table_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $this->table_id = $table_id;
+ SurveyUserSetting :: getInstance()->saveSettings('default_mc_table', $table_id);
+
+ $this->table_settings[$this->table_id] = array(
+ 'title' => '',
+ 'numerus' => 1,
+ 'percent' => 0,
+ 'sums' => 0,
+ 'navVsEno' => 1,
+ 'avgVar' => '',
+ 'delezVar' => '',
+ 'delez' => ''
+ );
+ }
+ else{
+ $this->table_id = SurveyUserSetting :: getInstance()->getSettings('default_mc_table');
+
+ // Preberemo nastavitve trenutno izbrane tabele
+ if(isset($this->table_id) && $this->table_id != ''){
+ $sql = sisplet_query("SELECT * FROM srv_mc_table WHERE id='$this->table_id' AND ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+ }
+ else{
+ $sql = sisplet_query("SELECT * FROM srv_mc_table WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id' ORDER BY time_created ASC");
+ }
+ $row = mysqli_fetch_array($sql);
+ $this->table_id = $row['id'];
+ $this->table_settings[$this->table_id] = array(
+ 'title' => $row['title'],
+ 'numerus' => $row['numerus'],
+ 'percent' => $row['percent'],
+ 'sums' => $row['sums'],
+ 'navVsEno' => $row['navVsEno'],
+ 'avgVar' => $row['avgVar'],
+ 'delezVar' => $row['delezVar'],
+ 'delez' => $row['delez']
+ );
+ }
+ }
+ else {
+ die("Napaka!");
+ }
+ }
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter() {
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ if ($this->headFileName !== null && $this->headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) || ($_time_profile_awk != "" && $_time_profile_awk != null)) {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD) {
+
+ if (isset($this->_HEADERS['testdata'])) {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+ }
+
+ function display () {
+ global $lang;
+ global $global_user_id;
+
+ // Napolnimo variable s katerimi lahko operiramo
+ $this->getVariableList();
+
+ //$this->displayLinks();
+ $this->displayFilters();
+
+ $this->displayExport();
+
+
+ echo '<div id="mc_holder">';
+
+
+ // Div s spremenljivkami za drag - zaenkrat samo radio, checkbox, dropdown, multigrid, multicheckbox - ZAENKRAT BREZ CHECKBOXOV (2,16)!
+ echo '<div id="spr_list"><ul>';
+ foreach($this->variablesList AS $spr){
+ if($spr['canChoose'] && in_array($spr['tip'], array(1,3,6))){
+
+ echo '<li class="draggable mc_draggable" id="'.$spr['spr_id'].'-'.$spr['sequence'].'">';
+ echo '<span class="strong">'.$spr['variable'].'</span> - '.$this->snippet($spr['naslov'], 25);
+ echo '</li>';
+ }
+ }
+ echo '</ul></div>';
+
+
+ // Izris diva za izbiro tabele
+ $this->displayMCTablesPopups();
+
+ // Izris diva za nastavitve tabele
+ echo '<div id="mc_table_settings" class="mc_table_settings">';
+ $this->displayTableSettings();
+ echo '</div>';
+
+ // Naslov tabele
+ echo '<div id="title_'.$this->table_id.'" class="mc_table_title">';
+ $this->displayTableTitle($this->table_settings[$this->table_id]['title']);
+ echo '</div>';
+
+ // Izris tabele
+ echo '<div id="mc_table_holder_'.$this->table_id.'" class="mc_table_holder">';
+ $this->displayTable();
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ // Prikaze tabelo s podatki
+ public function displayTable(){
+ global $lang;
+ global $site_url;
+
+ // Napolnimo variable ki so ze izbrane
+ $this->getSelectedVars();
+
+ echo '<table id="'.$this->table_id.'" cellspacing="0" cellpadding="0" class="mc_table">';
+
+
+ // Imamo 2 nivoja
+ if($this->colLevel2){
+
+ // Izrisemo VERTIKALNO izbrane spremenljivkec - 1. vrstica
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<tr><td class="borderless" '.$colspan.'></td>';
+ if(count($this->selectedVars['ver'])){
+ foreach($this->selectedVars['ver'] as $var){
+
+ $rowspan = count($var['sub']) > 0 ? '':' rowspan="2"';
+ $colspan = ' colspan="'.$var['span'].'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="undefined" class="spr vertical droppable full" '.$rowspan . $colspan.'>';
+
+ echo $this->snippet($this->variablesList[$var['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+
+ echo '</td>';
+ }
+ }
+ // Izrisemo se zadnjo prazno navpicno celico vrstico
+ echo '<td id="undefined" class="spr vertical droppable empty" rowspan="4">'.$lang['srv_multicrosstabs_add'].'</td>';
+ echo '</tr>';
+
+ // Izrisemo VARIABLE za spremenljivko - 2. vrstica
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<tr><td class="borderless" '.$colspan.'></td>';
+ if(count($this->selectedVars['ver'])){
+ foreach($this->selectedVars['ver'] as $var){
+
+ if(count($var['sub']) > 0){
+ // Loop cez variable spremenljivke
+ foreach($this->variablesList[$var['spr']]['options'] as $option){
+
+ $colspan = ' colspan="'.( $var['span'] / count($this->variablesList[$var['spr']]['options']) ).'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="undefined" class="var vertical full" '.$colspan.'>';
+
+ echo $this->snippet($option, 25);
+
+ echo '</td>';
+ }
+ }
+ }
+ }
+ echo '</tr>';
+
+ // Izris vrstic za 2. nivo - 3. in 4. vrstica
+
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<tr><td class="borderless" '.$colspan.'></td>';
+ if(count($this->selectedVars['ver'])){
+ foreach($this->selectedVars['ver'] as $parentVar){
+
+ foreach($this->variablesList[$parentVar['spr']]['options'] as $option){
+ // ce imamo childe na 2. nivoju
+ if(count($parentVar['sub']) > 0){
+ foreach($parentVar['sub'] as $var){
+
+ $colspan = ' colspan="'.( count($this->variablesList[$var['spr']]['options']) ).'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="'.$parentVar['vrstni_red'].'" class="spr vertical full" '.$colspan.'>';
+
+ echo $this->snippet($this->variablesList[$var['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+
+ echo '</td>';
+ }
+ }
+ else{
+ $rowspan = ' rowspan="2"';
+ $colspan = ' colspan="'.( $parentVar['span'] / count($this->variablesList[$parentVar['spr']]['options']) ).'"';
+ echo '<td id="'.$parentVar['vrstni_red'].'" spr_id="'.$parentVar['spr'].'" parent="undefined" class="var vertical full" '.$rowspan . $colspan.'>';
+
+ echo $this->snippet($option, 25);
+
+ echo '</td>';
+ }
+ }
+ }
+ }
+ echo '</tr>';
+
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<tr><td class="borderless" '.$colspan.'></td>';
+ if(count($this->selectedVars['ver'])){
+ foreach($this->selectedVars['ver'] as $parentVar){
+
+ foreach($this->variablesList[$parentVar['spr']]['options'] as $option){
+ // ce imamo childe na 2. nivoju
+ if(count($parentVar['sub']) > 0){
+ foreach($parentVar['sub'] as $var){
+
+ foreach($this->variablesList[$var['spr']]['options'] as $suboption){
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="'.$parentVar['vrstni_red'].'" class="var vertical full">';
+
+ echo $this->snippet($suboption, 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+
+ echo '</td>';
+ }
+ }
+ }
+ }
+ }
+ }
+ echo '</tr>';
+ }
+ // Imamo samo 1 nivo
+ else{
+ // Izrisemo VERTIKALNO izbrane spremenljivkec - 1. vrstica
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<tr><td class="borderless" '.$colspan.'></td>';
+ if(count($this->selectedVars['ver'])){
+ foreach($this->selectedVars['ver'] as $var){
+
+ $colspan = ' colspan="'.($this->table_settings[$this->table_id]['sums'] == 1 && !$this->rowLevel2 ? $var['span']+1 : $var['span']).'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="undefined" class="spr vertical droppable full" '.$colspan.'>';
+
+ echo $this->snippet($this->variablesList[$var['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+
+ echo '</td>';
+ }
+ }
+ // Nimamo nobene vertikalne spremenljivke in 2 horizontalni
+ elseif($this->rowLevel2){
+ echo '<td class="borderless"></td>';
+ }
+
+ // Izrisemo se zadnjo prazno navpicno celico vrstico
+ echo '<td id="undefined" class="spr vertical droppable empty" rowspan="2">'.$lang['srv_multicrosstabs_add'].'</td>';
+ echo '</tr>';
+
+ // Izrisemo VARIABLE za spremenljivko - 2. vrstica
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<tr><td class="borderless" '.$colspan.'></td>';
+ if(count($this->selectedVars['ver'])){
+ foreach($this->selectedVars['ver'] as $var){
+
+ // Loop cez variable spremenljivke
+ foreach($this->variablesList[$var['spr']]['options'] as $option){
+
+ $colspan = ' colspan="'.( $var['span'] / count($this->variablesList[$var['spr']]['options']) ).'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="undefined" class="var vertical full" '.$colspan.'>';
+
+ echo $this->snippet($option, 25);
+
+ echo '</td>';
+ }
+
+ // Suma (ce jo imamo vklopljeno)
+ if($this->table_settings[$this->table_id]['sums'] == 1 && !$this->rowLevel2){
+ echo '<td class="var sums">';
+ echo $lang['srv_analiza_crosstab_skupaj'];
+ echo '</td>';
+ }
+ }
+ }
+ echo '</tr>';
+ }
+
+
+
+ // Izrisemo HORIZONTALNO izbrane variable
+ if(count($this->selectedVars['hor'])){
+
+ // Imamo 2 nivoja vrstic
+ if($this->rowLevel2){
+ foreach($this->selectedVars['hor'] as $parentVar){
+
+ $cnt = 0;
+ $order0 = 0;
+
+ foreach($this->variablesList[$parentVar['spr']]['options'] as $option){
+
+ $cnt2 = 0;
+
+ // ce imamo childe na 2. nivoju
+ if(count($parentVar['sub']) > 0){
+ foreach($parentVar['sub'] as $var){
+
+ $cnt3 = 0;
+
+ foreach($this->variablesList[$var['spr']]['options'] as $suboption){
+
+ echo '<tr>';
+
+ if($cnt == 0){
+ $span = $this->table_settings[$this->table_id]['sums'] == 1 && count($this->selectedVars['ver']) == 0 ? $parentVar['span']+(count($parentVar['sub'])*count($this->variablesList[$parentVar['spr']]['options'])) : $parentVar['span'];
+ $rowspan = ' rowspan="'.$span.'"';
+ echo '<td id="'.$parentVar['vrstni_red'].'" spr_id="'.$parentVar['spr'].'" parent="undefined" class="spr horizontal droppable full" '.$rowspan.'>';
+
+ echo $this->snippet($this->variablesList[$parentVar['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+ echo '</td>';
+ }
+
+ // Variabla
+ if($cnt2 == 0){
+ $span = $this->table_settings[$this->table_id]['sums'] == 1 && count($this->selectedVars['ver']) == 0 ? $parentVar['span'] / count($this->variablesList[$parentVar['spr']]['options']) + count($parentVar['sub']) : $parentVar['span'] / count($this->variablesList[$parentVar['spr']]['options']);
+ $rowspan = ' rowspan="'.$span.'"';
+ echo '<td class="var horizontal full" '.$rowspan.'>';
+ echo $this->snippet($option, 25);
+ echo '</td>';
+ }
+
+ if($cnt3 == 0){
+ $span = $this->table_settings[$this->table_id]['sums'] == 1 && count($this->selectedVars['ver']) == 0 ? count($this->variablesList[$var['spr']]['options']) + 1 : count($this->variablesList[$var['spr']]['options']);
+ $rowspan = ' rowspan="'.$span.'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="'.$parentVar['vrstni_red'].'" class="spr horizontal full" '.$rowspan.'>';
+
+ echo $this->snippet($this->variablesList[$var['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+ echo '</td>';
+ }
+
+ // Variabla 2
+ echo '<td class="var horizontal full">';
+ echo $this->snippet($suboption, 25);
+ echo '</td>';
+
+ // Celice s podatki
+ $this->displayDataCells($parentVar, $order0, $var, $cnt3);
+
+ echo '<td class="empty"></td>';
+
+ echo '</tr>';
+
+ $cnt++;
+ $cnt2++;
+ $cnt3++;
+ }
+
+ $order0++;
+
+ // Izrisemo se sumo ce je vklopljena
+ if($this->table_settings[$this->table_id]['sums'] == 1 && count($this->selectedVars['ver']) == 0){
+
+ echo '<tr>';
+
+ echo '<td class="var sums">'.$lang['srv_analiza_crosstab_skupaj'].'</td>';
+
+ $crosstabs = $this->crosstabData[$parentVar['spr'].'-'.$var['spr']];
+
+ $keys1 = array_keys($crosstabs['options2']);
+ $key = ceil($cnt / (count($this->variablesList[$var['spr']]['options'])*count($parentVar['sub']))) - 1;
+ $val = $keys1[$key];
+
+ $this->displaySumsCell($parentVar, $var, $val, $orientation=0);
+
+ echo '<td class="empty"></td>';
+
+ echo '</tr>';
+ }
+ }
+ }
+ else{
+ echo '<tr>';
+
+ if($cnt == 0){
+ $rowspan = ' rowspan="'.$parentVar['span'].'"';
+ echo '<td id="'.$parentVar['vrstni_red'].'" spr_id="'.$parentVar['spr'].'" parent="undefined" class="spr horizontal droppable full" '.$rowspan.' colspan="2">';
+
+ echo $this->snippet($this->variablesList[$parentVar['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+ echo '</td>';
+ }
+
+ // Variabla
+ $rowspan = ' rowspan="'.( $parentVar['span'] / count($this->variablesList[$parentVar['spr']]['options']) ).'"';
+ echo '<td class="var horizontal full" '.$rowspan.' colspan="2">';
+ echo $this->snippet($option, 25);
+ echo '</td>';
+
+
+ // Celice s podatki
+ $this->displayDataCells($parentVar, $cnt);
+
+ echo '<td class="empty"></td>';
+
+ echo '</tr>';
+
+ $cnt++;
+ }
+ }
+ }
+ }
+ // Imamo samo 1 nivo vrstic
+ else{
+ foreach($this->selectedVars['hor'] as $var){
+
+ $cnt = 0;
+ foreach($this->variablesList[$var['spr']]['options'] as $option){
+ echo '<tr>';
+
+ if($cnt == 0){
+ $rowspan = ' rowspan="'.($this->table_settings[$this->table_id]['sums'] == 1 && count($this->selectedVars['ver']) > 0 && !$this->colLevel2 ? $var['span']+1 : $var['span']).'"';
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="undefined" class="spr horizontal droppable full" '.$rowspan.'>';
+
+ echo $this->snippet($this->variablesList[$var['spr']]['naslov'], 25);
+
+ // Gumb za brisanje
+ echo '<div class="delete_var" onclick="deleteVariable(this);"></div>';
+ echo '</td>';
+ }
+
+ // Variabla
+ echo '<td id="'.$var['vrstni_red'].'" spr_id="'.$var['spr'].'" parent="undefined" class="var horizontal full">';
+ echo $this->snippet($option, 25);
+ echo '</td>';
+
+ // Celice s podatki
+ $this->displayDataCells($var, $cnt);
+
+
+ echo '<td class="empty"></td>';
+
+ echo '</tr>';
+
+ $cnt++;
+ }
+
+ // Vrstica za sumo (ce jo imamo vklopljeno)
+ if($this->table_settings[$this->table_id]['sums'] == 1 && count($this->selectedVars['ver']) > 0 && !$this->colLevel2){
+ echo '<tr>';
+ echo '<td class="var sums">'.$lang['srv_analiza_crosstab_skupaj'].'</td>';
+
+ // Loop cez vse stolpce
+ foreach($this->selectedVars['ver'] as $spr2){
+
+ // Loop cez variable trenutnega stolpca
+ $cnt = 0;
+ foreach($this->variablesList[$spr2['spr']]['options'] as $var2){
+
+ $crosstabs = $this->crosstabData[$var['spr'].'-'.$spr2['spr']];
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val = $keys1[$cnt];
+
+ $this->displaySumsCell($var, $spr2, $val, $orientation=1);
+
+ $cnt++;
+ }
+
+ // Krizanje navpicne in vodoravne sume
+ $this->displaySumsCell($var, $spr2, 0, $orientation=2);
+ }
+
+ echo '<td class="empty"></td>';
+
+ echo '</tr>';
+ }
+ }
+ }
+ }
+
+
+ // Izrisemo se zadnjo prazno vodoravno vrstico
+ echo '<tr class="last">';
+
+ if($this->rowSpan == 0)
+ $colspan = ' colspan="1"';
+ elseif(!$this->rowLevel2)
+ $colspan = ' colspan="2"';
+ else
+ $colspan = ' colspan="4"';
+ echo '<td id="undefined" class="spr horizontal droppable empty" '.$colspan.'>';
+ echo $lang['srv_multicrosstabs_add'];
+ echo '</td>';
+
+ for($i=0; $i<=$this->colSpan; $i++){
+ echo '<td class="empty"></td>';
+ }
+
+ // Dodatne prazne celice ce imamo sumo
+ if($this->table_settings[$this->table_id]['sums'] == 1 && ((!$this->colLevel2 && !$this->rowLevel2) || count($this->selectedVars['ver']) == 0)){
+ for($i=0; $i<count($this->selectedVars['ver']); $i++){
+ echo '<td class="empty"></td>';
+ }
+
+ if(count($this->selectedVars['ver']) == 0 && $this->rowLevel2)
+ echo '<td class="empty"></td>';
+ }
+
+ echo '</tr>';
+
+
+ echo '</table>';
+
+
+
+ echo '<div class="mc_table_bottom_settings">';
+
+ // Izrisemo legendo
+ $this->displayLegend();
+
+
+ // Ce smo v custom reportu tega ne izpisemo
+ if($_GET['m'] != 'analysis_creport'){
+
+ // Zvezdica za vkljucitev v porocilo
+ SurveyAnalysisHelper::getInstance()->addCustomReportElement($type=10, $sub_type=0, $spr1=$this->table_id);
+
+
+ echo '<script type="text/javascript">';
+
+ // Nastavimo droppable (drugace po ajaxu ne dela)
+ echo '$(function(){createDroppable();});';
+
+ // Nastavimo gumb za brisanje spremenljivke
+ echo '$(".mc_table tr td.spr").mouseover(function(){$(this).find(".delete_var").show();});';
+ echo '$(".mc_table tr td.spr").mouseout(function(){$(this).find(".delete_var").hide();});';
+
+ echo '</script>';
+ }
+
+ echo '</div>';
+ }
+
+ // Izpis celic v vrstici s podatki
+ function displayDataCells($spr1, $var1, $spr2='', $var2=''){
+
+ // Ce nimamo nobenega krizanja izpisemo prazne
+ if($spr2 == '' && $this->colSpan == 0){
+ for($i=0; $i<$this->colSpan; $i++){
+ echo '<td class="data"></td>';
+ }
+ }
+
+ // Ce nimamo stolpcev - krizanje dveh vrstic
+ elseif($spr2 != '' && $this->colSpan == 0){
+
+ $spr1_temp = explode('-', $spr1['spr']);
+ $grd = $this->variablesList[$spr1['spr']]['grd_id'];
+ $variabla1 = array('seq' => $spr1_temp[1], 'spr' => $spr1_temp[0], 'grd' => $grd);
+
+ $spr2_temp = explode('-', $spr2['spr']);
+ $grd = $this->variablesList[$spr2['spr']]['grd_id'];
+ $variabla2 = array('seq' => $spr2_temp[1], 'spr' => $spr2_temp[0], 'grd' => $grd);
+
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+ }
+
+ //$var1 = floor(($var1) / (count($this->variablesList[$spr2['spr']]['options'])*count($spr1['sub'])));
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$var2];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2])) ? $crosstabs['crosstab'][$val1][$val2] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2])) ? $crosstabs['avg'][$val1][$val2] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2])) ? $crosstabs['delez'][$val1][$val2] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+ }
+
+ // Krizanje 1 vrstice in 1 stolpca
+ elseif($spr2 == '' && !$this->colLevel2){
+
+ // Loop cez vse stolpce
+ foreach($this->selectedVars['ver'] as $spr2){
+
+ $spr1_temp = explode('-', $spr1['spr']);
+ $grd = $this->variablesList[$spr1['spr']]['grd_id'];
+ $variabla1 = array('seq' => $spr1_temp[1], 'spr' => $spr1_temp[0], 'grd' => $grd);
+
+ $spr2_temp = explode('-', $spr2['spr']);
+ $grd = $this->variablesList[$spr2['spr']]['grd_id'];
+ $variabla2 = array('seq' => $spr2_temp[1], 'spr' => $spr2_temp[0], 'grd' => $grd);
+
+
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+ }
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ // Loop cez variable trenutnega stolpca
+ $cnt = 0;
+ foreach($this->variablesList[$spr2['spr']]['options'] as $var2){
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$cnt];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2])) ? $crosstabs['crosstab'][$val1][$val2] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2])) ? $crosstabs['avg'][$val1][$val2] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2])) ? $crosstabs['delez'][$val1][$val2] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+
+ $cnt++;
+ }
+
+ // Suma (ce jo imamo vklopljeno)
+ if($this->table_settings[$this->table_id]['sums'] == 1 && !$this->rowLevel2){
+ $this->displaySumsCell($spr1, $spr2, $val1, $orientation=0);
+ }
+ }
+ }
+
+ // Izpisemo vecnivojske podatke (krizanje 3 ali 4 spremenljivk)
+ else{
+
+ // Nastavimo 1. vrsticno variablo
+ $spr1_temp = explode('-', $spr1['spr']);
+ $grd = $this->variablesList[$spr1['spr']]['grd_id'];
+ $variabla1 = array('seq' => $spr1_temp[1], 'spr' => $spr1_temp[0], 'grd' => $grd);
+
+ // Krizanje 2 vrstic in 1 stolpca
+ if(!$this->colLevel2){
+
+ // Nastavimo 2. vrsticno variablo
+ $spr2_temp = explode('-', $spr2['spr']);
+ $grd = $this->variablesList[$spr2['spr']]['grd_id'];
+ $variabla2 = array('seq' => $spr2_temp[1], 'spr' => $spr2_temp[0], 'grd' => $grd);
+
+ // Loop cez vse stolpce
+ foreach($this->selectedVars['ver'] as $spr3){
+
+ $spr3_temp = explode('-', $spr3['spr']);
+ $grd = $this->variablesList[$spr3['spr']]['grd_id'];
+ $variabla3 = array('seq' => $spr3_temp[1], 'spr' => $spr3_temp[0], 'grd' => $grd);
+
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+ $variables[2] = array('seq' => $variabla3['seq'], 'spr' => $variabla3['spr'], 'grd' => $variabla3['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']];
+ }
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$var2];
+
+ // Loop cez variable trenutnega stolpca
+ $cnt = 0;
+ foreach($this->variablesList[$spr3['spr']]['options'] as $var3){
+
+ $keys3 = array_keys($crosstabs['options3']);
+ $val3 = $keys3[$cnt];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2][$val3])) ? $crosstabs['crosstab'][$val1][$val2][$val3] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2][$val3])) ? $crosstabs['avg'][$val1][$val2][$val3] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2][$val3])) ? $crosstabs['delez'][$val1][$val2][$val3] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+
+ $cnt++;
+ }
+ }
+ }
+
+ // Krizanje 1 vrstice in 2 stolpcev
+ elseif($spr2 == ''){
+
+ // Loop cez vse stolpce 1. navpicne spremenljivke
+ foreach($this->selectedVars['ver'] as $spr2){
+
+ $spr2_temp = explode('-', $spr2['spr']);
+ $grd = $this->variablesList[$spr2['spr']]['grd_id'];
+ $variabla2 = array('seq' => $spr2_temp[1], 'spr' => $spr2_temp[0], 'grd' => $grd);
+
+ // Loop cez variable 1. navpicne spremnljivke
+ $cnt2 = 0;
+ foreach($this->variablesList[$spr2['spr']]['options'] as $var2){
+
+ // Loop cez vse navpicne spremenljivke 2. nivoja - ce obstajajo
+ if(count($spr2['sub']) > 0){
+ foreach($spr2['sub'] as $spr3){
+
+ // Nastavimo navpicno spremenljivko 2. nivoja
+ $spr3_temp = explode('-', $spr3['spr']);
+ $grd = $this->variablesList[$spr3['spr']]['grd_id'];
+ $variabla3 = array('seq' => $spr3_temp[1], 'spr' => $spr3_temp[0], 'grd' => $grd);
+
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+ $variables[2] = array('seq' => $variabla3['seq'], 'spr' => $variabla3['spr'], 'grd' => $variabla3['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']];
+ }
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$cnt2];
+
+ // Loop cez variable spremenljivke 2. nivoja
+ $cnt3 = 0;
+ foreach($this->variablesList[$spr3['spr']]['options'] as $var3){
+
+ $keys3 = array_keys($crosstabs['options3']);
+ $val3 = $keys3[$cnt3];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2][$val3])) ? $crosstabs['crosstab'][$val1][$val2][$val3] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2][$val3])) ? $crosstabs['avg'][$val1][$val2][$val3] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2][$val3])) ? $crosstabs['delez'][$val1][$val2][$val3] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+
+ $cnt3++;
+ }
+ }
+ }
+ // 1 nivojska spremenljivka v stolpcu
+ else{
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+ }
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$cnt2];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2])) ? $crosstabs['crosstab'][$val1][$val2] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2])) ? $crosstabs['avg'][$val1][$val2] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2])) ? $crosstabs['delez'][$val1][$val2] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+ }
+
+ $cnt2++;
+ }
+ }
+ }
+
+
+
+ // Krizanje 2 vrstic in 2 stolpcev
+ else{
+
+ // Nastavimo 2. vrsticno variablo
+ $spr2_temp = explode('-', $spr2['spr']);
+ $grd = $this->variablesList[$spr2['spr']]['grd_id'];
+ $variabla2 = array('seq' => $spr2_temp[1], 'spr' => $spr2_temp[0], 'grd' => $grd);
+
+ // Loop cez vse stolpce 1. navpicne spremenljivke
+ foreach($this->selectedVars['ver'] as $spr3){
+
+ $spr3_temp = explode('-', $spr3['spr']);
+ $grd = $this->variablesList[$spr3['spr']]['grd_id'];
+ $variabla3 = array('seq' => $spr3_temp[1], 'spr' => $spr3_temp[0], 'grd' => $grd);
+
+ // Loop cez variable 1. navpicne spremnljivke
+ $cnt3 = 0;
+ foreach($this->variablesList[$spr3['spr']]['options'] as $var3){
+
+ // Loop cez vse navpicne spremenljivke 2. nivoja
+ if(count($spr3['sub']) > 0){
+ foreach($spr3['sub'] as $spr4){
+
+ // Nastavimo navpicno spremenljivko 2. nivoja
+ $spr4_temp = explode('-', $spr4['spr']);
+ $grd = $this->variablesList[$spr4['spr']]['grd_id'];
+ $variabla4 = array('seq' => $spr4_temp[1], 'spr' => $spr4_temp[0], 'grd' => $grd);
+
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr'].'-'.$spr4['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr'].'-'.$spr4['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+ $variables[2] = array('seq' => $variabla3['seq'], 'spr' => $variabla3['spr'], 'grd' => $variabla3['grd']);
+ $variables[3] = array('seq' => $variabla4['seq'], 'spr' => $variabla4['spr'], 'grd' => $variabla4['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr'].'-'.$spr4['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr'].'-'.$spr4['spr']];
+ }
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$var2];
+
+ $keys3 = array_keys($crosstabs['options3']);
+ $val3 = $keys3[$cnt3];
+
+ // Loop cez variable spremenljivke 2. nivoja
+ $cnt4 = 0;
+ foreach($this->variablesList[$spr4['spr']]['options'] as $var4){
+
+ $keys4 = array_keys($crosstabs['options4']);
+ $val4 = $keys4[$cnt4];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2][$val3][$val4])) ? $crosstabs['crosstab'][$val1][$val2][$val3][$val4] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2][$val3][$val4])) ? $crosstabs['avg'][$val1][$val2][$val3][$val4] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2][$val3][$val4])) ? $crosstabs['delez'][$val1][$val2][$val3][$val4] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+
+ $cnt4++;
+ }
+ }
+ }
+ // 1 nivo navpicne spremenljivke
+ else{
+ // Ce se nimamo izracunanih rezultatov jih izracunamo
+ if(isset($this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']]))
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']];
+ else{
+ $variables = array();
+ $variables[0] = array('seq' => $variabla1['seq'], 'spr' => $variabla1['spr'], 'grd' => $variabla1['grd']);
+ $variables[1] = array('seq' => $variabla2['seq'], 'spr' => $variabla2['spr'], 'grd' => $variabla2['grd']);
+ $variables[2] = array('seq' => $variabla3['seq'], 'spr' => $variabla3['spr'], 'grd' => $variabla3['grd']);
+
+ $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']] = $this->createCrostabulation($variables);
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr'].'-'.$spr3['spr']];
+ }
+
+ $keys1 = array_keys($crosstabs['options1']);
+ $val1 = $keys1[$var1];
+
+ $keys2 = array_keys($crosstabs['options2']);
+ $val2 = $keys2[$var2];
+
+ $keys3 = array_keys($crosstabs['options3']);
+ $val3 = $keys3[$cnt3];
+
+ $crosstab = (isset($crosstabs['crosstab'][$val1][$val2][$val3])) ? $crosstabs['crosstab'][$val1][$val2][$val3] : 0;
+ $percent = ($crosstab > 0) ? $this->getCrossTabPercentage($crosstabs['sumaVrstica'][$val1], $crosstab) : 0;
+ $avg = (isset($crosstabs['avg'][$val1][$val2][$val3])) ? $crosstabs['avg'][$val1][$val2][$val3] : 0;
+ $delez = (isset($crosstabs['delez'][$val1][$val2][$val3])) ? $crosstabs['delez'][$val1][$val2][$val3] : 0;
+
+ $this->displayDataCell($crosstab, $percent, $avg, $delez);
+ }
+
+ $cnt3++;
+ }
+ }
+ }
+
+
+ // Loop cez vse stolpce
+ /*for($i=0; $i<$this->colSpan; $i++){
+ echo '<td class="data"></td>';
+ }*/
+ }
+ }
+
+ // Izpis celic v vrstici s sumami ($orientation 0->vrstica, 1->stolpec, 2->skupaj)
+ function displaySumsCell($spr1, $spr2, $val, $orientation){
+
+ $crosstabs = $this->crosstabData[$spr1['spr'].'-'.$spr2['spr']];
+
+ echo '<td class="sums data">';
+ echo '<table class="mc_inner_cell">';
+
+ // Celica s skupno sumo
+ if($orientation == 2){
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="bold white">';
+ echo $crosstabs['sumaSkupna'];
+ echo '</td></tr>';
+ }
+
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+
+
+ // Povprecje
+ if($this->table_settings[$this->table_id]['avgVar'] > 0){
+
+ // Loop cez vse in izracunamo povprecje z ustreznimi utezmi
+ $avg = 0;
+ if($crosstabs['crosstab']){
+ $tempAvg = 0;
+ foreach($crosstabs['crosstab'] as $key1 => $row){
+ foreach($row as $key2 => $count){
+ $tempAvg += $count * $crosstabs['avg'][$key1][$key2];
+ }
+ }
+ $avg = ($crosstabs['sumaSkupna'] > 0) ? $tempAvg / $crosstabs['sumaSkupna'] : 0;
+ }
+
+ echo '<tr><td class="blue">';
+ echo $this->formatNumber($avg, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'));
+ echo '</td></tr>';
+ }
+
+ // Delez
+ if($this->table_settings[$this->table_id]['delezVar'] > 0){
+
+ // Loop cez vrstico in izracunamo skupen delez
+ $delez = 0;
+ if($crosstabs['delez']){
+ foreach($crosstabs['delez'] as $row){
+ foreach($row as $tempDelez){
+ $delez += $tempDelez;
+ }
+ }
+ }
+
+ echo '<tr><td class="red">';
+ echo $this->formatNumber($delez*100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+
+ // Suma na koncu vrstice
+ elseif($orientation == 0){
+ // Izpisemo podatek
+ if($crosstabs['sumaVrstica'][$val]){
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="bold white">';
+ echo $crosstabs['sumaVrstica'][$val];
+ echo '</td></tr>';
+ }
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+ else{
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="bold white">';
+ echo '0';
+ echo '</td></tr>';
+ }
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber(100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+
+ }
+
+ // Povprecje
+ if($this->table_settings[$this->table_id]['avgVar'] > 0){
+
+ // Loop cez vrstico in izracunamo povprecje z ustreznimi utezmi
+ $avg = 0;
+ if($crosstabs['crosstab'][$val]){
+ $tempAvg = 0;
+ foreach($crosstabs['crosstab'][$val] as $key => $count){
+ $tempAvg += $count * $crosstabs['avg'][$val][$key];
+ }
+ $avg = ($crosstabs['sumaVrstica'][$val] > 0) ? $tempAvg / $crosstabs['sumaVrstica'][$val] : 0;
+ }
+
+ echo '<tr><td class="blue">';
+ echo $this->formatNumber($avg, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'));
+ echo '</td></tr>';
+ }
+
+ // Delez
+ if($this->table_settings[$this->table_id]['delezVar'] > 0){
+
+ // Loop cez vrstico in izracunamo skupen delez
+ $delez = 0;
+ if($crosstabs['delez'][$val]){
+ foreach($crosstabs['delez'][$val] as $tempDelez){
+ $delez += $tempDelez;
+ }
+ }
+
+ echo '<tr><td class="red">';
+ echo $this->formatNumber($delez*100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+
+ // Suma za stolpce
+ else{
+ // Izpisemo podatek
+ if(isset($crosstabs['sumaStolpec'][$val])){
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="bold white">';
+ echo $crosstabs['sumaStolpec'][$val];
+ echo '</td></tr>';
+ }
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber($this->getCrossTabPercentage($crosstabs['sumaSkupna'], $crosstabs['sumaStolpec'][$val]), SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+ else{
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="bold white">';
+ echo '0';
+ echo '</td></tr>';
+ }
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber(0, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+
+ // Povprecje
+ if($this->table_settings[$this->table_id]['avgVar'] > 0){
+
+ // Loop cez vrstico in izracunamo povprecje z ustreznimi utezmi
+ $avg = 0;
+ if($crosstabs['crosstab']){
+ $tempAvg = 0;
+ foreach($crosstabs['crosstab'] as $key => $row){
+ if($row[$val] > 0)
+ $tempAvg += $row[$val] * $crosstabs['avg'][$key][$val];
+ }
+ $avg = ($crosstabs['sumaStolpec'][$val] > 0) ? $tempAvg / $crosstabs['sumaStolpec'][$val] : 0;
+ }
+
+ echo '<tr><td class="blue">';
+ echo $this->formatNumber($avg, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'));
+ echo '</td></tr>';
+ }
+
+ // Delez
+ if($this->table_settings[$this->table_id]['delezVar'] > 0){
+
+ // Loop cez vrstico in izracunamo skupen delez
+ $delez = 0;
+ if($crosstabs['delez']){
+ foreach($crosstabs['delez'] as $tempDelez){
+ $delez += $tempDelez[$val];
+ }
+ }
+
+ echo '<tr><td class="red">';
+ echo $this->formatNumber($delez*100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+
+ echo '</table>';
+ echo '</td>';
+ }
+
+ // Izpis celice z vrednostmi
+ function displayDataCell($crosstab, $percent, $avg, $delez){
+
+ echo '<td class="data">';
+ echo '<table class="mc_inner_cell">';
+
+ if($crosstab > 0){
+
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="white">';
+ echo $crosstab;
+ echo '</td></tr>';
+ }
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber($percent, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+ else{
+ // Numerus
+ if($this->table_settings[$this->table_id]['numerus'] == 1){
+ echo '<tr><td class="white">';
+ echo '0';
+ echo '</td></tr>';
+ }
+ // Procenti
+ if($this->table_settings[$this->table_id]['percent'] == 1){
+ echo '<tr><td class="white">';
+ echo $this->formatNumber(0, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+ }
+
+ // Povprecje
+ if($this->table_settings[$this->table_id]['avgVar'] > 0){
+ echo '<tr><td class="blue">';
+ echo $this->formatNumber($avg, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'));
+ echo '</td></tr>';
+ }
+
+ // Delez
+ if($this->table_settings[$this->table_id]['delezVar'] > 0){
+ echo '<tr><td class="red">';
+ //echo $this->formatNumber($delez, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'));
+ echo $this->formatNumber($delez*100, SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_PERCENT'), '%');
+ echo '</td></tr>';
+ }
+
+ echo '</table>';
+ echo '</td>';
+ }
+
+
+ function displayTableTitle($title){
+ global $lang;
+
+ $titleString = ($title == '') ? $lang['srv_table'] : $title;
+
+ echo '<div class="multicrosstab_title_inline" contenteditable="true">';
+ echo $titleString;
+ echo '</div>';
+ }
+
+ // Izpisemo nastavitve za tabelo (procenti, numerus, navedbe/enote...)
+ function displayTableSettings(){
+ global $lang;
+
+ echo '<h2>'.$lang['srv_multicrosstabs_settings'].'</h2>';
+
+ /*echo '<span class="clr"><input type="checkbox" id="numerus_'.$this->table_id.'" '.($this->table_settings[$this->table_id]['numerus'] == 1 ? ' checked="checked"':'').' onclick="changeMCSettings(\''.$this->table_id.'\', \'numerus\');" /><label for="numerus_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_numerus'].'</label></span>';
+ echo '<span class="clr"><input type="checkbox" id="percent_'.$this->table_id.'" '.($this->table_settings[$this->table_id]['percent'] == 1 ? ' checked="checked"':'').' onclick="changeMCSettings(\''.$this->table_id.'\', \'percent\');" /><label for="percent_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_percent'].'</label></span>';
+ //echo '<span class="clr"><input type="checkbox" id="avg_'.$this->table_id.'" '.($this->table_settings[$this->table_id]['avg'] == 1 ? ' checked="checked"':'').' onclick="changeMCSettings(\''.$this->table_id.'\', \'avg\');" /><label for="avg_'.$this->table_id.'"> Povprečje</label></span>';
+
+ echo '<span class="clr"><input type="checkbox" id="sums_'.$this->table_id.'" '.($this->table_settings[$this->table_id]['sums'] == 1 ? ' checked="checked"':'').' onclick="changeMCSettings(\''.$this->table_id.'\', \'sums\');" /><label for="sums_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_sum'].'</label></span>';
+
+ if($this->isCheckbox){
+ echo '<span class="clr" style="line-height: 20px;">';
+ echo '<label for="navVsEno0_'.$this->table_id.'"><input type="radio" id="navVsEno0_'.$this->table_id.'" name="navVsEno" '.($this->table_settings[$this->table_id]['navVsEno'] == 0 ? ' checked="checked"':'').' value="0" onclick="changeMCSettings(\''.$this->table_id.'\', \'navVsEno\');" />'.$lang['srv_analiza_crosstab_navedbe'].'</label>';
+ echo ' <label for="navVsEno1_'.$this->table_id.'"><input type="radio" id="navVsEno1_'.$this->table_id.'" name="navVsEno" '.($this->table_settings[$this->table_id]['navVsEno'] == 1 ? ' checked="checked"':'').' value="1" onclick="changeMCSettings(\''.$this->table_id.'\', \'navVsEno\');" />'.$lang['srv_analiza_crosstab_enote'].'</label>';
+ echo '</span>';
+ }*/
+
+ echo '<form name="mc_settings" method="post">';
+
+ echo '<input type="hidden" name="anketa" value="'.$this->ank_id.'" />';
+ echo '<input type="hidden" name="table_id" value="'.$this->table_id.'" />';
+
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_multicrosstabs_settings_val'].'</legend>';
+
+ // Prikaz numerusa
+ echo '<span class="clr"><input type="checkbox" id="numerus_'.$this->table_id.'" name="numerus" '.($this->table_settings[$this->table_id]['numerus'] == 1 ? ' checked="checked"':'').' value="1" /><label for="numerus_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_numerus'].'</label></span>';
+
+ // Prikaz procentov
+ echo '<span class="clr"><input type="checkbox" id="percent_'.$this->table_id.'" name="percent" '.($this->table_settings[$this->table_id]['percent'] == 1 ? ' checked="checked"':'').' value="1" /><label for="percent_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_percent'].'</label></span>';
+
+ // Prikaz vsot
+ echo '<span class="clr"><input type="checkbox" id="sums_'.$this->table_id.'" name="sums" '.($this->table_settings[$this->table_id]['sums'] == 1 ? ' checked="checked"':'').' value="1" /><label for="sums_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_sum'].'</label></span>';
+
+ // Navedbe / enote
+ /*if($this->isCheckbox){
+ echo '<span class="clr" style="line-height: 20px;">';
+ echo '<label for="navVsEno0_'.$this->table_id.'"><input type="radio" id="navVsEno0_'.$this->table_id.'" name="navVsEno" '.($this->table_settings[$this->table_id]['navVsEno'] == 0 ? ' checked="checked"':'').' value="0" />'.$lang['srv_analiza_crosstab_navedbe'].'</label>';
+ echo ' <label for="navVsEno1_'.$this->table_id.'"><input type="radio" id="navVsEno1_'.$this->table_id.'" name="navVsEno" '.($this->table_settings[$this->table_id]['navVsEno'] == 1 ? ' checked="checked"':'').' value="1" />'.$lang['srv_analiza_crosstab_enote'].'</label>';
+ echo '</span>';
+ }*/
+
+ echo '</fieldset>';
+
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_multicrosstabs_settings_avg'].'</legend>';
+
+ // Variabla za racunanje povprecja - numeric in ordinal (radio, dropdown, mg)
+ $checked = $this->table_settings[$this->table_id]['avgVar'] == '' ? false : true;
+ echo '<span class="clr"><input type="checkbox" id="avgSetting_'.$this->table_id.'" name="avgSetting" '.($checked ? ' checked="checked"':'').' onClick="toggleMCSetting(\'avgVar\');" /><label for="avgSetting_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_avg'].'</label>';
+ echo '<span id="avgVar" class="spaceLeft" '.($checked ? '' : ' style="display: none;"').'><select id="avgVar_'.$this->table_id.'" name="avgVar">';
+ echo '<option value="">'.$lang['srv_select_spr'].'...</option>';
+ foreach($this->variablesList AS $spr){
+ if( $spr['canChoose'] && ($spr['tip'] == 7 || (in_array($spr['tip'], array(1,3,6)) && $spr['skala'] == 0)) ){
+ echo '<option value="'.$spr['spr_id'].'-'.$spr['sequence'].'" '.($this->table_settings[$this->table_id]['avgVar'] == $spr['spr_id'].'-'.$spr['sequence'] ? ' selected="selected"' : '').'>('.$spr['variable'].') '.$this->snippet($spr['naslov'], 25).'</option>';
+ }
+ }
+ echo '</select></span>';
+ echo '</span>';
+
+ echo '</fieldset>';
+
+
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_multicrosstabs_settings_del'].'</legend>';
+
+ // Variabla za racunanje deleza - ordinal in nominal (radio, dropdown, mg, po novem tudi checkbox, multicheckbox)
+ $checked = $this->table_settings[$this->table_id]['delezVar'] == '' ? false : true;
+ echo '<span class="clr"><input type="checkbox" id="delezSetting_'.$this->table_id.'" name="delezSetting" '.($checked ? ' checked="checked"':'').' onClick="toggleMCSetting(\'delezVar\');" /><label for="delezSetting_'.$this->table_id.'"> '.$lang['srv_multicrosstabs_delez'].'</label>';
+
+ echo '<span id="delezVar" class="spaceLeft" '.($checked ? '' : ' style="display: none;"').'><select id="delezVar_'.$this->table_id.'" name="delezVar" onChange="setDelez(this.value);">';
+ echo '<option value="">'.$lang['srv_select_spr'].'...</option>';
+ foreach($this->variablesList AS $spr){
+ if($spr['canChoose'] && in_array($spr['tip'], array(1,3,6,2,16))){
+ echo '<option value="'.$spr['spr_id'].'-'.$spr['sequence'].'" '.($this->table_settings[$this->table_id]['delezVar'] == $spr['spr_id'].'-'.$spr['sequence'] ? ' selected="selected"' : '').'>('.$spr['variable'].') '.$this->snippet($spr['naslov'], 25).'</option>';
+ }
+ }
+ echo '</select></span>';
+ echo '</span>';
+
+ echo '<div id="delez" '.($checked ? '' : ' style="display: none;"').'>';
+ $this->displayDelez($this->table_settings[$this->table_id]['delezVar']);
+ echo '</div>';
+
+ echo '</fieldset>';
+
+
+ echo '</form>';
+
+
+ // Gumbi na dnu
+ echo '<div id="mcSettingsButtons">';
+
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" onclick="closeMCSettings(\''.$this->table_id.'\');">';
+ echo '<span>'.$lang['srv_zapri'].'</span>';
+ echo '</a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper spaceRight spaceLeft floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" onclick="saveMCSettings(\''.$this->table_id.'\');">';
+ echo '<span>'.$lang['srv_potrdi'].'</span>';
+ echo '</a>';
+ echo '</span>';
+
+ echo '</div>';
+ }
+
+ // Prikazemo opcije variable (checkboxe) za delez
+ function displayDelez($var){
+
+ // Ce imamo nastavljeno variablo za delez prikazemo vse njene opcije
+ if($var != ''){
+ $delez = unserialize($this->table_settings[$this->table_id]['delez']);
+
+ $cnt = 0;
+ foreach($this->variablesList[$var]['options'] as $option){
+
+ if($this->table_settings[$this->table_id]['delezVar'] == $var)
+ $val = $delez[$cnt];
+ else
+ $val = 0;
+
+ echo '<span class="clr">';
+ echo '<input type="checkbox" id="delez_'.$cnt.'" name="delez_'.$cnt.'" value="1" '.($val == 1 ? ' checked="checked"' : '').' /><label for="delez_'.$cnt.'"> '.$option.'</label>';
+ echo '</span>';
+
+ $cnt++;
+ }
+ }
+ }
+
+
+ // Prikazuje filtre
+ function displayFilters() {
+
+ if ($this->dataFileStatus == FILE_STATUS_SRV_DELETED || $this->dataFileStatus == FILE_STATUS_NO_DATA){
+ return false;
+ }
+
+ # nastavitve tabele multicrosstab
+ $SSH = new SurveyStaticHtml($this->ank_id);
+ $SSH -> displayMulticrosstabSettings();
+ }
+
+ // Prikaze dropdown z linki
+ function displayLinks() {
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->ank_id);
+ $SSH -> displayAnalizaSubNavigation();
+ }
+
+ // Prikaze izvoz za PDF/RTF
+ function displayExport () {
+
+ $href_print = makeEncodedIzvozUrlString('izvoz.php?b=export&m=multicrosstabs_izpis&anketa='.$this->ank_id);
+ $href_pdf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=multicrosstabs_izpis&anketa='.$this->ank_id);
+ $href_rtf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=multicrosstabs_izpis_rtf&anketa='.$this->ank_id);
+ $href_xls = makeEncodedIzvozUrlString('izvoz.php?b=export&m=multicrosstabs_izpis_xls&anketa='.$this->ank_id);
+
+ echo '<script>';
+ # nastavimopravilne linke
+ echo '$("#secondNavigation_links a#multicrosstabDoPdf").attr("href", "'.$href_pdf.'");';
+ echo '$("#secondNavigation_links a#multicrosstabDoRtf").attr("href", "'.$href_rtf.'");';
+ echo '$("#secondNavigation_links a#multicrosstabDoXls").attr("href", "'.$href_xls.'");';
+ # prikažemo linke
+ echo '$("#hover_export_icon a").removeClass("hidden");';
+ echo '$("#secondNavigation_links a").removeClass("hidden");';
+ echo '</script>';
+ }
+
+ // Prikazemo legendo (povprecje, delez)
+ function displayLegend(){
+ global $lang;
+
+ if($this->table_settings[$this->table_id]['avgVar'] > 0 || $this->table_settings[$this->table_id]['delezVar'] > 0){
+ echo '<div class="mc_table_legend">';
+
+ // Povprecje
+ if($this->table_settings[$this->table_id]['avgVar'] > 0){
+ echo '<span class="clr"><span class="blue">'.$lang['srv_multicrosstabs_avg'].': </span>'.$this->variablesList[$this->table_settings[$this->table_id]['avgVar']]['variable'].'</span>';
+ }
+
+ // Delez
+ if($this->table_settings[$this->table_id]['delezVar'] > 0){
+ echo '<span class="red">'.$lang['srv_multicrosstabs_delez'].': </span>'.$this->variablesList[$this->table_settings[$this->table_id]['delezVar']]['variable'];
+
+ $delez = unserialize($this->table_settings[$this->table_id]['delez']);
+ $string = '';
+ $cnt = 1;
+ foreach($delez as $val){
+ if($val == 1)
+ $string .= $cnt.', ';
+
+ $cnt++;
+ }
+ echo ' ('.substr($string, 0, -2).')';
+
+ }
+
+ echo '</div>';
+ }
+ }
+
+
+ // funkcija vrne seznam variabel za drag
+ public function getVariableList() {
+ if (isset($this->variablesList) && is_array($this->variablesList) && count($this->variablesList) > 0) {
+ return $this->variablesList;
+ } else {
+ # pobrišemo array()
+ $this->variablesList = array();
+ # zloopamo skozi header in dodamo variable (potrebujemo posamezne sekvence)
+ foreach ($this->_HEADERS AS $skey => $spremenljivka) {
+ if ((int)$spremenljivka['hide_system'] == 1 && in_array($spremenljivka['variable'],array('email','ime','priimek','telefon','naziv','drugo'))) {
+ continue;
+ }
+
+ $tip = $spremenljivka['tip'];
+ if (is_numeric($tip)
+ # tekstovnih tipov ne dodajamo
+
+ && $tip != 4 #text
+ && $tip != 5 #label
+ #&& $tip != 7 #number
+ #&& $tip != 8 #datum
+ && $tip != 9 #SN-imena
+ #&& $tip != 18 #vsota
+ #&& $tip != 19 #multitext
+ #&& $tip != 20 #multinumber
+ #&& $tip != 21 #besedilo*
+ && $tip != 22 #compute
+ && $tip != 25 #kvota
+ ) {
+ $cnt_all = (int)$spremenljivka['cnt_all'];
+ # radio in select in checkbox
+ if ($cnt_all == '1' || $tip == 1 || $tip == 3 || $tip == 2) {
+ # pri tipu radio ali select dodamo tisto variablo ki ni polje "drugo"
+ if ($tip == 1 || $tip == 3 ) {
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+
+ // Napolnimo variable
+ $options = $spremenljivka['options'];
+
+ # imamo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[$skey.'-'.$spremenljivka['grids'][0]['variables'][$vid]['sequence']] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>'undefined',
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][$vid]['sequence'],
+ 'naslov'=>strip_tags($spremenljivka['naslov']),
+ 'variable'=>$spremenljivka['variable'],
+ 'canChoose'=>true,
+ 'sub'=>0,
+ /*'cnt'=>count($spremenljivka['options']),
+ 'options'=>$spremenljivka['options']);*/
+ 'options'=>$options);
+ }
+ }
+ }
+ }
+ } else {
+
+ // Napolnimo variable
+ $options = array();
+ foreach($spremenljivka['grids'][0]['variables'] as $key => $var){
+ if(!$var['other'])
+ $options[($key+1)] = $var['naslov'];
+ }
+
+ # imamo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[$skey.'-'.$spremenljivka['grids'][0]['variables'][0]['sequence']] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>'undefined',
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'naslov'=>strip_tags($spremenljivka['naslov']),
+ 'variable'=>$spremenljivka['variable'],
+ 'canChoose'=>true,
+ 'sub'=>0,
+ /*'cnt'=>count($spremenljivka['grids'][0]));var_dump($spremenljivka['grids'][0]['variables']);*/
+ 'options'=>$options);
+ }
+ } else if ($cnt_all > 1){
+ # imamo več skupin ali podskupin, zato zlopamo skozi gride in variable
+ if (count($spremenljivka['grids']) > 0 ) {
+ $this->variablesList[$skey] = array(
+ 'tip'=>$tip,
+ 'naslov'=>strip_tags($spremenljivka['naslov']),
+ 'variable'=>$spremenljivka['variable'],
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # ali imamo en grid, ali več (ranking, vsota, text(vec kosov), number(vec kosov))
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+
+ // Napolnimo variable
+ $options = array();
+ foreach($spremenljivka['grids'][0]['variables'] as $key => $var){
+ if(!$var['other'])
+ $options[($key+1)] = $var['naslov'];
+ }
+
+ $this->variablesList[$skey.'-'.$variable['sequence']] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>'undefined',
+ 'sequence'=>$variable['sequence'],
+ 'naslov'=>strip_tags($variable['naslov']),
+ 'variable'=>$variable['variable'],
+ 'canChoose'=>true,
+ 'sub'=>1,
+ /*'cnt'=>$spremenljivka['cnt_all']);*/
+ 'options'=>$options);
+ }
+ }
+ }
+
+ }
+ # Imamo multicheckbox
+ else if($tip == 16 || $tip == 18) {
+
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+
+ // Napolnimo variable
+ $options = array();
+ foreach($spremenljivka['grids'][0]['variables'] as $key => $var){
+ if(!$var['other'])
+ $options[($key+1)] = $var['naslov'];
+ }
+
+ $sub++;
+ $this->variablesList[$skey.'-'.$grid['variables'][0]['sequence']] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>$gid,
+ 'sequence'=>$grid['variables'][0]['sequence'],
+ 'naslov'=>strip_tags($grid['naslov']),
+ 'variable'=>$grid['variable'],
+ 'canChoose'=>true,
+ 'sub'=>1,
+ /*'cnt'=>count($grid['variables']));*/
+ 'options'=>$options);
+ }
+ }
+ }
+ # imamo več gridov - multigrid, multitext, multinumber
+ else {
+
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[$skey] = array(
+ 'tip'=>$tip,
+ 'naslov'=>strip_tags($grid['naslov']),
+ 'variable'=>$grid['variable'],
+ 'canChoose'=>false,
+ 'sub'=>$sub);
+ }
+ if (count ($grid['variables']) > 0) {
+ $sub++;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+
+ // Napolnimo variable
+ $options = array();
+ if($spremenljivka['tip'] == 6){
+ $options = $spremenljivka['options'];
+ }
+ else{
+ foreach($spremenljivka['grids'][0]['variables'] as $key => $var){
+ if(!$var['other'])
+ $options[($key+1)] = $var['naslov'];
+ }
+ }
+
+ $this->variablesList[$skey.'-'.$variable['sequence']] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>'undefined',
+ 'sequence'=>$variable['sequence'],
+ 'naslov'=>strip_tags($variable['naslov']),
+ 'variable'=>$variable['variable'],
+ 'canChoose'=>true,
+ 'sub'=>$sub,
+ /*'cnt'=>count($spremenljivka['options']));*/
+ 'options'=>$options);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ return $this->variablesList;
+ }
+ }
+
+ // funkcija vrne izbrane variable v arrayu
+ public function getSelectedVars() {
+
+ // Najprej napolnimo prvi nivo
+ $sql = sisplet_query("SELECT * FROM srv_mc_element WHERE table_id='$this->table_id' AND parent='' ORDER BY vrstni_red");
+ while($row = mysqli_fetch_array($sql)){
+
+ $colSpan = 0;
+ $rowSpan = 0;
+
+ // Horizontalne spremenljivke
+ if($row['position'] == '0'){
+
+ $this->selectedVars['hor'][$row['vrstni_red']] = $row;
+
+ $sql2 = sisplet_query("SELECT * FROM srv_mc_element WHERE table_id='$this->table_id' AND parent='$row[vrstni_red]' AND position='0'");
+ // Ce ni 2.nivoja
+ if(mysqli_num_rows($sql2) == 0){
+ $rowSpan = count($this->variablesList[$row['spr']]['options']);
+ $this->selectedVars['hor'][$row['vrstni_red']]['span'] = $rowSpan;
+
+ if($this->variablesList[$row['spr']]['tip'] == 2 || $this->variablesList[$row['spr']]['tip'] == 16)
+ $this->isCheckbox = true;
+ }
+ // Napolnimo se 2.nivo
+ else{
+ while($row2 = mysqli_fetch_array($sql2)){
+ $this->selectedVars['hor'][$row['vrstni_red']]['sub'][$row2['vrstni_red']] = $row2;
+
+ $rowSpan += count($this->variablesList[$row['spr']]['options'])*count($this->variablesList[$row2['spr']]['options']);
+ $this->selectedVars['hor'][$row['vrstni_red']]['sub'][$row2['vrstni_red']]['span'] = count($this->variablesList[$row2['spr']]['options']);
+
+ $this->rowLevel2 = true;
+
+ if($this->variablesList[$row2['spr']]['tip'] == 2 || $this->variablesList[$row2['spr']]['tip'] == 16)
+ $this->isCheckbox = true;
+ }
+
+ $this->selectedVars['hor'][$row['vrstni_red']]['span'] = $rowSpan;
+ }
+
+ $this->rowSpan += $rowSpan;
+ }
+ // Vertikalne spremenljivke
+ else{
+
+ $this->selectedVars['ver'][$row['vrstni_red']] = $row;
+
+ $sql2 = sisplet_query("SELECT * FROM srv_mc_element WHERE table_id='$this->table_id' AND parent='$row[vrstni_red]' AND position='1'");
+ // Ce ni 2.nivoja
+ if(mysqli_num_rows($sql2) == 0){
+ $colSpan = count($this->variablesList[$row['spr']]['options']);
+ $fullColSpan = $colSpan;
+ $this->selectedVars['ver'][$row['vrstni_red']]['span'] = $colSpan;
+
+ if($this->variablesList[$row['spr']]['tip'] == 2 || $this->variablesList[$row['spr']]['tip'] == 16)
+ $this->isCheckbox = true;
+
+ if($this->table_settings[$this->table_id]['sums'] == 1)
+ $fullColSpan++;
+ }
+ // Napolnimo se 2.nivo
+ else{
+ while($row2 = mysqli_fetch_array($sql2)){
+ $this->selectedVars['ver'][$row['vrstni_red']]['sub'][$row2['vrstni_red']] = $row2;
+
+ $colSpan += count($this->variablesList[$row['spr']]['options'])*count($this->variablesList[$row2['spr']]['options']);
+ $fullColSpan += count($this->variablesList[$row['spr']]['options'])*count($this->variablesList[$row2['spr']]['options']);
+ $this->selectedVars['ver'][$row['vrstni_red']]['sub'][$row2['vrstni_red']]['span'] = count($this->variablesList[$row2['spr']]['options']);
+
+ $this->colLevel2 = true;
+
+ if($this->variablesList[$row2['spr']]['tip'] == 2 || $this->variablesList[$row2['spr']]['tip'] == 16)
+ $this->isCheckbox = true;
+ }
+
+ $this->selectedVars['ver'][$row['vrstni_red']]['span'] = $colSpan;
+ }
+
+ $this->colSpan += $colSpan;
+ $this->fullColSpan += $fullColSpan;
+ }
+ }
+
+ //echo 'Cols:'.$this->colSpan.'_Rows:'.$this->rowSpan.' ';
+ //var_dump($this->selectedVars['hor']);
+ }
+
+
+ // Izvedemo izracune crosstabulacij
+ public function createCrostabulation($variables) {
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $R_folder = $site_path . R_FOLDER.'/';
+
+ if ($this->dataFileName != '' && file_exists($this->dataFileName)){
+
+ $spr = array();
+ $grid = array();
+ $sekvence = array();
+ $var_options = array();
+ $_all_options = array();
+ foreach($variables as $key => $variable){
+
+ $spr[$key] = $this->_HEADERS[$variables[$key]['spr']];
+ $grid[$key] = $spr[$key]['grids'][$variables[$key]['grd']];
+ $sekvenca = $variables[$key]['seq'];
+
+ $spr_checkbox = false;
+
+
+ # za checkboxe gledamo samo odgovore ki so bili 1 in za vse opcije
+ if ($spr[$key]['tip'] == 2 || $spr[$key]['tip'] == 16) {
+
+ $spr_checkbox = true;
+
+ if ($spr[$key]['tip'] == 2) {
+ if (count($spr[$key]['grids'][0]['variables']) > 0)
+ foreach ($spr[$key]['grids'][0]['variables'] AS $_vkey =>$_variable) {
+ if ((int)$_variable['text'] != 1) {
+ $sekvence[$key][] = $_variable['sequence'];
+ }
+ } else {
+ $sekvence[$key] = explode('_',$spr[$key]['sequences']);
+ }
+ }
+ if ($spr1['tip'] == 16) {
+
+ foreach ($grid[$key]['variables'] AS $_variables) {
+
+ $sekvence[$key][] = $_variables['sequence'];
+ }
+ }
+ } else {
+ $sekvence[$key][] = $sekvenca;
+ }
+
+
+ # poiščemo pripadajočo spremenljivko
+ $var_options[$key] = $this->_HEADERS[$variable['spr']]['options'];
+
+ # najprej poiščemo (združimo) vse opcije ki so definirane kot opcije spremenljivke in vse ki so v crosstabih
+ if (count($var_options[$key]) > 0 && $spr_checkbox !== true ) {
+ foreach ($var_options[$key] as $okey => $opt) {
+ $_all_options[$key][$okey] = array('naslov'=>$opt, 'cnt'=>null, 'type'=>'o');
+ }
+ }
+
+ # za checkboxe dodamo posebej vse opcije
+ if ($spr_checkbox == true ) {
+ if ($spr[$key]['tip'] == 2 ) {
+ $grid[$key] = $this->_HEADERS[$variable['spr']]['grids']['0'];
+ }
+
+ foreach ($grid[$key]['variables'] As $vkey => $var) {
+ if ($var['other'] != 1) {
+ $_all_options[$key][$var['sequence']] = array('naslov'=>$var['naslov'], 'cnt'=>null, 'type'=>'o', 'vr_id'=> $var['variable']);
+ }
+ }
+ }
+ }
+
+
+ // Nastavimo string s katerim filtriramo datoteko za prave stolpce
+ foreach($sekvence as $sekvenca){
+ if(count($sekvenca) > 1){
+ foreach($sekvenca as $grd){
+ $crosstabVars .= '$'.$grd.',';
+ }
+ }
+ else
+ $crosstabVars .= '$'.$sekvenca[0].',';
+ }
+
+ // Ce imamo racunanje povprecja
+ $avgVar = 0;
+ if($this->table_settings[$this->table_id]['avgVar'] != ''){
+
+ $avg = explode('-',$this->table_settings[$this->table_id]['avgVar']);
+ $crosstabVars .= '$'.$avg[1].',';
+
+ $avgVar = 1;
+ }
+
+ // Ce imamo racunanje deleza
+ if($this->table_settings[$this->table_id]['delezVar'] != ''){
+
+ $delezVar = explode('-',$this->table_settings[$this->table_id]['delezVar']);
+
+ // Ce imamo delez za checkbox
+ if($this->variablesList[$this->table_settings[$this->table_id]['delezVar']]['tip'] == 2 || $this->variablesList[$this->table_settings[$this->table_id]['delezVar']]['tip'] == 16){
+ $delez = unserialize($this->table_settings[$this->table_id]['delez']);
+ $i = 0;
+ foreach($delez as $val){
+
+ if($val == 1){
+ $stolpec = (int)$delezVar[1] + $i;
+ $crosstabVars .= '$'.$stolpec.',';
+ }
+
+ $i++;
+ }
+ $delez = -1;
+ }
+ else{
+ $crosstabVars .= '$'.$delezVar[1].',';
+ $delez = unserialize($this->table_settings[$this->table_id]['delez']);
+ }
+ }
+
+ $crosstabVars = substr($crosstabVars, 0, -1);
+
+ // Ce se nimamo datoteke s pripravljenimi podatki jo ustvarimo
+ $tmp_file = $R_folder . '/TempData/crosstab_data.tmp';
+ if (!file_exists($tmp_file)) {
+ $this->prepareDataFile($crosstabVars);
+ }
+
+
+ // Inicializiramo R in pozenemo skripto za crosstabulacije
+ $R = new SurveyAnalysisR($this->ank_id);
+ $crosstabs = $R->createMultiCrosstabulation($sekvence, $avgVar, $delez);
+
+
+ $crosstabs['options1'] = $_all_options[0];
+ $crosstabs['options2'] = $_all_options[1];
+ if(isset($_all_options[2]))
+ $crosstabs['options3'] = $_all_options[2];
+ if(isset($_all_options[3]))
+ $crosstabs['options4'] = $_all_options[3];
+
+ $crosstabs['isCheckbox'] = $this->isCheckbox;
+
+
+ // Testiranje...
+ /*echo '<div style="width: 800px; position: absolute;top:0;left:0; background-color: #eeffff;">';
+ var_dump($crosstabs['sumaVrstica']);
+ var_dump($crosstabs['sumaStolpec']);
+ var_dump($crosstabs['sumaSkupna']);
+ echo '</div>';*/
+
+
+ // Na koncu pobrisemo zacasen file s podatki
+ $this->deleteDataFile();
+
+
+ return $crosstabs;
+ }
+ }
+
+
+ // Pripravimo file iz katerega preberemo podatke in izvedemo crosstabulacije
+ public function prepareDataFile($cols){
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $R_folder = $site_path . R_FOLDER.'/';
+
+ # pogoji so že dodani v _CURRENT_STATUS_FILTER
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ # dodamo status filter za vse sekvence checkbox-a da so == 1
+ if ($additional_status_filter != null) {
+ $status_filter .= $additional_status_filter;
+ }
+
+ # odstranimo vse zapise, kjer katerakoli od variabel vsebuje missing
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_pageMissing_answers = $this->getInvalidAnswers(MISSING_TYPE_CROSSTAB);
+
+
+ // File kamor zapisemo filtrirane podatke
+ $tmp_file = $R_folder . '/TempData/crosstab_data.tmp';
+
+ # polovimo obe sekvenci
+ /*if (count($sekvences1)>0)
+ foreach ($sekvences1 AS $sequence1) {
+ if (count($sekvences2)>0)
+ foreach ($sekvences2 AS $sequence2) {
+ #skreira variable: $crosstab, $cvar1, $cvar2
+
+ $additional_filter = '';
+ if ($spr_1_checkbox == true) {
+ $_seq_1_text = ''.$sequence1;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter = ' && ($'.$sequence1.' == 1)';
+ } else {
+ $_seq_1_text = '$'.$sequence1;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key1 => $missing1) {
+ $additional_filter .= ' && ($'.$sequence1.' != '.$m_key1.')';
+ }
+ }
+
+ if ($spr_2_checkbox == true) {
+ $_seq_2_text = ''.$sequence2;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter .= ' && ($'.$sequence2.' == 1)';
+ } else {
+ $_seq_2_text = '$'.$sequence2;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key2 => $missing2) {
+ $additional_filter .= ' && ($'.$sequence2.' != '.$m_key2.')';
+ }
+ }
+
+ if (IS_WINDOWS) {
+ #$command = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$_status_filter.' { print \"$crosstab[\x27\",$'.$sequence1.',\"\x27][\x27\",$'.$sequence2.',\"\x27]++; $options1[\x27\",$'.$sequence1.',\"\x27]++; $options2[\x27\",$'.$sequence2.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ $command = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$additional_filter.' { print $0 }" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ #$command = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$_status_filter.' { print "$crosstab[\x27",$'.$sequence1.',"\x27][\x27",$'.$sequence2.',"\x27]++; $options1[\x27",$'.$sequence1.',"\x27]++; $options2[\x27",$'.$sequence2.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ $command = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$additional_filter.' { print $0 }\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out = shell_exec($command);
+ }
+
+ }*/
+
+
+ // Filtriramo podatke po statusu in loopih in jih zapisemo v temp folder R-ja
+ if (IS_WINDOWS) {
+ $command = 'awk -F"|" "BEGIN {{OFS=\",\"} {ORS=\"\n\"}} '.$status_filter.' { print '.$cols.' }" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command = 'awk -F"|" \'BEGIN {{OFS=","} {ORS="\n"}} '.$status_filter.' { print '.$cols.'; }\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out = shell_exec($command);
+
+ return $out;
+ }
+
+ // Pobrisemo zacasen file s podatki
+ public function deleteDataFile(){
+ global $site_path;
+
+ $R_folder = $site_path . R_FOLDER.'/';
+ $tmp_file = $R_folder . '/TempData/crosstab_data.tmp';
+
+ // Na koncu pobrisemo zacasen file s podatki
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+ }
+
+
+ // Prikaze izbiro med vsemi tabelami
+ function displayMCTables(){
+ global $site_path;
+ global $global_user_id;
+ global $lang;
+
+ // Trenutna aktivna tabela
+ $sql = sisplet_query("SELECT * FROM srv_mc_table WHERE id='$this->table_id' AND ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+ $current_table = mysqli_fetch_array($sql);
+
+ echo '<h2>'.$lang['srv_multicrosstabs_tables'].'</h2>';
+
+
+ echo '<div id="mc_tables_left">';
+
+ // Prednastavljen profil
+ echo '<span id="mc_tables" class="mc_tables select">';
+
+ $mc_tables = $this->getTables();
+ foreach($mc_tables as $table){
+ echo '<div class="option'.($this->table_id == $table['id'] ? ' active' : '').'" id="mc_table_'.$table['id'].'" value="'.$table['id'].'">'.$table['name'].'</div>';
+ }
+
+ echo '</span>';
+
+
+ // Na dnu imamo gumba brisi in preimenuj
+ echo '<div style="float:left;">';
+ echo '<a href="#" onclick="mc_table_action(\'show_rename\'); return false;">'.$lang['srv_multicrosstabs_tables_rename'].'</a><br/>'."\n";
+ echo '<a href="#" onclick="mc_table_action(\'show_delete\'); return false;">'.$lang['srv_multicrosstabs_tables_delete'].'</a>'."\n";
+ echo '</div>';
+
+
+ // Cas kreirranja tabele
+ echo '<div style="float:right; text-align:right;">';
+ $time_created = strtotime($current_table['time_created']);
+ echo $lang['srv_multicrosstabs_tables_time'].': <span class="bold">'.date("d.m.Y H:i", $time_created).'</span><br />';
+ echo '</div>';
+
+ echo '</div>';
+
+
+ // cover Div
+ echo '<div id="dsp_cover_div"></div>'."\n";
+
+ echo '<span class="clr"></span>';
+
+ echo '<div style="position:absolute; bottom:15px; right:15px;">';
+
+ //echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="save_creport_profile(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="use_mc_table(); return false;"><span>'.$lang['srv_multicrosstabs_tables_use'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" title="'.$lang['srv_multicrosstabs_tables_add'].'"><div class="buttonwrapper"><a class="ovalbutton" href="#" onclick="mc_table_action(\'show_new\'); return false;"><span>'.$lang['srv_multicrosstabs_tables_add'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton" href="#" onclick="close_mc_tables(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+
+ echo '</div>';
+ }
+
+ function displayMCTablesPopups(){
+ global $lang;
+
+ // div za kreacijo novega
+ echo '<div id="newMCTable">';
+
+ echo '<h2>'.$lang['srv_new_table'].'</h2>';
+
+ echo '<div style="float:left; width:400px; text-align:right;">'.$lang['srv_multicrosstabs_tables_name'].': '."\n";
+ echo '<input id="newMCTableName" name="newMCTableName" type="text" value="" size="50" /></div>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="mc_table_action(\'new\'); return false;"><span>'.$lang['save'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="mc_table_action(\'cancel_new\'); return false;"><span>'.$lang['srv_zapri'].'</span></a></span></span>'."\n";
+ echo '<div class="floatRight clr" style="padding: 15px 5px 15px 0;"><a href="#" onClick="mc_table_action(\'goto_archive\');">'.$lang['srv_analiza_arhiv'].'</a></div>';
+ echo '</div>'."\n";
+
+ // div za preimenovanje
+ echo '<div id="renameMCTable">'.$lang['srv_multicrosstabs_tables_name'].': '."\n";
+ echo '<input id="renameMCTableName" name="renameMCTableName" type="text" size="45" />'."\n";
+ echo '<input id="renameMCTableId" type="hidden" value="' . $this->table_id . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="mc_table_action(\'rename\'); return false;"><span>'.$lang['srv_multicrosstabs_tables_rename_short'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="mc_table_action(\'cancel_rename\'); return false;"><span>'.$lang['srv_zapri'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+
+ // div za brisanje
+ echo '<div id="deleteMCTable">'.$lang['srv_multicrosstabs_tables_delete_confirm'].': <span id="deleteMCTableName" style="font-weight:bold;"></span>?'."\n";
+ echo '<input id="deleteMCTableId" type="hidden" value="' . $this->table_id . '" />'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="mc_table_action(\'delete\'); return false;"><span>'.$lang['srv_multicrosstabs_tables_delete_short'].'</span></a></span></span>'."\n";
+ echo '<span class="floatRight spaceLeft" ><span class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="mc_table_action(\'cancel_delete\'); return false;"><span>'.$lang['srv_zapri'].'</span></a></span></span>'."\n";
+ echo '</div>'."\n";
+ }
+
+ // Vrnemo vse tabele uporabnika
+ public function getTables(){
+ global $global_user_id;
+
+ $mc_tables = array();
+
+ $sql = sisplet_query("SELECT * FROM srv_mc_table WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id' ORDER BY time_created ASC");
+ while($row = mysqli_fetch_array($sql)){
+ $mc_tables[] = $row;
+ }
+
+ return $mc_tables;
+ }
+
+
+ function ajax(){
+ global $lang;
+ global $global_user_id;
+
+ $this->getVariableList();
+
+ if (isset ($_POST['anketa']))
+ $this->ank_id = $_POST['anketa'];
+
+ if (isset($_POST['table_id']))
+ $this->table_id = $_POST['table_id'];
+
+
+ if ($_GET['a'] == 'add_variable') {
+
+ if (isset($_POST['spr'])) $spr = $_POST['spr'];
+ if (isset($_POST['parent'])) $parent = $_POST['parent'];
+ if (isset($_POST['position'])) $position = $_POST['position'];
+
+ // Dobimo vrstni red
+ $sql = sisplet_query("SELECT COUNT(id) AS cnt FROM srv_mc_element WHERE table_id='$this->table_id' AND parent='$parent' AND position='$position'");
+ $row = mysqli_fetch_array($sql);
+ $vrstni_red = $row['cnt'];
+
+ sisplet_query("INSERT INTO srv_mc_element (table_id, spr, parent, vrstni_red, position) VALUES('$this->table_id', '$spr', '$parent', '$vrstni_red', '$position')");
+
+ $this->displayTable();
+ }
+
+ if ($_GET['a'] == 'remove_variable') {
+
+ if (isset($_POST['vrstni_red'])) $vrstni_red = $_POST['vrstni_red'];
+ if (isset($_POST['position'])) $position = $_POST['position'];
+ if (isset($_POST['parent'])) $parent = $_POST['parent'];
+
+ // Ce brisemo element na 1. nivoju
+ if($parent == 'undefined'){
+ // Pobrisemo element
+ sisplet_query("DELETE FROM srv_mc_element WHERE table_id='$this->table_id' AND position='$position' AND vrstni_red='$vrstni_red' AND parent=''");
+
+ // Pobrisemo se vse childe
+ sisplet_query("DELETE FROM srv_mc_element WHERE table_id='$this->table_id' AND position='$position' AND parent='$vrstni_red'");
+
+ // Popravimo vrstni red ostalih
+ sisplet_query("UPDATE srv_mc_element SET vrstni_red=vrstni_red-1 WHERE table_id='$this->table_id' AND position='$position' AND vrstni_red>'$vrstni_red' AND parent=''");
+
+ // Popravimo parente pri childih
+ sisplet_query("UPDATE srv_mc_element SET parent=parent-1 WHERE table_id='$this->table_id' AND position='$position' AND parent>'$vrstni_red' AND parent!=''");
+ }
+ // Brisemo element na 2. nivoju
+ else{
+ // Pobrisemo element
+ sisplet_query("DELETE FROM srv_mc_element WHERE table_id='$this->table_id' AND position='$position' AND vrstni_red='$vrstni_red' AND parent='$parent'");
+
+ // Popravimo vrstni red ostalih childov
+ sisplet_query("UPDATE srv_mc_element SET vrstni_red=vrstni_red-1 WHERE table_id='$this->table_id' AND position='$position' AND vrstni_red>'$vrstni_red' AND parent='$parent'");
+ }
+
+
+ $this->displayTable();
+ }
+
+ if ($_GET['a'] == 'change_settings') {
+
+ if (isset($_POST['what'])) $what = $_POST['what'];
+ if (isset($_POST['value'])) $value = $_POST['value'];
+
+ $this->table_settings[$this->table_id][$what] = $value;
+ sisplet_query("UPDATE srv_mc_table SET $what='$value' WHERE table_id='$this->table_id'");
+
+
+ $this->displayTable();
+ }
+
+ if ($_GET['a'] == 'edit_title') {
+
+ $value = isset($_POST['value']) ? $_POST['value'] : '';
+
+ sisplet_query("UPDATE srv_mc_table SET title='$value' WHERE id='$this->table_id'");
+ }
+
+ if ($_GET['a'] == 'save_settings') {
+
+ $this->table_settings[$this->table_id]['numerus'] = (isset($_POST['numerus'])) ? $_POST['numerus'] : 0;
+ $this->table_settings[$this->table_id]['percent'] = (isset($_POST['percent'])) ? $_POST['percent'] : 0;
+ $this->table_settings[$this->table_id]['sums'] = (isset($_POST['sums'])) ? $_POST['sums'] : 0;
+
+ $this->table_settings[$this->table_id]['navVsEno'] = (isset($_POST['navVsEno'])) ? $_POST['navVsEno'] : 0;
+
+ $this->table_settings[$this->table_id]['avgVar'] = (isset($_POST['avgVar']) && isset($_POST['avgSetting'])) ? $_POST['avgVar'] : '';
+
+ $this->table_settings[$this->table_id]['delezVar'] = (isset($_POST['delezVar']) && isset($_POST['delezSetting'])) ? $_POST['delezVar'] : '';
+ // Ce imamo nastavljeno variablo za delez loopamo cez njene opcije in pogledamo katere so checkane
+ if($this->table_settings[$this->table_id]['delezVar'] != ''){
+ $delez = array();
+ $cnt = 0;
+ foreach($this->variablesList[$this->table_settings[$this->table_id]['delezVar']]['options'] as $option){
+ $val = (isset($_POST['delez_'.$cnt])) ? $_POST['delez_'.$cnt] : 0;
+ $delez[$cnt] = $val;
+ $cnt++;
+ }
+ $this->table_settings[$this->table_id]['delez'] = serialize($delez);
+ }
+ else{
+ $this->table_settings[$this->table_id]['delez'] = '';
+ }
+
+
+ $sql = sisplet_query("UPDATE srv_mc_table SET
+ numerus='".$this->table_settings[$this->table_id]['numerus']."',
+ percent='".$this->table_settings[$this->table_id]['percent']."',
+ sums='".$this->table_settings[$this->table_id]['sums']."',
+ navVsEno='".$this->table_settings[$this->table_id]['navVsEno']."',
+ avgVar='".$this->table_settings[$this->table_id]['avgVar']."',
+ delezVar='".$this->table_settings[$this->table_id]['delezVar']."',
+ delez='".$this->table_settings[$this->table_id]['delez']."'
+ WHERE id='".$this->table_id."'");
+ if(!$sql) echo mysqli_error($GLOBALS['connect_db']);
+ $this->displayTable();
+ }
+
+ if ($_GET['a'] == 'set_delez') {
+
+ //$this->table_settings[$this->table_id]['delezVar'] = (isset($_POST['delezVar'])) ? $_POST['delezVar'] : '';
+ $delezVar = (isset($_POST['delezVar'])) ? $_POST['delezVar'] : '';
+
+ $this->displayDelez($delezVar);
+ }
+
+ if ($_GET['a'] == 'mc_show_tables'){
+
+ $this->displayMCTables();
+ }
+
+ if ($_GET['a'] == 'use_mc_table'){
+
+ $value = isset($_POST['value']) ? $_POST['value'] : $this->table_id;
+ SurveyUserSetting :: getInstance()->saveSettings('default_mc_table', $value);
+ }
+
+ if ($_GET['a'] == 'rename_table'){
+
+ $id = isset($_POST['id']) ? $_POST['id'] : '';
+ $name = isset($_POST['name']) ? $_POST['name'] : '';
+ sisplet_query("UPDATE srv_mc_table SET name='$name' WHERE id='$id' AND ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+
+ $this->displayMCTables();
+ }
+
+ if ($_GET['a'] == 'delete_table'){
+
+ $id = isset($_POST['id']) ? $_POST['id'] : '';
+ sisplet_query("DELETE FROM srv_mc_table WHERE id='$id' AND ank_id='$this->ank_id' AND usr_id='$global_user_id'");
+
+ // Preklopimo na prvo tabelo
+ $sql = sisplet_query("SELECT id FROM srv_mc_table WHERE ank_id='$this->ank_id' AND usr_id='$global_user_id' ORDER BY time_created ASC");
+ $row = mysqli_fetch_array($sql);
+
+ $this->table_id = $row['id'];
+ SurveyUserSetting :: getInstance()->saveSettings('default_mc_table', $row['id']);
+
+ $this->displayMCTables();
+ }
+
+ if ($_GET['a'] == 'new_table'){
+
+ $name = isset($_POST['name']) ? $_POST['name'] : '';
+ sisplet_query("INSERT INTO srv_mc_table (ank_id, usr_id, time_created, name) VALUES('$this->ank_id', '$global_user_id', NOW(), '$name')");
+ $table_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ $this->table_id = $table_id;
+ SurveyUserSetting :: getInstance()->saveSettings('default_mc_table', $table_id);
+ }
+
+ if ($_GET['a'] == 'mc_change_table'){
+
+ $id = isset($_POST['id']) ? $_POST['id'] : $this->table_id;
+ $this->table_id = $id;
+
+ $this->displayMCTables();
+ }
+ }
+
+
+ // Skrajsa tekst in doda '...' na koncu
+ function snippet($text, $length=64, $tail="..."){
+ $text = trim($text);
+ $txtl = strlen($text);
+ if($txtl > $length)
+ {
+ for($i=1;$text[$length-$i]!=" ";$i++)
+ {
+ if($i == $length)
+ {
+ return substr($text,0,$length) . $tail;
+ }
+ }
+ $text = substr($text,0,$length-$i+1) . $tail;
+ }
+ return strip_tags($text);
+ }
+
+ /** Naredimo formatiran izpis
+ *
+ * @param $value
+ * @param $digit
+ * @param $sufix
+ */
+ static function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands) . $sufix;
+
+ return $result;
+ }
+
+ function getCrossTabPercentage ($sum, $value) {
+ $result = 0;
+ if ($value ) {
+ $result = (int)$sum == 0 ? 0 : $value / $sum * 100;
+ }
+
+ return $result;
+ }
+
+ /** Sestavi array nepravilnih odgovorov
+ *
+ */
+ function getInvalidAnswers($type) {
+ $result = array();
+ $missingValuesForAnalysis = SurveyMissingProfiles :: GetMissingValuesForAnalysis($type);
+
+ foreach ($missingValuesForAnalysis AS $k => $answer) {
+ $result[$k] = array('text'=>$answer,'cnt'=>0);
+ }
+ return $result;
+ }
+
+
+}
+
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyTTest.php b/admin/survey/classes/surveyAnalysis/class.SurveyTTest.php
new file mode 100644
index 0000000..34819a1
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyTTest.php
@@ -0,0 +1,1207 @@
+<?php
+/** Class ki skrbi za T-test
+ * December 2011
+ *
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+
+define("EXPORT_FOLDER", "admin/survey/SurveyData");
+define("BC_PRECISION", 20);
+define("R_FOLDER", "admin/survey/R");
+
+class SurveyTTest
+{
+ private $sid; # id ankete
+ private $db_table; # katere tabele uporabljamo
+ public $_HEADERS = array(); # shranimo podatke vseh variabel
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za osnovne funkcije data fajla
+
+ public $variablesList = null; # Seznam vseh variabel nad katerimi lahko izvajamo crostabulacije (zakeširamo)
+
+ public $showChart = false; # ali prikazujemo graf pod tabelo
+
+ private $sessionData; # podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ function __construct($sid) {
+
+ if ((int)$sid > 0) {
+ $this->sid = $sid;
+
+ # polovimo vrsto tabel (aktivne / neaktivne)
+ SurveyInfo :: getInstance()->SurveyInit($this->sid);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) {
+ $this->db_table = '_active';
+ }
+
+
+ # Inicializiramo in polovimo nastavitve missing profila
+ SurveyStatusProfiles::Init($this->sid);
+ SurveyUserSetting::getInstance()->Init($this->sid, $global_user_id);
+
+ SurveyStatusProfiles :: Init($this->sid);
+ SurveyMissingProfiles :: Init($this->sid,$global_user_id);
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+ SurveyZankaProfiles :: Init($this->sid, $global_user_id);
+ SurveyTimeProfiles :: Init($this->sid, $global_user_id);
+ SurveyVariablesProfiles :: Init($this->sid);
+
+ SurveyDataSettingProfiles :: Init($this->sid);
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->sid);
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileName = $this->SDF->getDataFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->sid);
+ $this->sessionData = SurveyUserSession::getData();
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA || $this->dataFileStatus == FILE_STATUS_NO_FILE || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ Common::noDataAlert();
+ exit();
+ }
+
+ if ($this->headFileName !== null && $this->headFileName != '') {
+ $this->_HEADERS = unserialize(file_get_contents($this->headFileName));
+ }
+
+ # nastavimo vse filtre
+ $this->setUpFilter();
+
+ } else {
+ echo 'Invalid Survey ID!';
+ exit();
+ }
+ }
+
+ function ajax() {
+
+ if ( isset($_POST['spr2'])) {
+ # če imamo novo spremenljivko, pobrišemo staro sejo
+ if (isset($this->sessionData['ttest']['spr2']) && $this->sessionData['ttest']['spr2'] != $_POST['spr2']) {
+ $this->sessionData['ttest'] = null;
+ unset($this->sessionData['ttest']);
+ }
+ $this->sessionData['ttest']['spr2'] = $_POST['spr2'];
+ }
+ if ( isset($_POST['grid2'])) {
+ $this->sessionData['ttest']['grid2'] = $_POST['grid2'];
+ }
+ if ( isset($_POST['seq2'])) {
+ $this->sessionData['ttest']['seq2'] = $_POST['seq2'];
+ }
+ if ( isset($_POST['label2'])) {
+ $this->sessionData['ttest']['label2'] = $_POST['label2'];
+ }
+ if ( isset($_POST['sub_conditions'])) {
+ $this->sessionData['ttest']['sub_conditions'] = $_POST['sub_conditions'];
+ }
+
+ if ( isset($_POST['seq'])) {
+ $i=0;
+ if (count($_POST['seq']) > 0) {
+ foreach ($_POST['seq'] AS $_seq1) {
+ $this->sessionData['ttest']['variabla'][$i]['seq'] = $_seq1;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['spr'])) {
+ $i=0;
+ if (count($_POST['spr']) > 0) {
+ foreach ($_POST['spr'] AS $_spr1) {
+ $this->sessionData['ttest']['variabla'][$i]['spr'] = $_spr1;
+ $i++;
+ }
+ }
+ }
+ if ( isset($_POST['grd'])) {
+ $i=0;
+ if (count($_POST['grd']) > 0) {
+ foreach ($_POST['grd'] AS $_grd1) {
+ $this->sessionData['ttest']['variabla'][$i]['grd'] = $_grd1;
+ $i++;
+ }
+ }
+ }
+
+ if ( isset($_POST['showChart'])) {
+ $this->sessionData['ttest_charts']['showChart'] = ($_POST['showChart'] == 'true');
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ # izvedemo akcijo
+ switch ($_GET['a']) {
+ case 'spremenljivkaChange':
+ $this->spremenljivkaChange();
+ break;
+ case 'variableChange':
+ $this->variableChange();
+ break;
+ default:
+ break;
+ }
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function Display() {
+
+ # ali imamo testne podatke
+ if ($this->_HAS_TEST_DATA) {
+ # izrišemo bar za testne podatke
+ $SSH -> displayTestDataBar(true);
+ $SSH = new SurveyStaticHtml($this->sid);
+ }
+
+ /*echo '<div id="dataOnlyValid">';
+ SurveyStatusProfiles::displayOnlyValidCheckbox();
+ echo '</div>';*/
+
+ //$this->DisplayLinks();
+
+ echo '<div id="ttest_variables">';
+ $this->DisplayVariables();
+ echo '</div>'; # id="ttest_variables"
+ echo '<br class="clr">';
+ echo '<div id="ttestResults">';
+ $this->variableChange();
+ echo '</div>'; # id="ttestResults"
+ }
+
+ // Izvoz pdf in rtf
+ function displayExport () {
+
+ $variables2 = $this->getSelectedVariables() ;
+ if (is_array($variables2) && count($variables2)>0 ) {
+
+ $href_pdf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=ttest_izpis&anketa=' . $this->sid);
+ $href_rtf = makeEncodedIzvozUrlString('izvoz.php?b=export&m=ttest_izpis_rtf&anketa=' . $this->sid);
+ $href_xls = makeEncodedIzvozUrlString('izvoz.php?b=export&m=ttest_izpis_xls&anketa=' . $this->sid);
+
+ echo '<script>';
+ # nastavimopravilne linke
+ echo '$("#secondNavigation_links a#ttestDoPdf").attr("href", "'.$href_pdf.'");';
+ echo '$("#secondNavigation_links a#ttestDoRtf").attr("href", "'.$href_rtf.'");';
+ echo '$("#secondNavigation_links a#ttestDoXls").attr("href", "'.$href_xls.'");';
+ # prikažemo linke
+ echo '$("#hover_export_icon").removeClass("hidden");';
+ echo '$("#secondNavigation_links a").removeClass("hidden");';
+ echo '</script>';
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function DisplayLinks() {
+ # izrišemo navigacijo za analize
+ $SSH = new SurveyStaticHtml($this->sid);
+ //$SSH -> displayAnalizaSubNavigation();
+
+ # izrišemo desne linke do posameznih nastavitev
+ $SSH -> displayAnalizaRightOptions(M_ANALYSIS_TTEST);
+ }
+
+
+ /** Funkcija ki nastavi vse filtre
+ *
+ */
+ private function setUpFilter() {
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ # poiščemo kater profil uporablja uporabnik
+ $_currentMissingProfile = SurveyUserSetting :: getInstance()->getSettings('default_missing_profile');
+ $this->currentMissingProfile = (isset($_currentMissingProfile) ? $_currentMissingProfile : 1);
+
+ # filtriranje po statusih
+ $this->_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK($this->_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # dodamo še ife
+
+ SurveyConditionProfiles :: setHeader($this->_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) || ($_time_profile_awk != "" && $_time_profile_awk != null)) {
+ $this->_CURRENT_STATUS_FILTER = '('.$this->_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_condition_profile_AWK;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ $this->_CURRENT_STATUS_FILTER .= ' && '.$_time_profile_awk;
+ }
+ $this->_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+
+ if ($this->dataFileStatus == FILE_STATUS_OK || $this->dataFileStatus == FILE_STATUS_OLD) {
+
+ if (isset($this->_HEADERS['testdata'])) {
+ $this->_HAS_TEST_DATA = true;
+ }
+ }
+ }
+
+ function DisplayVariables() {
+ global $lang;
+
+ $numerus = $this->getVariableList(1);
+ $selectedVar = $this->getSelectedVariables();
+
+ $variables = $this->getVariableList(2);
+
+ echo '<span id="ttestSpremenljivkaSpan" class="floatLeft">';
+ echo $lang['srv_ttest_label1'];
+ echo '<br />';
+
+ echo '<select id="ttestSpremenljivka" name="ttestSpremenljivka" onchange="ttestSpremenljivkaChange();" autocomplete="off">';
+ echo '<option value="0" selected="selected" >'. $lang['srv_ttest_select1_option'] . '</option>';
+ if (count($variables)) {
+ foreach ($variables as $variable) {
+ echo '<option value="'.$variable['spr_id'].'"'
+ . ( isset($variable['grd_id']) ? ' grid="'.$variable['grd_id'].'" ' : '')
+ . ( isset($variable['vr_id']) ? ' vred="'.$variable['vr_id'].'" ' : '')
+ . ( isset($variable['sequence']) ? ' seq2="'.$variable['sequence'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( $variable['spr_id'] != '' && $variable['spr_id'] == $this->sessionData['ttest']['spr2'] && $variable['sequence'] == $this->sessionData['ttest']['seq2'] ? ' selected="selected"':'')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ .$variable['variableNaslov'] . '</option>';
+ }
+ }
+ echo '</select>'; # name="ttestSpremenljivka"
+ echo '<br class="clr"/><br/>';
+ #.(count($this->sessionData['ttest']['sub_conditions']) == 2?'':'class="active"').
+ $_active = $this->checkSubConditionsActive();
+ if ($this->sessionData['ttest']['spr2'] > 0) {
+ echo '<div id="ttestVariablesSpan"'.($_active < 2 ? ' class="active"' : '').'>';
+ $this->spremenljivkaChange();
+ echo '</div>';
+ } else {
+ echo '<div id="ttestVariablesSpan" style="display:none" '.($_active < 2 ? ' class="active"' : '').'></div>';
+ }
+ echo '</span>';
+
+ $cntSubConditionsActive = $this->checkSubConditionsActive();
+ echo '<span class="floatLeft spaceRight">&nbsp;</span>';
+ echo '<span id="ttestNumerusSpan" class="floatLeft'.($cntSubConditionsActive == 2 ? '' : ' gray').'">'; #gray
+ echo $lang['srv_ttest_label2'];
+ echo '<br />';
+ echo '<select id="ttestNumerus" name="ttestNumerus" onchange="ttestVariableChange();" autocomplete="off" '.($cntSubConditionsActive == 2 ? '' : ' disabled="disabled"').'>'; #
+ echo '<option value="0" selected="selected" >'. $lang['srv_ttest_select2_option'] . '</option>';
+ if (count($numerus)) {
+ foreach ($numerus as $variable) {
+ echo '<option value="'.$variable['spr_id'].'"'
+ . ( isset($variable['grd_id']) ? ' grd="'.$variable['grd_id'].'" ' : '')
+ . ( isset($variable['vr_id']) ? ' vrd="'.$variable['vr_id'].'" ' : '')
+ . ( isset($variable['sequence']) ? ' seq="'.$variable['sequence'].'" ' : '')
+ . (( (int)$variable['canChoose'] == 1) ? '' : ' disabled="disabled" ')
+ . ( $variable['spr_id'] != '' && $variable['spr_id'] == $selectedVar[0]['spr'] && $variable['sequence'] == $selectedVar[0]['seq']?' selected="selected"':'')
+ . '> '
+ . ( (int)$variable['sub'] == 0 ? '' : ( (int)$variable['sub'] == 1 ? '&nbsp;&nbsp;' : '&nbsp;&nbsp;&nbsp;&nbsp;' ))
+ . $variable['variableNaslov'] . '</option>';
+ }
+ }
+ echo '</select>'; # name="ttestSpremenljivka"
+ echo '</span>';
+
+ echo '<br /><span style="margin-left: 30px;">';
+ echo '<label><input id="showChart" type="checkbox" onchange="showTableChart(\'ttest\');" '.($this->sessionData['ttest_charts']['showChart']==true?' checked="checked"':'' ).'>'.$lang['srv_show_chart'].'</label>';
+ echo '</span>';
+ echo '<span style="margin-left: 30px;"><a href="https://www.1ka.si/d/sl/pomoc/prirocniki/ttest?from1ka=1" target="_blank">';
+ echo $lang['srv_ttest_interpretacija_note'];
+ echo '</a></span>';
+ echo Help::display('srv_ttest_interpretation');
+
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ /** funkcija vrne seznam primern variabel za crostabe
+ *
+ */
+ function getVariableList($witch) {
+ # pobrišemo array()
+ $this->variablesList = array();
+ # zloopamo skozi header in dodamo variable (potrebujemo posamezne sekvence)
+ foreach ($this->_HEADERS AS $skey => $spremenljivka) {
+ $tip = $spremenljivka['tip'];
+ if ($witch == 1) {
+ # prvi drop down, morajo biti numerične ali ordinalne
+ # skala - 0 Ordinalna
+ # skala - 1 Nominalna
+
+ $skala = isset($spremenljivka['skala']) ? $spremenljivka['skala'] : 1;
+
+ # če radio nimajo podane skale jo damo na 0
+ $skala = ($skala == -1 && ($tip == 6 || $tip == 16) ) ? 0 : $skala ;
+
+ $_dropdown_condition = is_numeric($tip) && ((int)$skala === 0 # ordinalna
+ || $tip == 7 # number
+ || $tip == 18 # vsota
+ || $tip == 20) # multi number
+ ? true : false;
+ } else {
+ #drugi dropdown
+ # tekstovnih in numeričnih tipov ne dodajamo
+ $_dropdown_condition = is_numeric($tip) && $tip != 4 #text
+ && $tip != 5 #label
+ && $tip != 7 #number
+ && $tip != 8 #datum
+ && $tip != 9 #SN-imena
+ && $tip != 18 #vsota
+ && $tip != 19 #multitext
+ && $tip != 20 #multinumber
+ && $tip != 21 #besedilo*
+ && $tip != 22 #compute
+ && $tip != 25 #kvota
+ ? true : false;
+ }
+ if ($_dropdown_condition) {
+ $cnt_all = (int)$spremenljivka['cnt_all'];
+ # radio in select in checkbox
+ if ($cnt_all == '1' || $tip == 1 || $tip == 3 || $tip == 2) {
+ # pri tipu radio ali select dodamo tisto variablo ki ni polje "drugo"
+ if ($tip == 1 || $tip == 3 ) {
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][$vid]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+
+ }
+ }
+ }
+ }
+ } else if ($tip == 2){
+ if ($witch == 1) {
+ #pri checkboxu ponudimo vsako podvariablo posebej
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # imampo samo eno sekvenco grids[0]
+ if (count ($spremenljivka['grids'][0]['variables']) > 0) {
+
+ foreach ($spremenljivka['grids'][0]['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'vr_id'=>$vid,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } else {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+
+ } else {
+ # imampo samo eno sekvenco grids[0]variables[0]
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$spremenljivka['grids'][0]['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>0);
+ }
+
+ } else if ($cnt_all > 1){
+ # imamo več skupin ali podskupin, zato zlopamo skozi gride in variable
+ if (count($spremenljivka['grids']) > 0 ) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+
+ 'variableNaslov'=>'('.$spremenljivka['variable'].')&nbsp;'.strip_tags($spremenljivka['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>0);
+ # ali imamo en grid, ali več (tabele
+ if (count($spremenljivka['grids']) == 1 ) {
+ # če imamo samo en grid ( lahko je več variabel zaradi polja drugo.
+ $grid = $spremenljivka['grids'][0];
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ }
+
+ } else if($tip == 16||$tip == 18) {
+ # imamo multicheckbox
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'grd_id'=>$gid,
+ 'sequence'=>$grid['variables'][0]['sequence'],
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>1);
+ }
+ }
+ } else {
+ # imamo več gridov - tabele
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ $sub = 0;
+ if ($grid['variable'] != '') {
+ $sub++;
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'variableNaslov'=>'('.$grid['variable'].')&nbsp;'.strip_tags($grid['naslov']),
+ 'canChoose'=>false,
+ 'sub'=>$sub);
+ }
+ if (count ($grid['variables']) > 0) {
+ $sub++;
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if ($variable['other'] != 1) {
+ $this->variablesList[] = array(
+ 'tip'=>$tip,
+ 'spr_id'=>$skey,
+ 'sequence'=>$variable['sequence'],
+ 'variableNaslov'=>'('.$variable['variable'].')&nbsp;'.strip_tags($variable['naslov']),
+ 'canChoose'=>true,
+ 'sub'=>$sub);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ return $this->variablesList;
+ }
+
+
+ function spremenljivkaChange() {
+ global $lang;
+
+ if (isset($this->sessionData['ttest']['spr2']) && $this->sessionData['ttest']['spr2'] != 0){
+ $_spr = explode('_',$this->sessionData['ttest']['spr2']);
+ #$spr = $_spr[0];
+ $spr = $this->sessionData['ttest']['spr2'];
+
+ if (isset($this->sessionData['ttest']['grid2'])){
+ $grid = $this->sessionData['ttest']['grid2'];
+ }
+ # poiščemo pripadajoče variable
+ $_spr_data = $this->_HEADERS[$this->sessionData['ttest']['spr2']];
+ echo $lang['srv_ttest_kategories_note'].' ('.$_spr_data['variable'].') '.$_spr_data['naslov'];
+ echo '<br/>';
+ switch ($_spr_data['tip']) {
+ case 1: #radio
+ case 3: #dropdown
+ case 17: #dropdown
+ #nardimo inpute za vse opcije
+ $sekvenca = $_spr_data['sequences'];
+ foreach ($_spr_data['options'] as $value => $option) {
+ echo '<label '.($this->checkboxSubCondition($spr.'_'.$sekvenca.'_'.$value) == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" type="checkbox" value="'.$spr.'_'.$sekvenca.'_'.$value.'" onchange="ttestVariableChange();"'.$this->checkboxSubCondition($spr.'_'.$sekvenca.'_'.$value).'/>('.$value.') - '.$option.'</label><br/>';
+ }
+ break;
+ case 2: #checkbox
+ #nardimo inpute za vse opcije
+ $option = '1';
+ foreach ($_spr_data['grids'][0]['variables'] as $vid => $variable) {
+ echo '<label '.($this->checkboxSubCondition($spr.'_'.$variable['sequence'].'_'.$option) == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" type="checkbox" value="'.$spr.'_'.$variable['sequence'].'_'.$option. '" onchange="ttestVariableChange();"'.$this->checkboxSubCondition($spr.'_'.$variable['sequence'].'_'.$option).'/>('.$variable['variable'].') - '.$variable['naslov'].'</label><br/>';
+ }
+ break;
+ case 6: #mgrid
+ #nardimo inpute za vse opcije
+ $sekvenca = $this->sessionData['ttest']['seq2'];
+ foreach ($_spr_data['options'] as $value => $option) {
+ //$sekvenca = $_spr_data['grids'][$value]['variables'][0]['sequence'];
+ echo '<label '.($this->checkboxSubCondition($spr.'_'.$sekvenca.'_'.$value) == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" type="checkbox" value="'.$spr.'_'.$sekvenca.'_'.$value.'" onchange="ttestVariableChange();"'.$this->checkboxSubCondition($spr.'_'.$sekvenca.'_'.$value).'/>('.$value.') - '.$option.'</label><br/>';
+ }
+ break;
+ case 16: #mcheck
+ #nardimo inpute za vse opcije
+ # poiščemo pripadajočo sekvenco
+ #nardimo inpute za vse opcije
+ $option = '1';
+ foreach ($_spr_data['grids'][$grid]['variables'] as $vid => $variable) {
+ echo '<label '.($this->checkboxSubCondition($spr.'_'.$variable['sequence'].'_'.$option) == ' disabled="disabled"' ? 'class="gray"' : '').'><input name="subTtest" type="checkbox" value="'.$spr.'_'.$variable['sequence'].'_'.$option.'" onchange="ttestVariableChange();"'.$this->checkboxSubCondition($spr.'_'.$variable['sequence'].'_'.$option).'/>('.$variable['variable'].') - '.$variable['naslov'].'</label><br/>';
+ }
+ break;
+
+ default:
+ if ((int)$_spr_data['tip'] > 0)
+ echo'TODO for type:'.$_spr_data['tip'];
+ break;
+ }
+ } else if ($this->sessionData['ttest']['spr2'] == 0){
+
+
+ echo $lang['srv_ttest_select1_option'].'!';
+ echo '<br/>';
+
+
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function variableChange() {
+ global $admin_type;
+
+ if (count($this->sessionData['ttest']['sub_conditions']) > 1 ) {
+ $variables1 = $this->getSelectedVariables();
+ if (count($variables1) > 0) {
+ // ikone za izvoz
+ $this->displayExport();
+ foreach ($variables1 AS $v_first) {
+
+ $ttest = null;
+ /*$ttest = $this->createTTestOld($v_first, $this->sessionData['ttest']['sub_conditions']);
+ $this->displayTtestTable($ttest);*/
+ $ttest = $this->createTTest($v_first, $this->sessionData['ttest']['sub_conditions']);
+ $this->displayTtestTable($ttest);
+
+ // Zvezdica za vkljucitev v porocilo
+ $spid1 = $this->sessionData['ttest']['variabla'][0]['spr'];
+ $seq1 = $this->sessionData['ttest']['variabla'][0]['seq'];
+ $grid1 = $this->sessionData['ttest']['variabla'][0]['grd'];
+ $sub1 = $this->sessionData['ttest']['sub_conditions'][0];
+ $sub2 = $this->sessionData['ttest']['sub_conditions'][1];
+
+ $spid2 = $this->sessionData['ttest']['spr2'];
+ $seq2 = $this->sessionData['ttest']['seq2'];
+ $grid2 = $this->sessionData['ttest']['grid2'];
+
+ $spr1 = $seq2.'-'.$spid2.'-'.$grid2.'-'.$sub1.'-'.$sub2;
+ $spr2 = $seq1.'-'.$spid1.'-'.$grid1;
+ SurveyAnalysis::addCustomReportElement($type=7, $sub_type=0, $spr1, $spr2);
+
+ // Izrisemo graf za tabelo
+ if(isset($this->sessionData['ttest_charts']['showChart']) && $this->sessionData['ttest_charts']['showChart'] == true){
+ $tableChart = new SurveyTableChart($this->sid, $this, 'ttest');
+ $tableChart->display();
+ }
+ }
+ }
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ function getSelectedVariables() {
+
+ $selected = array();
+ if (count($this->sessionData['ttest']['variabla']) > 0 ) {
+ foreach ($this->sessionData['ttest']['variabla'] AS $var1) {
+ if ((int)$var1['seq'] > 0) {
+ $selected[] = $var1;
+ }
+ }
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ return count($selected) > 0 ? $selected : null;
+ }
+
+
+ function createTTest($v_first, $sub_vars) {
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $R_folder = $site_path . R_FOLDER.'/';
+
+ if ($this->dataFileName != '' && file_exists($this->dataFileName)) {
+
+ // Nastavimo stolpce za katere izvajamo ttest
+ $ttestVars = '';
+ $sub_conditions = array();
+ $i=1;
+ foreach ($sub_vars as $sub_condition) {
+ if ($i < 3) {
+ $_tmp = explode('_',$sub_condition);
+ $ttestVars .= '$'.$_tmp[2].',';
+ $sub_conditions[] = $_tmp[3];
+ $i++;
+ }
+ }
+
+ $ttestVars .= '$'.$v_first['seq'].',';
+ $ttestVars = substr($ttestVars, 0, -1);
+
+ // Ce se nimamo datoteke s pripravljenimi podatki jo ustvarimo
+ $tmp_file = $R_folder . '/TempData/crosstab_data.tmp';
+ if (!file_exists($tmp_file)) {
+ $this->prepareDataFile($ttestVars);
+ }
+
+
+ // Inicializiramo R in pozenemo skripto za crosstabulacije
+ $R = new SurveyAnalysisR($this->sid);
+ $result = $R->createTTest($sub_conditions);
+
+ // Na koncu pobrisemo zacasen file s podatki
+ $this->deleteDataFile();
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ return $result;
+ }
+
+ function createTTestOld($v_first, $sub_vars) {
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ if ($this->dataFileName != '' && file_exists($this->dataFileName)) {
+
+ $spr1 = $this->_HEADERS[$v_first['spr']];
+ $grid1 = $spr1['grids'][$v_first['grd']];
+ $sequence1 = $v_first['seq'];
+
+ # za checkboxe gledamo samo odgovore ki so bili 1 in za vse opcije
+ $sekvences1 = array();
+ $spr_1_checkbox = false;
+
+ if ($spr1['tip'] == 2 || $spr1['tip'] == 16) {
+
+ $spr_1_checkbox = true;
+ if (isset($sequence1) && (int)$sequence1 > 0) {
+ $sekvences1[] = (int)$sequence1;
+ } else {
+ if ($spr1['tip'] == 2) {
+
+ $sekvences1 = explode('_',$spr1['sequences']);
+ }
+ if ($spr1['tip'] == 16) {
+
+ foreach ($grid1['variables'] AS $_variables) {
+ $sekvences1[] = $_variables['sequence'];
+ }
+ }
+ }
+ } else {
+ $sekvences1[] = $sequence1;
+ }
+ # pogoji so že dodani v _CURRENT_STATUS_FILTER
+ # dodamo filter za loop-e
+ if (isset($this->_CURRENT_LOOP['filter']) && $this->_CURRENT_LOOP['filter'] != '') {
+ $status_filter = $this->_CURRENT_STATUS_FILTER.' && '.$this->_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+ }
+
+ # nastavimo subfiltre za drugo variablo
+ $sub_conditions = array();
+ $i=1;
+ foreach ($sub_vars as $sub_condition) {
+ if ($i < 3) {
+ $_tmp = explode('_',$sub_condition);
+ $sub_conditions[$i] = ' && ($'.$_tmp[2].' == '.$_tmp[3].')';
+ $i++;
+ }
+ }
+
+
+ # dodamo status filter za vse sekvence checkbox-a da so == 1
+ if ($additional_status_filter != null) {
+ $status_filter .= $additional_status_filter;
+ }
+
+ # odstranimo vse zapise, kjer katerakoli od variabel vsebuje missing
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_pageMissing_answers = $this->getInvalidAnswers (MISSING_TYPE_CROSSTAB);
+
+ # polovimo obe sequenci
+ $tmp_file = $folder . 'tmp_ttest_'.$this->sid.'.TMP';
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+ if (count($sekvences1)>0){
+ foreach ($sekvences1 AS $sequence1) {
+ if (count($sub_conditions) > 1) {
+ foreach ($sub_conditions as $subkey =>$sub_condition) {
+
+ #skreira variable: $ttest, $cvar1, $cvar2
+
+ $additional_filter = '';
+ if ($spr_1_checkbox == true) {
+ $_seq_1_text = ''.$sequence1;
+
+ # pri checkboxih gledamo samo kjer je 1 ( ne more bit missing)
+ $additional_filter = ' && ($'.$sequence1.' == 1)';
+ } else {
+ $_seq_1_text = '$'.$sequence1;
+
+ # dodamo še pogoj za missinge
+ foreach ($_pageMissing_answers AS $m_key1 => $missing1) {
+ #$additional_filter .= ' && ($'.$sequence1.' != '.$m_key1.')';
+ }
+ }
+
+ if (IS_WINDOWS) {
+ $command1 = 'awk -F"|" "BEGIN {{OFS=\"\"} {ORS=\"\n\"}} '.$status_filter.$sub_condition.$additional_filter.' { print \"$ttest[\x27\",'.$subkey.',\"\x27][\x27\",'.$_seq_1_text.',\"\x27]++;\"}" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command1 = 'awk -F"|" \'BEGIN {{OFS=""} {ORS="\n"}} '.$status_filter.$sub_condition.$additional_filter.' { print "$ttest[\x27\",'.$subkey.',\"\x27][\x27",'.$_seq_1_text.',"\x27]++;"}\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out = shell_exec($command1);
+ }
+ }
+ }
+ }
+ $file_handler = fopen($tmp_file,"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($tmp_file);
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+
+ # naredimo izračune
+ #najprej izračunamo frekvenco in povprečje
+ # zloopamo preko posamezneka pod pogoja
+ $result = array();
+
+ $cnt = 0;
+ if (count($ttest) > 0) {
+ foreach ($ttest AS $subkey => $_ttests) {
+ $cnt++;
+ # zloopamo preko frekvenc in nardimo izračune
+ $sum_all = 0;
+ $n = 0;
+ if(count($_ttests) > 0) {
+ foreach ($_ttests AS $value => $freq) {
+ #$n = bcadd($n,$freq,BC_PRECISION);
+ #$sum_all = bcadd($sum_all,bcmul($value,$freq,BC_PRECISION),BC_PRECISION);
+ $n += $freq;
+ $sum_all += $value * $freq;
+ }
+ }
+ #n = frekvenca
+ #$x = ($n <> 0)
+ # ? bcdiv($sum_all,$n,BC_PRECISION)
+ # : 0;
+
+ $x = ($n <> 0)
+ ? $sum_all / $n
+ : 0;
+
+ $result[$cnt] = array('n'=>$n, 'x'=>$x);
+
+ # izračunamo še standardno diviacijo
+ $sum_pow_xi_fi_avg = 0;
+ if(count($_ttests) > 0) {
+ foreach ($_ttests AS $value => $freq) {
+
+ $xi = $value;
+ $fi = $freq;
+ #$sum_pow_xi_fi_avg += pow(($xi - $avg),2) * $fi;
+ #$sum_pow_xi_fi_avg = bcadd($sum_pow_xi_fi_avg, bcmul(bcpow(bcsub($xi,$x,BC_PRECISION),2,BC_PRECISION),$fi,BC_PRECISION));
+ $sum_pow_xi_fi_avg += pow( ($xi - $x), 2 ) * $fi ;
+ }
+ }
+ #varianca
+ #$s2 = (($n - 1) > 0) ? sqrt($sum_pow_xi_fi_avg / ($n -1)) : 0;
+ #$s2 = (bcsub($n, 1, BC_PRECISION) <> 0)
+ # ? bcsqrt( bcdiv($sum_pow_xi_fi_avg, bcsub($n, 1, BC_PRECISION), BC_PRECISION), BC_PRECISION)
+ # : 0;
+ $s2 = ( $n - 1 <> 0 )
+ ? sqrt( $sum_pow_xi_fi_avg / ($n - 1) )
+ : 0;
+ $result[$cnt]['s2'] = $s2;
+ # standardna napaka
+ #se = s2 / sqrt(n)
+ #$se = $n > 0
+ # ? bcdiv($s2, bcsqrt($n, BC_PRECISION), BC_PRECISION)
+ # : 0;
+ $se = $n > 0
+ ? $s2 / sqrt($n)
+ : 0;
+
+ $result[$cnt]['se'] = $se;
+ #se2 = *se^2
+ #$se2 = bcpow($se, 2, BC_PRECISION);
+ $se2 = pow($se, 2);
+ $result[$cnt]['se2'] = $se2;
+
+ #margini => 1,96*ee
+ #$margin = bcmul(1.96, $se, BC_PRECISION);
+ $margin = 1.96 * $se;
+ $result[$cnt]['margin'] = $margin;
+ }
+ }
+ #razlika povprečij => $d = x1 -x2
+ #$d = bcsub($result[1]['x'], $result[2]['x'], BC_PRECISION);
+ $d = $result[1]['x'] - $result[2]['x'];
+ $result['d'] = $d;
+
+ #sed : std. error difference
+ #$sed = bcsqrt( bcadd($result[1]['se2'], $result[2]['se2'], BC_PRECISION), BC_PRECISION );
+ $sed = sqrt( $result[1]['se2'] + $result[2]['se2']);
+ $result['sed'] = $sed;
+
+ #ttest => t = d / sed
+ #$t = ($sed <> 0)
+ # ? bcdiv($d, $sed, BC_PRECISION)
+ # : 0;
+ $t = ($sed <> 0)
+ ? $d / $sed
+ : 0;
+ $result['t'] = $t;
+
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ return $result;
+ }
+
+ // Pripravimo file iz katerega preberemo podatke in izvedemo ttest
+ function prepareDataFile($cols){
+ global $site_path;
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+ $R_folder = $site_path . R_FOLDER.'/';
+
+
+ if (isset($this->_CURRENT_LOOP['filter']) && $this->_CURRENT_LOOP['filter'] != '') {
+ $status_filter = $this->_CURRENT_STATUS_FILTER.' && '.$this->_CURRENT_LOOP['filter'];
+ } else {
+ $status_filter = $this->_CURRENT_STATUS_FILTER;
+ }
+
+ # dodamo status filter za vse sekvence checkbox-a da so == 1
+ if ($additional_status_filter != null) {
+ $status_filter .= $additional_status_filter;
+ }
+
+ # odstranimo vse zapise, kjer katerakoli od variabel vsebuje missing
+ $_allMissing_answers = SurveyMissingValues::GetMissingValuesForSurvey(array(1,2,3));
+ $_pageMissing_answers = $this->getInvalidAnswers(MISSING_TYPE_CROSSTAB);
+
+
+ // File kamor zapisemo filtrirane podatke
+ $tmp_file = $R_folder . '/TempData/ttest_data.tmp';
+
+
+ // Filtriramo podatke po statusu in loopih in jih zapisemo v temp folder R-ja
+ if (IS_WINDOWS) {
+ $command = 'awk -F"|" "BEGIN {{OFS=\",\"} {ORS=\"\n\"}} '.$status_filter.' { print '.$cols.' }" '.$this->dataFileName.' >> '.$tmp_file;
+ } else {
+ $command = 'awk -F"|" \'BEGIN {{OFS=","} {ORS="\n"}} '.$status_filter.' { print '.$cols.'; }\' '.$this->dataFileName.' >> '.$tmp_file;
+ }
+
+ $out = shell_exec($command);
+
+ return $out;
+ }
+
+ // Pobrisemo zacasen file s podatki
+ function deleteDataFile(){
+ global $site_path;
+
+ $R_folder = $site_path . R_FOLDER.'/';
+ $tmp_file = $R_folder . '/TempData/ttest_data.tmp';
+
+ // Na koncu pobrisemo zacasen file s podatki
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+ }
+
+
+ /** Sestavi array nepravilnih odgovorov
+ *
+ */
+ function getInvalidAnswers($type) {
+ $result = array();
+ $missingValuesForAnalysis = SurveyMissingProfiles :: GetMissingValuesForAnalysis($type);
+
+ foreach ($missingValuesForAnalysis AS $k => $answer) {
+ $result[$k] = array('text'=>$answer,'cnt'=>0);
+ }
+ return $result;
+ }
+
+ function displayTtestTable($ttest) {
+ global $lang;
+
+ # preverimo ali imamo izbrano odvisno spremenljivko
+ $spid1 = $this->sessionData['ttest']['variabla'][0]['spr'];
+ $seq1 = $this->sessionData['ttest']['variabla'][0]['seq'];
+ $grid1 = $this->sessionData['ttest']['variabla'][0]['grd'];
+
+ if (is_array($ttest) && count($ttest) > 0 && (int)$seq1 > 0) {
+ if ($this->isArchive == false) {
+ echo '<div id="displayFilterNotes">';
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile();
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString($doNewLine );
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString($doNewLine, true);
+ SurveyDataSettingProfiles :: getVariableTypeNote($doNewLine );
+ # če rekodiranje
+ $SR = new SurveyRecoding($this->sid);
+ $SR -> getProfileString();
+ echo '</div>';
+
+ echo '<br class="clr" />';
+ }
+ $spr_data_1 = $this->_HEADERS[$spid1];
+ if ($grid1 == 'undefined') {
+
+ # imamp lahko več variabel
+ $seq = $seq1;
+ foreach ($spr_data_1['grids'] as $gkey => $grid ) {
+
+ foreach ($grid['variables'] as $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($sequence == $seq) {
+ $sprLabel1 = '('.$variable['variable'].') '. $variable['naslov'];
+ }
+ }
+ }
+ } else {
+ # imamo subgrid
+ $sprLabel1 = '('.$spr_data_1['grids'][$grid1]['variable'].') '. $spr_data_1['grids'][$grid1]['naslov'];
+ }
+
+ # polovio labele
+ $spid2 = $this->sessionData['ttest']['spr2'];
+ $sprLabel2 = trim($this->sessionData['ttest']['label2']);
+ $label1 = $this->getVariableLabels($this->sessionData['ttest']['sub_conditions'][0]);
+ $label2 = $this->getVariableLabels($this->sessionData['ttest']['sub_conditions'][1]);
+ echo '<table border="0" class="ttestTable">';
+ echo '<tr>';
+ #labele
+ echo '<td class="lightGreen" rowspan="2" >';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" onclick="showspremenljivkaSingleVarPopup(\''.$spid2.'\'); return false;">';
+ echo $sprLabel2.'</a>';
+ echo '</span>';
+ echo '</td>';
+
+ echo '<td class="lightGreen" colspan="9">';
+ echo '<span class="anl_variabla">';
+ echo '<a href="#" onclick="showspremenljivkaSingleVarPopup(\''.$spid1.'\'); return false;">';
+ echo $sprLabel1.'</a>';
+ echo '</span>';
+ echo '</td>';
+ echo '</tr>';
+ echo '<tr>';
+ #echo '<th colspan="2">&nbsp;</th>';
+ #frekvenca
+ echo '<th >n</th>';
+ #povprečje
+ echo '<th><span class="avg">x</span></th>';
+ #varianca
+ echo '<th>s&#178;</th>';
+ #standardna napaka
+ echo '<th>se(<span class="avg">x</span>)</th>';
+ #margini
+ echo '<th>&#177;1,96&#215;se(<span class="avg">x</span>)</th>';
+ #d
+ echo '<th>d</th>';
+ #sed
+ echo '<th>se(d)</th>';
+ #signifikanca
+ echo '<th>Sig.</th>';
+ #ttest
+ echo '<th>t</th>';
+ echo '</tr>';
+
+ echo '<tr>';
+
+ #labele
+
+ echo '<td class="lightGreen">'.$label1.'</td>';
+ #frekvenca
+ echo '<td>'.$this->formatNumber($ttest[1]['n'],0).'</td>';
+ #povprečje
+ echo '<td>'.$this->formatNumber($ttest[1]['x'],3).'</td>';
+ #varianca
+ echo '<td>'.$this->formatNumber($ttest[1]['s2'],3).'</td>';
+ #standardna napaka
+ echo '<td>'.$this->formatNumber($ttest[1]['se'],3).'</td>';
+ #margini
+ echo '<td>'.$this->formatNumber($ttest[1]['margin'],3).'</td>';
+ #d
+ echo '<td rowspan="2">'.$this->formatNumber($ttest['d'],3).'</td>';
+ #sed
+ echo '<td rowspan="2">'.$this->formatNumber($ttest['sed'],3).'</td>';
+ #sig
+ echo '<td rowspan="2">'.$this->formatNumber($ttest['sig'],3).'</td>';
+ #ttest
+ echo '<td rowspan="2">'.$this->formatNumber($ttest['t'],3).'</td>';
+ echo '</tr>';
+
+ echo '<tr>';
+ #labele
+ echo '<td class="lightGreen">'.$label2.'</td>';
+ #frekvenca
+ echo '<td>'.$this->formatNumber($ttest[2]['n'],0).'</td>';
+ #povprečje
+ echo '<td>'.$this->formatNumber($ttest[2]['x'],3).'</td>';
+ #varianca
+ echo '<td>'.$this->formatNumber($ttest[2]['s2'],3).'</td>';
+ #standardna napaka
+ echo '<td>'.$this->formatNumber($ttest[2]['se'],3).'</td>';
+ #margini
+ echo '<td>'.$this->formatNumber($ttest[2]['margin'],3).'</td>';
+ echo '</tr>';
+ echo '</table>';
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ /** Naredimo formatiran izpis
+ *
+ * @param $value
+ * @param $digit
+ * @param $sufix
+ */
+
+ static function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands).$sufix;
+
+ return $result;
+ }
+
+ function getVariableLabels($sub_conditions) {
+ $_tmp = explode('_',$sub_conditions);
+ $spr = $this->_HEADERS[$_tmp[0].'_'.$_tmp[1]];
+ switch ($spr['tip']) {
+ case 1: #radio
+ case 3: #dropdown
+ $label = $spr['options'][$_tmp[3]];
+ break;
+ case 2: #checkbox
+ foreach ($spr['grids'][0]['variables'] as $vkey => $variable) {
+ if($variable['sequence'] == $_tmp[2]) {
+ $label = '('.$variable['variable'].') - '.$variable['naslov'];
+ }
+ }
+ break;
+ case 6: #mgrid
+ $label = $spr['options'][$_tmp[3]];
+ break;
+ case 16: #mcheck
+ $label = $spr['options'][$_tmp[3]];
+ break;
+ default:
+ $label = 'TODO: getVariableLabels for type:'.$spr['tip'];
+ break;
+ }
+ return $label;
+ }
+
+ function checkboxSubCondition($checkCondition) {
+
+ $cnt = $this->checkSubConditionsActive();
+ $sub_Conditions = $this->sessionData['ttest']['sub_conditions'];
+ if (is_array($sub_Conditions) && count($sub_Conditions) > 0) {
+ foreach ($sub_Conditions AS $sub_condition) {
+ if ($sub_condition == $checkCondition) {
+ return ' checked="checked"';
+ }
+ }
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ return $cnt == 2 ? ' disabled="disabled"' : null;
+ }
+
+ function checkSubConditionsActive() {
+
+ $cnt = 0;
+
+ $needle = $this->sessionData['ttest']['spr2'];
+ $length = strlen($needle);
+ $sub_Conditions = $this->sessionData['ttest']['sub_conditions'];
+ if (is_array($sub_Conditions) && count($sub_Conditions) > 0) {
+ foreach ($sub_Conditions AS $haystack) {
+ $cnt += (int)(substr($haystack, 0, $length) === $needle);
+ }
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ return $cnt;
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyAnalysis/class.SurveyTableChart.php b/admin/survey/classes/surveyAnalysis/class.SurveyTableChart.php
new file mode 100644
index 0000000..8b51105
--- /dev/null
+++ b/admin/survey/classes/surveyAnalysis/class.SurveyTableChart.php
@@ -0,0 +1,2853 @@
+<?php
+/**
+* @author Peter Hrvatin
+* @date April 2012
+*/
+
+define("SAA_FOLDER", "AnalysisArchive");
+
+class SurveyTableChart {
+
+ public $anketa; # id ankete
+ public $folder = ''; # pot do folderja
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ public $uid; # id userja
+
+ private $classInstance; // instanca razreda (crosstabs, ttest...) z vsemi podatki
+ private $podstran; // podstran iz katere kreimramo graf (tip grafa -> crosstab, ttest, povprecje)
+ private $counter; // kateri graf po vrsti izrisemo (ce jih je vec)
+ private $crossCheck = false; // ce imamo odvisno spremenljivko pri crosstabu checkbox jo obravnavamo posebej
+
+ public $skin = '1ka'; # nastavitev skina za grafe
+ public $fontSize = 8; # velikost fonta v grafih
+ public $quality = 1; # kvaliteta (sirina) slike (1 -> 800px, 2 -> 1600px)
+
+ public $numerusText = ''; // dodaten text pri numerusu (veljavni, navedbe)
+
+ private $crosstabVars; // kateri graf po vrsti izrisemo (ce jih je vec)
+
+ public $break_forSpr; // break neodvisna spremenljivka
+ public $break_frequencys; // break izracunane frekvence
+ public $break_spremenljivka; // break odvisna spremenljivka
+ public $break_crosstab = 0; // break crosstab tabela
+
+ public $settings = array(); // nastavitve grafa
+ public $settings_mode=0; // zavihek nastavitev (osnovno/napredno)
+
+ public $returnChartAsHtml = false; # ali vrne rezultat analiz kot html ali ga izpiše
+ public $isArchive = false; # nastavimo na true če smo v arhivu
+ public $chartArchiveTime = ''; # unikatnost
+
+ private $sessionData; // podatki ki so bili prej v sessionu - za nastavitve, ki se prenasajo v izvoze...
+
+
+ /**
+ * Konsturktor
+ *
+ * @param int $anketa
+ */
+ function __construct($anketa, $classInstance=null, $podstran='crosstab', $counter=0) {
+ global $global_user_id, $site_path;
+
+ $this->folder = $site_path . EXPORT_FOLDER.'/';
+
+ $this->anketa = $anketa;
+
+ if ((int)$this->anketa > 0) { # če je poadan anketa ID
+
+ $this->classInstance = $classInstance;
+ $this->podstran = $podstran;
+ $this->counter = $counter;
+
+ #inicializiramo SurveyAnalasys
+ SurveyAnalysis::Init($this->anketa);
+ //SurveyAnalysis::$setUpJSAnaliza = false;
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($this->anketa);
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileName = $this->SDF->getDataFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+ if ($this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_NO_FILE
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED){
+ exit;
+ return false;
+ }
+ //polovimo podatke o nastavitvah trenutnega profila (missingi..)
+ SurveyAnalysis::$missingProfileData = SurveyMissingProfiles::getProfile(SurveyAnalysis::$currentMissingProfile);
+
+ #preberemo HEADERS iz datoteke
+ SurveyAnalysis::$_HEADERS = unserialize(file_get_contents($this->headFileName));
+
+ # odstranimo sistemske variable tipa email, ime, priimek, geslo
+ SurveyAnalysis::removeSystemVariables();
+
+ # polovimo frekvence
+ SurveyAnalysis::getFrequencys();
+
+ // preberemo nastavitve iz baze (prej v sessionu)
+ SurveyUserSession::Init($this->anketa);
+ $this->sessionData = SurveyUserSession::getData();
+ }
+ else {
+ //die("Napaka!");
+ }
+
+ if ( SurveyInfo::getInstance()->SurveyInit($this->anketa))
+ {
+ $this->uid = $global_user_id;
+ SurveyUserSetting::getInstance()->Init($this->anketa, $this->uid);
+ }
+
+
+ $this->skin = SurveyUserSetting :: getInstance()->getSettings('default_chart_profile_skin');
+ $this->fontSize = SurveyDataSettingProfiles :: getSetting('chartFontSize');
+ $this->quality = (isset($this->sessionData['charts']['hq']) && $this->sessionData['charts']['hq'] == 1) ? 3 : 1;
+ }
+
+
+ function display(){
+ global $site_path;
+ global $lang;
+
+ $chartID = $this->getChartID();
+
+ switch($this->podstran){
+
+ case 'crosstab':
+ echo '<div class="crosstab_chart_holder tableChart" id="tableChart_'.$chartID.'">';
+ $this->displayCrosstabChart($chartID);
+ echo '</div>';
+
+ break;
+
+ case 'ttest':
+ echo '<div class="ttest_chart_holder tableChart" id="tableChart_'.$chartID.'">';
+ $this->displayTTestChart($chartID);
+ echo '</div>';
+
+ break;
+
+ case 'mean':
+ echo '<div class="mean_chart_holder tableChart" id="tableChart_'.$chartID.'">';
+ $this->displayMeanChart($chartID);
+ echo '</div>';
+
+ break;
+
+ case 'break':
+ echo '<div class="break_chart_holder tableChart" id="tableChart_'.$chartID.'">';
+ $this->displayBreakChart($chartID);
+ echo '</div>';
+
+ break;
+ }
+ }
+
+
+ // Izrisemo graf v crosstabih
+ function displayCrosstabChart($chartID){
+ global $site_path;
+ global $lang;
+
+ // preverimo ce imamo checkbox v odvisni spr - imamo posebne nastavitve
+ if (count($this->classInstance->variabla2) > 0) {
+ foreach ($this->classInstance->variabla2 AS $key => $var) {
+ $spr_tip = $this->classInstance->_HEADERS[$var['spr']]['tip'];
+ if ( $spr_tip == 2 || $spr_tip == 16 ) {
+ $this->crossCheck = true;
+ }
+ }
+ }
+ if (count($this->classInstance->variabla1) > 0 && $is_check == false ) { # če še ni bil checkbox
+ foreach ($this->classInstance->variabla1 AS $key => $var) {
+ $spr_tip = $this->classInstance->_HEADERS[$var['spr']]['tip'];
+ if ( $spr_tip == 2 || $spr_tip == 16 ) {
+ $this->crossCheck = true;
+ }
+ }
+ }
+ // zaenkrat ne upoastevamo
+ $this->crossCheck = false;
+
+ // defult nastavitve posameznega grafa
+ if(isset($this->sessionData['crosstab_charts'][$chartID]))
+ $this->settings = $this->sessionData['crosstab_charts'][$chartID];
+ else
+ $this->settings = $this->getDefaultSettings();
+
+
+ // Napolnimo podatke za graf
+ $DataSet = $this->getCrosstabDataSet($chartID, $this->settings);
+
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = $this->generateChartId($chartID, $this->settings, $DataSet->GetNumerus());
+
+ // Ce se nimamo zgeneriranega grafa
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+
+ switch($this->settings['type']){
+
+ // Sestavljeni stolpec - horizontalen
+ case 0:
+ $Test = $this->createHorStructBars($DataSet);
+ break;
+
+ // Sestavljeni stolpec - vertikalen
+ case 1:
+ $Test = $this->createVerStructBars($DataSet);
+ break;
+
+ // Horizontalni stolpci
+ case 3:
+ $Test = $this->createHorBars($DataSet, 1);
+ break;
+
+ // Navpicni stolpci
+ case 4:
+ $Test = $this->createVerBars($DataSet, 1);
+ break;
+
+ // Pie chart
+ case 2:
+ $Test = $this->createPie($DataSet, $this->settings['show_legend']);
+ break;
+
+ // Pie chart
+ case 5:
+ $Test = $this->create3DPie($DataSet, $this->settings['show_legend']);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+
+ if ($this->isArchive == false ) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.$this->anketa.'_'.$this->chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+
+ // zapisemo ime slike v session za izvoze
+ $this->settings['name'] = $imgName;
+ $this->sessionData['crosstab_charts'][$chartID] = $this->settings;
+
+ // Zapisemo se variable v session
+ $this->sessionData['crosstab_charts'][$chartID]['spr1'] = $this->classInstance->variabla1[0];
+ $this->sessionData['crosstab_charts'][$chartID]['spr2'] = $this->classInstance->variabla2[0];
+
+ // Naslov posameznega grafa
+ echo '<div class="chart_title">';
+
+ if($this->settings['type'] == 1 || $this->settings['type'] == 4){
+ $title = '<table><tr>';
+ $title .= '<td style="width:380px;">'.$this->crosstabVars[0] . '</td><td style="width:40px;"> / </td><td style="width:380px;">' . $this->crosstabVars[1].'</td>';
+ $title .= '</tr></table>';
+ }
+ else{
+ $title = $this->crosstabVars[0];
+ }
+ echo $title;
+
+ echo '</div>';
+
+ echo '<div class="chart_img" id="chart_img_'.$chartID.'" onclick="tableChartAdvancedSettings(\''.$chartID.'\', \'crosstab\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgPath.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ $this->displaySingleSettings($chartID, $this->settings);
+ echo '</div>';
+
+ // Zvezdica za vkljucitev v porocilo
+ $variables1 = $this->classInstance->getSelectedVariables(2);
+ $variables2 = $this->classInstance->getSelectedVariables(1);
+ $counter = 0;
+ $var1 = array();
+ $var2 = array();
+ foreach ($variables1 AS $v_first) {
+ foreach ($variables2 AS $v_second) {
+ if($counter == $this->counter){
+ $var1 = $v_first;
+ $var2 = $v_second;
+
+ break 2;
+ }
+ else
+ $counter++;
+ }
+ }
+
+ $spr2 = $var1['seq'].'-'.$var1['spr'].'-'.$var1['grd'];
+ $spr1 = $var2['seq'].'-'.$var2['spr'].'-'.$var2['grd'];
+ SurveyAnalysis::addCustomReportElement($type=5, $sub_type=1, $spr1, $spr2);
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ // Izrisemo graf v ttestu
+ function displayTTestChart($chartID){
+ global $site_path;
+ global $lang;
+
+ // defult nastavitve posameznega grafa
+ if(isset($this->sessionData['ttest_charts'][$chartID]))
+ $this->settings = $this->sessionData['ttest_charts'][$chartID];
+ else
+ $this->settings = $this->getDefaultSettings();
+
+
+ // Napolnimo podatke za graf
+ $DataSet = $this->getTTestDataSet($chartID, $this->settings);
+
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = $this->generateChartId($chartID, $this->settings, $DataSet->GetNumerus());
+
+ // Ce se nimamo zgeneriranega grafa
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+
+ switch($this->settings['type']){
+
+ // Horizontalni stolpci
+ case 0:
+ $Test = $this->createHorBars($DataSet, $legend=0);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+
+ if ($this->isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.$this->anketa.'_'.$this->chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+
+ // zapisemo ime slike v session za izvoze
+ $this->settings['name'] = $imgName;
+ $this->sessionData['ttest_charts'][$chartID] = $this->settings;
+
+ // Naslov posameznega grafa
+ echo '<div class="chart_title">';
+ $title = $lang['srv_chart_ttest_title'].':<br />';
+ $title .= '<table><tr>';
+ $title .= '<td style="width:380px; text-align: right;">'.$this->crosstabVars[0] . '</td><td style="width:40px;"> / </td><td style="width:380px; text-align: left;">' . $this->crosstabVars[1].'</td>';
+ $title .= '</tr></table>';
+ echo $title;
+ echo '</div>';
+
+ echo '<div class="chart_img" id="chart_img_'.$chartID.'" onclick="tableChartAdvancedSettings(\''.$chartID.'\', \'ttest\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgPath.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ $this->displaySingleSettings($chartID, $this->settings);
+ echo '</div>';
+
+ // Zvezdica za vkljucitev v porocilo
+ $spid1 = $this->sessionData['ttest']['variabla'][0]['spr'];
+ $seq1 = $this->sessionData['ttest']['variabla'][0]['seq'];
+ $grid1 = $this->sessionData['ttest']['variabla'][0]['grd'];
+ $sub1 = $this->sessionData['ttest']['sub_conditions'][0];
+ $sub2 = $this->sessionData['ttest']['sub_conditions'][1];
+
+ $spid2 = $this->sessionData['ttest']['spr2'];
+ $seq2 = $this->sessionData['ttest']['seq2'];
+ $grid2 = $this->sessionData['ttest']['grid2'];
+
+ $spr1 = $seq2.'-'.$spid2.'-'.$grid2.'-'.$sub1.'-'.$sub2;
+ $spr2 = $seq1.'-'.$spid1.'-'.$grid1;
+ SurveyAnalysis::addCustomReportElement($type=7, $sub_type=1, $spr1, $spr2);
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ // Klicemo pri pdf/rtf izpisih da se pravilno nastavi session
+ function setTTestChartSession(){
+
+ // Zgeneriramo id vsake tabele (glede na izbrani spremenljivki za generiranje)
+ $spid1 = $this->sessionData['ttest']['variabla'][0]['spr'];
+ $seq1 = $this->sessionData['ttest']['variabla'][0]['seq'];
+ $grid1 = $this->sessionData['ttest']['variabla'][0]['grd'];
+ $sub1 = $this->sessionData['ttest']['sub_conditions'][0];
+ $sub2 = $this->sessionData['ttest']['sub_conditions'][1];
+ $chartID = $sub1.'_'.$sub2.'_'.$spid1.'_'.$seq1.'_'.$grid1;
+
+ // defult nastavitve posameznega grafa
+ if(isset($this->sessionData['ttest_charts'][$chartID]))
+ $this->settings = $this->sessionData['ttest_charts'][$chartID];
+ else
+ $this->settings = $this->getDefaultSettings();
+
+ // Napolnimo podatke za graf
+ $DataSet = $this->getTTestDataSet($chartID, $this->settings);
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = $this->generateChartId($chartID, $this->settings, $DataSet->GetNumerus());
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+
+ // zapisemo ime slike v session za izvoze
+ $this->settings['name'] = $imgName;
+ $this->sessionData['ttest_charts'][$chartID] = $this->settings;
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ // Izrisemo graf v povprecjih
+ function displayMeanChart($chartID){
+ global $site_path;
+ global $lang;
+
+ // defult nastavitve posameznega grafa
+ if(isset($this->sessionData['mean_charts'][$chartID]))
+ $this->settings = $this->sessionData['mean_charts'][$chartID];
+ else
+ $this->settings = $this->getDefaultSettings();
+
+
+ // Napolnimo podatke za graf
+ $DataSet = $this->getMeanDataSet($chartID, $this->settings);
+
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = $this->generateChartId($chartID, $this->settings, $DataSet->GetNumerus());
+
+ // Ce se nimamo zgeneriranega grafa
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+
+ switch($this->settings['type']){
+
+ // Povprecja - horizontalni stolpci
+ case 0:
+ $Test = $this->createHorBars($DataSet, $legend=0, $fixedScale=1);
+ break;
+
+ // Povprecja - radar
+ case 1:
+ $Test = $this->createRadar($DataSet, 1, $fixedScale=1);
+ break;
+
+ // Povprecja - vertikalna crta
+ case 2:
+ $Test = $this->createVerLine($DataSet, $legend=0, $fixedScale=1);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+
+ if ($this->isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.$this->anketa.'_'.$this->chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+
+ // zapisemo ime slike v session za izvoze
+ $this->settings['name'] = $imgName;
+ $this->sessionData['mean_charts'][$chartID] = $this->settings;
+
+ // Naslov posameznega grafa
+ $title = '';
+ echo '<div class="chart_title">';
+ echo $title;
+ echo '</div>';
+
+ echo '<div class="chart_img" id="chart_img_'.$chartID.'" onclick="tableChartAdvancedSettings(\''.$chartID.'\', \'mean\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgPath.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ $this->displaySingleSettings($chartID, $this->settings);
+ echo '</div>';
+
+ // Zvezdica za vkljucitev v porocilo
+ $variables1 = $this->classInstance->getSelectedVariables(1);
+ $variables2 = $this->classInstance->getSelectedVariables(2);
+
+ $pos1 = floor($this->counter / count($variables2));
+ $pos2 = $this->counter % count($variables2);
+
+ $spr1 = $variables1[$pos1]['seq'].'-'.$variables1[$pos1]['spr'].'-'.$variables1[$pos1]['grd'];
+ $spr2 = $variables2[$pos2]['seq'].'-'.$variables2[$pos2]['spr'].'-'.$variables2[$pos2]['grd'];
+ SurveyAnalysis::addCustomReportElement($type=6, $sub_type=1, $spr1, $spr2);
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ // Izrisemo graf v breaku
+ function displayBreakChart($chartID){
+ global $site_path;
+ global $lang;
+
+ $tip = $this->break_spremenljivka['tip'];
+ $skala = $this->break_spremenljivka['skala'];
+
+ // Izrisemo poseben break graf (multigrid, multicheckbox, multitext, multinumber)
+ if( in_array($tip, array(7,17,18,20,)) || ($tip == 6 && $skala == 0) ){
+
+ // defult nastavitve posameznega grafa
+ if(isset($this->sessionData['break_charts'][$chartID]))
+ $this->settings = $this->sessionData['break_charts'][$chartID];
+ else
+ $this->settings = $this->getDefaultSettings();
+
+
+ // Pri number ne dovolimo radarja in ne sortiranja po kategorijah
+ if($tip == 7){
+ if($this->settings['type'] == 0)
+ $this->settings['type'] = 1;
+
+ if($this->settings['sort'] == 1)
+ $this->settings['sort'] = 0;
+ }
+
+
+ // Napolnimo podatke za graf
+ $DataSet = $this->getBreakDataSet($chartID, $this->settings);
+
+
+ // Cache
+ $Cache = new pCache(dirname(__FILE__).'/../../pChart/Cache/');
+
+ $ID = $this->generateChartId($chartID, $this->settings, $DataSet->GetNumerus());
+
+ // Ce se nimamo zgeneriranega grafa
+ if( !$Cache->isInCache($ID, $DataSet->GetData()) ){
+
+ switch($this->settings['type']){
+
+ // Povprecja - radar
+ case 0:
+ $Test = $this->createRadar($DataSet, 1);
+ break;
+
+ // Povprecja - vertikalni stolpci
+ case 1:
+ $Test = $this->createVerBars($DataSet, 1);
+ break;
+
+ // Povprecja - horizontalni stolpci
+ case 2:
+ $Test = $this->createHorBars($DataSet, 1);
+ break;
+
+ // Povprecja - linijski graf
+ case 3:
+ $Test = $this->createLine($DataSet, 1);
+ break;
+ }
+
+ // Shranimo v cache
+ $Cache->WriteToCache($ID,$DataSet->GetData(),$Test);
+ }
+
+ // dobimo ime slike c cache-u
+ $imgName = $Cache->GetHash($ID,$DataSet->GetData());
+
+ if ($this->isArchive == false) {
+ $imgPath = 'pChart/Cache/'.$imgName;
+ } else {
+ $imgPath = SAA_FOLDER.'/pChart/'.$this->anketa.'_'.$this->chartArchiveTime.'_'.$imgName;
+ copy('pChart/Cache/'.$imgName, $imgPath);
+ }
+
+ // zapisemo ime slike v session za izvoze
+ $this->settings['name'] = $imgName;
+ $this->sessionData['break_charts'][$chartID] = $this->settings;
+
+ // Zapisemo se variable v session
+ $this->sessionData['break_charts'][$chartID]['forSpr'] = $this->break_forSpr;
+ $this->sessionData['break_charts'][$chartID]['frequencys'] = $this->break_frequencys;
+ $this->sessionData['break_charts'][$chartID]['spremenljivka'] = $this->break_spremenljivka;
+
+
+ // Naslov posameznega grafa
+ echo '<div class="chart_title">';
+
+ //var_dump($this->break_spremenljivka);
+ $title = $this->break_spremenljivka['naslov'] . ' ('.$this->break_spremenljivka['variable'].')';
+
+ if($tip == 20){
+
+ $gkey = $this->break_spremenljivka['break_sub_table']['key'];
+ $grid = $this->break_spremenljivka['grids'][$gkey];
+ $subtitle = $grid['naslov'] . ' ('.$grid['variable'].')';
+
+ $title .= '<br />'.$subtitle;
+ }
+
+ echo $title;
+
+ echo '</div>';
+
+
+ echo '<div class="chart_img" id="chart_img_'.$chartID.'" onclick="tableChartAdvancedSettings(\''.$chartID.'\', \'break\');" style="cursor:pointer">';
+ // dodamo timestamp ker browser shrani sliko v cache in jo v dolocenih primerih ajaxa ne refresha
+ echo '<img src="'.$imgPath.'?'.time().'" />';
+ echo '</div>';
+
+ echo '<div class="chart_settings printHide iconHide">';
+ $this->displaySingleSettings($chartID, $this->settings);
+ echo '</div>';
+
+
+ // Zvezdica za vkljucitev v porocilo - Multinumber
+ if($tip == 20){
+
+ // Preberemo za kateri grid izrisujemo tabelo
+ $gkey = $this->break_spremenljivka['break_sub_table']['key'];
+
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $this->break_spremenljivka['grids'][$gkey]['variables'][0]['sequence'].'-'.$this->break_spremenljivka['id'].'-undefined';
+ SurveyAnalysis::Init($this->anketa);
+ SurveyAnalysis::addCustomReportElement($type=9, $sub_type=1, $spr1, $spr2);
+ }
+ // Zvezdica za vkljucitev v porocilo - multigrid, number, vsota, ranking
+ else{
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $this->break_spremenljivka['grids'][0]['variables'][0]['sequence'].'-'.$this->break_spremenljivka['id'].'-undefined';
+ SurveyAnalysis::Init($this->anketa);
+ SurveyAnalysis::addCustomReportElement($type=9, $sub_type=1, $spr1, $spr2);
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ // Izrisemo crosstab graf
+ else{
+ $this->podstran = 'crosstab';
+ $this->displayCrosstabChart($chartID);
+ }
+ }
+
+
+ // Napolnimo podatke za crosstab graf
+ public function getCrosstabDataSet($chartID, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+
+ $dataArray = array();
+ $dataPercentArray = array();
+ $gridArray = array();
+ $variableArray = array();
+
+
+ if ($this->classInstance->getSelectedVariables(1) !== null && $this->classInstance->getSelectedVariables(2) !== null) {
+ $variables1 = $this->classInstance->getSelectedVariables(2);
+ $variables2 = $this->classInstance->getSelectedVariables(1);
+ $counter = 0;
+ foreach ($variables1 AS $v_first) {
+ foreach ($variables2 AS $v_second) {
+
+ // izrisemo graf ki ustreza vrstnemu redu
+ if($counter == $this->counter){
+ $crosstabs = null;
+ $crosstabs_value = null;
+
+ $crosstabs = $this->classInstance->createCrostabulation($v_first, $v_second);
+ $crosstabs_value = $crosstabs['crosstab'];
+
+ # podatki spremenljivk
+ $spr1 = $this->classInstance->_HEADERS[$v_first['spr']];
+ $spr2 = $this->classInstance->_HEADERS[$v_second['spr']];
+
+ $grid1 = $spr1['grids'][$v_first['grd']];
+ $grid2 = $spr2['grids'][$v_second['grd']];
+
+ #število vratic in število kolon
+ $cols = count($crosstabs['options1']);
+ $rows = count($crosstabs['options2']);
+
+ # ali prikazujemo vrednosti variable pri spremenljivkah
+ $show_variables_values = $this->classInstance->doValues;
+
+
+ # za multicheckboxe popravimo naslov, na podtip
+ $sub_q1 = null;
+ $sub_q2 = null;
+ if ($spr1['tip'] == '6' || $spr1['tip'] == '7' || $spr1['tip'] == '16' || $spr1['tip'] == '17' || $spr1['tip'] == '18' || $spr1['tip'] == '19' || $spr1['tip'] == '20' || $spr1['tip'] == '21' ) {
+ foreach ($spr1['grids'] AS $grid) {
+ foreach ($grid['variables'] AS $variable) {
+ if ($variable['sequence'] == $v_first['seq']) {
+ $sub_q1 .= strip_tags($spr1['naslov']);
+ if ($show_variables_values == true ) {
+ $sub_q1 .= ' ('.strip_tags($spr1['variable']).')';
+ }
+ if ($spr1['tip'] == '16') {
+ $sub_q1 .= '<br />'. strip_tags($grid1['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($grid1['variable']) . ')' : '');
+ } else {
+ $sub_q1 .= '<br />' . strip_tags($variable['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($variable['variable']) . ')' : '');
+ }
+ }
+ }
+ }
+ }
+ if ($sub_q1 == null) {
+ $sub_q1 .= strip_tags($spr1['naslov']);
+ $sub_q1 .= ($show_variables_values == true ? '&nbsp;('.strip_tags($spr1['variable']).')' : '');
+ }
+ if ($spr2['tip'] == '6' || $spr2['tip'] == '7' || $spr2['tip'] == '16' || $spr2['tip'] == '17' || $spr2['tip'] == '18' || $spr2['tip'] == '19' || $spr2['tip'] == '20' || $spr2['tip'] == '21') {
+ foreach ($spr2['grids'] AS $grid) {
+ foreach ($grid['variables'] AS $variable) {
+ if ($variable['sequence'] == $v_second['seq']) {
+ $sub_q2 .= strip_tags($spr2['naslov']);
+ if ($show_variables_values == true) {
+ $sub_q2 .= ' ('.strip_tags($spr2['variable']).')';
+ }
+ if ($spr2['tip'] == '16') {
+ $sub_q2.= '<br />' . strip_tags($grid2['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($grid2['variable']) . ')' : '');
+ } else {
+ $sub_q2.= '<br />' . strip_tags($variable['naslov']) . ($show_variables_values == true ? ' (' . strip_tags($variable['variable']) . ')' : '');
+ }
+ }
+ }
+ }
+ }
+ if ($sub_q2 == null) {
+ $sub_q2 .= strip_tags($spr2['naslov']);
+ $sub_q2 .= ($show_variables_values == true ? ' ('.strip_tags($spr2['variable']).')' : '');
+ }
+
+ // ZGORNJA LABELA - NEODVISNA
+ //$sub_q2;
+ // STRANSKA LABELA - ODVISNA
+ //$sub_q1;
+
+ $this->crosstabVars = array($sub_q1, $sub_q2);
+
+ // NASLOVI GRIDOV
+ $grid_cnt=0;
+ if (count($crosstabs['options1']) > 0 ) {
+ foreach ($crosstabs['options1'] as $ckey1 =>$crossVariabla) {
+ $grid_cnt++;
+
+ #ime variable
+ $gridArray[$grid_cnt] = $crossVariabla['naslov'];
+
+ /*echo $crossVariabla['naslov'];
+ # če ni tekstovni odgovor dodamo key
+ if ($crossVariabla['type'] != 't' && $show_variables_values == true) {
+ if ($crossVariabla['vr_id'] == null ) {
+ echo '<br/> ( '.$ckey1.' )';
+ } else {
+ echo '<br/> ( '.$crossVariabla['vr_id'].' )';
+ }
+ }*/
+ }
+ }
+
+
+ $var_cnt=0;
+ if (count($crosstabs['options2']) > 0) {
+ foreach ($crosstabs['options2'] as $ckey2 =>$crossVariabla2) {
+ $var_cnt++;
+
+ // NASLOVI VARIABEL
+ $variableArray[$var_cnt] = $crossVariabla2['naslov'];
+
+ /*echo $crossVariabla2['naslov'];
+ # če ni tekstovni odgovor dodamo key
+ if ($crossVariabla2['type'] !== 't' && $show_variables_values == true ) {
+ if ($crossVariabla2['vr_id'] == null) {
+ echo '<br/> ( '.$ckey2.' )';
+ } else {
+ echo '<br/> ( '.$crossVariabla2['vr_id'].' )';
+ }
+ }*/
+
+
+ // VREDNOSTI
+ $cnt=0;
+ foreach ($crosstabs['options1'] as $ckey1 => $crossVariabla1) {
+ $cnt++;
+
+ $dataArray[$cnt][] = ((int)$crosstabs_value[$ckey1][$ckey2] > 0) ? $crosstabs_value[$ckey1][$ckey2] : 0;
+ $dataPercentArray[$cnt][] = $this->classInstance->getCrossTabPercentage($crosstabs['sumaVrstica'][$ckey2], $crosstabs_value[$ckey1][$ckey2]);
+
+ /*
+ # celica z vebino
+ {
+ # prikazujemo eno ali več od: frekvenc, odstotkov, residualov
+ if ($this->classInstance->crossChk0) {
+ # izpišemo frekvence crostabov
+ echo ((int)$crosstabs_value[$ckey1][$ckey2] > 0) ? $crosstabs_value[$ckey1][$ckey2] : 0;
+ }
+ }*/
+ }
+ }
+ }
+
+ }
+
+ $counter++;
+ }
+ }
+ }
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ // PRAVILNO OBRNJENA - GRIDI SO SERIJE
+ for($i=1; $i<=$grid_cnt; $i++){
+
+ // procenti
+ if($settings['value_type'] == 0){
+ if(count($dataPercentArray[$i]) > 0)
+ $DataSet->AddPoint($dataPercentArray[$i],'Vrednosti_'.$i);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+ }
+ // frekvence
+ elseif($settings['value_type'] == 1){
+ if(count($dataArray[$i]) > 0)
+ $DataSet->AddPoint($dataArray[$i],'Vrednosti_'.$i);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+ }
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ $DataSet->SetSerieName($gridArray[$i],'Vrednosti_'.$i);
+ }
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($variableArray,"Variable");
+ $DataSet->SetAbsciseLabelSerie("Variable");
+
+ if($settings['value_type'] == 0){
+ $DataSet->SetYAxisUnit("%");
+ $DataSet->SetYAxisFormat("number");
+ }
+
+ // NAROBE OBRNJENA - VARIABLE SO SERIJE
+ /*for($i=1; $i<=$var_cnt; $i++){
+
+ if(count($dataArray[$i]) > 0)
+ $DataSet->AddPoint($dataArray[$i],'Vrednosti_'.$i);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti_'.$i);
+
+ $DataSet->AddSerie('Vrednosti_'.$i);
+ $DataSet->SetSerieName($variableArray[$i],'Vrednosti_'.$i);
+ }
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($gridArray,"Variable");
+ $DataSet->SetAbsciseLabelSerie("Variable");*/
+
+
+ return $DataSet;
+ }
+
+ // Napolnimo podatke za ttest graf
+ public function getTTestDataSet($chartID, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $DataSet = null;
+
+
+ $variables1 = $this->classInstance->getSelectedVariables();
+ foreach ($variables1 AS $v_first) {
+ if($this->counter == $counter){
+ $ttest = null;
+ $ttest = $this->classInstance->createTTest($v_first, $this->sessionData['ttest']['sub_conditions']);
+
+ break;
+ }
+ }
+
+ $spid1 = $this->sessionData['ttest']['variabla'][0]['spr'];
+ $seq1 = $this->sessionData['ttest']['variabla'][0]['seq'];
+ $grid1 = $this->sessionData['ttest']['variabla'][0]['grd'];
+
+ if (is_array($ttest) && count($ttest) > 0 && (int)$seq1 > 0) {
+
+ $spr_data_1 = $this->classInstance->_HEADERS[$spid1];
+ if ($grid1 == 'undefined') {
+
+ # imamp lahko več variabel
+ $seq = $seq1;
+ foreach ($spr_data_1['grids'] as $gkey => $grid ) {
+
+ foreach ($grid['variables'] as $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($sequence == $seq) {
+ $sprLabel1 = '('.$variable['variable'].') '. $variable['naslov'];
+ }
+ }
+ }
+ } else {
+ # imamo subgrid
+ $sprLabel1 = '('.$spr_data_1['grids'][$grid1]['variable'].') '. $spr_data_1['grids'][$grid1]['naslov'];
+ }
+
+ $sprLabel2 = trim(str_replace('&nbsp;','',$this->sessionData['ttest']['label2']));
+
+ $this->crosstabVars = array($sprLabel1, $sprLabel2);
+
+ $label1 = $this->classInstance->getVariableLabels($this->sessionData['ttest']['sub_conditions'][0]);
+ $label2 = $this->classInstance->getVariableLabels($this->sessionData['ttest']['sub_conditions'][1]);
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ //nastavimo t, ki se izpise pod legendo
+ $t = $this->classInstance->formatNumber($ttest['t'],3);
+ $DataSet->SetNumerus($t);
+
+ $DataSet->AddPoint($this->classInstance->formatNumber($ttest[1]['x'],3),'Vrednost');
+ $DataSet->AddPoint($this->classInstance->formatNumber($ttest[2]['x'],3),'Vrednost');
+
+ $DataSet->AddSerie('Vrednost');
+
+ $DataSet->AddPoint(array(0 => $label1, 1 => $label2),"Variable");
+ $DataSet->SetAbsciseLabelSerie("Variable");
+ }
+
+ return $DataSet;
+ }
+
+ // Napolnimo podatke za mean graf
+ public function getMeanDataSet($chartID, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+
+ $dataArray = array();
+ $gridArray = array();
+ $variableArray = array();
+
+
+ $variables1 = $this->classInstance->getSelectedVariables(2);
+ $variables2 = $this->classInstance->getSelectedVariables(1);
+
+ if (is_array($variables2) && count($variables2) > 0) {
+ foreach ($variables2 AS $v_second) {
+ if (is_array($variables1) && count($variables1) > 0) {
+ foreach ($variables1 AS $v_first) {
+ $_means = $this->classInstance->createMeans($v_first, $v_second);
+ if ($_means != null) {
+ $means[$c1][0] = $_means;
+ }
+ $c1++;
+ }
+ }
+ }
+ }
+
+ // Zaenkrat prikazemo samo graf za prvo tabelo
+ if (is_array($means) && count($means) > 0) {
+ $counter=0;
+ foreach ($means AS $mean_sub_grup) {
+
+ // Izrisemo pravi graf po vrsti ki pripada tabeli
+ if($counter == $this->counter){
+ $_means = $mean_sub_grup;
+ break;
+ }
+
+ $counter++;
+ }
+ }
+
+
+ #število vratic in število kolon
+ $cols = count($_means);
+ # preberemo kr iz prvega loopa
+ $rows = count($_means[0]['options']);
+
+
+ // loop po vrsticah
+ if (count($_means[0]['options']) > 0) {
+ foreach ($_means[0]['options'] as $ckey2 =>$crossVariabla2) {
+
+ // IME VARIABLE
+ $variableArray[] = $crossVariabla2['naslov'];
+
+ // VREDNOST VARIABLE
+ $dataArray[] = $this->classInstance->formatNumber($_means[0]['result'][$ckey2], SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_RESIDUAL'));
+ }
+ }
+
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1)
+ array_multisort($dataArray, SORT_DESC, $variableArray);
+
+
+ if(count($dataArray) > 0)
+ $DataSet->AddPoint($dataArray,'Vrednosti');
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti');
+
+ $DataSet->AddSerie('Vrednosti');
+ $DataSet->SetSerieName('Povprečja','Vrednosti');
+
+ // Pri povprecjih vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($variableArray,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie("Variable");
+
+
+ return $DataSet;
+ }
+
+ // Napolnimo podatke za break graf
+ public function getBreakDataSet($chartID, $settings, $refresh=0){
+ global $site_path;
+ global $lang;
+
+ $keysCount = count($this->break_frequencys);
+ $sequences = explode('_',$this->break_spremenljivka['sequences']);
+ $forSpremenljivka = $this->classInstance->_HEADERS[$this->break_forSpr];
+ $tip = $this->break_spremenljivka['tip'];
+
+ # izračunamo povprečja za posamezne sekvence
+ $means = array();
+ $totalMeans = array();
+ $totalFreq = array();
+ foreach ($this->break_frequencys AS $fkey => $options) {
+ foreach ($options AS $oKey => $option) {
+ foreach ($sequences AS $sequence) {
+ $means[$fkey][$oKey][$sequence] = $this->classInstance->getMeansFromKey($option[$sequence]);
+ }
+ }
+ }
+
+
+ //polnimo podatke
+ $DataSet = new pData;
+
+ $dataArray = array();
+ $variableArray = array();
+
+
+ // Polnimo podatke za multigrid dropdown, number, vsoto, ranking
+ if($this->break_spremenljivka['tip'] != 20){
+
+ $cnt=0;
+ foreach ($this->break_frequencys AS $fkey => $fkeyFrequency) {
+ $variableArray[] = $forSpremenljivka['grids'][0]['variables'][$cnt]['naslov'];
+ $cnt++;
+ foreach ($options AS $oKey => $option) {
+
+ $grid_count = 0;
+
+ foreach ($this->break_spremenljivka['grids'] AS $gkey => $grid) {
+
+ foreach ($grid['variables'] AS $vkey => $variable) {
+ $sequence = $variable['sequence'];
+ if ($variable['other'] != 1) {
+
+ $grid_count++;
+
+ #povprečja
+ $avg = $this->classInstance->formatNumber($means[$fkey][$oKey][$sequence],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ # enote
+ $enote = (int)$this->break_frequencys[$fkey][$oKey][$sequence]['validCnt'];
+
+ $tempArray = array();
+
+ $tempArray['avg'] = str_replace(",","",$avg);
+ $tempArray['unit'] = $enote;
+ $tempArray['key'] = $variable['variable'];
+ $tempArray['variable'] = $variable['naslov'];
+
+ $dataArray[] = $tempArray;
+
+ $totalMeans[$sequence] += ($means[$fkey][$oKey][$sequence]*(int)$this->break_frequencys[$fkey][$oKey][$sequence]['validCnt']);
+ $totalFreq[$sequence]+= (int)$this->break_frequencys[$fkey][$oKey][$sequence]['validCnt'];
+ }
+
+ }
+
+ }
+ }
+ }
+ }
+
+ // Polnimo podatke za multinumber
+ else{
+ // Nastavimo pravo podtabelo
+ $gkey = $this->break_spremenljivka['break_sub_table']['key'];
+ $grid = $this->break_spremenljivka['grids'][$gkey];
+
+ $cnt=0;
+ foreach ($this->break_frequencys AS $fkey => $fkeyFrequency) {
+ $variableArray[] = $forSpremenljivka['grids'][0]['variables'][$cnt]['naslov'];
+ $cnt++;
+ foreach ($forSpremenljivka['options'] AS $oKey => $option) {
+
+ # če je osnova checkbox vzamemo samo tam ko je 1
+ if(($forSpremenljivka['tip'] == 2 && $option == 1) || $forSpremenljivka['tip'] != 2 ) {
+
+ $grid_count = 0;
+
+ foreach ($grid['variables'] AS $vkey => $variable) {
+
+ $grid_count++;
+
+ $sequence = $variable['sequence'];
+
+ #povprečja
+ $avg = $this->classInstance->formatNumber($means[$fkey][$oKey][$sequence],SurveyDataSettingProfiles :: getSetting('NUM_DIGIT_AVERAGE'),'');
+ # enote
+ $enote = (int)$this->break_frequencys[$fkey][$oKey][$sequence]['validCnt'];
+
+ $tempArray = array();
+
+ $tempArray['avg'] = str_replace(",","",$avg);
+ $tempArray['unit'] = $enote;
+ $tempArray['key'] = $variable['variable'];
+ $tempArray['variable'] = $variable['naslov'] . ' ('.$variable['variable'].')';
+
+ $dataArray[] = $tempArray;
+
+ $totalMeans[$sequence] += ($means[$fkey][$oKey][$sequence]*(int)$this->break_frequencys[$fkey][$oKey][$sequence]['validCnt']);
+ $totalFreq[$sequence]+= (int)$this->break_frequencys[$fkey][$oKey][$sequence]['validCnt'];
+
+ }
+ }
+ }
+ }
+ }
+
+ $variable_count = count($variableArray);
+
+ // Normalno obrnjen graf - gridi v stolpcih, variable v legendi (deli stolpcev)
+ if($settings['rotate'] != 1){
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$grid_count; $j++){
+ $offset = $j*$grid_count;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sortiramo podaatke po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$grid_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ else{
+ for($j=0; $j<($variable_count*$grid_count); $j++){
+ $sorted_keys[] = $j;
+ }
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$variable_count; $j++){
+
+ unset($vrednosti);
+ unset($vrednostiEnote);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ // odmik glede na sortirane po prvem gridu (sort po kategorijah ali brez)
+ if($settings['sort'] < 3){
+ $offset = $sorted_keys[$j] /*$j*/ * $grid_count;
+
+ for($i=0; $i<$grid_count; $i++){
+ $vrednosti[] = $dataArray[$i+$offset]['avg'];
+ $vrednostiEnote[] = $dataArray[$i+$offset]['unit'];
+
+ $vrednostiKey[] = $dataArray[$i+$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$i+$offset]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$sorted_keys[$j]);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$sorted_keys[$j]);
+
+ $DataSet->AddSerie('Vrednosti'.$sorted_keys[$j]);
+ $DataSet->SetSerieName($variableArray[$sorted_keys[$j]],'Vrednosti'.$sorted_keys[$j]);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,'Variable'.$sorted_keys[$j]);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$sorted_keys[$j]);
+ }
+
+ // sort po prvi kategoriji
+ else{
+ for($i=0; $i<$grid_count; $i++){
+ $vrednosti[] = $dataArray[$j*$grid_count + $sorted_keys[$i]]['avg'];
+ $vrednostiEnote[] = $dataArray[$j*$grid_count + $sorted_keys[$i]]['unit'];
+
+ $vrednostiKey[] = $dataArray[$j*$grid_count + $sorted_keys[$i]]['key'];
+ $vrednostiVariable[] = $dataArray[$j*$grid_count + $sorted_keys[$i]]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$j);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$j);
+
+ $DataSet->AddSerie('Vrednosti'.$j);
+ $DataSet->SetSerieName($variableArray[$j],'Vrednosti'.$j);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($vrednostiVariable,'Variable'.$j);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$j);
+ }
+ }
+ }
+ // Obratno obrnjen graf - gridi v legendi (deli stolpca), variable v stolpcih - default ce imamo samo en grid
+ else{
+
+ // Sortiramo podaatke ce je potrebno
+ if($settings['sort'] == 1){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$grid_count; $j++){
+ $offset = $j;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ // Sortiramo podaatke po prvi kategoriji
+ elseif($settings['sort'] == 3){
+
+ $tmp = Array();
+
+ // preberemo prve vrednosti iz vsakega stolpca
+ for($j=0; $j<$variable_count; $j++){
+ $offset = $j * $grid_count;
+ $tmp[] = (int)$dataArray[$offset]['avg'];
+ }
+
+ // sortiramo vrednosti in preberemo kljuce
+ arsort($tmp);
+ $sorted_keys = array_keys($tmp);
+ }
+ else{
+ for($j=0; $j<$grid_count; $j++){
+ $sorted_keys[] = $j;
+ }
+ }
+
+ // Poberemo podatke v posamezne tabele
+ for($j=0; $j<$grid_count; $j++){
+
+ // odmik glede na sortirane po prvem gridu (sort po kategorijah ali brez)
+ if($settings['sort'] < 3){
+ $offset = $sorted_keys[$j];
+
+ unset($vrednosti);
+ unset($vrednostiEnote);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ for($i=0; $i<$variable_count; $i++){
+
+ $vrednosti[] = $dataArray[$i*$grid_count+$offset]['avg'];
+ $vrednostiEnote[] = $dataArray[$i*$grid_count+$offset]['unit'];
+
+ $vrednostiKey[] = $dataArray[$i*$grid_count+$offset]['key'];
+ $vrednostiVariable[] = $dataArray[$i*$grid_count+$offset]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$vrednostiKey[0]);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$vrednostiKey[0]);
+
+ $DataSet->AddSerie('Vrednosti'.$vrednostiKey[0]);
+ $DataSet->SetSerieName($vrednostiVariable[0],'Vrednosti'.$vrednostiKey[0]);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($variableArray,'Variable'.$vrednostiKey[0]);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$vrednostiKey[0]);
+ }
+
+ // sort po prvi kategoriji
+ else{
+ $offset = $sorted_keys[$j];
+
+ unset($vrednosti);
+ unset($vrednostiEnote);
+ unset($vrednostiKey);
+ unset($vrednostiVariable);
+
+ for($i=0; $i<$variable_count; $i++){
+
+ $vrednosti[] = $dataArray[$sorted_keys[$i]*$grid_count + $j]['avg'];
+ $vrednostiEnote[] = $dataArray[$sorted_keys[$i]*$grid_count + $j]['unit'];
+
+ $vrednostiKey[] = $dataArray[$sorted_keys[$i]*$grid_count + $j]['key'];
+ $vrednostiVariable[] = $dataArray[$sorted_keys[$i]*$grid_count + $j]['variable'];
+ }
+
+ if(count($vrednosti) > 0)
+ $DataSet->AddPoint($vrednosti,'Vrednosti'.$vrednostiKey[0]);
+ else
+ $DataSet->AddPoint(array(0),'Vrednosti'.$vrednostiKey[0]);
+
+ $DataSet->AddSerie('Vrednosti'.$vrednostiKey[0]);
+ $DataSet->SetSerieName($vrednostiVariable[0],'Vrednosti'.$vrednostiKey[0]);
+
+ // Vedno izpisemo cela imena variabel
+ $DataSet->AddPoint($variableArray,'Variable'.$vrednostiKey[0]);
+ //$DataSet->AddPoint($vrednostiKey,"Variable");
+
+ $DataSet->SetAbsciseLabelSerie('Variable'.$vrednostiKey[0]);
+ }
+ }
+ }
+
+ return $DataSet;
+ }
+
+ public function setBreakVariables($forSpr,$frequencys,$spremenljivka){
+
+ $this->break_forSpr = $forSpr;
+ $this->break_frequencys = $frequencys;
+ $this->break_spremenljivka = $spremenljivka;
+ }
+
+
+ // Default nastavitve grafov
+ public function getDefaultSettings(){
+
+ $colors = array_fill(0, 6, '');
+
+ $settings = array(
+ 'type' => 0, // tip radarja
+ 'sort' => 0, // sortiranje po velikosti
+ 'value_type' => 0, // tip vrednosti (veljavni, frekvence, procenti...)
+ 'show_legend' => 0, // prikaz legende
+ 'scale_limit' => 0, // zacni skalo z 0 / z najmanjso vrednostjo pri numericih
+ 'interval' => 10, // stevilo intervalov pri numericih
+ 'radar_type' => 0, // tip radarj (crte / liki)
+ 'radar_scale' => 0, // skala pri radarju (na osi / diagonalno)
+ 'labelWidth' => 50, // sirina label (50% / 20%)
+ 'barLabel' => 1, // prikaz label v stolpicnih grafih
+ 'rotate' => 0, // obrnjeni gridi in variable (pri multinumber...)
+ 'hq' => 1, // visoka locljivost grafa
+ 'show_numerus' => 1, // prikaz numerusa
+ 'colors' => $colors // custom barve grafa
+ );
+
+ return $settings;
+ }
+
+ // ID grafa glede na podstran
+ public function getChartID(){
+ global $lang;
+
+ // crosstab
+ if($this->podstran == 'crosstab' || ($this->podstran == 'break' && $this->break_crosstab == 1)){
+ $variables1 = $this->classInstance->getSelectedVariables(2);
+ $variables2 = $this->classInstance->getSelectedVariables(1);
+ $counter = 0;
+ $var1 = array();
+ $var2 = array();
+ foreach ($variables1 AS $v_first) {
+ foreach ($variables2 AS $v_second) {
+ if($counter == $this->counter){
+ $var1 = $v_first;
+ $var2 = $v_second;
+
+ break 2;
+ }
+ else
+ $counter++;
+ }
+ }
+
+ // Zgeneriramo id vsake tabele (glede na izbrani spremenljivki za generiranje)
+ $chartID = implode('_', $var1).'_'.implode('_', $var2);
+ $chartID .= '_counter_'.$this->counter;
+ }
+
+ // ttest
+ elseif($this->podstran == 'ttest'){
+ // Zgeneriramo id vsake tabele (glede na izbrani spremenljivki za generiranje)
+ $spid1 = $this->sessionData['ttest']['variabla'][0]['spr'];
+ $seq1 = $this->sessionData['ttest']['variabla'][0]['seq'];
+ $grid1 = $this->sessionData['ttest']['variabla'][0]['grd'];
+ $sub1 = $this->sessionData['ttest']['sub_conditions'][0];
+ $sub2 = $this->sessionData['ttest']['sub_conditions'][1];
+
+ $spid2 = $this->sessionData['ttest']['spr2'];
+ $seq2 = $this->sessionData['ttest']['seq2'];
+ $grid2 = $this->sessionData['ttest']['grid2'];
+
+ $chartID = $sub1.'_'.$sub2.'_'.$spid1.'_'.$seq1.'_'.$grid1;
+ }
+
+ // means
+ elseif($this->podstran == 'mean'){
+ // Zgeneriramo id vsake tabele (glede na izbrani spremenljivki za generiranje)
+ $variables1 = $this->classInstance->getSelectedVariables(1);
+ $variables2 = $this->classInstance->getSelectedVariables(2);
+
+ $pos1 = floor($this->counter / count($variables2));
+ $pos2 = $this->counter % count($variables2);
+
+ $chartID = implode('_', $variables1[$pos1]).'_'.implode('_', $variables2[$pos2]);
+ $chartID .= '_counter_'.$this->counter;
+ }
+
+ // break
+ else{
+ if($this->break_spremenljivka['tip'] == 20){
+ // Preberemo za kateri grid izrisujemo tabelo
+ $gkey = $this->break_spremenljivka['break_sub_table']['key'];
+
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $this->break_spremenljivka['grids'][$gkey]['variables'][0]['sequence'].'-'.$this->break_spremenljivka['id'].'-undefined';
+ }
+ else{
+ $spr1 = $this->sessionData['break']['seq'].'-'. $this->sessionData['break']['spr'].'-undefined';
+ $spr2 = $this->break_spremenljivka['grids'][0]['variables'][0]['sequence'].'-'.$this->break_spremenljivka['id'].'-undefined';
+ }
+
+ $chartID = $spr1.'_'.$spr2;
+ }
+
+ return $chartID;
+ }
+
+ // Zgeneriramo unikaten hash ID grafa
+ public function generateChartId($chartID, $settings, $numerus){
+
+ // ce posebej prizgemo legendo pri pie chartu
+ if($settings['show_legend'] == 1 && ($settings['type'] == 2 || $settings['type'] == 5))
+ $legend = '_legend';
+ else
+ $legend = '';
+
+ $ID = $this->anketa.'_chart_'.$chartID.'_counter_'.$counter.'_mv_'.SurveyAnalysis::$missingProfileData['display_mv_type'];
+
+ foreach ($settings AS $key => $val) {
+ if($key == 'colors'){
+
+ $ID .= '_colors';
+
+ foreach ($val AS $colKey => $color){
+ $ID .= '_'.$color;
+ }
+ }
+
+ elseif($key != 'name')
+ $ID .= '_'.$key.'_'.$val;
+ }
+
+ $ID .= '_skin_'.$this->skin;
+
+ $ID .= '_numerus_'.$numerus.'_numerusText_'.SurveyDataSettingProfiles :: getSetting('chartNumerusText');
+
+ $ID .= '_pieZeros_'.SurveyDataSettingProfiles :: getSetting('chartPieZeros');
+
+ $ID .= '_chartFontSize_'.SurveyDataSettingProfiles :: getSetting('chartFontSize');
+
+ //$ID .= '_hq_'.$this->quality;
+
+ return $ID;
+ }
+
+ // nastavimo prave barve ustrezne skinu
+ public function setChartColors($chart, $skin){
+
+ // Ce nimmo posebej nastavljenih barv
+ if($this->settings['colors'][0] == ''){
+ // ce je nastavljen globalen custom skin
+ if(is_numeric($skin)){
+ $skin = SurveyChart::getCustomSkin($skin);
+ $colors = explode('_', $skin['colors']);
+
+ $count = 0;
+ foreach($colors as $color){
+
+ $rgb = SurveyChart::html2rgb($color);
+ $chart->setColorPalette($count,$rgb[0],$rgb[1],$rgb[2]);
+
+ $count++;
+ }
+ }
+
+ // imamo nastavljenega enega od default skinov
+ else{
+ switch ($skin){
+
+ // 1ka skin
+ case '1ka':
+ default:
+ $chart->setColorPalette(0,30,136,229);
+ $chart->setColorPalette(1,255,166,8);
+ $chart->setColorPalette(2,72,229,194);
+ $chart->setColorPalette(3,242,87,87);
+ $chart->setColorPalette(4,117,70,68);
+ $chart->setColorPalette(5,248,202,0);
+ $chart->setColorPalette(6,255,112,166);
+ break;
+
+ // zivahen skin
+ case 'lively':
+ $chart->setColorPalette(0,224,9,13);
+ $chart->setColorPalette(1,4,23,227);
+ $chart->setColorPalette(2,0,255,8);
+ $chart->setColorPalette(3,255,247,3);
+ $chart->setColorPalette(4,255,149,0);
+ $chart->setColorPalette(5,0,251,255);
+ $chart->setColorPalette(6,166,0,255);
+ break;
+
+ // blag skin
+ case 'mild':
+ $chart->setColorPalette(0,188,224,46);
+ $chart->setColorPalette(1,224,100,46);
+ $chart->setColorPalette(2,224,214,46);
+ $chart->setColorPalette(3,46,151,224);
+ $chart->setColorPalette(4,176,46,224);
+ $chart->setColorPalette(5,224,46,117);
+ $chart->setColorPalette(6,92,224,46);
+ break;
+
+ // Office skin
+ case 'office':
+ $chart->setColorPalette(0,79,129,189);
+ $chart->setColorPalette(1,192,80,77);
+ $chart->setColorPalette(2,155,187,89);
+ $chart->setColorPalette(3,128,100,162);
+ $chart->setColorPalette(4,75,172,198);
+ $chart->setColorPalette(5,247,150,70);
+ $chart->setColorPalette(6,146,169,207);
+ break;
+
+ // Pastel skin
+ case 'pastel':
+ $chart->setColorPalette(0,121,159,11);
+ $chart->setColorPalette(1,215,161,37);
+ $chart->setColorPalette(2,146,100,190);
+ $chart->setColorPalette(3,24,132,132);
+ $chart->setColorPalette(4,76,198,139);
+ $chart->setColorPalette(5,138,136,35);
+ $chart->setColorPalette(6,108,153,210);
+ break;
+
+ // zelen skin
+ case 'green':
+ $chart->createColorGradientPalette(168,188,56,248,255,136,5);
+ $chart->setColorPalette(5,255,255,0);
+ $chart->setColorPalette(6,232,3,182);
+ break;
+
+ // moder skin
+ case 'blue':
+ $chart->createColorGradientPalette(82,124,148,174,216,240,5);
+ $chart->setColorPalette(5,255,255,0);
+ $chart->setColorPalette(6,232,3,182);
+ break;
+
+ // rdeč skin
+ case 'red':
+ $chart->createColorGradientPalette(255,0,0,80,10,10,5);
+ $chart->setColorPalette(5,255,255,0);
+ $chart->setColorPalette(6,232,3,182);
+ break;
+
+ // skin za vec kot 5 moznosti
+ case 'multi':
+ $chart->setColorPalette(0,140,0,0);
+ $chart->setColorPalette(1,240,8,0);
+ $chart->setColorPalette(2,255,138,130);
+ $chart->setColorPalette(3,242,196,200);
+ $chart->setColorPalette(4,11,3,135);
+ $chart->setColorPalette(5,4,0,252);
+ $chart->setColorPalette(6,151,148,242);
+ $chart->setColorPalette(7,0,133,31);
+ $chart->setColorPalette(8,24,217,3);
+ $chart->setColorPalette(9,139,245,157);
+ $chart->setColorPalette(10,237,202,45);
+ $chart->setColorPalette(11,253,255,120);
+ $chart->setColorPalette(12,156,0,125);
+ $chart->setColorPalette(13,255,0,246);
+ $chart->setColorPalette(14,242,3,162);
+ $chart->setColorPalette(15,237,154,216);
+ $chart->setColorPalette(16,0,123,145);
+ $chart->setColorPalette(17,0,204,250);
+ $chart->setColorPalette(18,174,238,245);
+ $chart->setColorPalette(19,0,255,200);
+ $chart->setColorPalette(20,255,111,0);
+ $chart->setColorPalette(21,255,162,0);
+ $chart->setColorPalette(22,255,201,120);
+ $chart->setColorPalette(23,161,92,133);
+ $chart->setColorPalette(24,205,159,245);
+ $chart->setColorPalette(25,179,245,103);
+ $chart->setColorPalette(26,135,171,108);
+ $chart->setColorPalette(27,73,132,145);
+ $chart->setColorPalette(28,70,96,99);
+ $chart->setColorPalette(29,156,95,103);
+ break;
+ }
+ }
+ }
+ else{
+ for($i=0; $i<7; $i++){
+
+ $color = $this->settings['colors'][$i];
+ $color = substr($color, 1);
+
+ list($r, $g, $b) = array($color[0].$color[1], $color[2].$color[3], $color[4].$color[5]);
+
+ $r = hexdec($r);
+ $g = hexdec($g);
+ $b = hexdec($b);
+
+ $chart->setColorPalette($i,$r,$g,$b);
+ }
+ }
+
+ return $chart;
+ }
+
+
+ // Funkcije za izris posameznih tipov grafov - vertikalni stolpci
+ function createVerBars($DataSet, $show_legend=0){
+ global $lang;
+
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+
+ $angle = 0;
+ $addHeight = 0;
+ $roundText = 15;
+ if($countGrids > 5){
+ $angle = 45;
+ $addHeight = 110;
+ $roundText = 30;
+ }
+
+ // Initialise the graph
+ $Test = new pChart($this->settings['hq']*800,$this->settings['hq']*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ $Test->setGraphArea($this->settings['hq']*100,$this->settings['hq']*40,$this->settings['hq']*650,$this->settings['hq']*220);
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,$angle,0,TRUE,1,FALSE,$roundText);
+ $Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Draw the bar graph
+ $Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(), false, 95, $this->settings['barLabel']);
+
+ if($show_legend == 1)
+ $Test->drawLegend($this->settings['hq']*680,$this->settings['hq']*30,$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ // Prikaz napisa frekvence/odstotki (samo crosstabi)
+ if($this->podstran == 'crosstab'){
+ if($this->settings['value_type'] == '0')
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*210,$this->settings['hq']*60,$this->settings['hq']*110,$lang['srv_chart_percent'],$Angle=90,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ else
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*210,$this->settings['hq']*60,$this->settings['hq']*110,$lang['srv_chart_freq'],$Angle=90,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - horizontalni stolpci
+ function createHorBars($DataSet, $show_legend=0, $fixedScale=0){
+ global $lang;
+
+ // Nastavimo visino grafa (ce imamo vec kot 7 variabel/gridov)
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+ $addHeight = $countGrids > 5 ? ($countGrids-5)*30 : 0;
+
+ // Initialise the graph
+ $Test = new MyHorBar($this->settings['hq']*800,$this->settings['hq']*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Dolge labele
+ $startX = ($this->settings['labelWidth'] == 20) ? 225 : 360;
+ $roundText = ($this->settings['labelWidth'] == 20) ? 35 : 65;
+
+ $Test->setGraphArea($this->settings['hq']*$startX,$this->settings['hq']*70,$this->settings['hq']*650,$this->settings['hq']*(220+$addHeight));
+
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+ // Če gre za hierarhijo, potem je fiksna skala
+ if(SurveyInfo::checkSurveyModule('hierarhija', $this->anketa))
+ $Test->setFixedScale(1,5,4);
+
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,0,0,TRUE,1,FALSE,$roundText);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Draw the bar graph
+ $Test->drawHorBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(), $this->settings['barLabel']);
+
+ // Finish the graph
+ if($show_legend == 1)
+ $Test->drawLegend($this->settings['hq']*680,$this->settings['hq']*60,$DataSet->GetDataDescription(),255,255,255);
+
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ // Prikaz napisa frekvence in 1. spremenljivke na vrhu (samo crosstabi)
+ if($this->podstran == 'crosstab'){
+ if($this->settings['value_type'] == '0')
+ $Test->drawTextBox($this->settings['hq']*480,$this->settings['hq']*30,$this->settings['hq']*580,$this->settings['hq']*40,$lang['srv_chart_percent'],$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ else
+ $Test->drawTextBox($this->settings['hq']*480,$this->settings['hq']*30,$this->settings['hq']*580,$this->settings['hq']*40,$lang['srv_chart_freq'],$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+
+ $strings = explode('<br />',$this->crosstabVars[1]);
+ $substr1 = (strlen($strings[0]) > 50) ? substr($strings[0], 0, 47).'...' : $strings[0];
+ $substr2 = (strlen($strings[1]) > 50) ? substr($strings[1], 0, 47).'...' : $strings[1];
+
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*20,$this->settings['hq']*280,$this->settings['hq']*30,$substr1,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_CENTER,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*38,$this->settings['hq']*280,$this->settings['hq']*43,$substr2,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_CENTER,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+ // Prikaz t vrednosti pri ttest grafu
+ if($this->podstran == 'ttest' && $this->settings['show_numerus'] == '1'){
+ $t = 't = '.$DataSet->GetNumerus();
+ $Test->drawTextBox($this->settings['hq']*680,$this->settings['hq']*210,$this->settings['hq']*795,$this->settings['hq']*220,$t,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - vertikalni sestavljeni stolpci
+ function createVerStructBars($DataSet){
+ global $lang;
+
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+
+ $angle = 0;
+ $addHeight = 0;
+ $roundText = 15;
+ if($countGrids > 5){
+ $angle = 45;
+ $addHeight = 110;
+ $roundText = 30;
+ }
+
+ // Initialise the graph
+ $Test = new pChart($this->settings['hq']*800,$this->settings['hq']*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Pri navadnem radio in checkbox vprasanju imamo samo en stolpec - zato so dimenzije drugacne
+ /*if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3)
+ $Test->setGraphArea($this->settings['hq']*250,$this->settings['hq']*40,$this->settings['hq']*500,$this->settings['hq']*220);
+ else*/
+ $Test->setGraphArea($this->settings['hq']*100,$this->settings['hq']*40,$this->settings['hq']*650,$this->settings['hq']*220);
+
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0,0,0,0,TRUE,$angle,0,TRUE,1,FALSE,$roundText);
+ $Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ // Draw the bar graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ $Test->drawStackedBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(), $this->settings['barLabel'], 95);
+
+ $Test->drawLegend($this->settings['hq']*680,$this->settings['hq']*30,$DataSet->GetDataDescription(),255,255,255,$Rs=-1,$Gs=-1,$Bs=-1,$Rt=0,$Gt=0,$Bt=0,$Border=false,$reverse=true);
+
+ $Test->setFontProperties("Fonts/verdana.ttf",$this->settings['hq']*10);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ // Prikaz napisa frekvence (samo crosstabi)
+ if($this->podstran == 'crosstab'){
+ if($this->settings['value_type'] == '0')
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*210,$this->settings['hq']*60,$this->settings['hq']*110,$lang['srv_chart_percent'],$Angle=90,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ else
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*210,$this->settings['hq']*60,$this->settings['hq']*110,$lang['srv_chart_freq'],$Angle=90,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - horizontalni sestavljeni stolpci
+ function createHorStructBars($DataSet){
+ global $lang;
+
+ // Nastavimo visino graffa (ce imamo vec kot 7 variabel/gridov)
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+ $addHeight = $countGrids > 5 ? ($countGrids-5)*30 : 0;
+
+ // Initialise the graph
+ $Test = new MyHorBar($this->settings['hq']*800,$this->settings['hq']*(250+$addHeight+50));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Dolge labele
+ $startX = ($this->settings['labelWidth'] == 20) ? 225 : 360;
+ $roundText = ($this->settings['labelWidth'] == 20) ? 35 : 65;
+
+ // Pri navadnem radio in checkbox vprasanju imamo samo en stolpec - zato so dimenzije drugacne
+ /*if($spremenljivka['tip'] == 1 || $spremenljivka['tip'] == 2 || $spremenljivka['tip'] == 3){
+ $Test->setGraphArea($this->settings['hq']*200,$this->settings['hq']*50,$this->settings['hq']*630,$this->settings['hq']*220);
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*243,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*295,200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0,0,0,0,TRUE,0,0,TRUE);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+ }
+ else{*/
+ $Test->setGraphArea($this->settings['hq']*$startX,$this->settings['hq']*70,$this->settings['hq']*650,$this->settings['hq']*(220+$addHeight));
+ $Test->drawFilledRoundedRectangle(7,7,793,243+$addHeight,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*(295+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_ADDALLSTART0,0,0,0,TRUE,0,0,TRUE,1,FALSE,$roundText);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+ //}
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Draw the bar graph
+ $Test->drawStackedHorBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),$this->settings['barLabel'],95);
+
+
+ // pri vodoravnih strukturnih stolpcih izrisemo legendo na dnu
+ $Test->drawVerticalLegend($this->settings['hq']*400,$this->settings['hq']*(240+$addHeight),$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties("Fonts/verdana.ttf",$this->settings['hq']*10);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ // Prikaz napisa frekvence in 1. spremenljivke na vrhu (samo crosstabi)
+ if($this->podstran == 'crosstab'){
+ if($this->settings['value_type'] == '0')
+ $Test->drawTextBox($this->settings['hq']*480,$this->settings['hq']*30,$this->settings['hq']*580,$this->settings['hq']*40,$lang['srv_chart_percent'],$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ else
+ $Test->drawTextBox($this->settings['hq']*480,$this->settings['hq']*30,$this->settings['hq']*580,$this->settings['hq']*40,$lang['srv_chart_freq'],$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+ $strings = explode('<br />',$this->crosstabVars[1]);
+ $substr1 = (strlen($strings[0]) > 50) ? substr($strings[0], 0, 47).'...' : $strings[0];
+ $substr2 = (strlen($strings[1]) > 50) ? substr($strings[1], 0, 47).'...' : $strings[1];
+
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*20,$this->settings['hq']*280,$this->settings['hq']*30,$substr1,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_CENTER,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ $Test->drawTextBox($this->settings['hq']*50,$this->settings['hq']*38,$this->settings['hq']*280,$this->settings['hq']*43,$substr2,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_CENTER,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+ }
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - krozni graf
+ function createPie($DataSet, $show_legend=1){
+ global $lang;
+
+ // Initialise the graph
+ $Test = new pChart($this->settings['hq']*800,$this->settings['hq']*280);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ // Pri pie grafu uporabimo antialiasing
+ $Test->setAntialias(true, 20);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ //$Test->setGraphArea(50,40,685,220);
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*273,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*275,200,200,200);
+ //$Test->createColorGradientPalette(195,204,56,223,110,41,3);
+ //$Test->createColorGradientPalette(168,188,56,248,255,136,5);
+
+ // Draw the pie graph
+ $labels = ($this->settings['sort'] == 1) ? 'custom_percent_sort' : 'custom_percent';
+ $Test->drawFlatPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),$this->settings['hq']*390,$this->settings['hq']*145,$this->settings['hq']*95,$labels);
+
+ $Test->setAntialias(false, 0);
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ //$Test->drawLegend(700,30,$DataSet->GetDataDescription(),255,255,255);
+
+ if($show_legend == 1)
+ $Test->drawPieLegend($this->settings['hq']*600,$this->settings['hq']*50,$DataSet->GetData(),$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*10);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - krozni graf
+ function create3DPie($DataSet, $show_legend=1){
+ global $lang;
+
+ // Initialise the graph
+ $Test = new pChart($this->settings['hq']*800,$this->settings['hq']*280);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ // Pri pie grafu uporabimo antialiasing
+ $Test->setAntialias(true, 20);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ //$Test->setGraphArea(50,40,685,220);
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*273,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*275,200,200,200);
+ //$Test->createColorGradientPalette(195,204,56,223,110,41,3);
+ //$Test->createColorGradientPalette(168,188,56,248,255,136,5);
+
+ // Draw the pie graph
+ $labels = ($this->settings['sort'] == 1) ? 'custom_percent_sort' : 'custom_percent';
+ $Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),$this->settings['hq']*390,$this->settings['hq']*130,$this->settings['hq']*95,$labels,$EnhanceColors=true,$Skew=50,$SpliceHeight=$this->settings['hq']*20,$SpliceDistance=0,$Decimals=0);
+
+ $Test->setAntialias(false, 0);
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ //$Test->drawLegend(700,30,$DataSet->GetDataDescription(),255,255,255);
+
+ if($show_legend == 1)
+ $Test->drawPieLegend($this->settings['hq']*600,$this->settings['hq']*50,$DataSet->GetData(),$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*10);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - linijski graf
+ function createVerLine($DataSet, $show_legend=0, $fixedScale=1){
+ global $lang;
+
+ // Nastavimo visino grafa (ce imamo vec kot 7 variabel/gridov)
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+ $addHeight = $countGrids > 5 ? ($countGrids-5)*30 : 0;
+
+ // Initialise the graph
+ $Test = new MyHorBar($this->settings['hq']*800,$this->settings['hq']*(250+$addHeight));
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ $Test->setGraphArea($this->settings['hq']*270,$this->settings['hq']*50,$this->settings['hq']*530,$this->settings['hq']*(220+$addHeight));
+
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*(243+$addHeight),5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*(245+$addHeight),200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+
+
+ /*$VMax = count($spremenljivka['options']);
+ $Divisions = $VMax-1;
+
+ $Test->setFixedScale($VMin=1, $VMax, $Divisions);*/
+
+
+ $Test->drawHorScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,0,0,TRUE,1,$rightScale=FALSE,$roundText=40);
+ $Test->drawHorGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*6);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ // Draw the line graph
+ $Test->drawVerLineGraph($DataSet->GetData(),$DataSet->GetDataDescription(), $insideValues=false);
+
+ // Finish the graph
+ if($show_legend == 1)
+ $Test->drawLegend($this->settings['hq']*680,$this->settings['hq']*30,$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - radar
+ function createRadar($DataSet, $show_legend=0, $fixedScale=0){
+ global $lang;
+
+ $Data = $DataSet->GetData();
+ $countGrids = count($Data);
+
+ // Initialise the graph
+ $Test = new pChart($this->settings['hq']*800,$this->settings['hq']*350);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ // Pri radar grafu uporabimo antialiasing
+ $Test->setAntialias(true, 20);
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ $Test->setGraphArea($this->settings['hq']*100,$this->settings['hq']*40,$this->settings['hq']*650,$this->settings['hq']*320);
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*343,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*345,200,200,200);
+ //$Test->drawGraphArea(255,255,255,TRUE);
+ //$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,20,20,20,TRUE,$angle,0,TRUE,1,FALSE,$roundText);
+ //$Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ $Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ $VMax = -1;
+
+ // Draw the radar
+ $Test->drawRadarAxis($DataSet->GetData(),$DataSet->GetDataDescription(),true,5,0,0,0,160,160,160,$VMax,$this->settings['radar_scale']);
+ // Tip radarja - navaden ali samo crte
+ if($this->settings['radar_type'] == 1)
+ $Test->drawFilledRadar($DataSet->GetData(),$DataSet->GetDataDescription(),50,5,$VMax);
+ else{
+ $Test->setLineStyle($Width=(2*$this->settings['hq']),$DotSize=0);
+ $Test->drawRadar($DataSet->GetData(),$DataSet->GetDataDescription(),5,$VMax);
+ }
+
+ $Test->setAntialias(false, 0);
+
+ // Finish the graph
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ if($show_legend == 1)
+ $Test->drawLegend($this->settings['hq']*680,$this->settings['hq']*30,$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties("Fonts/verdana.ttf",$this->settings['hq']*10);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+ return $Test;
+ }
+
+ // Funkcije za izris posameznih tipov grafov - linijski graf
+ function createLine($DataSet, $show_legend=0, $fixedScale=0){
+
+ // Initialise the graph
+ $Test = new pChart($this->settings['hq']*800,$this->settings['hq']*280);
+
+ // Nastavimo barve grafu glede na skin
+ $Test = $this->setChartColors($Test, $this->skin);
+
+ $count = count($DataSet->GetData());
+
+ // Kot label na x osi
+ $angle = 0;
+ if($count > 6)
+ $angle = 45;
+
+ $Test->setLineStyle($this->settings['hq'],$DotSize=0);
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ $Test->setGraphArea($this->settings['hq']*100,$this->settings['hq']*40,$this->settings['hq']*650,$this->settings['hq']*220);
+ $Test->drawFilledRoundedRectangle($this->settings['hq']*7,$this->settings['hq']*7,$this->settings['hq']*793,$this->settings['hq']*273,5,255,255,255);
+ //$Test->drawRoundedRectangle(5,5,795,245,5,128,128,128);
+ $Test->drawRectangle($this->settings['hq']*5,$this->settings['hq']*5,$this->settings['hq']*795,$this->settings['hq']*275,200,200,200);
+ $Test->drawGraphArea(255,255,255,TRUE);
+ $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,0,0,0,TRUE,$angle,0,TRUE);
+ if($count <= 20)
+ $Test->drawGrid(4,TRUE,230,230,230,50);
+
+ // Draw the 0 line
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+ //$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+ // Draw the bar graph
+ $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
+ if($count <= 20)
+ $Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),$this->settings['hq']*3,$this->settings['hq']*2,255,255,255);
+
+ if($show_legend == 1)
+ $Test->drawLegend($this->settings['hq']*680,$this->settings['hq']*30,$DataSet->GetDataDescription(),255,255,255);
+
+ $Test->setFontProperties(dirname(__FILE__).'/../../pChart/Fonts/verdana.ttf',$this->settings['hq']*$this->fontSize);
+
+
+ $Test->drawTextBox($this->settings['hq']*690,$this->settings['hq']*(210+$addHeight),$this->settings['hq']*795,$this->settings['hq']*(220+$addHeight),$numerus,$Angle=0,$R=0,$G=0,$B=0,$Align=ALIGN_LEFT,$Shadow=FALSE,$BgR=-1,$BgG=-1,$BgB=-1,$Alpha=0);
+
+ return $Test;
+ }
+
+
+ // Nastavitve posameznega grafa
+ function displaySingleSettings($chartID, $settings=0){
+ global $site_path;
+ global $lang;
+
+ // Ikone izvoza na vrhu posameznih nastavitev
+ //$this->displayExportIcons($chartID);
+
+
+ echo '<div id="switch_left_'.$chartID.'_loop_0" class="switch_left '.($this->settings_mode == 1 ? ' non-active' : '').'" onClick="chartSwitchSettings(\''.$chartID.'\', \'0\', \'0\')">'.$lang['srv_chart_settings_basic'].'</div>';
+ //echo '<span id="switch_middle_'.$chartID.'_loop_0" class="'.($this->settings_mode == 1 ? 'rightHighlight' : 'leftHighlight').'"></span>';
+ echo '<div id="switch_right_'.$chartID.'_loop_0" class="switch_right '.($this->settings_mode == 0 ? ' non-active' : '').'" onClick="chartSwitchSettings(\''.$chartID.'\', \'1\', \'0\')">'.$lang['srv_chart_settings_advanced'].'</div>';
+
+
+ // OSNOVNE NASTAVITVE
+ echo '<div class="chart_settings_inner" id="chart_settings_basic_'.$chartID.'_loop_0" '.($this->settings_mode == 1 ? ' style="display:none;"' : '').'>';
+
+ //echo '<span class="title">'.$lang['srv_chart_settings'].'</span>';
+
+ switch($this->podstran){
+ case 'crosstab':
+ $this->displayCrosstabSettings($chartID, $settings);
+ break;
+
+ case 'ttest':
+ $this->displayTTestSettings($chartID, $settings);
+ break;
+
+ case 'mean':
+ $this->displayMeanSettings($chartID, $settings);
+ break;
+
+ case 'break':
+ $this->displayBreakSettings($chartID, $settings);
+ break;
+
+ default:
+ break;
+ }
+
+ echo '</div>';
+
+
+ // NAPREDNE NASTAVITVE
+ echo '<div class="chart_settings_inner" id="chart_settings_advanced_'.$chartID.'_loop_0" '.($this->settings_mode == 0 ? ' style="display:none;"' : '').'>';
+
+ switch($this->podstran){
+
+ case 'crosstab':
+ case 'mean':
+ case 'break':
+ // visoka locljivost grafa
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_hq'].': ';
+ echo '<input type="checkbox" id="tablechart_hq_'.$chartID.'" name="tablechart_hq" '.($settings['hq']=='3'?' checked="checked"':'').' onchange="changeTableChart(\''.$chartID.'\', \''.$this->podstran.'\', \'hq\');">';
+
+ echo '</div>';
+ break;
+
+ case 'ttest':
+ // prikaz numerusa
+ echo '<div class="chart_setting">';
+
+ $checked = ($settings['show_numerus']=='1') ? ' checked="checked"': '';
+
+ echo $lang['srv_chart_showNumerus'].': ';
+ echo '<input type="checkbox" id="tablechart_show_numerus_'.$chartID.'" name="tablechart_show_numerus" '.$checked.' onchange="changeTableChart(\''.$chartID.'\', \'ttest\', \'show_numerus\');">';
+
+ echo '</div>';
+
+ default:
+ break;
+ }
+
+
+ // Link na urejanje label
+ //echo '<span class="edit" style="margin-top:15px;" onclick="chartAdvancedSettings(\''.$this->counter.'\');">'.$lang['srv_chart_advancedLink_labels'].'</span>';
+ // Vprasajcek za pomoc
+ //echo Help :: display('displaychart_settings_labels');
+
+ // Link na urejanje barv
+ echo '<span class="edit" onclick="tableChartAdvancedSettings(\''.$chartID.'\', \''.$this->podstran.'\')">'.$lang['srv_chart_advancedLink_colors'].'</span>';
+ // Vprasajcek za pomoc
+ echo Help :: display('displaychart_settings_colors');
+
+ // Link na rekodiranje
+ //echo '<span class="edit" onclick="chartAdvancedSettings(\''.$this->counter.'\', \'3\');">'.$lang['srv_chart_advancedLink_recoding'].'</span>';
+ // Vprasajcek za pomoc
+ //echo Help :: display('displaychart_settings_recoding');
+
+
+ echo '</div>';
+ }
+
+ // ikone na vrhu posameznih nastavitev (izvozi)
+ function displayExportIcons($chartID){
+ global $site_path;
+ global $lang;
+
+ // linki
+ echo '<div class="chart_setting_exportLinks">';
+
+ // Ikona za print
+ echo '<a href="#" onclick="showAnalizaSingleChartPopup(\''.$chartID.'\',\''.M_ANALYSIS_CHARTS.'\'); return false;">';
+ echo '<span class="faicon print_small icon-grey_dark_link" title="' . $lang['PRN_Izpis'] . '"></span>';
+ echo '</a>';
+
+ // Izvoz posameznega grafa v PDF/RTF/PPT
+ echo '&nbsp;<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts&anketa='.$this->anketa.'&sprID='.$chartID).'" target="_blank" title="'.$lang['PDF_Izpis'].'"><span class="faicon pdf"></span>&nbsp;</a>';
+ echo '&nbsp;<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts_rtf&anketa='.$this->anketa.'&sprID='.$chartID).'" target="_blank" title="'.$lang['RTF_Izpis'].'"><span class="faicon rtf"></span>&nbsp;</a>';
+ echo '&nbsp;<a href="'.makeEncodedIzvozUrlString('izvoz.php?m=charts_ppt&anketa='.$this->anketa.'&sprID='.$chartID).'" target="_blank" title="'.$lang['PPT_Izpis'].'"><span class="faicon ppt"></span>&nbsp;</a>';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za crosstab graf
+ function displayCrosstabSettings($chartID, $settings){
+ global $site_path;
+ global $lang;
+
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="tablechart_type_'.$chartID.'" name="tablechart_type" onchange="changeTableChart(\''.$chartID.'\', \'crosstab\', \'type\');">';
+
+ if($this->crossCheck){
+ // navedbe
+ if($this->classInstance->crossNavVsEno == 0){
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_pie'].'</option>';
+ echo ' <option value="5" '.($settings['type']=='5'?' selected="selected"':'').'>'.$lang['srv_chart_3Dpie'].'</option>';
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_structure_hor'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_structure_ver'].'</option>';
+ }
+ // enote
+ else{
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_structure_hor'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_structure_ver'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ }
+ }
+ else{
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_structure_hor'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_structure_ver'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="4" '.($settings['type']=='4'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ }
+
+ echo '</select>';
+ echo '</div>';
+
+
+ // tip izpisa vrednosti
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_valtype'].': <select id="tablechart_value_type_'.$chartID.'" name="tablechart_value_type" onchange="changeTableChart(\''.$chartID.'\', \'crosstab\', \'value_type\');">';
+
+ echo ' <option value="0" '.($settings['value_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_percent'].'</option>';
+ echo ' <option value="1" '.($settings['value_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_freq'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+
+ // prikaz label v stolpcih
+ //if($settings['type'] == 0 || $settings['type'] == 1){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_barLabel'].': ';
+ echo '<input type="checkbox" id="tablechart_barLabel_'.$chartID.'" name="tablechart_barLabel" '.($settings['barLabel']=='1'?' checked="checked"':'').' onchange="changeTableChart(\''.$chartID.'\', \'crosstab\', \'barLabel\');">';
+
+ echo '</div>';
+ //}
+
+
+ // sirina label
+ /*if($settings['type'] == 0 || $settings['type'] == 3){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="tablechart_labelWidth_'.$chartID.'" name="tablechart_labelWidth" onchange="changeTableChart(\''.$chartID.'\', \'crosstab\', \'labelWidth\');">';
+
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }*/
+ }
+
+ // Nastavitve za ttest graf
+ function displayTTestSettings($chartID, $settings){
+ global $site_path;
+ global $lang;
+
+ // sirina label
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="tablechart_labelWidth_'.$chartID.'" name="tablechart_labelWidth" onchange="changeTableChart(\''.$chartID.'\', \'ttest\', \'labelWidth\');">';
+
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+
+
+ // visoka locljivost grafa
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_hq'].': ';
+ echo '<input type="checkbox" id="tablechart_hq_'.$chartID.'" name="tablechart_hq" '.($settings['hq']=='3'?' checked="checked"':'').' onchange="changeTableChart(\''.$chartID.'\', \'ttest\', \'hq\');">';
+
+ echo '</div>';
+ }
+
+ // Nastavitve za mean graf
+ function displayMeanSettings($chartID, $settings){
+ global $site_path;
+ global $lang;
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="tablechart_type_'.$chartID.'" name="tablechart_type" onchange="changeTableChart(\''.$chartID.'\', \'mean\', \'type\');">';
+
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_avg_hor'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_avg_radar'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_avg_line'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+
+ // sortiranje
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': ';
+ echo '<input type="checkbox" id="tablechart_sort_'.$chartID.'" name="tablechart_sort" '.($settings['sort']=='1'?' checked="checked"':'').' onchange="changeTableChart(\''.$chartID.'\', \'mean\', \'sort\');">';
+
+ echo '</div>';
+
+
+ // sirina label
+ if($settings['type'] == 0){
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_wide_chart'].': <select id="tablechart_labelWidth_'.$chartID.'" name="tablechart_labelWidth" onchange="changeTableChart(\''.$chartID.'\', \'mean\', \'labelWidth\');">';
+
+ echo ' <option value="50" '.($settings['labelWidth']=='50'?' selected="selected"':'').'>50%</option>';
+ echo ' <option value="20" '.($settings['labelWidth']=='20'?' selected="selected"':'').'>20%</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+ }
+
+
+ // Tip radarja
+ if($settings['type'] == 1){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="tablechart_radar_type_'.$chartID.'" name="tablechart_radar_type" onchange="changeTableChart(\''.$chartID.'\', \'mean\', \'radar_type\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == 1){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="tablechart_radar_scale_'.$chartID.'" name="tablechart_radar_scale" onchange="changeTableChart(\''.$chartID.'\', \'mean\', \'radar_scale\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+ }
+
+ // Nastavitve za crosstab graf
+ function displayBreakSettings($chartID, $settings){
+ global $site_path;
+ global $lang;
+
+ $tip = $this->break_spremenljivka['tip'];
+
+ // Tip grafa
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_type'].':<br /> <select style="width:140px;" id="tablechart_type_'.$chartID.'" name="tablechart_type" onchange="changeTableChart(\''.$chartID.'\', \'break\', \'type\');">';
+
+ if($tip != 7)
+ echo ' <option value="0" '.($settings['type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar'].'</option>';
+ echo ' <option value="1" '.($settings['type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_vertical'].'</option>';
+ echo ' <option value="2" '.($settings['type']=='2'?' selected="selected"':'').'>'.$lang['srv_chart_horizontal'].'</option>';
+ echo ' <option value="3" '.($settings['type']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_line'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+
+ // sortiranje
+ echo '<div class="chart_setting">';
+
+ echo $lang['srv_chart_sort'].': <select id="tablechart_sort_'.$chartID.'" name="tablechart_sort" onchange="changeTableChart(\''.$chartID.'\', \'break\', \'sort\');">';
+
+ echo ' <option value="0" '.($settings['sort']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_sort_no'].'</option>';
+ if($tip != 7)
+ echo ' <option value="1" '.($settings['sort']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_sort_category'].'</option>';
+ echo ' <option value="3" '.($settings['sort']=='3'?' selected="selected"':'').'>'.$lang['srv_chart_sort_first'].'</option>';
+
+ echo '</select>';
+
+ echo '</div>';
+
+ // Obrnjeni gridi in variable
+ echo '<div class="chart_setting">';
+
+ if($settings['rotate']=='1'){
+ echo $lang['srv_chart_rotate_grids'].' ';
+ echo '<span onclick="changeTableChart(\''.$chartID.'\', \'break\', \'rotate\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="tablechart_rotate_'.$chartID.'" name="tablechart_rotate" value="0">';
+ echo ' '.$lang['srv_chart_rotate_vars'].' ';
+ }
+ else{
+ echo $lang['srv_chart_rotate_vars'].' ';
+ echo '<span onclick="changeTableChart(\''.$chartID.'\', \'break\', \'rotate\');" style="cursor: pointer;"><img src="img_0/random_off.png" title="Obrni grafe/variable" /></span>';
+ echo '<input type="hidden" id="tablechart_rotate_'.$chartID.'" name="tablechart_rotate" value="1">';
+ echo ' '.$lang['srv_chart_rotate_grids'];
+ }
+ echo '</div>';
+
+ // Tip radarja
+ if($settings['type'] == '0'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_type'].': <select id="tablechart_radar_type_'.$chartID.'" name="tablechart_radar_type" onchange="changeTableChart(\''.$chartID.'\', \'break\', \'radar_type\');">';
+
+ echo ' <option value="0" '.($settings['radar_type']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_type']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_type1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+
+ // Postavitev skale pri radarju
+ if($settings['type'] == '0'){
+ echo '<div class="chart_setting">';
+ echo $lang['srv_chart_radar_scale'].': <select id="tablechart_radar_scale_'.$chartID.'" name="tablechart_radar_scale" onchange="changeTableChart(\''.$chartID.'\', \'break\', \'radar_scale\');">';
+
+ echo ' <option value="0" '.($settings['radar_scale']=='0'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale0'].'</option>';
+ echo ' <option value="1" '.($settings['radar_scale']=='1'?' selected="selected"':'').'>'.$lang['srv_chart_radar_scale1'].'</option>';
+
+ echo '</select>';
+ echo '</div>';
+ }
+ }
+
+ // Napredne nastavitve grafa
+ function displayAdvancedSettings($chartID){
+ global $site_path;
+ global $lang;
+
+ echo '<h2>'.$lang['srv_detail_settings'].'</h2>';
+
+ echo '<div class="popup_close"><a href="#" onClick="chartCloseAdvancedSettings(); return false;">✕</a></div>';
+
+ echo '<form method="post" name="table_chart_advanced_settings" onsubmit="tableChartSaveAdvancedSettings(\''.$chartID.'\'); return false;">';
+
+ echo '<input type="hidden" name="anketa" value="'.$this->anketa.'" />';
+ echo '<input type="hidden" name="podstran" value="'.$this->podstran.'" />';
+ echo '<input type="hidden" name="chartID" value="'.$chartID.'" />';
+
+ // urejanje barv
+ echo '<div id="chartSettingsArea1" class="chartSettingsArea">';
+ $this->displayAdvancedSettingsColors($chartID);
+ echo '</div>';
+
+ // urejanje label
+ echo '<div id="chartSettingsArea2" class="chartSettingsArea" style="visibility: hidden;">';
+ //$this->displayAdvancedSettingsLabels($chartID);
+ echo '</div>';
+
+ echo '</form>';
+
+ /* ZAVIHKI NA DESNI */
+ echo '<div id="chartTabs" class="chartSettingsTabs">';
+
+ echo '<ul>';
+ echo '<li id="chartTab1" class="chartTab active" onClick="chartTabAdvancedSettings(\'1\');">';
+ echo $lang['srv_chart_advanced_colors'];
+ echo '</li>';
+ echo '</ul>';
+
+ echo '</div>';
+
+
+ /* GUMBI NA DNU */
+ echo '<div id="chartSettingsButtons" class="buttons_holder">';
+
+ echo '<span class="buttonwrapper spaceRight floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_gray" onclick="chartCloseAdvancedSettings(); return false;"><span>'.$lang['srv_zapri'].'</span></a>';
+ echo '</span>';
+
+ echo '<span class="buttonwrapper floatLeft">';
+ echo '<a class="ovalbutton ovalbutton_orange" onclick="tableChartSaveAdvancedSettings(\''.$chartID.'\'); return false;"><span>'.$lang['srv_potrdi'].'</span></a>';
+ echo '</span>';
+
+ echo '</div>';
+ }
+
+ // Urejanje barv posameznega grafa
+ function displayAdvancedSettingsColors($chartID){
+ global $site_path;
+ global $lang;
+
+ echo '<script type="text/javascript" charset="utf-8">
+ $(document).ready(function() {
+ var f = $.farbtastic(\'#picker\');
+ var p = $(\'#picker\').css(\'opacity\', 0.25);
+ var selected;
+ $(\'.colorwell\')
+ .each(function () { f.linkTo(this); $(this).css(\'opacity\', 0.75); })
+ .focus(function() {
+ if (selected) {
+ $(selected).css(\'opacity\', 0.75).removeClass(\'colorwell-selected\');
+ }
+ f.linkTo(this);
+ p.css(\'opacity\', 1);
+ $(selected = this).css(\'opacity\', 1).addClass(\'colorwell-selected\');
+ });
+ });
+ </script>';
+
+
+ echo ' <div id="picker" style="float: right;"></div>';
+
+ $default_colors = SurveyChart::getDefaultColors($this->skin);
+
+ for($i=0; $i<7; $i++){
+ $name = 'color'.($i+1);
+ $value = ($this->settings['colors'][$i] != '') ? $this->settings['colors'][$i] : $default_colors[$i];
+
+ echo ' <div class="form-item"><label for="'.$name.'">'.$lang['srv_color'].' '.($i+1).': </label><input type="text" id="'.$name.'" name="'.$name.'" class="colorwell" value="'.$value.'" /></div>';
+ }
+
+ // reset na default barvo
+ echo '<br /><span class="as_link clr" onClick="chartAdvancedSettingsSetColor(\''.(is_numeric($this->skin) ? implode("_",$default_colors) : $this->skin).'\')">'.$lang['srv_chart_advanced_default_color'].'</span>';
+
+ // nastavitev ene od palet
+ echo '<br /><span class="clr">'.$lang['srv_chart_advanced_skin'].': ';
+ echo '<select name="chart_advanced_color" id="chart_advanced_color" onChange="chartAdvancedSettingsSetColor(this.value)">';
+ echo ' <option' . ($this->skin == '1ka' ? ' selected="selected"' : '') . ' value="1ka">'.$lang['srv_chart_skin_1ka'].'</option>';
+ echo ' <option' . ($this->skin == 'lively' ? ' selected="selected"' : '') . ' value="lively">'.$lang['srv_chart_skin_0'].'</option>';
+ echo ' <option' . ($this->skin == 'mild' ? ' selected="selected"' : '') . ' value="mild">'.$lang['srv_chart_skin_1'].'</option>';
+ echo ' <option' . ($this->skin == 'office' ? ' selected="selected"' : '') . ' value="office">'.$lang['srv_chart_skin_6'].'</option>';
+ echo ' <option' . ($this->skin == 'pastel' ? ' selected="selected"' : '') . ' value="pastel">'.$lang['srv_chart_skin_7'].'</option>';
+ echo ' <option' . ($this->skin == 'green' ? ' selected="selected"' : '') . ' value="green">'.$lang['srv_chart_skin_2'].'</option>';
+ echo ' <option' . ($this->skin == 'blue' ? ' selected="selected"' : '') . ' value="blue">'.$lang['srv_chart_skin_3'].'</option>';
+ echo ' <option' . ($this->skin == 'red' ? ' selected="selected"' : '') . ' value="red">'.$lang['srv_chart_skin_4'].'</option>';
+ echo ' <option' . ($this->skin == 'multi' ? ' selected="selected"' : '') . ' value="multi">'.$lang['srv_chart_skin_5'].'</option>';
+
+ $customSkins = $this->getCustomSkins();
+ foreach($customSkins as $customSkin){
+ echo ' <option' . ($this->skin == $customSkin['id'] ? ' selected="selected"' : '') . ' value="'.$customSkin['colors'].'">'.$customSkin['name'].'</option>';
+ }
+ echo '</select></span>';
+ }
+
+ function getCustomSkins(){
+ global $global_user_id;
+
+ $skins = array();
+
+ $sql = sisplet_query("SELECT * FROM srv_chart_skin WHERE usr_id='$global_user_id'");
+ while($row = mysqli_fetch_array($sql)){
+ $skins[] = $row;
+ }
+
+ return $skins;
+ }
+
+
+ /** Funkcije ki skrbijo za ajax del
+ *
+ */
+ public function ajax() {
+
+ if (isset ($_POST['anketa'])) {
+ $anketa = $_POST['anketa'];
+ $this->anketa = $_POST['anketa'];
+ }
+ if (isset ($_POST['chartID']))
+ $chartID = $_POST['chartID'];
+ if (isset ($_POST['chart_type']))
+ $chart_type = $_POST['chart_type'];
+ if (isset ($_POST['podstran']))
+ $this->podstran = $_POST['podstran'];
+
+
+ // dobimo vse nastavitve iz sessiona
+ if(isset($this->sessionData[$this->podstran.'_charts'][$chartID]))
+ $this->settings = $this->sessionData[$this->podstran.'_charts'][$chartID];
+ else
+ $this->settings = $this->getDefaultSettings();
+
+
+ if (isset ($_POST['what']))
+ $what = $_POST['what'];
+ if (isset ($_POST['value']))
+ $value = $_POST['value'];
+
+ $this->settings[$what] = $value;
+ $this->sessionData[$this->podstran.'_charts'][$chartID] = $this->settings;
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ if ($_GET['a'] == 'table_chart_advanced_settings') {
+ $this->displayAdvancedSettings($chartID);
+ }
+
+ if ($_GET['a'] == 'chart_save_advanced_settings') {
+ // SHRANIMO BARVE
+ // preverimo najprej ce shranjujemo vrednosti, ki so enake kot izbran skin
+ $default = true;
+ $default_colors = SurveyChart::getDefaultColors($this->skin);
+ for($i=1; $i<8; $i++){
+ if($_POST['color'.$i] != $default_colors[$i-1]){
+ $default = false;
+ break;
+ }
+ }
+ for($i=1; $i<8; $i++){
+
+ // ce niso default vrednosti shranimo nastavljeno barvo
+ if($default == false)
+ $color = $_POST['color'.$i];
+ // ce so default vrednosti shranimo prazno
+ else
+ $color = '';
+
+ $this->settings['colors'][$i-1] = $color;
+ }
+
+ $this->sessionData[$this->podstran.'_charts'][$chartID] = $this->settings;
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+ }
+
+ // Globalne nastavitve za vse grafe
+ if ($_GET['a'] == 'change_global_settings') {
+ SurveyUserSetting :: getInstance()->saveSettings('default_chart_profile_'.$what, $value);
+ //$this->display();
+ }
+
+ if ($_GET['a'] == 'change_chart') {
+ if($this->podstran == 'break'){
+ $this->classInstance = new SurveyBreak($this->anketa);
+
+ $this->break_forSpr = $this->sessionData['break_charts'][$chartID]['forSpr'];
+ $this->break_frequencys = $this->sessionData['break_charts'][$chartID]['frequencys'];
+ $this->break_spremenljivka = $this->sessionData['break_charts'][$chartID]['spremenljivka'];
+ }
+
+ // imamo crosstab graf
+ else{
+ $this->classInstance = new SurveyCrosstabs();
+ $this->classInstance->Init($this->anketa);
+
+ // Napolnimo podatke crosstabu
+ $crossData1 = $this->sessionData['crosstab_charts'][$chartID]['spr1'];
+ $crossData2 = $this->sessionData['crosstab_charts'][$chartID]['spr2'];
+
+ $this->classInstance->setVariables($crossData1['seq'],$crossData1['spr'],$crossData1['grd'],$crossData2['seq'],$crossData2['spr'],$crossData2['grd']);
+
+ $this->break_spremenljivka['tip'] = 1;
+ $this->break_spremenljivka['skala'] = 0;
+ }
+
+ $this->displayBreakChart($chartID);
+ }
+
+ if ($_GET['a'] == 'chart_reload_advanced_settings') {
+ // SHRANIMO BARVE
+ // preverimo najprej ce shranjujemo vrednosti, ki so enake kot izbran skin
+ $default = true;
+ $default_colors = SurveyChart::getDefaultColors($this->skin);
+ for($i=1; $i<8; $i++){
+ if($_POST['color'.$i] != $default_colors[$i-1]){
+ $default = false;
+ break;
+ }
+ }
+ for($i=1; $i<8; $i++){
+
+ // ce niso default vrednosti shranimo nastavljeno barvo
+ if($default == false)
+ $color = $_POST['color'.$i];
+ // ce so default vrednosti shranimo prazno
+ else
+ $color = '';
+
+ $this->settings['colors'][$i-1] = $color;
+ }
+
+ $this->sessionData[$this->podstran.'_charts'][$chartID] = $this->settings;
+
+ if($this->podstran == 'break'){
+ $this->classInstance = new SurveyBreak($this->anketa);
+
+ $this->break_forSpr = $this->sessionData['break_charts'][$chartID]['forSpr'];
+ $this->break_frequencys = $this->sessionData['break_charts'][$chartID]['frequencys'];
+ $this->break_spremenljivka = $this->sessionData['break_charts'][$chartID]['spremenljivka'];
+ }
+
+ // imamo crosstab graf
+ else{
+ $this->classInstance = new SurveyCrosstabs();
+ $this->classInstance->Init($this->anketa);
+
+ // Napolnimo podatke crosstabu
+ $crossData1 = $this->sessionData['crosstab_charts'][$chartID]['spr1'];
+ $crossData2 = $this->sessionData['crosstab_charts'][$chartID]['spr2'];
+
+ $this->classInstance->setVariables($crossData1['seq'],$crossData1['spr'],$crossData1['grd'],$crossData2['seq'],$crossData2['spr'],$crossData2['grd']);
+
+ $this->break_spremenljivka['tip'] = 1;
+ $this->break_spremenljivka['skala'] = 0;
+ }
+
+ // Shranimo spremenjene nastavitve v bazo
+ SurveyUserSession::saveData($this->sessionData);
+
+ $this->displayBreakChart($chartID);
+ }
+ }
+
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyData/class.ExclusiveLock.php b/admin/survey/classes/surveyData/class.ExclusiveLock.php
new file mode 100644
index 0000000..2103345
--- /dev/null
+++ b/admin/survey/classes/surveyData/class.ExclusiveLock.php
@@ -0,0 +1,80 @@
+<?php
+
+class ExclusiveLock
+{
+ protected $key; // Lock key
+ protected $own = false; // Owner of lock
+
+
+ public function __construct($key=NULL) {
+
+ if ($key == NULL) {
+ throw new Exception('ExclusiveLock: Key must not be NULL!');
+ }
+
+ $this->key = $key;
+ }
+
+ function __destruct() {
+
+ if($this->own == TRUE) {
+ $this->unlock();
+ }
+ }
+
+
+ // Poskusamo zakleniti datoteke za doloceno anketo
+ public function lock() {
+ global $global_user_id;
+
+ // Preverimo ce je datoteka zaklenjena in če je od tega minilo manj kot 15 minut
+ $sqlLocked = sisplet_query("SELECT COUNT(*)
+ FROM srv_lock
+ WHERE lock_key = '$this->key' AND locked='1' AND last_lock_date > NOW() - INTERVAL 15 MINUTE");
+ list($lockCount) = mysqli_fetch_row($sqlLocked);
+
+ // Datoteka je zaklenjena - mi nimamo dostopa do nje
+ if ($lockCount > 0){
+ $this->own = false;
+ }
+ // Datoteka je odklenjena - jo zaklenemo
+ else{
+ $sqlLock = sisplet_query("INSERT INTO srv_lock
+ (lock_key, locked, usr_id, last_lock_date)
+ VALUES
+ ('".$this->key."', '1', '".$global_user_id."', NOW())
+ ON DUPLICATE KEY
+ UPDATE locked='1', usr_id='".$global_user_id."', last_lock_date=NOW()");
+
+ // Uspesno smo zaklenili datoteko - nastavimo, da smo owner in lahko operiramo z datoteko
+ if ($sqlLock) {
+ $this->own = true;
+ }
+ }
+
+ return $this->own;
+ }
+
+ // Odklenemo datoteko, ki jo generiramo
+ public function unlock() {
+
+ // Ce smo owner lahko odkelenmo datoteke za anketo
+ if($this->own){
+
+ // Updejtamo lock = '0' in popravimo datum odklepanja
+ $sqlUnlock = sisplet_query("UPDATE srv_lock SET locked='0', last_unlock_date=NOW() WHERE lock_key='".$this->key."'");
+ }
+
+ // Po odklepanju nismo vec owner
+ $this->own = false;
+ }
+
+ // Pridobimo datum zadnjega zaklepanja
+ function getLockDate(){
+
+ $sql = sisplet_query("SELECT DATE_FORMAT(last_lock_date, '%m.%d.%Y %T') FROM srv_lock WHERE lock_key='".$this->key."' AND locked='1'");
+ list($lastLockDate) = mysqli_fetch_row($sql);
+
+ return $lastLockDate;
+ }
+}; \ No newline at end of file
diff --git a/admin/survey/classes/surveyData/class.SurveyDataCollect.php b/admin/survey/classes/surveyData/class.SurveyDataCollect.php
new file mode 100644
index 0000000..75cdd06
--- /dev/null
+++ b/admin/survey/classes/surveyData/class.SurveyDataCollect.php
@@ -0,0 +1,4382 @@
+<?php
+
+/**
+ *
+ * Created on 17.12.2019
+ *
+ * @author: Peter Hrvatin
+ *
+ * Class za ustvarjanje datotek s podatki
+ *
+*/
+
+set_time_limit(2400); # 30 minut
+
+global $site_path;
+
+class SurveyDataCollect{
+
+
+ // Osnovni podatki (id ankete, path...)
+ private $folder = ''; // Folder kamor shranjujemo vse podatke
+ private $sid = null; // id ankete
+ private $db_table = ''; // ali se uporablja aktivna tabela
+ private $survey = null; // podatki ankete
+
+
+ // Errorji
+ private $noErrors = true; // ali smo naleteli na napako, prekinemo izvajanje
+ private $errors = array(); // beležimo napake
+
+ // Zacsno za logiranje in testiranje
+ private $log = array();
+
+
+ // Ostale nastavitve
+ private $header_file_name = null; // Ime header datoteke
+ private $data_file_name = null; // Ime data datoteke
+ private $data_file_time = null; // datum zadnjega userja v data datoteki
+
+ private $max_anketa_time = null; // datum zadnje spremembe v anketi
+ private $max_usr_time = null; // datum zadnje spremembe v tabelu userjev
+
+ private $collect_all_status = 1; // ali so zbrani vsi statusi
+ private $has_test_data = false; // ali vnosi vsebujejo testne podatke
+ private $is_valid_user_limit = ''; // sql ali zbiramo vse statuse
+ private $force_show_hiden_system = false; // ali prisilimo prikaz sistemskih vprašanj (email. ime, priimek)
+ private $last_update = null; // kdaj je bila zadnja sprememba
+
+ private $fileStatus = FILE_STATUS_NO_DATA; // status datoteke z podatki 1 = OK, 0 = OLD .....
+
+
+ // Pointer do headerja
+ private $_HEADER = null;
+
+
+ // Kesiranje respondentov
+ private $_qry_users = null; // cache query za vprašanja
+ private $_str_users = null; // cache string za user_id ji
+ private $_cnt_all_users = 0; // cache za število userjev
+
+ // Kesiranje strani
+ private $_str_groups = null; // cache string za strani
+ private $_array_groups = null; // cache array za strani
+ private $_cnt_groups = 0; // cache število za strani
+
+ // Kesiranje vprasanj
+ private $AllQuestionsData = null; // cache array z podatki vseh vprašanj
+ private $AllQuestionsOrder = null; // cache array z vrstnim redom vseh vprašanj, upoštevajoč loope
+ private $_str_questions = null; // cache string za id-je vprašanj
+ private $_cnt_questions = 0; // cache za število vprašanj
+ private $_cnt_questions_types = null; // cache za število vprasanj po posameznih tipih (da ne klicemo funkcij po nepotrebnem)
+
+ // Kesiranje vrednosti v vprasanjih
+ private $_array_vrednosti = null; // cache array z vrednostmi
+
+ // Kesiranje gridov
+ private $_array_gridi = null; // cache array z gridi
+
+ // Prikaz vrstnega reda v randomiziranih vprasanjih / blokih
+ private $_array_random = null; // cache array za random bloke in vprasanja
+ private $_str_blocks = null; // cache string za id-je blokov
+
+ // Kesiranje loopov
+ private $_array_loop_on_spr = null; // cache array z loopi in na katero spremenljvko se nanaša
+ private $_array_loop_parent = null; // cache array z spremenljivkami in pripadajočimiloop idji
+ private $_array_vre_on_loop = null; // cache array z vrednostmi v posameznem loopu
+ private $_array_spr_in_loop = null; // cache array z id-lopi za posamezno spremenljvko
+ private $_array_loop_has_spr = null; // cache array katere spremenljvike vsebuje posamezen loop
+ private $_array_vrednosti_in_loops = null; // cache array vseh vrednosti ki se pojavljajo v loopih
+ private $_cnt_loop = 0; // cache za število vseh loopov
+
+ // Kesiranje ostalih dodatnih nastavitev
+ private $SNVariablesForSpr = null; // cache array spremenljivk z variablami
+ private $_array_users_from_CMS = null; // cache za e-maile uporanikov iz CMS
+ private $_array_SPSS = null; // cache array za spss izvoz za uporabnika
+ private $_array_user_grupa = null; // cache array casov respondentov po straneh
+ private $_user_spr_answer_count = array(); // stejemo variable na spremenljivko da spreminjamo -3 samo za variable katerih spremenljivka nima veljavnih vrednosti
+ private $sysMissingMap = array(); // za osnovni mapping sistemskih missingov, -1,-2,-3,-4,-5
+
+ // Rekodiranje
+ private $_array_recode = null; // cache array vseh rekodiranih vrednosti
+ private $_array_recoded = array(); // cache array vseh že rekodiranih vrednosti
+
+
+ // POINTER - Array-i do podatkov
+ private $_array_data_vrednost = null;
+ private $_array_data_vrednost_cond = null;
+ private $_array_data_text = null;
+ private $_array_data_grids = null;
+ private $_array_data_check_grids = null;
+ private $_array_data_rating = null;
+ private $_array_data_text_grid = null;
+ private $_array_data_text_upload = null;
+ private $_array_data_map = null;
+ private $_array_data_heatmap = null;
+ private $_array_data_heatmap_regions = null;
+ private $_array_data_random = null;
+
+
+
+ function __construct($sid = null) {
+ global $site_path, $lang, $mysql_database_name;
+
+ // Zacasno povecamo ram samo za veliko nijz anketo
+ if($sid == '123146' && $mysql_database_name == 'www1kasi'){
+ ini_set('memory_limit', '2048M');
+ }
+
+ if (is_numeric($sid) && (int)$sid > 0) {
+
+ // Nastavimo id ankete
+ $this->sid = $sid;
+
+ // Nastavimo globalni folder kjer se generirajo datoteke
+ $this->folder = $site_path . EXPORT_FOLDER.'/';
+
+ // Nastavimo spremenljivke, ki so potrebne pri generiranju datoteke (cas zadnjega vnosa, status datoteke...)
+ $this->prepareVariables();
+
+ // Za vsak slucaj resetiramo vse pointerje
+ $this->cleanup();
+
+
+ // Inicializiramo razrede za dodatne nastavitve
+ SurveyStatusProfiles::Init($this->sid);
+ SurveySetting::getInstance()->Init($this->sid);
+ }
+ else {
+
+ $SL = new SurveyLog();
+ $SL->addMessage(SurveyLog::DEBUG, 'SurveyDataCollect constructor - survey id == 0!');
+ $SL->write();
+
+ echo 'Napaka! Manjka ID ankete!';
+
+ /*return false;
+ exit();*/
+
+ die();
+ }
+ }
+
+
+ // Nastavimo spremenljivke potrebne za generiranje datoteke
+ private function prepareVariables(){
+
+ // Dobimo instanco razreda SurveyDataFile
+ $sdf = SurveyDataFile::get_instance();
+
+ // Nastavimo spremenljivke, ki so ze nastavljene v razredu SurveyDataFile
+ $this->header_file_name = $sdf->getHeaderFileName();
+ $this->data_file_name = $sdf->getDataFileName();
+ $this->data_file_time = $sdf->getDataFileTime();
+
+ $this->last_update = $sdf->getFileUpdated();
+ $this->fileStatus = $sdf->getStatus();
+ $this->has_test_data = $sdf->getHasTestData();
+ $this->max_usr_time = $sdf->getLastResponseTime();
+
+ $this->collect_all_status = $sdf->getCollectAllStatus();
+
+ if ((int)$this->collect_all_status == 0)
+ $this->is_valid_user_limit = " AND u.last_status IN (5,6) ";
+ else
+ $this->is_valid_user_limit = '';
+
+
+ // Dobimo podatke o anketi
+ $qry_survey = sisplet_query("SELECT *, UNIX_TIMESTAMP(edit_time) AS srv_edit_time FROM srv_anketa WHERE id='".$this->sid."'");
+ $this->survey = mysqli_fetch_assoc($qry_survey);
+
+ // Aktivne tabele za podatke v bazi
+ if ((int)$this->survey['db_table'] == 1)
+ $this->db_table = '_active';
+ else
+ $this->db_table = '';
+
+ // Zadnji cas editiranja ankete
+ $this->max_anketa_time = (int)$this->survey['srv_edit_time'];
+
+ // Ali prisilimo prikaz sistemskih spremenljivk
+ if ($this->survey['show_email'] == 1 || SurveyInfo::getInstance()->checkSurveyModule('360_stopinj'))
+ $this->force_show_hiden_system = true;
+ else
+ $this->force_show_hiden_system = false;
+ }
+
+
+ // Ustvarimo vse nove datoteke s podatki
+ public function createFiles() {
+ global $site_url, $lang, $site_path;
+
+ // Najprej zakesiramo vse podatke
+ $this->cache_data();
+
+ // Zgeneriramo datoteko z naslovno vrstico
+ $CH = (int)$this->createHeadFile();
+
+ // Zgeneriramo datoteko s podatki
+ $CD = (int)$this->createDataFile();
+ }
+
+ // Posodobimo datoteke ker so zastarele
+ public function updateFilesIncremental() {
+ global $site_url, $lang, $site_path;
+
+ // Pobrišemo odvecne response
+ $this->deleteUsers();
+
+ // Zakesiramo vse podatke
+ $this->cache_data();
+
+ // Zgeneriramo datoteko z naslovno vrstico
+ //$CH = (int)$this->createHeadFile();
+
+ // Zgeneriramo datoteko s podatki
+ $CD = (int)$this->createDataFile();
+ }
+
+
+ // Kreiramo datoteko z naslovno vrstico
+ private function createHeadFile() {
+
+ $result = false;
+
+ // za vsak slučaj
+ $this->_HEADER = null;
+
+ // Ce imamo query za vprasanja
+ if ($this->_str_questions !== '') {
+
+ // Izvedemo zbiranje podatkov v $this->_HEADER array
+ $this->CollectHeaders();
+
+ // Zapišemo header datoteko
+ file_put_contents($this->header_file_name, serialize($this->_HEADER));
+ unset($this->_HEADER);
+
+ // Ce ni napak updejtamo zapis v bazi
+ if ($this->noErrors) {
+
+ // data time damo na 0 ker moramo datoteko s podatki zgenerirati čisto na novo.
+ $updated = sisplet_query("INSERT INTO srv_data_files
+ (sid, head_file_time, data_file_time) VALUES ('".$this->sid."', FROM_UNIXTIME('".$this->max_anketa_time."'), '0000-00-00')
+ ON DUPLICATE KEY UPDATE head_file_time = FROM_UNIXTIME('".$this->max_anketa_time."'), data_file_time = '0000-00-00'");
+ sisplet_query("COMMIT");
+
+ if ($updated) {
+ $result = true;
+ }
+ else {
+ $this->trigerError('updateHeader', mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ }
+ else {
+ $this->trigerError('createHeaderFile', 'Not set this->survey[edit_header_time] ('.$this->sid.')');
+ }
+
+ return $result;
+ }
+
+ // Kreiramo datoteko z responsi
+ private function createDataFile() {
+
+ $result = false;
+
+ // Pobrišemo še morebitne prazne vrstice
+ if (IS_WINDOWS) {
+ $cmd1 = 'sed "/^$/d" '.$this->data_file_name.' > '.$this->data_file_name.'.empt && mv '.$this->data_file_name.'.empt '.$this->data_file_name;
+ }
+ else {
+ $cmd1 = 'sed \'/^$/d\' '.$this->data_file_name.' > '.$this->data_file_name.'.empt && mv '.$this->data_file_name.'.empt '.$this->data_file_name;
+ }
+ $out_command1 = shell_exec($cmd1);
+
+ if (file_exists($this->data_file_name.'.empt')) {
+ unlink($this->data_file_name.'.empt');
+ }
+
+ // preverimo ali datoteka obstaja in ali že imamo zapise da prilagodimo line seperator
+ $this->new_line_seperator = null;
+
+ $lines = $this->getLinesCnt();
+
+ if ((int)$lines > 0) {
+ $this->new_line_seperator = NEW_LINE;
+ }
+
+ // Datoteko pripravimo za dodajanje
+ $file_handler = fopen($this->data_file_name, "a");
+
+ if ($this->noErrors) {
+
+ $_tmpCnt = 0;
+
+ // v loopu dodamo podatke v data file
+ if ($this->noErrors && count($this->_str_users) > 0) {
+
+ foreach ($this->_str_users AS $c => $string_user) {
+
+ // Zakesiramo podatke za vse odgovore respondenta
+ $this->cache_data_respondent($string_user);
+
+ // Ce ni errorjev izvedemo zbiranje podatkov
+ if ($this->noErrors) {
+ $this->CollectData($c, $file_handler);
+ }
+
+ $_tmpCnt++;
+ }
+ }
+
+ // Peverimo da res ni prišlo do napak
+ if ($this->noErrors) {
+
+ // Nastavimo cas zadnjega respondenta
+ $sdf = SurveyDataFile::get_instance();
+ $this->max_usr_time = $sdf->setLastResponseTime();
+
+ $updated = sisplet_query("INSERT INTO srv_data_files
+ (sid, data_file_time, last_update ) VALUES ('".$this->sid."', FROM_UNIXTIME('".$this->max_usr_time."'), NOW())
+ ON DUPLICATE KEY UPDATE data_file_time = FROM_UNIXTIME('".$this->max_usr_time."'), last_update = NOW()");
+
+ if ($updated) {
+ $result = true;
+ }
+ else {
+ $this->trigerError('updateDataSql', mysqli_error($GLOBALS['connect_db']));
+ }
+ }
+ }
+
+ // Zapremo datoteko
+ if ($file_handler !== null) {
+ fclose($file_handler);
+
+ // Se enkrat izvedemo generiranje ce imamo filter za uporabnost (ker ga racunamo na podlagi ze obstojece datoteke)
+ if (SurveyStatusProfiles::usabilitySettings()) {
+ $SUR = new SurveyUsableResp($this->sid, $generateDataFile=true);
+
+ // Resetiramo status filter (da izracunamo za vse enote)
+ $SUR->setStatusFilter($status_filter='');
+
+ // Izracunamo uporabnost za vsako enoto
+ $usability = $SUR->calculateData();
+
+ $file_handler_old = fopen($this->data_file_name,"r");
+
+ $data_file_name_new = $this->folder . 'export_data_'.$this->sid.'_2.dat';
+ $file_handler_new = fopen($data_file_name_new,"a");
+
+ // Beremo datoteko vrstico po vrstico
+ $cnt = 1;
+ while (($line = fgets($file_handler_old)) !== false) {
+
+ // dodamo vrstici na koncu uporabnost
+ $usability_status = (isset($usability['data'][$cnt]['status'])) ? $usability['data'][$cnt]['status'] : 0;
+ $line = str_replace($this->new_line_seperator, '', $line);
+ $line .= STR_DLMT . $usability_status;
+
+ fwrite($file_handler_new, $line . $this->new_line_seperator);
+
+ $cnt++;
+ }
+
+ fclose($file_handler_old);
+ fclose($file_handler_new);
+
+ // Pobrisemo staro datoteko
+ unlink($file_handler_old);
+
+ // Preimenujemo novo datoteko
+ rename($data_file_name_new, $this->data_file_name);
+ }
+ }
+
+ // Naredimo še cleanup pointerjev
+ $this->cleanup();
+
+ return $result;
+ }
+
+
+
+ /***** ZBIRANJE PODATKOV ZA DATOTEKO *****/
+
+ /**
+ * Vsako spremenljivko shranimo pod svojim ID-jem
+ * spremenljivka ima enega ali več gridov ( odviso od dimenzi: eno=>(radio, check, vsota...) multi=>(multigrid, multicheck, multibox)
+ * vsak grid pa lahko ima eno ali več variabel (odgovor, tekstovni odgovor... )
+ *
+ * vse skupaj shranjujemo v urejenem arrayu
+ * HEADERS[SPR_ID] => array( tip => tip variable
+ * variable => ime Variable
+ * naslov => Naslov variable
+ * cnt_grids => koliko je gridov
+ * grids[ID] => array(
+ * variables[ID] => array(variable => ime variable
+ * naslov => naslov variable
+ * other => ali je polje drugo
+ * text => ali je tekstovni odgovor
+ * spss => polje za spss
+ * )
+ * )
+ * )
+ */
+ public function CollectHeaders() {
+ global $lang;
+ global $admin_type;
+
+ // v header dodomo userid
+ $sequence = 1; # vodimo zaporedno števiko polja v bazi
+ $_data_sequence = 1; # vodimo zaporedno števiko polja v bazi kjer se začnejo "resni" podatki
+
+
+ // DODATNE NASTAVITVE
+ // Vsi status
+ if ((int)$this->collect_all_status > 0) {
+ $_HEADER['_settings']['collectAllStatus'] = '1';
+ }
+ // Samo ustrezni statusi 6 in 5
+ else {
+ $_HEADER['_settings']['collectAllStatus'] = '0';
+ }
+
+ // Obstajajo testni podatki
+ if ($this->has_test_data == true) {
+ $_HEADER['_settings']['hasTestData'] = '1';
+ }
+ else {
+ $_HEADER['_settings']['hasTestData'] = '0';
+ }
+
+ // Force-amo zbiranje skritih sistemskih vprasanj
+ if ($this->force_show_hiden_system == true) {
+ $_HEADER['_settings']['force_show_hiden_system'] = '1';
+ }
+ else {
+ $_HEADER['_settings']['force_show_hiden_system'] = '0';
+ }
+
+
+ // Preštejemo normalne variable, ki niso sistemske kot je email, ime.... in se v podatkih prikazujejo normalno
+ $_HEADER['_settings']['count_normal_data_variables'] = 0;
+
+ // Preštejemo sistemske kot je email, ime.... in se v podatkih ne smejo prikazovat
+ $_HEADER['_settings']['count_system_data_variables'] = 0;
+
+
+ // user ID
+ $_HEADER['uid']= array ('tip'=>'m', 'variable'=>'uid', 'naslov' =>'User ID',
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'uid', 'naslov'=>'User ID','spss'=>'F11.0','sequence'=>$sequence))
+ ,'naslov'=>'uid','cnt_vars' => 1)));
+ $_HEADER['uid']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // ustreznost uporabnika
+ $_HEADER['relevance']= array ('tip'=>'m', 'variable'=>'relevance', 'naslov' =>$lang['srv_data_relevance'],
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'relevance', 'naslov'=>$lang['srv_data_relevance'],'spss'=>'F3.0','sequence'=>$sequence))
+ ,'naslov'=>$lang['srv_data_relevance'],'cnt_vars' => 1)));
+ $_HEADER['relevance']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // EMAIL VABILO - invitation
+ $_HEADER['invitation']= array ('tip'=>'m', 'variable'=>'invitation', 'naslov' =>$lang['srv_data_invitation'],
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'invitation', 'naslov'=>$lang['srv_data_invitation'],'spss'=>'F3.0','sequence'=>$sequence))
+ ,'naslov'=>$lang['srv_data_invitation'],'cnt_vars' => 1)));
+ $_HEADER['invitation']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // status uporabnika
+ $_HEADER['status']= array ('tip'=>'m', 'variable'=>'status', 'naslov' =>$lang['srv_data_status'],
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'status', 'naslov'=>$lang['srv_data_status'],'spss'=>'F3.0','sequence'=>$sequence))
+ ,'naslov'=>$lang['srv_data_status'],'cnt_vars' => 1)));
+ $_HEADER['status']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // ali je uporabnik lurker
+ $_HEADER['lurker']= array ('tip'=>'m', 'variable'=>'lurker', 'naslov' =>$lang['srv_data_lurker'],
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'lurker', 'naslov'=>$lang['srv_data_lurker'],'spss'=>'F3.0','sequence'=>$sequence))
+ ,'naslov'=>$lang['srv_data_lurker'],'cnt_vars' => 1)));
+ $_HEADER['lurker']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // Cas vnosa
+ $_HEADER['unx_ins_date']= array ('tip'=>'m', 'variable'=>'unx_ins_date', 'naslov' =>'unx_ins_date',
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'unx_ins_date', 'naslov'=>'unx_ins_date','spss'=>'F20.0','sequence'=>$sequence))
+ ,'naslov'=>'unx_ins_date','cnt_vars' => 1)));
+ $_HEADER['unx_ins_date']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // Recnum
+ $_HEADER['recnum'] = array('tip'=>'m', 'variable'=>'recnum', 'naslov' =>'Record number',
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'recnum','naslov'=>'Record number','spss'=>'F5.0','sortType'=>'number','sequence'=>$sequence)),
+ 'naslov'=>'recnum','cnt_vars' => 1)));
+ $_HEADER['recnum']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+ // Dodamo geslo - code
+ if ($this->force_show_hiden_system == true) {
+ $_HEADER['code'] = array('tip'=>'m', 'variable'=>'code', 'naslov' =>'Geslo',
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'code','naslov'=>'Geslo','spss'=>'A6','sequence'=>$sequence)),
+ 'naslov'=>'Geslo','cnt_vars' => 1)));
+ $_HEADER['code']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+ }
+
+ // Ce vsebuje testne podatke dodamo tudi to polje
+ if ($this->has_test_data) {
+ $_HEADER['testdata']= array ('tip'=>'m', 'variable'=>'testdata', 'naslov' =>$lang['srv_data_test'],
+ 'grids' => array(0 => Array('variables'=>array(0 => Array ('variable'=>'testdata', 'naslov'=>$lang['srv_data_test'],'spss'=>'F3.0','sequence'=>$sequence))
+ ,'naslov'=>$lang['srv_data_test'],'cnt_vars' => 1)));
+ $_HEADER['testdata']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+ }
+
+ // date insert (Meta)
+ $_HEADER['itime']= array ('tip'=>'m', 'variable'=>'itime', 'naslov' =>$lang['srv_data_date'],
+ 'grids' => array(0 =>
+ Array('variables'=>array(0 =>
+ Array ('variable'=>'itime', 'naslov'=>$lang['srv_data_date'],'spss'=>'DATETIMEw','sortType'=>'date','sequence'=>$sequence))
+ ,'naslov'=>$lang['srv_data_date'],'cnt_vars' => 1)));
+ $_HEADER['itime']['sequences'] = $sequence;
+ $sequence++;
+ $_data_sequence++;
+
+
+
+ // s katero sekvenco se začnejo podatki
+ $_HEADER['_settings']['dataSequence'] = $_data_sequence;
+
+ // naredimo pointerje na podatke če še ne obstajajo
+ $_array_vrednosti = $this->get_vrednosti(); // za vrednosti ankete
+ $_array_gridi = $this->get_gridi(); // za vrednosti ankete
+
+
+ $cntHs = 0;
+
+ // Stejemo loope za numeric vprasanje
+ $num_loop_cnt = array();
+
+ // dodamo vprašanja ki so v loopu
+ if ($this->noErrors && count($this->AllQuestionsOrder) > 0) {
+
+ foreach ($this->AllQuestionsOrder AS $_vprasanje_array) {
+
+ $cntHs++;
+
+ # dodelimo vrednosti loopa
+ $rowVprasanje = $this->AllQuestionsData[$_vprasanje_array['id']];
+
+ // nastavimo vrstni red ce loopamo po numericu
+ $num_loop_cnt[$_vprasanje_array['id']]++;
+
+ # spremenljivki dodamo loop_id da je konsistentno z podatki
+ $rowVprasanje['spr_id'] = $rowVprasanje['spr_id'].'_'.$_vprasanje_array['loop_id'];
+ $_vrednosti = $this->get_vrednosti($this->_array_loop_on_spr[$rowVprasanje['if_id']]);
+ $_loop_vrednost = $this->_array_vre_on_loop[$rowVprasanje['if_id']][$_vprasanje_array['loop_id']];
+
+ $spr_id = $rowVprasanje['spr_id'];
+ $vrednostLoopSufix = '';
+
+ # popravimo ime variable če smo v loopu
+ if(isset($this->_array_vre_on_loop[$rowVprasanje['if_id']][$_vprasanje_array['loop_id']])) {
+
+ // Posebej obravnavamo loop po numeric vprasanju - samo nastavimo suffix _1, _2...
+ if($this->_array_vre_on_loop[$rowVprasanje['if_id']][$_vprasanje_array['loop_id']] == 'num_loop'){
+ $rowVprasanje['variable'] = strip_tags($rowVprasanje['variable'])."_".$num_loop_cnt[$_vprasanje_array['id']];
+ }
+ else{
+ # id spremenljivke po kateri loopamo
+ $_loop_on_spr_id = $this->_array_loop_on_spr[$rowVprasanje['if_id']];
+
+ #variabla spremenljivke po kateri loopamo
+ $_loop_on_spr_variable = $this->AllQuestionsData[$_loop_on_spr_id]['variable'];
+
+ # id variable po kateri loopamo (v okviru $_loop_on_spr_id)
+ $_loop_on_variable_id = $_vrednosti[$_loop_vrednost];
+
+ # naslov variable po keteri loopamo (v okviru $_loop_on_spr_id)
+ $_vrednost_naslov = $_array_vrednosti[$_loop_on_spr_id][$_loop_on_variable_id['id']]['naslov'];
+ $rowVprasanje['variable'] = strip_tags($rowVprasanje['variable'])."_".$_vrednosti[$_loop_vrednost]['variable'];
+ $vrednostLoopSufix = "_".$_vrednosti[$_loop_vrednost]['variable'];
+
+ if ($_vrednost_naslov != '' && $_loop_on_spr_variable != '' && $rowVprasanje['naslov'] != '') {
+ # zamenjamo ime spremenljivke med #q1# (#q1# z naslovom trenutne variable)
+ $rowVprasanje['naslov'] = str_replace("#$_loop_on_spr_variable#", "$_vrednost_naslov", $rowVprasanje['naslov']);
+ }
+ }
+ }
+
+ # pomožne variable
+ $tip = $rowVprasanje['tip'];
+ $_tmp_spr_id = explode('_',$rowVprasanje['spr_id']);
+ $spr_id = $_tmp_spr_id[0];
+ $spr_data_id = $rowVprasanje['spr_id'];
+
+ // Pri kalkulaciji izpisemo labelo v imenu, ce jo imamo
+ $spr_naslov = ($tip == '22' && $rowVprasanje['label'] != '') ? strip_tags($rowVprasanje['label']) : strip_tags($rowVprasanje['naslov']);
+
+ $spr_naslov_graf = strip_tags($rowVprasanje['naslov_graf']);
+ $spr_edit_graf = $rowVprasanje['edit_graf'];
+ $spr_wide_graf = $rowVprasanje['wide_graf'];
+ $spr_antonucci = $rowVprasanje['antonucci'];
+ $spr_variable = strip_tags($rowVprasanje['variable']);
+ $spr_size = $rowVprasanje['size'];
+ $spr_cela = $rowVprasanje['cela'];
+ $grid_subtitle1 = $rowVprasanje['grid_subtitle1'];
+ $grid_subtitle2 = $rowVprasanje['grid_subtitle2'];
+ $spr_decimalna = $rowVprasanje['decimalna'];
+ $spr_skala = $rowVprasanje['skala'];
+ $spr_sistem = $rowVprasanje['sistem'];
+ $spr_upload = $rowVprasanje['upload'];
+ $spr_signature = $rowVprasanje['signature'];
+ $spr_random = $rowVprasanje['random'];
+
+ #!!! po novem tako ali tako število znakov za spss lovimo iz datoteke s podatki
+
+ # TODO $spss_lngth mora biti enak za vse in sicer je enak največjemu možnemu številu znakov
+ # TODO zato je potrebno zdužit vse ($spss_lngth, $spss_lngth2, $spss_lngth3)
+ $spss_lngth = $this->_array_SPSS[$spr_id]['text'];
+ $spss_lngth2 = $this->_array_SPSS[$spr_id]['text2'];
+ $spss_lngth3 = isset($this->_array_SPSS[$spr_id]['vrednost']) && $this->_array_SPSS[$spr_id]['vrednost'] != '' ? $this->_array_SPSS[$spr_id]['vrednost'] : 0;
+
+ $_HEADER[$spr_data_id] = array('spr_id'=>$spr_id, 'tip'=>$tip, 'variable'=>$spr_variable, 'naslov'=>$spr_naslov, 'sistem'=>$spr_sistem, 'skala'=>$spr_skala, 'naslov_graf'=>$spr_naslov_graf, 'edit_graf'=>$spr_edit_graf, 'wide_graf'=>$spr_wide_graf);
+ # kontrola sistemskih skritih spremenljivk
+ # kadar ne vsilimo prikaza sistemskih spremenljivk (lahko omogoči le admin)
+ if ($this->force_show_hiden_system == false
+ && $spr_sistem == '1'
+ && in_array($spr_variable,unserialize (SYSTEM_VARIABLES)) # unserialize (SYSTEM_VARIABLES) -> definition.php = array('email','telefon','ime','priimek','naziv','drugo')
+ # pri formi ali glasovanjzu prikazujemo tudi sistemske
+ && ( $this->survey['survey_type'] != 1 && $this->survey['survey_type'] != 0)) {
+
+ $_HEADER[$spr_data_id]['hide_system'] = '1';
+
+ # povečamo števec sistemskih variabel
+ $_HEADER['_settings']['count_system_data_variables'] ++;
+ } else {
+ # povečamo števec normalnih
+ $_HEADER['_settings']['count_normal_data_variables'] ++;
+ }
+
+ # če je sistemska variabla jo označimo
+ if (in_array($spr_variable,unserialize (SYSTEM_VARIABLES))) {
+ $_HEADER[$spr_data_id]['is_system'] = '1';
+ }
+
+ if ( $spr_upload == '1' || $spr_upload == '2') {
+ $_HEADER[$spr_data_id]['upload'] = '1';
+ }
+
+ if ( $spr_signature == '1' ) {
+ $_HEADER[$spr_data_id]['signature'] = '1';
+ }
+
+ if (isset($rowVprasanje['enota']) && $rowVprasanje['enota'] > 0) {
+ $_HEADER[$spr_data_id]['enota'] = $rowVprasanje['enota'];
+ }
+
+ # dodoamo loop parent
+ if (isset($rowVprasanje['loop_parent']) && $rowVprasanje['loop_parent'] > 0) {
+ $_HEADER[$spr_data_id]['loop_parent'] = $rowVprasanje['loop_parent'];
+ $_HEADER[$spr_data_id]['antonucci'] = $rowVprasanje['antonucci'];
+ }
+
+ # dodoamo parent loop id
+ if (isset($_vprasanje_array['parent_loop_id']) && $_vprasanje_array['parent_loop_id'] > 0) {
+ $_HEADER[$spr_data_id]['parent_loop_id'] = $_vprasanje_array['parent_loop_id'];
+ }
+ # Dodamo še loop id
+ $_HEADER[$spr_data_id]['loop_id'] = $_vprasanje_array['loop_id'];
+
+ $_GRIDS = array();
+ $_seq_prefix = '';
+ $_sequences = '';
+
+ // v odvisnosti od tipa vprašanja pohandlamo podatke
+ switch ( $tip ) {
+
+ # RADIO
+ case 1:
+ # DROPDOWN
+ case 3:
+ $cnt=0;
+ # dodamo header variable
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$spr_naslov, 'variable'=>$spr_variable, 'other'=>false,'text'=>false,'spss'=>'F'.$spss_lngth3.'.0','sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+
+ if (count($arrayVrednost)>0) {
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+ # dodamo še eno polje za tekstovne odgovore drugo
+ if ($vrednost['other'] == 1) {
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],'naslov'=>$vrednost['naslov'],
+ 'variable'=>$spr_variable.'_'.$vrednost['vrstni_red'].STR_OTHER_TEXT, 'other'=>true,'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_GRIDS[0]['cnt_other'] += 1;
+ } // end if
+ #dodamo opcije (za spss)
+ if ($vrednost['other'] == 0 || $vrednost['other'] == 1) {
+ $_HEADER[$spr_data_id]['options'][$vrednost['variable']] = ($vrednost['naslov'] != null) ? $vrednost['naslov'] : $vrednost['variable'];
+ $_HEADER[$spr_data_id]['options_graf'][$vrednost['variable']] = ($vrednost['naslov_graf'] != null) ? $vrednost['naslov_graf'] : $_HEADER[$spr_data_id]['options'][$vrednost['variable']];
+ }
+ } // end foreach
+
+ } // end if
+
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_HEADER[$spr_data_id]['cnt_all'] = $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+
+ if (isset($rowVprasanje['inline_edit'])) $_HEADER[$spr_data_id]['inline_edit'] = $rowVprasanje['inline_edit'];
+ break;
+
+
+ # CHECKBOX
+ case 2:
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ $cnt=0;
+ if (count($arrayVrednost)>0) {
+ foreach ($arrayVrednost as $vrednost) {
+
+ # dodamo header variable samo za ne -missing variable
+ if ($vrednost['other'] == 0 || $vrednost['other'] == 1) {
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'], 'naslov'=>$vrednost['naslov'], 'variable'=>$vrednost['variable'].$vrednostLoopSufix, 'other'=>false,'text'=>false,'spss'=>'F'.$spss_lngth3.'.0','sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ #dodamo še header za polja drugo
+ if ($vrednost['other'] == 1) {
+ // dodamo v array 'variables'
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'], 'naslov'=>$vrednost['naslov'], 'variable'=>$vrednost['variable'].$vrednostLoopSufix.STR_OTHER_TEXT, 'other'=>true,'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_GRIDS[0]['cnt_other'] += 1;
+ } // end if
+ }
+ } // end foreach
+ } // end if
+
+ #dodamo opcije (za spss)
+ $_HEADER[$spr_data_id]['options']['0'] = '0';
+ $_HEADER[$spr_data_id]['options']['1'] = '1';
+
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_HEADER[$spr_data_id]['cnt_all'] = $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # TEXT
+ case 4:
+ $cnt=0;
+ # dodamo header variable
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$spr_naslov, 'variable'=>$spr_variable, 'other'=>false, 'text'=>true, 'spss'=>'A'.$spss_lngth,'sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_HEADER[$spr_data_id]['cnt_all'] = $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # MULTIRADIO
+ case 6:
+ # ali je dvojni grid
+ $double = (int)($rowVprasanje['enota'] == 3);
+
+ $double_data = array();
+ # Pri multigridu je logika obratna. variable predstavljajo podvprašanja, srv_grid pa odgovore
+ $cntGrid = 0;
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost)>0) {
+ # če imamo dvojni grid gremo 2_skozi
+ for ($i=1; $i<=$double+1;$i++) {
+ // for $double
+ $double_data[$i]['subtitle'] = $rowVprasanje['grid_subtitle'.$i];
+ if ($double == 1) {
+ $var_appendix = '_'.$i;
+ } else {
+ $var_appendix = '';
+ }
+ $part = $i;
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+
+ // Za kombinirane tabele popravimo ime variable
+ if($rowVprasanje['gru_id'] == -2){
+ $arr = explode("_", $spr_variable, 2);
+ $sprVar = $arr[0];
+ $vrednost['variable'] = $sprVar.'_'.$vrednost['variable'];
+ }
+
+ # dodamo header samo za nemissing variable
+ if ($vrednost['other'] == 0 || $vrednost['other'] == 1) {
+ $cnt = 0;
+ $_GRIDS[$cntGrid]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],
+ 'naslov'=>$vrednost['naslov'],
+ 'naslov2'=>$vrednost['naslov2'],
+ 'variable'=>$vrednost['variable'].$var_appendix.$vrednostLoopSufix,
+ 'other'=>false,
+ 'text'=>false,
+ 'spss'=>'F'.$spss_lngth3.'.0','sequence'=>$sequence,
+ 'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ if ($vrednost['other'] == 1) {
+ $_GRIDS[$cntGrid]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],'naslov'=>$vrednost['naslov'], 'variable'=>$vrednost['variable'].$var_appendix.$vrednostLoopSufix.STR_OTHER_TEXT, 'other'=>true,'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_GRIDS[$cntGrid]['cnt_other'] += 1;
+ } // end if
+ $_GRIDS[$cntGrid]['cnt_vars'] = $cnt;
+ $_GRIDS[$cntGrid]['naslov'] = $vrednost['variable'].$var_appendix;
+ $_GRIDS[$cntGrid]['part'] = $i;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $cntGrid++;
+ }
+ } // end foreach
+
+ } // end for $double
+ } // end if
+
+ #dodamo opcije (za spss)
+ $arrayGrids = $_array_gridi[$spr_id];
+ if (count($arrayGrids) > 0) {
+ foreach ($arrayGrids AS $kid => $grid) {
+ if ($grid['other'] == 0 || $grid['other'] == 1) {
+ $_HEADER[$spr_data_id]['options'][$grid['variable']] = ($grid['naslov'] != null) ? $grid['naslov'] : $grid['variable'];
+ // Opcije za dodaten naslov grida pri grafu
+ $_HEADER[$spr_data_id]['options_graf'][$grid['variable']] = ($grid['naslov_graf'] != null) ? $grid['naslov_graf'] : $_HEADER[$spr_data_id]['options'][$grid['variable']];
+ }
+ }
+ }
+
+ $_HEADER[$spr_data_id]['cnt_grids'] = $cntGrid;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+
+ if ($double == 1) {
+ $_HEADER[$spr_data_id]['double'] = $double_data;
+ }
+ break;
+
+
+ # NUMBER
+ case 7:
+
+ # pri number lahko imamo dve variabli grida, če je size 2
+ $cnt_v = 0;
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost) > 0) {
+ $cnt=0;
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+ if ($vrednost['other'] == 0) {
+
+ if ($spr_size > 1) {
+ # če imamo več variabel
+ $_variable = $vrednost['variable'].$vrednostLoopSufix;
+ }
+ else { #imamo samo eno variablo
+ $_variable = $spr_variable.$vrednostLoopSufix;
+ }
+
+ // Ce nimamo enote je naslov enak naslovu vprasanja
+ if(!isset($rowVprasanje['enota']) || $rowVprasanje['enota'] == 0)
+ $vrednost['naslov'] = $spr_naslov;
+
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'], 'naslov'=>$vrednost['naslov'], 'variable'=>$_variable, 'other'=>false, 'text'=>false,'spss'=>'F'.($spr_cela+$spr_decimalna).($spr_decimalna > 0 ? ('.'.$spr_decimalna) : '.0'),'sortType'=>'number','sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt_v++;
+ $cnt++;
+ } // end if
+
+ } // end foreach
+ $_GRIDS[0]['cnt_vars'] = $cnt_v;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+
+ } // end if
+ $_GRIDS[0]['enota'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt_v;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # DATUM
+ case 8:
+ $cnt=0;
+
+ # dodamo header variable
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$spr_naslov, 'variable'=>$spr_variable, 'other'=>false, 'text'=>true,'spss'=>'A10','sortType'=>'date','sequence'=>$sequence);
+
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # MULTICHECKBOX
+ case 16:
+ # MULTITEXT
+ case 19:
+ # MULTINUMBER
+ case 20:
+ // srv_variable predstavljajo podvprašanja, srv_grid pa možne pododkovore
+ $_spss = ($tip == 16)
+ ? 'F'.$spss_lngth3.'.0'
+ : (($tip == 19)
+ ? 'A'.$spss_lngth2
+ : 'F'.($spr_cela+$spr_decimalna).($spr_decimalna > 0 ? ('.'.$spr_decimalna) : '.0'));
+
+ $row = Cache::srv_spremenljivka($spr_id);
+ $newParams = new enkaParameters($row['params']);
+ $is_datum = $newParams->get('multigrid-datum');
+ #'sortType'=>'date'
+ $grid_id=0;
+
+ $arrayGrids = $_array_gridi[$spr_id];
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost) > 0) {
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+
+ // Za kombinirane tabele popravimo ime variable
+ if($rowVprasanje['gru_id'] == -2){
+ $arr = explode("_", $spr_variable, 2);
+ $sprVar = $arr[0];
+ $vrednost['variable'] = $sprVar.'_'.$vrednost['variable'];
+ }
+
+ $cnt=0;
+ if (count($arrayGrids) > 0) {
+ foreach ($arrayGrids AS $kid => $grid) {
+ if ($grid['other'] == 0 || $grid['other'] == 1) {
+ $_GRIDS[$grid_id]['variables'][$cnt] = array('vr_id'=>$vrednost['id'], 'gr_id'=>$grid['id'], 'naslov'=>$grid['naslov'], 'variable'=>$vrednost['variable'].'_'.$grid['variable'].$vrednostLoopSufix, 'other'=>false, 'text'=>false,'spss'=>$_spss,'sequence'=>$sequence,'naslov_graf'=>$grid['naslov_graf']);
+
+ if((int)$is_datum === 1) {
+ $_GRIDS[$grid_id]['variables'][$cnt]['sortType'] ='date';
+ }
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ }
+ } // end foreach
+ if ($vrednost['other'] == 1) {
+ $_GRIDS[$grid_id]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],'naslov'=>$vrednost['naslov'], 'variable'=>$vrednost['variable'].$vrednostLoopSufix.STR_OTHER_TEXT, 'other'=>true,'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_GRIDS[$grid_id]['cnt_other'] += 1;
+ } // end if
+
+ } // end if
+
+ $_GRIDS[$grid_id]['cnt_vars'] = $cnt;
+ $_GRIDS[$grid_id]['naslov'] = $vrednost['naslov'];
+ $_GRIDS[$grid_id]['variable'] = $vrednost['variable'];
+ $_GRIDS[$grid_id]['naslov_graf'] = $vrednost['naslov_graf'];
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $grid_id++;
+ } // end foreach
+ } // end if
+
+ if ($tip == 16) {
+ #dodamo opcije (za spss)
+ $_HEADER[$spr_data_id]['options']['0'] = '0';
+ $_HEADER[$spr_data_id]['options']['1'] = '1';
+ }
+
+ $_HEADER[$spr_data_id]['cnt_grids'] = $grid_id;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # RANKING
+ case 17:
+ # VSOTA
+ case 18:
+ $_spss = ($tip == 17)
+ ? 'F'.$spss_lngth3.'.0'
+ : 'F'.($spr_cela+$spr_decimalna).($spr_decimalna > 0 ? ('.'.$spr_decimalna) : '.0');
+
+ $cnt=0;
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost) > 0) {
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],'naslov'=>$vrednost['naslov'], 'variable'=>$vrednost['variable'].$vrednostLoopSufix, 'other'=>false, 'text'=>false,'spss'=>$_spss,'sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ if ($tip == 17) {
+ $_HEADER[$spr_data_id]['options'][$vrednost['vrstni_red']] = $vrednost['vrstni_red'];
+ }
+ } // end foreach
+ } // end if
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0][ 'cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # BESEDILO*
+ case 21:
+ $cnt=0;
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost) > 0) {
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+ if ($vrednost['other'] == 0) {
+
+ $_variable = (count($arrayVrednost) == 1)
+ ? $spr_variable
+ : $vrednost['variable'].$vrednostLoopSufix ;
+ $_naslov = (trim($vrednost['naslov']) != '' && trim($vrednost['naslov']) != $lang['srv_new_text']) ? $vrednost['naslov'] : $spr_naslov;
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],'naslov'=>$_naslov, 'variable'=>$_variable, 'other'=>false, 'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ } // end if
+ } // end foreach
+ } // end if
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # KALKULACIJA
+ case 22:
+ $cnt=0;
+ # dodamo header variable
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$spr_naslov, 'variable'=>$spr_variable, 'other'=>false, 'text'=>true,'spss'=>'F'.$spss_lngth.'.0','sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # KVOTA
+ case 25:
+ $cnt=0;
+ # dodamo header variable
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$spr_naslov, 'variable'=>$spr_variable, 'other'=>false, 'text'=>true,'spss'=>'F'.$spss_lngth.'.0','sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # SN - IMENA
+ case 9:
+ $cnt=0;
+ $arrayVrednost = $this->SNVariablesForSpr[$_vprasanje_array['id']];
+ if (count($arrayVrednost) > 0) {
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost,'naslov'=>($spr_variable.'_'.($cnt+1)), 'variable'=>($spr_variable.'_'.($cnt+1)), 'other'=>false, 'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ } // end foreach
+ } // end if
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ break;
+
+
+ # Lokacija
+ case 26:
+ $row = Cache::srv_spremenljivka($spr_id);
+
+ if($row['enota'] == 3){
+ $cnt=0;
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost) > 0) {
+ foreach ($arrayVrednost as $kid=> $vrednost) {
+ if ($vrednost['other'] == 0) {
+
+ $_variable = (count($arrayVrednost) == 1) ? $spr_variable
+ : $vrednost['variable'].$vrednostLoopSufix ;
+ $_naslov = (trim($vrednost['naslov']) != '' && trim($vrednost['naslov']) != $lang['srv_new_text']) ? $vrednost['naslov'] : $_variable;
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'],'naslov'=>$_naslov, 'variable'=>$_variable, 'other'=>false, 'text'=>true,'spss'=>'A'.$spss_lngth,'sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ } // end if
+ } // end foreach
+ } // end if
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_GRIDS[0]['cnt_vars'] = $cnt;
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_all'] += $cnt;
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ }
+ else{
+ $newParams = new enkaParameters($row['params']);
+ $is_podvprasanje = $newParams->get('marker_podvprasanje') == 1;
+ $multi_input_type = $newParams->get('multi_input_type');
+ if($multi_input_type == 'marker'){
+ $arrayNaslovov = ($is_podvprasanje) ?
+ array(array('naslov' => $lang['srv_data_column_naslov_map'], 'variable' => $spr_variable.'a'),
+ array('naslov' => $lang['srv_data_column_vrednost_map'], 'variable' => $spr_variable.'b'),
+ array('naslov' => $lang['srv_data_column_koordinate_map'], 'variable' => $spr_variable.'c'))
+ : array(array('naslov' => $lang['srv_data_column_naslov_map'], 'variable' => $spr_variable.'a'),
+ array('naslov' => $lang['srv_data_column_koordinate_map'], 'variable' => $spr_variable.'b'));
+ }
+ else
+ $arrayNaslovov = array(array('naslov' => $lang['srv_data_column_koordinate_map'], 'variable' => $spr_variable.'a'));
+
+ //kot grid
+ $cnt=0;
+ # dodamo header variable
+ foreach($arrayNaslovov as $naslo){
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$naslo['naslov'], 'variable'=>$naslo['variable'], 'other'=>false, 'text'=>true, 'spss'=>'A'.$spss_lngth,'sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+
+ $cnt++;
+ }
+ //$cnt++;
+ $_GRIDS[0]['cnt_vars'] = count($arrayNaslovov);
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_grids'] = count($arrayNaslovov);
+ $_HEADER[$spr_data_id]['cnt_all'] = count($arrayNaslovov);
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+ }
+ break;
+
+
+ # HEATMAP
+ case 27:
+ $arrayNaslovov = array($lang['srv_data_column_koordinate_map']);
+ //kot grid
+ $cnt=0;
+ # dodamo header variable
+ foreach($arrayNaslovov as $naslo){
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>null, 'naslov'=>$naslo, 'variable'=>$spr_variable, 'other'=>false, 'text'=>true, 'spss'=>'A'.$spss_lngth,'sequence'=>$sequence);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ }
+ //checkbox vrednosti za imena obmocij
+ $arrayVrednost = $_array_vrednosti[$spr_id];
+ if (count($arrayVrednost)>0) {
+ foreach ($arrayVrednost as $vrednost) {
+
+ # dodamo header variable samo za ne -missing variable
+ if ($vrednost['other'] == 0 || $vrednost['other'] == 1) {
+ $_GRIDS[0]['variables'][$cnt] = array('vr_id'=>$vrednost['id'], 'naslov'=>$vrednost['naslov'], 'variable'=>$vrednost['variable'].$vrednostLoopSufix, 'other'=>false,'text'=>false,'spss'=>'F'.$spss_lngth3.'.0','sequence'=>$sequence,'naslov_graf'=>$vrednost['naslov_graf']);
+ $_sequences .= $_seq_prefix.$sequence;
+ $_seq_prefix = '_';
+ $sequence++;
+ $cnt++;
+ #dodamo še header za polja drugo
+ }
+ } // end foreach
+ } // end if
+ //checkbox vrednosti za imena obmocij - konec
+ #dodamo opcije (za spss)
+ $_HEADER[$spr_data_id]['options']['0'] = '0';
+ $_HEADER[$spr_data_id]['options']['1'] = '1';
+
+
+ $_GRIDS[0]['cnt_vars'] = $cnt; //stevilo stolpcev pod enim vprasanjem
+ $_GRIDS[0]['naslov'] = $spr_variable;
+ $_HEADER[$spr_data_id]['cnt_grids'] = 1;
+ $_HEADER[$spr_data_id]['cnt_all'] = $cnt; //koliko stolpcev mora pokriti naslov tega vprasanja
+ $_HEADER[$spr_data_id]['sequences'] = $_sequences;
+
+ break;
+ }
+
+ $_HEADER[$spr_data_id]['grids'] = $_GRIDS;
+ } // end foreach ($this->AllQuestionsOrder AS $_vprasanje_array) {
+ } // end if (count($this->AllQuestionsOrder) > 0)
+
+
+ // DODAMO SPECIAL META
+ // s katero sekvenco se začnejo meta podatki
+ $_HEADER['_settings']['metaSequence'] = $sequence;
+
+ $_HEADER['meta'] = array('tip'=>'sm', 'variable'=>'smeta', 'naslov' =>$lang['srv_displaydata_meta'],'cnt_all'=>2);
+
+ // Datum insert, datum edit, datume in čase za posamezno stran
+ $_g_cnt = 0;
+ $_tmp_seq = $sequence;
+
+ // Na zacetku prikazemo randomizacijo ce je prisotna pri kaksnem vprasanju ali bloku
+ foreach ($this->_array_random as $random_parent) {
+
+ if($random_parent['type'] == 'spr'){
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'Random '.$random_parent['variable']);
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][0] = Array ('variable'=>'random_'.$random_parent['id'],'naslov'=>$random_parent['variable'],'sequence'=>$sequence);
+ $_g_cnt++;
+ $sequence++;
+ }
+ elseif($random_parent['type'] == 'blok_spr'){
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'Random B'.$random_parent['number']);
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][0] = Array ('variable'=>'random_'.$random_parent['id'],'naslov'=>'B'.$random_parent['number'],'sequence'=>$sequence);
+ $_g_cnt++;
+ $sequence++;
+ }
+ elseif($random_parent['type'] == 'blok_blok'){
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'Random B'.$random_parent['number']);
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][0] = Array ('variable'=>'random_'.$random_parent['id'],'naslov'=>'B'.$random_parent['number'],'sequence'=>$sequence);
+ $_g_cnt++;
+ $sequence++;
+ }
+ }
+
+ // če mamo da prepozna uporabnika iz sispleta
+ if ((int)$this->survey['user_from_cms'] > 0) {
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'E-mail iz CMS');
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][0] = Array ('variable'=>'usr_from_cms','naslov'=>'E-mail iz CMS','spss'=>'A256','sequence'=>$sequence);
+ $sequence++;
+ $_g_cnt ++;
+ }
+
+ // datum
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>$lang['date']);
+
+ // time insert
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][0] = Array ('variable'=>'t_insert','naslov'=>$lang['date_insert'],'spss'=>'DATETIMEw','sortType'=>'date','sequence'=>$sequence);
+ $sequence++;
+
+ // time header
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][1] = Array ('variable'=>'t_edit','naslov'=>$lang['date_edit'],'spss'=>'DATETIMEw','sortType'=>'date','sequence'=>$sequence);
+ $sequence++;
+
+ // dodamo št. variabel na grupo
+ $_HEADER['meta']['grids'][$_g_cnt]['cnt_vars'] = 2;
+ $_g_cnt ++;
+
+ # datumi in časi po posameznih straneh
+ # zaloopamo skozi strani
+
+ // zaloopamo skozi strani
+ $page = 1;
+ foreach ($this->_array_groups as $gid => $grupa) {
+
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>$lang['page'].' '.$page);
+
+ # date on page
+ $_HEADER['meta']['grids'][$_g_cnt]['variables'][0] = Array ('variable'=>'date_'.$page,'naslov'=>'datum_'.$page,'spss'=>'DATETIMEw','sortType'=>'date','sequence'=>$sequence);
+ $sequence++;
+
+ $_HEADER['meta']['grids'][$_g_cnt]['cnt_vars'] = 1;
+
+ $page++;
+ $_g_cnt++;
+ }
+
+ // IP
+ $ip = SurveySetting::getInstance()->getSurveyMiscSetting('survey_ip');
+ $ip_show = SurveySetting::getInstance()->getSurveyMiscSetting('survey_show_ip');
+ if($ip==0 && $ip_show==1 && ($admin_type == 0 || $admin_type == 1)){
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'IP',
+ 'variables' => array( 0 => Array ('variable'=>'IP','naslov'=>'IP','spss'=>'A32','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+ }
+
+ // Browser
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>$lang['browser'],
+ 'variables' => array( 0 => Array ('variable'=>'Browser','naslov'=>$lang['browser'],'spss'=>'A256','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // Browser version
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>$lang['browser_version'],
+ 'variables' => array( 0 => Array ('variable'=>'BrowserVersion','naslov'=>$lang['browser_version'],'spss'=>'A256','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // OS
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'OS',
+ 'variables' => array( 0 => Array ('variable'=>'OS','naslov'=>$lang['srv_para_graph_os'],'spss'=>'A256','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // Device
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>$lang['srv_para_graph_device'],
+ 'variables' => array( 0 => Array ('variable'=>'Device','naslov'=>$lang['srv_para_graph_device'],'spss'=>'A256','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // Referer
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'Referer',
+ 'variables' => array( 0 => Array ('variable'=>'Referer','naslov'=>'Referer','spss'=>'A256','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // unsubscribed
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>'Unsubscribed',
+ 'variables' => array( 0 => Array ('variable'=>'Unsubscribed','naslov'=>'Unsubscribed','spss'=>'A2','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // jezik - language
+ $_HEADER['meta']['grids'][$_g_cnt] = Array('naslov'=>$lang['lang'],
+ 'variables' => array( 0 => Array ('variable'=>'Language','naslov'=>$lang['lang'],'spss'=>'A256','sequence'=>$sequence)));
+ $sequence++; $_g_cnt++;
+
+ // dodamo št. variabel za celotno skupino
+ $_HEADER['meta']['cnt_all'] = $sequence - $_tmp_seq;
+
+
+ // USABILITY - ce vsebuje nastavitev da filtriramo po uporabnosti dodamo tudi to polje
+ if (SurveyStatusProfiles::usabilitySettings()) {
+ $_HEADER['usability'] = Array('naslov'=>$lang['srv_usableResp_usability'],
+ 'variables' => array( 0 => Array ('variable'=>'Usability','naslov'=>$lang['srv_usableResp_usability'],'spss'=>'A2','sequence'=>$sequence)));
+
+ $sequence++;
+ }
+
+ $this->_HEADER = $_HEADER;
+ }
+
+ // Zbiramo podatke
+ public function CollectData($c, $file_handler) {
+ global $site_path, $site_url, $lang, $admin_type;
+
+ # osvežimo podatke
+ if (mysqli_num_rows($this->_qry_users[$c]) > 0) {
+ mysqli_data_seek($this->_qry_users[$c], 0);
+ }
+
+ $_tmpCnt = $c * MAX_USER_PER_LOOP;
+
+ $_dataLine = "";
+
+ // Dobimo vse jezike za katere obstaja jezikovna datoteka
+ include_once($site_path.'lang/jeziki.php');
+ $jeziki = $lang_all_global['ime'];
+ // lang od 0 je privzet
+ $jeziki[0] = $lang['language'];
+ $jeziki[$lang['id']] = $lang['language'];
+
+ if ($this->noErrors) {
+
+ while ($rowUser = mysqli_fetch_assoc($this->_qry_users[$c])) {
+
+ #sleep(1);
+ $_tmpCnt++;
+
+ $uid = $rowUser['usr_id'];
+ # dodamo usr id k podatkom
+ $_dataLine .= $rowUser['usr_id'];
+
+ # dodamo ustreznost k podatkom - relevance
+ $_dataLine .= STR_DLMT. (($rowUser['status'] == 5 || $rowUser['status'] == 6) && $rowUser['lurker'] == 0 ? '1' : '0');
+
+ # dodamo email (invitation)k podatkom - če je bilo poslano z emailom ali je uporabnik ročno vnesel email
+ $_dataLine .= STR_DLMT. ((int)$rowUser['inv_res_id'] > 0 || (int)$rowUser['inv_res_id'] == -1
+ # uporabnik je bil dodan z email vabilom
+ ? ((int)$rowUser['status'] == 1 || (int)$rowUser['status'] >= 3
+ # email je bil odposlan
+ ? '1'
+ # email ni bil odposlan ali je bila napaka
+ : '2')
+ # uporabnik ni bil dodan z email vabilom
+ : '0');
+
+ # dodamo status k podatkom
+ $_dataLine .= STR_DLMT.$rowUser['status'];
+
+ # dodamo lurkerje
+ $_dataLine .= STR_DLMT.$rowUser['lurker'];
+
+ #dodamo unx_ins_date
+ $_dataLine .= STR_DLMT.max($rowUser['unx_ins_date'],$rowUser['unx_edt_date']);
+
+ #dodamo recnum
+ $_dataLine .= STR_DLMT.$rowUser['recnum'];
+
+ #dodamo geslo
+ if ($this->force_show_hiden_system == true) {
+ $_dataLine .= STR_DLMT.$rowUser['pass'];
+ }
+
+ # če vsebuje testne podatke dodamo tudi kolono z tem statusom
+ if ($this->has_test_data) {
+ $_dataLine .= STR_DLMT.(int)$rowUser['testdata'];
+ }
+
+ # dodamo insert time k podatkom
+ $_dataLine .= STR_DLMT.date("d.m.Y",strtotime($rowUser['time_insert']));
+
+ #dodamo uporabnikove podatke
+ # zloopamo skozi vprašanja
+
+ # dodamo vprašanja ki so v loopu
+ $userAnswerLine = '';
+
+ #resetiramo
+ $this->_user_spr_answer_count = array('cnt'=>0, 'last'=>0, 'spremenljivke'=>array());
+ $pages = array();
+ if ($this->noErrors && count($this->AllQuestionsOrder) > 0) {
+ foreach ($this->AllQuestionsOrder AS $_vprasanje_array) {
+
+ $rowVprasanje = $this->AllQuestionsData[$_vprasanje_array['id']];
+
+ # spremenljivki dodamo loop_id da je konsistentno z podatki
+ $rowVprasanje['spr_id'] = $rowVprasanje['spr_id'].'_'.$_vprasanje_array['loop_id'];
+ if (isset($this->_array_loop_on_spr[$rowVprasanje['if_id']])) {
+ $_vrednosti = $this->get_vrednosti($this->_array_loop_on_spr[$rowVprasanje['if_id']]);
+ }
+
+ if(isset($this->_array_vre_on_loop[$rowVprasanje['if_id']][$_vprasanje_array['loop_id']])) {
+ $_loop_vrednost = $this->_array_vre_on_loop[$rowVprasanje['if_id']][$_vprasanje_array['loop_id']];
+ }
+
+ # popravimo ime variable če smo v loopu
+ if(isset($this->_array_vre_on_loop[$rowVprasanje['if_id']][$_vprasanje_array['loop_id']])) {
+ $rowVprasanje['variable'] = strip_tags($rowVprasanje['variable'])."_".$_vrednosti[$_loop_vrednost]['variable'];
+ }
+
+ # pomožne variable
+ $tip = $rowVprasanje['tip'];
+ $_tmp_spr_id = explode('_',$rowVprasanje['spr_id']);
+ $spr_id = $_tmp_spr_id[0];
+ $spr_data_id = $rowVprasanje['spr_id'];
+ $spr_naslov = strip_tags($rowVprasanje['naslov']);
+ $spr_variable = strip_tags($rowVprasanje['variable']);
+ $spr_size = $rowVprasanje['size'];
+ $spr_cela = $rowVprasanje['cela'];
+ $grid_subtitle1 = $rowVprasanje['grid_subtitle1'];
+ $grid_subtitle2 = $rowVprasanje['grid_subtitle2'];
+ $spr_decimalna = $rowVprasanje['decimalna'];
+ $spr_skala = $rowVprasanje['skala'];
+ $spr_sistem = $rowVprasanje['sistem'];
+ $spr_page = $rowVprasanje['gru_id'];
+ $spr_upload = $rowVprasanje['upload'];
+ $spr_signature = $rowVprasanje['signature'];
+ $spr_visible = $rowVprasanje['visible'];
+ $spr_dostop = $rowVprasanje['dostop'];
+ $pages[$spr_page] = true;
+
+ # ponastavimo katere vrednosti se beležijo kot neodgovori na spremenljivko
+ # ali je to -3 ali -1. Če uporabnik še ni bil na tej strani je -3 če ne je -1
+ # ali pa če gre za email vabila dodamo status -3
+ if ((($rowUser['status'] == 6 || $rowUser['status'] == 5 ) && $rowUser['lurker'] != 1) ) {
+ // Ce je skrito je -2 (-2d da ga pobrisemo z -3 ce je potrebno)
+ if($spr_visible == 0 || !(($admin_type <= $spr_dostop && $admin_type>=0) || ($admin_type==-1 && $spr_dostop==4))){
+ $VALUE_FOR_MISSING = '-2d';
+ }
+ else{
+ # če so veljavni odgovori damo -1 ali -3
+ # na -3 popravimo na okncu
+ #$VALUE_FOR_MISSING = isset($this->_array_user_grupa[$uid][$spr_page]) ? '-1' : '-1';
+ $VALUE_FOR_MISSING = '-1';
+ }
+ }
+ else if ( $rowUser['status'] == 0 || $rowUser['status'] == 1 || $rowUser['status'] == 2 ) {
+ # če je email vabilo
+ #$VALUE_FOR_MISSING = '-3';
+ $VALUE_FOR_MISSING = '-5';
+ }
+ else {
+ # to so lurkerji
+ # če imamo neveljavne odgovore damo -5
+ $VALUE_FOR_MISSING = '-5';
+ }
+ # array z vrednosmi rabimo za podatke in za polja drugo
+ if (isset($this->_array_vrednosti[$spr_id])) {
+ $spr_vrednosti = $this->_array_vrednosti[$spr_id];
+ }
+ #gridi
+ if (isset($this->_array_gridi[$spr_id])) {
+ $spr_gridi = $this->_array_gridi[$spr_id];
+ }
+
+ #ODGOVORI
+ #tekstovno odgovori
+ $spr_data_text = $this->get_array_data_text($uid,$spr_data_id);
+ unset($this->_array_data_text[$uid][$spr_data_id]);
+ # vrednostni odgovori
+ $spr_data_vred = $this->get_array_data_vrednost($uid,$spr_data_id);
+ unset($this->_array_data_vrednost[$uid][$spr_data_id]);
+ # preslkočeni vrednostni odgovori
+ $spr_data_vrednost_cond = $this->get_array_data_vrednost_cond($uid,$spr_data_id);
+ unset($this->_array_data_vrednost_cond[$uid][$spr_data_id]);
+ # grid odgovori
+ $spr_data_grid = $this->get_array_data_grids($uid,$spr_data_id);
+ unset($this->_array_data_grids[$uid][$spr_data_id]);
+ # grid odgovori za checkbox
+ $spr_data_grid_check = $this->get_array_data_check_grids($uid,$spr_data_id);
+ unset($this->_array_data_check_grids[$uid][$spr_data_id]);
+ # ranking odgovori
+ $spr_data_ranking = $this->get_array_data_rating($uid,$spr_data_id);
+ unset($this->_array_data_rating[$uid][$spr_data_id]);
+ # textgrid odgovori
+ $spr_data_grid_text = $this->get_array_data_text_grid($uid,$spr_data_id);
+ unset($this->_array_data_text_grid[$uid][$spr_data_id]);
+ # lokacijski odgovori
+ $spr_data_map = $this->get_array_data_map($uid,$spr_data_id);
+ unset($this->_array_data_map[$uid][$spr_data_id]);
+ # heatmap odgovori
+ $spr_data_heatmap = $this->get_array_data_heatmap($uid,$spr_data_id);
+ unset($this->_array_data_heatmap[$uid][$spr_data_id]);
+ $spr_data_heatmap_regions = $this->get_array_data_heatmap_regions($uid,$spr_data_id);
+ unset($this->_array_data_heatmap_regions[$uid][$spr_data_id]);
+
+
+ // v odvisnosti od tipa vprašanja pohandlamo podatke
+ switch ( $tip ) {
+
+ # RADIO BUTTON in DROPDOWN - SELECT
+ case 1:
+ case 3:
+
+ $answer = null;
+ $_vred = null;
+
+ if (is_array($spr_data_vred)) {
+ $key = key($spr_data_vred);
+
+ if (isset($spr_data_vred[$key])) {
+ $_vred = $spr_data_vred[$key];
+ }
+ }
+ else {
+ $_vred = $VALUE_FOR_MISSING;
+ }
+
+ if ($_vred > 0) {
+ $answer = $spr_vrednosti[$_vred]['variable'];
+ }
+ else {
+ $answer = $_vred;
+ }
+
+ if ( $answer == '' || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ }
+
+ # dodamo podatek
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+ // poiščemo polja drugo
+ if (count($spr_vrednosti) > 0){
+
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+
+ if ($vrednost['other'] == 1) {
+
+ if ($answer == -1 || $answer == -2 || $answer == -3 || $answer == -4 || $answer == -96 || $answer == -97 || $answer == -98 || $answer == -99 ) {
+ $answerOther = $answer;
+ }
+ else {
+
+ if (isset($spr_data_text[$vid]['text'])) {
+ $answerOther = ($spr_data_text[$vid]['text'] == "" || $spr_data_text[$vid]['text'] == null) ? $VALUE_FOR_MISSING : $spr_data_text[$vid]['text'];
+ }
+ elseif($spr_vrednosti[$vid]['variable'] != $answer){
+ // Ce je bil -1 texta ni mogel vnesti in mora bit -2
+ if($VALUE_FOR_MISSING == -1)
+ $answerOther = '-2d';
+ else
+ $answerOther = $VALUE_FOR_MISSING;
+ }
+ else {
+ $answerOther = $VALUE_FOR_MISSING;
+ }
+ }
+
+ // dodamo podatek
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerOther,$uid);
+ }
+ }
+ }
+
+ break;
+
+
+ # CHECKBOX
+ case 2:
+ $answer = null;
+ $_tmp_answers = array();
+
+ $_anything_set = false;
+ $_has_missing = NULL;
+
+ # najprej dodelimo odgovore posameznim vrednostim če obstatajo
+ if (count($spr_vrednosti) > 0){
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+
+ if (isset($spr_data_vred[$vid]) && $_has_missing == NULL) {
+
+ // če je spr_data_vrednost obstaja je checkbox obkljukan
+ // preverimo ali imamo missing
+ if ($vrednost['other'] != 0 && $vrednost['other'] != 1 ) {
+ # odgovor je missing, vse vrednosti nastavimo na ta missing, zato pobrišemo morebitne že dodane odgovore
+ unset($_tmp_answers);
+ unset($spr_data_vred[$vid]);
+
+ $_has_missing = $spr_vrednosti[$vid]['variable'];
+ }
+ else {
+ $_tmp_answers[$vid] = 1;
+ unset($spr_data_vred[$vid]);
+ $_anything_set = true;
+ }
+ }
+ else if (isset($spr_data_vrednost_cond[$vid])) {
+ $_tmp_answers[$vid] = $spr_data_vrednost_cond[$vid];
+ }
+ }
+ }
+
+ // če ni nič nastavljeno, je lahko samo -1, -2, -3,-4
+ $missing_answers = 0;
+ # preverimo ali so ostale še kakšne vrednosti, potem so najbrž missingi
+ #najprej preverimo missing na variabli
+ if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ unset($_tmp_answers);
+ $_has_missing = end($spr_data_vred);
+ $missing_answers = $_has_missing;
+ $_anything_set = false;
+ }
+
+ if ($_anything_set == false || $_has_missing != null) {
+ if ($_has_missing != null) {
+ # immamo misssing value
+ $missing_answers = $_has_missing;
+ } else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $missing_answers = end($spr_data_vred); # lahko da je -2, -4
+ } else {
+ // lahko je -1, -3
+ $missing_answers = $VALUE_FOR_MISSING;
+ }
+ }
+
+ # še enkrat zloopamo skozi vrednosti in dodelimo odgovore, tudi za polja drugo
+ if (count($spr_vrednosti) > 0) {
+ if ($missing_answers == 0 ) {
+ $missing_answers = $VALUE_FOR_MISSING;
+ }
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ # dodamo samo variable ki niso missing
+ if ($vrednost['other'] == 0 || $vrednost['other'] == 1) {
+ if (isset($_tmp_answers[$vid])) {
+ $answer = $_tmp_answers[$vid];
+ } else if ($_anything_set == true){
+ #pri checkboxu je lahko tudi 0
+ $answer = 0;
+ } else {
+ $answer = $missing_answers;
+ }
+
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+ #dodamo še polje drugo
+ if ($vrednost['other'] == 1) {
+
+ #ce smo meli checkboc obkljukan
+ if (isset($_tmp_answers[$vid])) {
+ $answerOther = ($spr_data_text[$vid]['text'] == "" || $spr_data_text[$vid]['text'] == null) ? $VALUE_FOR_MISSING : $spr_data_text[$vid]['text'];
+ } else if ($missing_answers !== null) {
+ // Ce je bil 0 texta ni mogel vnesti in mora bit -2
+ if($VALUE_FOR_MISSING == -1)
+ $answerOther = '-2d';
+ else
+ $answerOther = $missing_answers;
+ } else if ($answer == 0) {
+ $answerOther = $VALUE_FOR_MISSING;
+ } else {
+ $answerOther = $answer;
+ }
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerOther,$uid);
+
+ }
+ }
+ }
+ }
+
+ break;
+
+ # TEXT
+ case 4:
+ $answer = null;
+
+ # ce obstaja $spr_data_vred je po vsej vrjetnosti missing
+ if ( count($spr_data_vred) > 0 ) {
+ $key = key($spr_data_vred);
+ $answer = $spr_data_vred[$key];
+ //unset ($spr_data_vred[$key]);
+ }
+ else {
+ $answer = $spr_data_text[0]['text'];
+ }
+
+ if ( $answer == '' || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ }
+
+ // dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+ break;
+
+
+ # MULTI RADIO BUTTON
+ case 6:
+
+ # dvojni gridi so zapisani v $spr_data_grid_check
+ if ((int)$rowVprasanje['enota'] != 3) {
+
+ # ni dvojni grid
+ $answer = null;
+
+ # zloopamo skozi podvprašanja (srv_vrednost
+ if (count($spr_vrednosti) > 0){
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+
+ $missing_answer = false;
+
+ if (is_array($spr_data_vred) && count($spr_data_vred) == 1 ) {
+ $answer = end($spr_data_vred); # lahko da je -2, -4
+ $missing_answer = true;
+ }
+ else if (isset($spr_data_grid[$vid])) {
+ if ($spr_data_grid[$vid] > 0) {
+ if ($spr_gridi[$spr_data_grid[$vid]]['other'] == 0) {
+ # preberemo grid vrednost
+ $answer = $spr_gridi[$spr_data_grid[$vid]]['variable']; // tukaj dodelimo ime variable, lahko bi tudi id ali vrstni red???
+ $missing_answer = false;
+ } else {
+ $answer = $spr_gridi[$spr_data_grid[$vid]]['other'];
+ }
+ }else {
+ # je missing
+ $answer = $spr_data_grid[$vid];
+ $missing_answer = true;
+ }
+ }
+ else {
+ $answer = $VALUE_FOR_MISSING;
+ $missing_answer = true;
+ }
+
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+
+ if ($vrednost['other'] == 1) {
+ # če answer ni missing
+ if ($missing_answer == false) {
+ if (isset($spr_data_text[$vid]['text'])) {
+ $answerOther = ($spr_data_text[$vid]['text'] == "" || $spr_data_text[$vid]['text'] == null) ? $VALUE_FOR_MISSING : $spr_data_text[$vid]['text'];
+ }else {
+ $answerOther = $VALUE_FOR_MISSING;
+ }
+ }
+ else {
+ $answerOther = $answer;
+ }
+
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerOther,$uid);
+ }
+ }
+ }
+ }
+ else {
+ # DOUBLE GRID
+
+ # če imamo dvojni grid gremo 2_skozi
+ $double = (int)($rowVprasanje['enota'] == 3);
+ $_tmp_answers = array();
+
+ for ($i=1; $i<=$double+1;$i++) {
+ // for $double
+
+ # sfiltriramo odgovore za posamezen part
+ $_tmp_part_answers = array();
+ if (count($spr_data_grid_check) > 0) {
+ foreach($spr_data_grid_check as $vre_id => $grids) {
+ if (count($grids) > 0) {
+ foreach($grids AS $gid => $grid) {
+ if ($spr_gridi[$gid]['part'] == $i) {
+ if ($spr_gridi[$gid]['other'] == 0) {
+ $_tmp_part_answers[$vre_id] = $spr_gridi[$gid]['variable'];
+ } else {
+ $_tmp_part_answers[$vre_id] = $spr_gridi[$gid]['other'];
+ }
+ }
+ }
+ }
+ }
+ }
+ $answer = null;
+ # zloopamo skozi podvprašanja (srv_vrednost
+ if (count($spr_vrednosti) > 0) {
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ $missing_answer=false;
+ if (is_array($spr_data_vred) && count($spr_data_vred) == 1 ) {
+ $answer = end($spr_data_vred); # lahko da je -2, -4
+ $missing_answer = true;
+ } else if (isset($_tmp_part_answers[$vid])) {
+ if ($_tmp_part_answers[$vid] > 0) {
+ # preberemo grid vrednost
+ $answer = $_tmp_part_answers[$vid]; // tukaj dodelimo ime variable, lahko bi tudi id ali vrstni red???
+ $missing_answer = false;
+ } else {
+ $answer = $_tmp_part_answers[$vid]; // tukaj dodelimo ime variable, lahko bi tudi id ali vrstni red???
+ $missing_answer = true;
+ }
+ } else {
+ $answer = $VALUE_FOR_MISSING;
+ $missing_answer = true;
+ }
+
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+
+ if ($vrednost['other'] == 1) {
+ # če answer ni missing
+ if ($missing_answer == false) {
+ $answerOther = ($spr_data_text[$vid]['text'] == "" || $spr_data_text[$vid]['text'] == null) ? $VALUE_FOR_MISSING : $spr_data_text[$vid]['text'];
+ } else {
+ $answerOther = $answer;
+ }
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerOther,$uid);
+
+ }
+ }
+ }
+ } // for $double
+ }
+
+ break;
+
+
+ # NUMBER in DATE
+ case 7:
+ case 8:
+
+ $_vred = null;
+ $answer0 = null;
+
+ # ce imamo odgovor
+ if (isset ($spr_data_text[0])) {
+ $answer0 = ($spr_data_text[0]['text'] != '') ? $spr_data_text[0]['text'] : $VALUE_FOR_MISSING;
+
+ }
+ else if (is_array($spr_data_vred)) {
+ $key = key($spr_data_vred);
+ if (isset($spr_data_vred[$key])) {
+ $_vred = $spr_data_vred[$key];
+ }
+ #pogledamo če je odgovor missing:
+ if (isset($spr_vrednosti[$_vred])) {
+ $answer0 = $spr_vrednosti[$_vred]['variable'];
+ } else {
+ $answer0 = $_vred;
+ }
+
+ }
+
+ $answer0 = ($answer0 == null ) ? $VALUE_FOR_MISSING : $answer0;
+
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer0,$uid);
+
+
+ # ve imamo size = 2
+ if ($tip == 7 && $spr_size > 1) {
+
+ $answer1 = null;
+ # ce imamo odgovor
+ if (isset ($spr_data_text[0])) {
+ $answer1 = ($spr_data_text[0]['text2'] != '') ? $spr_data_text[0]['text2'] : $VALUE_FOR_MISSING;
+ } else if (is_array($spr_data_vred)) {
+ $key = key($spr_data_vred);
+ if (isset($spr_data_vred[$key])) {
+ $_vred = $spr_data_vred[$key];
+ }
+ #pogledamo če je odgovor missing:
+ if (isset($spr_vrednosti[$_vred])) {
+ $answer1 = $spr_vrednosti[$_vred]['variable'];
+ } else {
+ $answer1 = $_vred;
+ }
+ }
+
+ $answer1 = ($answer1 == null ) ? $VALUE_FOR_MISSING : $answer1;
+
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer1,$uid);
+
+ }
+
+ break;
+
+
+ # MULTI CHECKBOX
+ case 16:
+ # delamo na nivoju $spr_vrednosti kar predstavlja podvprašanje
+ if (count($spr_vrednosti) > 0) {
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ $_tmp_answers = array();
+ $_anything_set = false;
+ $_missing_answer = NULL;
+ # zloopamo skozi podvprašanja in nastavimo izbrane odgovore
+ if (count($spr_gridi) > 0) {
+ foreach ($spr_gridi AS $gid => $grid) {
+ if (isset($spr_data_grid_check[$vid][$gid]) && $_missing_answer == NULL) {
+ # če je spr_data_vrednost obstaja je checkbox obkljukan
+ #Najprej preverimo ali je odgovro missing...
+ if ($spr_gridi[$gid]['other'] == 0 || $spr_gridi[$gid]['other'] == 1) {
+ $_tmp_answers[$vid][$gid] = 1;
+ $_anything_set = true;
+ } else {
+ $_missing_answer = $spr_gridi[$gid]['other'];
+ # izrišemo morebitne 1 ke pri vrednostih ki imajo kakršnkoli missing
+ # ker ne more bit hkrati -99 ne vem in veljavni odgovor
+ unset($_tmp_answers);
+ $_anything_set = false;
+ }
+ unset($spr_data_grid_check[$vid][$gid]);
+ }
+ }
+ }
+ # nastavimo ali missinge, ali neveljavne ali 0;
+ if ($_anything_set == false) {
+ if ($_missing_answer != NULL) {
+ # missing je že nastavljen
+ } else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $_missing_answer = end($spr_data_vred);
+ } else {
+ $_missing_answer = $VALUE_FOR_MISSING;
+ }
+ }
+ # dodamo odgovore
+ if (count($spr_gridi)>0) {
+ foreach ($spr_gridi AS $gid => $grid) {
+ # dodamo samo gride ki niso missingi
+ if ($spr_gridi[$gid]['other'] == 0 || $spr_gridi[$gid]['other'] == 1) {
+ $answer = '0';
+ # če je nastavljen missing so vsi gridi na podvprašanje enaki missingu
+ if ($_missing_answer != NULL ) {
+ $answer = $_missing_answer;
+ } else if (isset($_tmp_answers[$vid][$gid])) {
+ $answer = $_tmp_answers[$vid][$gid];
+ }
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id, $answer,$uid);
+
+ }
+ }
+ # dodamo še odgovore other text
+ if ($vrednost['other'] == 1) {
+ if ($_missing_answer != null) {
+ $answerOther = $_missing_answer;
+ } else if (isset($spr_data_text[$vid]['text']) && $spr_data_text[$vid]['text'] !== '') {
+ $answerOther = $spr_data_text[$vid]['text'];
+ } else {
+ if ($_anything_set == false) {
+ if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $answerOther = end($spr_data_vred);
+ } else {
+ $answerOther = $VALUE_FOR_MISSING;
+ }
+ } else {
+ $answerOther = $VALUE_FOR_MISSING;
+ }
+ }
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerOther,$uid);
+
+ }
+ }
+ } // end foreach spr_vrednost
+ } // end if count spr_vrednost
+
+ break;
+
+
+ # RANKING
+ case 17:
+
+ if (count($spr_vrednosti ) > 0){
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ $answer = null;
+ if (isset($spr_data_ranking[$vid])) {
+ $answer = $spr_data_ranking[$vid];
+ } else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $answer = end($spr_data_vred);
+ }
+
+ if ($answer == "" || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ } // end if
+
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+ } // end foreach
+ }
+
+ break;
+
+
+ #VSOTA
+ case 18:
+
+ if (count($spr_vrednosti ) > 0){
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ $answer = null;
+
+ if (isset($spr_data_text[$vid]['text'])) {
+ $answer = $spr_data_text[$vid]['text'];
+ }
+ else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $answer = end($spr_data_vred);
+ }
+
+ if ($answer == "" || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ } // end if
+
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+ } // end foreach
+ }
+
+ break;
+
+
+ # MULTITEXT in MULTINUMBER
+ case 19:
+ case 20:
+
+ $answer = null;
+ $_tmp_answers = array();
+ $_anything_set = array();
+
+ $missing_value_temp = $VALUE_FOR_MISSING;
+
+ # preverimo al mamo missing (-2 ali -4, ce je bila naknadno dodana) nad celo spremenljivko
+ if (isset($spr_data_vred) && count($spr_data_vred) == 1) {
+ $missing_value_temp = (is_array($spr_data_vred) && count($spr_data_vred) == 1 ) ? end($spr_data_vred) : $VALUE_FOR_MISSING;
+ }
+
+ $is_grid_missing = array();
+
+ # zloopamo skozi podvprašanja in nastavimo izbrane odgovore
+ if (count($spr_vrednosti ) > 0) {
+
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+
+ if (count($spr_gridi) > 0) {
+
+ foreach ($spr_gridi AS $gid => $grid) {
+
+ # dodajamo samo odgovore ki so veljavni
+ if ($grid['other'] == 0) {
+
+ # imamo veljaven odgovor
+ if (isset($spr_data_grid_text[$vid][$gid])) {
+ $_tmp_answers[$vid][$gid] = $spr_data_grid_text[$vid][$gid];
+ $_anything_set[$vid] = true;
+ }
+ else if (isset($spr_data_grid[$vid])) {
+ $_tmp_answers[$vid][$gid] = $spr_gridi[$spr_data_grid[$vid]]['other'];
+ }
+ else {
+ $_tmp_answers[$vid][$gid] = $missing_value_temp;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ # dodamo odgovore
+ if(count($spr_vrednosti) > 0)
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ if(count($spr_gridi) > 0)
+ foreach ($spr_gridi AS $gid => $grid) {
+ if ($grid['other'] == 0) {
+ # dodamo samo veljavne gride
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$_tmp_answers[$vid][$gid],$uid);
+
+
+ }
+ }
+
+ # dodamo še odgovore other text
+ if ($vrednost['other'] == 1) {
+ # če mamo missing dodamo missing
+ if (isset($is_grid_missing[$vid])) {
+ $answerOther = $is_grid_missing[$vid];
+ } else if ($_anything_set[$vid]) {
+ $answerOther = ($spr_data_text[$vid]['text'] == "" || $spr_data_text[$vid]['text'] == null) ? $missing_value_temp : $spr_data_text[$vid]['text'];
+ } else {
+ $answerOther = $missing_value_temp;
+ }
+
+ # dodamo odgvor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerOther,$uid);
+ }
+ }
+
+ break;
+
+
+ # BESEDILO *
+ case 21:
+
+ # zloopamo skozi podvprašanja in nastavimo izbrane odgovore
+ if(count($spr_vrednosti) > 0){
+
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+
+ if ($vrednost['other'] == 0) {
+
+ $answer = null;
+
+ # imamo signature vprašanje
+ if($spr_signature == 1){
+
+ if(isset($spr_data_text[$vid]['text']))
+ $answer = $spr_data_text[$vid]['text'] . ' ';
+
+ if(@getimagesize($site_url.'main/survey/uploads/'.$rowUser['usr_id'].'_'.$spr_id.'_'.$this->sid.'.png'))
+ $answer .= '('.$site_url.'main/survey/uploads/'.$rowUser['usr_id'].'_'.$spr_id.'_'.$this->sid.'.png)';
+ }
+ else if (isset($spr_data_text[$vid]['text']) && $spr_signature != 1) {
+
+ if ($spr_upload == 1 || $spr_upload == 2) {
+ # imamo upload vprašanje
+ # imena datotek
+ $filename = substr($this->get_array_data_text_upload($spr_data_text[$vid]['text']),strlen($uid.'_'));
+ $answer = ''.$site_url.'main/survey/download.php?anketa='.$this->sid.'&code='.$spr_data_text[$vid]['text'].'';
+ }
+ else {
+ # imamo normalno text vprašanje
+ $answer = $spr_data_text[$vid]['text'];
+ }
+
+ }
+ else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+
+ #$answer = end($spr_data_vred);
+
+ $key = key($spr_data_vred);
+ if (isset($spr_data_vred[$key])) {
+ $_vred = $spr_data_vred[$key];
+ }
+ #pogledamo če je odgovor missing:
+ if (isset($spr_vrednosti[$_vred])) {
+ $answer = $spr_vrednosti[$_vred]['variable'];
+ } else {
+ $answer = $_vred;
+ }
+ }
+
+ if ($answer == "" || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ } // end if
+
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+ }
+ }
+ }
+
+ break;
+
+
+ # Kalkulacija
+ case 22:
+
+ $_vred = null;
+ $answer0 = null;
+
+ # ce imamo odgovor
+ if (isset ($spr_data_text[0]) && $spr_data_text[0]['text'] != '') {
+ $answer0 = $spr_data_text[0]['text'];
+ } else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $answer0 = end($spr_data_vred);
+ }
+
+ $answer0 = ($answer0 == null ) ? $VALUE_FOR_MISSING : $answer0;
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer0,$uid);
+
+ break;
+
+
+ # Kvota
+ case 25:
+
+ $_vred = null;
+ $answer0 = null;
+
+ # ce imamo odgovor
+ if (isset ($spr_data_text[0]) && $spr_data_text[0]['text'] != '') {
+ $answer0 = $spr_data_text[0]['text'];
+ } else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $answer0 = end($spr_data_vred);
+ }
+
+ $answer0 = ($answer0 == null ) ? $VALUE_FOR_MISSING : $answer0;
+ # dodamo odgovor
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer0,$uid);
+
+ break;
+
+
+ # SN - IMENA *
+ case 9:
+
+ # zloopamo skozi podvprašanja in nastavimo izbrane odgovore
+ $arrayVrednost = $this->SNVariablesForSpr[$_vprasanje_array['id']];
+ if (!is_array($arrayVrednost)) {
+ $arrayVrednost = array();
+ }
+ if(count($spr_vrednosti) > 0)
+ foreach ($spr_vrednosti AS $vid => $vrednost) {
+ if (in_array($vid,$arrayVrednost)) {
+ $answer = null;
+ if (isset($spr_data_text[$vid]['text'])) {
+ # imamo normalno text vprašanje
+ $answer = $spr_data_text[$vid]['text'];
+
+ } else if (is_array($spr_data_vred) && count($spr_data_vred) > 0 ) {
+ $answer = end($spr_data_vred);
+ }
+
+ if ($answer == "" || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ } // end if
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+
+ }
+ }
+
+ break;
+
+
+ # LOKACIJA
+ case 26:
+
+ $row = Cache::srv_spremenljivka($spr_id);
+
+ if($row['enota'] == 3){
+
+ if(count($spr_vrednosti) > 0){
+ # zloopamo skozi podvprašanja in nastavimo izbrane odgovore
+ if (isset ($spr_data_map)) {
+ if(empty($spr_data_map)){
+ //missingi, lahko da je -4
+ $missing_value_temp = (is_array($spr_data_vred) && count($spr_data_vred) == 1 ) ? end($spr_data_vred) : $VALUE_FOR_MISSING;
+ for($i = 0; $i < count($spr_vrednosti); $i++){
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$missing_value_temp,$uid);
+ }
+ }
+ else{
+ $answerArr = (count($spr_data_map['izpis']) > 0) ? $spr_data_map['izpis'] : $VALUE_FOR_MISSING;
+
+ if(count($spr_data_map) > 0)
+ foreach ($spr_data_map['izpis'] AS $izpis) {
+ $answer = null;
+
+ if (isset($izpis['vrednost'])) {
+ # imamo normalno text vprašanje
+ $answer = $izpis['vrednost'];
+ }
+ if ($answer == "" || $answer == null) {
+ $answer = $VALUE_FOR_MISSING;
+ } // end if
+
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answer,$uid);
+ }
+ }
+ }
+ }
+ }
+ else{
+ $_vred = null;
+ $answerArr = null;
+ $answerAdd = null;
+ $answerVre = null;
+ $answerKoo = null;
+
+ $newParams = new enkaParameters($row['params']);
+ $is_podvprasanje = $newParams->get('marker_podvprasanje') == 1;
+ //$podvprasanje_naslov = '';
+ $is_podvprasanje ? $podvprasanje_naslov = $newParams->get('naslov_podvprasanja_map') :
+ $podvprasanje_naslov = '';
+
+ $multi_input_type = $newParams->get('multi_input_type');
+
+ # ce imamo odgovor
+ if (isset ($spr_data_map)) {
+ $missing_value_temp = (is_array($spr_data_vred) && count($spr_data_vred) == 1 ) ? end($spr_data_vred) : $VALUE_FOR_MISSING;
+ $answerArr = (is_countable($spr_data_map['izpis']) && count($spr_data_map['izpis']) > 0) ? $spr_data_map['izpis'] : $missing_value_temp;
+ }
+ else if (is_array($spr_data_map)) {
+ $key = key($spr_data_map);
+
+ if (isset($spr_data_map[$key])) {
+ $_vred = $spr_data_map[$key];
+ }
+
+ // pogledamo če je odgovor missing:
+ if (isset($spr_vrednosti[$_vred])) {
+ $answerAdd = $spr_vrednosti[$_vred]['variable'];
+ $answerVre = $spr_vrednosti[$_vred]['variable'];
+ $answerKoo = $spr_vrednosti[$_vred]['variable'];
+ } else {
+ $answerAdd = $_vred;
+ $answerVre = $_vred;
+ $answerKoo = $_vred;
+ }
+ }
+
+ if ($answerArr == null || $answerArr == $missing_value_temp){
+ $answerAdd = $answerVre = $answerKoo = $missing_value_temp;
+ }
+ elseif($answerArr[0]['address'] == '-2'){
+ $answerAdd = $answerVre = $answerKoo = '-2';
+ }
+ else{
+ foreach($answerArr as $varArr){
+ if($answerKoo != null){
+ $answerAdd .= '<br>'.$varArr['address'];
+ $answerVre .= '<br>'.$varArr['vrednost'];
+ $answerKoo .= '<br>'.$varArr['koordinate'];
+ }
+ else{
+ $answerAdd = $varArr['address'];
+ $answerVre = $varArr['vrednost'];
+ $answerKoo = $varArr['koordinate'];
+ }
+ }
+ }
+
+ # dodamo odgovor
+ if($multi_input_type == 'marker')
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerAdd,$uid);
+ if($is_podvprasanje)
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerVre,$uid);
+
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerKoo,$uid);
+ }
+
+ break;
+
+
+ // HEATMAP
+ case 27:
+ $_vred = null;
+ $answerArr = null;
+ $answerAdd = null;
+ $answerVre = null;
+ $answerKoo = null;
+
+ $row = Cache::srv_spremenljivka($spr_id);
+ $newParams = new enkaParameters($row['params']);
+
+ // ce imamo odgovor
+ if (isset ($spr_data_heatmap)) {
+ $answerArr = (is_countable($spr_data_heatmap['izpis']) && count($spr_data_heatmap['izpis']) > 0) ? $spr_data_heatmap['izpis'] : $VALUE_FOR_MISSING;
+ }
+ else if (is_array($spr_data_heatmap)) {
+ $key = key($spr_data_heatmap);
+ if (isset($spr_data_heatmap[$key])) {
+ $_vred = $spr_data_heatmap[$key];
+ $_vred = $spr_data_heatmap[$key];
+ }
+ #pogledamo če je odgovor missing:
+ if (isset($spr_vrednosti[$_vred])) {
+ $answerAdd = $spr_vrednosti[$_vred]['variable'];
+ $answerVre = $spr_vrednosti[$_vred]['variable'];
+ $answerKoo = $spr_vrednosti[$_vred]['variable'];
+ } else {
+ $answerAdd = $_vred;
+ $answerVre = $_vred;
+ $answerKoo = $_vred;
+ }
+ }
+
+ if ($answerArr == null || $answerArr == $VALUE_FOR_MISSING){
+ $answerAdd = $answerVre = $answerKoo = $VALUE_FOR_MISSING;
+ }
+ elseif($answerArr[0]['address'] == '-2'){
+ $answerAdd = $answerVre = $answerKoo = '-2';
+ }
+ else{
+ foreach($answerArr as $varArr){
+ $answerAdd .= '<br>'.$varArr['address'];
+ $answerVre .= '<br>'.$varArr['vrednost'];
+ $answerKoo .= '<br>'.$varArr['koordinate'];
+ }
+ }
+
+ # dodamo odgovor za koordinate
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerKoo,$uid);
+
+ // za območja
+ if (is_array($spr_data_heatmap_regions)) {
+
+ //priprava spremenljivk za koordinate točk
+ $pointx = $this->preparePointCoords($answerKoo, 1, 0);
+ $pointy = $this->preparePointCoords($answerKoo, 0, 1);
+ $numberOfPointsInside=array();
+
+ if (count($spr_vrednosti) > 0) {
+ $i=0;
+ foreach ($this->_array_data_heatmap_regions[(int)$spr_id] AS $regions){
+ $answerReg = null;
+ $numberOfPointsInside[$regions['region_name']] = 0; // Belezi stevilo tock znotraj trenutnega obmocja
+
+ // Pretvori polje s tockami obmocja v ustrezno obliko
+ $poly = $this->convertPolyString($regions['region_coords']);
+
+ // preveri, ali je posamezna tocka znotraj trenutnega obmocja
+ for ($z=0; $z<sizeof($pointx); $z++){
+ $inside = $this->insidePoly($poly, $pointx[$z]["x"], $pointy[$z]["y"]);
+ if ($inside == true){
+ $numberOfPointsInside[$regions['region_name']]++;
+ }
+ }
+
+ // Priprava odgovora za preglednico s podatki
+ // Ce je missing
+ if($answerKoo < 0){
+ $answerReg = $answerKoo;
+ }
+ else{
+ $answerReg = $numberOfPointsInside[$regions['region_name']];
+ }
+
+ $i++;
+
+ // dodamo odgovor s stevilom tock znotraj obmocja
+ $userAnswerLine .= STR_DLMT.$this->recode_answer($spr_id,$answerReg,$uid);
+
+ }
+ }
+ }
+ //za območja - konec
+
+ break;
+ }
+ } // end while
+ } // end if ($this->noErrors)
+
+
+ // popravimo -1, -4 in -2d (text za drugo) => -3, začnemo odzadaj in spreminjamo -1, -4 in -2d v -3 dokler obstajajo ampak samo če status ni 6
+ $changed = false;
+ if ((int)$rowUser['status'] !== 6 && !empty($userAnswerLine)) {
+
+ // ugotovimo do katere spremenljivke sploh zamenjujemo vrednosti ker če je pri tabelah odgovor vsaj na 1 variablo, potem tam pustimo -1
+ $valuesToChange = $this->calculateValuesToChange($uid);
+ $userAnswerLineArray = explode('|',$userAnswerLine);
+
+ $reversed = array_reverse($userAnswerLineArray);
+ foreach ($reversed AS $key => $value) {
+
+ if ($key+1 > $valuesToChange) {
+ break;
+ }
+
+ if ($value == -1 || $value == -4 || $value == '-2d') {
+ $reversed[$key] = -3;
+ $changed = true;
+ }
+ else {
+ $reversed[$key] = $value;
+ }
+ }
+
+ if ($changed) {
+ $userAnswerLineArray = array_reverse($reversed);
+ $userAnswerLine = (implode('|', $userAnswerLineArray));
+ }
+ }
+
+ // Popravimo -2d (text za drugo, ce je naknadno nastavljen na -2, ker ni bil oznacen radio/checkbox za drugo)
+ $userAnswerLine = str_replace('-2d','-2',$userAnswerLine);
+
+ // Naknadno popravimo se -2, ce je lurker (-5), ker nekatere drugace ostanejo
+ if ($VALUE_FOR_MISSING == -5) {
+ $userAnswerLine = str_replace('-2','-5',$userAnswerLine);
+ }
+
+ // dodamo podatke k userju
+ $_dataLine .= $userAnswerLine;
+
+
+ // DODAMO META PODATKE
+ if ($this->noErrors) {
+
+ // Random vrstni redi
+
+ foreach ($this->_array_random as $random_parent) {
+
+ $type = ($random_parent['type'] == 'spr') ? 'spr' : 'block';
+ $random_data = $this->get_array_data_random($uid, $random_parent['id'], $type);
+ unset($this->_array_data_random[$uid][$type][$random_parent['id']]);
+
+ $_dataLine .= STR_DLMT.$random_data;
+ }
+
+ # če mamo da prepozna uporabnika iz sispleta
+ if ((int)$this->survey['user_from_cms'] > 0) {
+ $_dataLine .= STR_DLMT;
+ if ((int)$rowUser['user_id'] > 0) {
+ $_dataLine .= $this->get_user_CMS_email((int)$rowUser['user_id']);
+ }
+ }
+
+ # datum insert, datum edit
+ $_dataLine .= STR_DLMT.datetime($rowUser['time_insert']);
+ $_dataLine .= STR_DLMT.datetime($rowUser['time_edit']);
+
+ # strani in časi
+ foreach ($this->_array_groups AS $gid => $grupa) {
+
+ if ($this->_array_user_grupa[$uid][$gid] != '') {
+ $_dataLine .= STR_DLMT.datetime($this->_array_user_grupa[$uid][$gid]);
+ } else {
+ $_dataLine .= STR_DLMT.'';
+ }
+ }
+
+ /* ZARADI VAROVANJA PODATKOV SMO ZAČASNO ONEMOGOČILI LOVLJENJE IP-jev */
+ $ip = SurveySetting::getInstance()->getSurveyMiscSetting('survey_ip');
+ $ip_show = SurveySetting::getInstance()->getSurveyMiscSetting('survey_show_ip');
+ if($ip==0 && $ip_show==1 && ($admin_type == 0 || $admin_type == 1)){
+ $_dataLine .= STR_DLMT.$rowUser['ip'];
+ }
+
+ $_dataLine .= STR_DLMT.$rowUser['useragent'];
+ $_dataLine .= STR_DLMT.$rowUser['browser'];
+ $_dataLine .= STR_DLMT.$rowUser['os'];
+ $_dataLine .= STR_DLMT.$lang['srv_para_graph_device'.$rowUser['device']];
+ $_dataLine .= STR_DLMT.$rowUser['referer'];
+ $_dataLine .= STR_DLMT.$rowUser['unsubscribed'];
+ $_dataLine .= STR_DLMT.$jeziki[$rowUser['language']];
+ }
+
+
+ // Pocistimo vrednosti, ker drugace v nekaterih primereih prihaja do zelo cudnih bugov
+ unset($rowVprasanje);
+ unset($spr_vrednosti);
+ unset($spr_gridi);
+
+
+ // Zapišemo vsako vrstico posebej
+ if ($this->noErrors && !empty($_dataLine)) {
+
+ // zapišemo vrstico z predhodnim vrivom nove vrstice
+ $success = fwrite($file_handler, $this->new_line_seperator . $_dataLine);
+ fflush($file_handler);
+
+ // Imamo napako - vse skupaj prekinemo
+ if ((int)$success <= 0) {
+ $this->noErrors = false;
+ }
+
+ $_dataLine = null;
+ unset($_dataLine);
+ }
+ else {
+ # dodamo v log napako
+ $SL = new SurveyLog();
+ $SL->addMessage(SurveyLog::ERROR, " ERROR user ".$rowUser['usr_id']." for ank_id".$this->sid);
+ $SL->write();
+ }
+
+ $this->new_line_seperator = NEW_LINE;
+
+ } // end while user loop
+ } // end if ($this->noErrors)
+ }
+
+ /***** KONEC - ZBIRANJE PODATKOV ZA DATOTEKO *****/
+
+
+
+ /***** KESIRANJE PODATKOV ANKETE (vprasanja, strani, gridi...) *****/
+
+ // Glavna funkcija preko katere na zacetku izvedemo vso kesiranje
+ private function cache_data(){
+
+ // Zakesiramo query za respondente
+ $this->create_qry_users();
+
+
+ // Zakesiramo strani v anketi
+ $this->get_groups();
+
+ // Zakesiramo vsa vprasanja v anketi
+ $this->get_vprasanja();
+
+ // Randomizacija v blokih in vprasanjih
+ $this->get_random();
+
+ // Za vrednosti ankete
+ $this->get_vrednosti();
+
+ // Za gride ankete
+ $this->get_gridi();
+
+ // Skreira array z polji za spss
+ $this->get_SPSS();
+
+
+ // Polovimo missing vrednosti ce so nastavljene drugače kot privzeto
+ // TODO če uporabnik na anketi spremeni da naj bo -1 -6 se to ne upošteva.
+ $this->setSurveyMissingValues();
+ }
+
+ // Naredimo query za respondente (srv_users)
+ private function create_qry_users() {
+
+ if ($this->_qry_users === null ) {
+
+ if ((int)$this->data_file_time > 0 && file_exists($this->folder . 'export_data_'.$this->sid.'.dat')) {
+ # delamo inkremental
+ $inkremental_user_limit = " AND u.time_edit > FROM_UNIXTIME('".(int)$this->data_file_time."') ";
+ }
+ else {
+ # lovimo vse userje - datoteko generiramo na novo
+ $inkremental_user_limit = '';
+ }
+
+ $_qry_cnt = sisplet_query("SELECT count(*) FROM srv_user AS u WHERE u.ank_id = '".$this->sid."' AND u.preview='0' AND u.deleted='0' ".$inkremental_user_limit .$this->is_valid_user_limit);
+ $_allUsers_count = mysqli_fetch_row($_qry_cnt);
+
+ $this->_cnt_all_users = 0;
+
+ // naredimo array querijev za userje, limitirano po max vrednosti userjev na loop (MAX_USER_PER_LOOP)
+ $c = 0;
+ do {
+ // Naredimo query
+ $this->_qry_users[$c] = sisplet_query("SELECT u.id AS usr_id, u.cookie, u.recnum, u.last_status as status, u.pass, u.testdata, u.lurker, u.unsubscribed, UNIX_TIMESTAMP(u.time_insert) AS unx_ins_date, UNIX_TIMESTAMP(u.time_edit) AS unx_edt_date, u.user_id, u.inv_res_id, u.time_insert, u.time_edit, u.ip, REPLACE(u.useragent,'|',' ') as useragent, u.browser, u.os, u.device, REPLACE(u.referer,'|',' ') as referer, language
+ FROM srv_user AS u
+ WHERE u.ank_id = '".$this->sid."' AND u.preview='0' AND u.deleted='0' ".$inkremental_user_limit . $this->is_valid_user_limit."
+ ORDER BY u.id ASC
+ LIMIT ".($c * MAX_USER_PER_LOOP).",".MAX_USER_PER_LOOP."");
+
+ if (!$this->_qry_users[$c]) {
+ $this->trigerError('create_qry_users', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ // Naredimo še string z id userjev za večkratno uporabo
+ $str = '';
+ if (mysqli_num_rows($this->_qry_users[$c]) > 0) {
+ $prefix ='';
+ while ($row = mysqli_fetch_assoc($this->_qry_users[$c])) {
+ $str .= $prefix.$row['usr_id'];
+ $prefix = ',';
+ }
+ $this->_str_users[$c] = ' AND usr_id IN ('.$str.') ';
+ }
+ $this->_cnt_all_users += mysqli_num_rows($this->_qry_users[$c]);
+
+ $c ++;
+ }
+ while ($c * MAX_USER_PER_LOOP <= $_allUsers_count['0']);
+ }
+ }
+
+ // Zakesiramo strani v anketi (srv_grupa)
+ private function get_groups() {
+
+ if ($this->_cnt_groups == 0) {
+
+ $qry_groups = sisplet_query("SELECT id FROM srv_grupa WHERE ank_id='".$this->sid."' ORDER BY vrstni_red");
+ if (!$qry_groups) {
+ $this->trigerError('get_groups', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ // koliko strani imamo v anketi
+ $this->_cnt_groups = mysqli_num_rows($qry_groups);
+
+ // naredimo še string z id grupami za večkratno uporabo
+ $str = '';
+ $cnt = 0;
+ if ($this->_cnt_groups > 0) {
+ $this->_array_groups = array();
+ $prefix ='';
+
+ while ($row = mysqli_fetch_assoc($qry_groups)) {
+ $cnt++;
+
+ $this->_array_groups[$row['id']] = $row['id'];
+ $str .= $prefix.$row['id'];
+ $prefix = ',';
+ }
+
+ $this->_str_groups = $str;
+ }
+ }
+ }
+
+ // Zakesiramo vsa vprasanja v anketi
+ private function get_vprasanja(){
+
+ // Delamo samo 1x
+ if ( $this->AllQuestionsData !== null && $this->AllQuestionsOrder != null) {
+ return array('AllQuestionsData'=>$this->AllQuestionsData, 'AllQuestionsOrder'=>$this->AllQuestionsOrder);
+ }
+
+
+ // Po novem lovimo tudi sistemske pa jih odstranimo pri prikazu in izvozih
+ $_qry_questions = sisplet_query("SELECT s.id, s.tip, s.variable, REPLACE(REPLACE(REPLACE(s.naslov,'\n',' '),'\r','<br>'),'|','<br>') as naslov, s.label, s.gru_id, s.gru_id, s.random, s.size, s.cela, s.decimalna, s.skala, s.enota, s.sistem, s.upload, s.signature, s.grid_subtitle1, s.grid_subtitle2, s.inline_edit, REPLACE(REPLACE(REPLACE(s.naslov_graf,'\n',' '),'\r','<br>'),'|','<br>') as naslov_graf, s.edit_graf, s.wide_graf, antonucci, s.visible, s.dostop
+ FROM srv_spremenljivka AS s, srv_grupa AS g
+ WHERE s.gru_id = g.id AND g.ank_id = '".$this->sid."' AND s.tip != '5'
+ ORDER BY g.vrstni_red, s.vrstni_red");
+ if (!$_qry_questions) {
+ $this->trigerError('get_vprasanja', mysqli_error($GLOBALS['connect_db']));
+ return false;
+ }
+
+ // Prestejemo vprasanja v anketi
+ $this->_cnt_questions = mysqli_num_rows($_qry_questions);
+
+ // Ce nimamo vprasanj v anketi ne gremo naprej
+ if ($this->_cnt_questions == 0) {
+ $this->trigerError('get_vprasanja', 'Ni vprasanj v anketi');
+ return false;
+ }
+
+
+ // Za SN - imena (modul social network)
+ if(SurveyInfo::getInstance()->checkSurveyModule('social_network')){
+
+ $_result = array();
+
+ while ($rowVprasanje = mysqli_fetch_assoc($_qry_questions)) {
+ if($rowVprasanje['tip'] == 9) {
+ $_result[] = $rowVprasanje['id'];
+ }
+ }
+
+ if (count($_result) > 0) {
+ foreach ($_result AS $spr_id) {
+ $qry = sisplet_query("SELECT vre_id FROM srv_data_text".$this->db_table." WHERE spr_id = '".$spr_id."' GROUP BY vre_id");
+ while ( $row = mysqli_fetch_assoc($qry)) {
+ if ( $row['vre_id'] > 0 ) {
+ $this->SNVariablesForSpr[$spr_id][$row['vre_id']] = $row['vre_id'];
+ }
+ }
+ }
+ }
+
+ mysqli_data_seek($_qry_questions, 0);
+ }
+
+
+ // Polovimo spremenljivke za survey Grid Multiple - kombinirano tabelo
+ $sgmMap = array();
+ $sqlSgmMap = sisplet_query("SELECT sgm.parent AS sgm_parrent, s.id, s.tip, s.variable, REPLACE(REPLACE(REPLACE(s.naslov,'\n',' '),'\r','<br>'),'|','<br>') as naslov, s.gru_id, s.size, s.random, s.cela, s.decimalna, s.skala, s.enota, s.sistem, s.upload, s.signature, s.grid_subtitle1, s.grid_subtitle2, s.inline_edit, REPLACE(REPLACE(REPLACE(s.naslov_graf,'\n',' '),'\r','<br>'),'|','<br>') as naslov_graf, s.edit_graf, s.wide_graf, s.antonucci, s.visible, s.dostop
+ FROM srv_spremenljivka AS s JOIN srv_grid_multiple AS sgm ON (s.id = sgm.spr_id)
+ WHERE sgm.ank_id = '$this->sid'
+ ORDER BY sgm.vrstni_red");
+ while ($sgmRow = mysqli_fetch_assoc($sqlSgmMap)) {
+ $sgmMap[$sgmRow['sgm_parrent']][] = $sgmRow;
+ }
+
+
+ // Preverimo ali so bili skreirani loopi
+ if ($this->_array_loop_on_spr == null || $this->_array_spr_in_loop == null) {
+ $this->get_loops();
+ }
+
+
+ // Pripravimo array-e za kesiranje vprasanj
+ $this->AllQuestionsData = array();
+ $this->AllQuestionsOrder = array();
+ $star_loop_id = null;
+
+ // Spremenljivka za kreacijo stringa z id spremenljivkami za večkratno uporabo
+ $sprIds = array();
+ $cnt = 0;
+
+ // Loop po vseh vprasanjih v anketi
+ while ($rowMainVprasanje = mysqli_fetch_assoc($_qry_questions)) {
+
+ // Naredimo array z id spremenljivkami za večkratno uporabo - za kombinirano tabelo posebej dodamo se podtabele
+ if ($rowMainVprasanje['tip'] != 24) {
+ $sprIds[] = $rowMainVprasanje['id'];
+ }
+ else {
+ $sqlSub = sisplet_query("SELECT s.id FROM srv_spremenljivka AS s JOIN srv_grid_multiple AS sgm ON (s.id = sgm.spr_id)
+ WHERE sgm.parent = '".$rowMainVprasanje['id']."'
+ ORDER BY sgm.vrstni_red");
+ while (list($subSprId) = mysqli_fetch_row($sqlSub)) {
+ $sprIds[] = $subSprId;
+ }
+ }
+
+
+ $rowVprasanja = array();
+
+ if (!is_countable($sgmMap[$rowMainVprasanje['id']]) || count($sgmMap[$rowMainVprasanje['id']]) == 0) {
+ $rowVprasanja[] = $rowMainVprasanje;
+ }
+ else {
+ // preverimo parent tip. mora biti 24
+ if ((int)$rowMainVprasanje['tip'] == 24){
+
+ // imamo kombinirano vprašanje
+ foreach ($sgmMap[$rowMainVprasanje['id']] AS $sgmRow) {
+ $tmpVprasanje = $sgmRow;
+
+ // popravimo variablo in besedilo
+ $tmpVprasanje['sgm_parrent'] = $rowMainVprasanje['id'];
+ $tmpVprasanje['variable'] = $rowMainVprasanje['variable'].'_'.$sgmRow['variable'];
+ $tmpVprasanje['naslov'] = $rowMainVprasanje['naslov'];
+ $rowVprasanja[] = $tmpVprasanje;
+ }
+ }
+ // če ne ni kombinirana tabela
+ else {
+ $rowVprasanja[] = $rowMainVprasanje;
+ }
+ }
+
+ if (count($rowVprasanja) > 0) {
+
+ foreach ($rowVprasanja AS $rowVprasanje) {
+
+ $spr_id = $rowVprasanje['id'];
+
+ $this->AllQuestionsData[$rowVprasanje['id']] = array(
+ 'id' => $rowVprasanje['id'],
+ 'spr_id' => $spr_id,
+ 'sgm_parrent' => $rowVprasanje['sgm_parrent'],
+ 'tip' => $rowVprasanje['tip'],
+ 'gru_id' => $rowVprasanje['gru_id'],
+ 'variable' => strip_tags($rowVprasanje['variable']),
+ 'naslov' => strip_tags($rowVprasanje['naslov']),
+ 'label' => strip_tags($rowVprasanje['label']),
+ 'size' => $rowVprasanje['size'],
+ 'cela' => $rowVprasanje['cela'],
+ 'grid_subtitle1' => $rowVprasanje['grid_subtitle1'],
+ 'grid_subtitle2' => $rowVprasanje['grid_subtitle2'],
+ 'decimalna' => $rowVprasanje['decimalna'],
+ 'skala' => $rowVprasanje['skala'],
+ 'sistem' => $rowVprasanje['sistem'],
+ 'enota' => $rowVprasanje['enota'],
+ 'if_id' => (isset($this->_array_spr_in_loop[$spr_id]) ? $this->_array_spr_in_loop[$spr_id] : 0),
+ 'upload' => $rowVprasanje['upload'],
+ 'signature' => $rowVprasanje['signature'],
+ 'naslov_graf' => $rowVprasanje['naslov_graf'],
+ 'edit_graf' => $rowVprasanje['edit_graf'],
+ 'wide_graf' => $rowVprasanje['wide_graf'],
+ 'antonucci' => $rowVprasanje['antonucci'],
+ 'visible' => $rowVprasanje['visible'],
+ 'dostop' => $rowVprasanje['dostop'],
+ 'random' => $rowVprasanje['random']
+ );
+
+ if ($rowVprasanje['inline_edit'] != 0) {
+ $this->AllQuestionsData[$rowVprasanje['id']]['inline_edit'] = $rowVprasanje['inline_edit'];
+ }
+
+ // Zabelezimo stevilo vprasanj po tipu
+ $this->_cnt_questions_types[$rowVprasanje['tip']] = (isset($this->_cnt_questions_types[$rowVprasanje['tip']])) ? $this->_cnt_questions_types[$rowVprasanje['tip']]+1 : 1;
+
+ // če je spremenljivka parent od loopa jo dodamo
+ if (isset($this->_array_loop_parent[$spr_id]) && $this->_array_loop_parent[$spr_id] > 0) {
+ $this->AllQuestionsData[$rowVprasanje['id']]['loop_parent'] = $this->_array_loop_parent[$spr_id];
+ $this->AllQuestionsData[$rowVprasanje['id']]['antonucci'] = $rowVprasanje['antonucci'];
+ }
+
+ // dodamo vprašanje v vrstni red, če je vprašanje v loopu dodamo loop
+ if (!isset($this->_array_spr_in_loop[$spr_id])) {
+
+ // vprašanje ni v loopu
+ $this->AllQuestionsOrder[] = array('id'=>$spr_id, 'loop_id'=>0);
+
+ // nismo v loopu
+ $star_loop_id = null;
+ }
+ else {
+ // vprašanje je v lopu
+ $trenutni_loop_id = $this->_array_spr_in_loop[$spr_id]; # id loopa v katerem se nahaja spremenljivk
+
+ // na katero spremenljivko se dela loop
+ $loop_on_spr = $this->_array_loop_on_spr[$trenutni_loop_id];
+
+ // če ta loop in pripadajoča vprašanja še niso bila dodana v vrstni red, jih dodamoše ni bil
+ if ($trenutni_loop_id != $star_loop_id) {
+
+ // loop še ni bil sprocesiran;
+ $_vrednosti_v_loopu = $this->_array_vre_on_loop[$trenutni_loop_id];
+
+ // preverimo ali smo v navadnem loopu ali v SN loopu
+ if (isset($this->SNVariablesForSpr[$loop_on_spr]) == false) {
+
+ // smo v navadnem loopu
+ // kolikokrat moramo iti skozi loop
+ if (count($_vrednosti_v_loopu)) {
+
+ foreach ($_vrednosti_v_loopu AS $li_id => $vrednost) {
+
+ // dodamo vprašanja ki so v posameznemm loopu.
+ if (count($this->_array_loop_has_spr[$trenutni_loop_id])) {
+ foreach($this->_array_loop_has_spr[$trenutni_loop_id] AS $vprasanje) {
+ $this->AllQuestionsOrder[] = array('id'=>$vprasanje,'loop_id'=>$li_id,'vre_id'=>$vrednost, 'parent_loop_id'=>$trenutni_loop_id);
+ }
+ }
+ }
+ }
+ }
+ else {
+ // smo v SN loopu - skozi loop gremo samo za vrednosti ki so dodane kot sn imena
+ if (count($_vrednosti_v_loopu)) {
+ foreach ($_vrednosti_v_loopu AS $li_id => $vrednost) {
+
+ if (in_array($vrednost,$this->SNVariablesForSpr[$loop_on_spr])) {
+
+ // dodamo vprašanja ki so v posameznemm loopu.
+ if (count($this->_array_loop_has_spr[$trenutni_loop_id])) {
+ foreach($this->_array_loop_has_spr[$trenutni_loop_id] AS $vprasanje) {
+ $this->AllQuestionsOrder[] = array('id'=>$vprasanje,'loop_id'=>$li_id,'vre_id'=>$vrednost, 'parent_loop_id'=>$trenutni_loop_id);
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ # priredimo kateri loop smo že obdelali, da ne bomo 2x
+ $star_loop_id = $trenutni_loop_id;
+ }
+ }
+ }
+ }
+ }
+
+ // Naredimo string z id spremenljivkami za večkratno uporabo
+ if (count($sprIds) > 0) {
+ $this->_str_questions = implode(',', $sprIds);
+ }
+
+ return array('AllQuestionsData'=>$this->AllQuestionsData, 'AllQuestionsOrder'=>$this->AllQuestionsOrder);
+ }
+
+ // Polovimo podatke za loop ce je kaksen v anketi
+ private function get_loops() {
+
+ // na katero spremenljivko se veže loop
+ $this->_array_loop_on_spr = array();
+ $this->_array_loop_parent = array();
+
+ $qryLoop_spr_select = sisplet_query("SELECT l.if_id, l.spr_id
+ FROM srv_branching AS b, srv_loop AS l
+ WHERE b.ank_id = '".$this->sid."' AND b.element_if = l.if_id");
+ while (list($loop_id,$spr_id) = mysqli_fetch_row($qryLoop_spr_select)) {
+ $this->_array_loop_parent[$spr_id] = $loop_id;
+ $this->_array_loop_on_spr[$loop_id] = $spr_id;
+
+ $_cnt_loop++;
+ }
+
+ // katere vrednosti uporablja posamezen loop ( kolikokrat se loop zavrti)
+ $this->_array_vre_on_loop = array();
+ $this->_array_vrednosti_in_loops = array();
+
+ $qry_vre_on_loop_select = sisplet_query("SELECT ld.id, ld.if_id, ld.vre_id
+ FROM srv_loop_data AS ld
+ WHERE ld.if_id IN
+ (SELECT l.if_id
+ FROM srv_branching AS b, srv_loop AS l
+ WHERE b.ank_id = '".$this->sid."' AND b.element_if = l.if_id)
+ ORDER BY if_id, ld.vre_id, ld.id");
+ while (list($id, $loop_id,$vre_id) = mysqli_fetch_row($qry_vre_on_loop_select)) {
+
+ // če imamp SN -imena in je loop na SN - imena ne loopamo po vseh vrednostih, ampak samo po max vnosih
+ $this->_array_vre_on_loop[$loop_id][$id] = $vre_id;
+ $this->_array_vrednosti_in_loops[] = $vre_id;
+
+ // Posebej nastavimo ce gre za loop po numeric vprasanju
+ if($vre_id == null){
+ $this->_array_vre_on_loop[$loop_id][$id] = 'num_loop';
+ $this->_array_vrednosti_in_loops[] = 'num_loop';
+ }
+ }
+
+ // preverimo katere spremenljvke so v katerem loopu
+ $this->_array_spr_in_loop = array();
+ $this->_array_loop_has_spr = array();
+ $b = new Branching ($this->sid);
+ $_loops = $b->spremenljivke_in_loop();
+
+ if (count($_loops) > 0 ) {
+
+ foreach ($_loops AS $lkey => $spr_ids) {
+
+ if (count($spr_ids) > 0 ) {
+ $this->_array_loop_has_spr[$lkey] = array();
+
+ foreach ($spr_ids AS $spr_id) {
+ $this->_array_spr_in_loop[$spr_id] = $lkey;
+ $this->_array_loop_has_spr[$lkey][] = $spr_id;
+ }
+ }
+ }
+ }
+ }
+
+ // Zakesiramo vrednosti vprasanj v anketi
+ private function get_vrednosti($spid=null) {
+
+ // Ce ze imamo podatek in iscemo za posamezno spremenljivko
+ if ($spid != null && (int)$spid > 0 && isset($this->_array_vrednosti[$spid])) {
+ return $this->_array_vrednosti[$spid];
+ }
+
+ // Ce ze imamo pripravljen cel array
+ if ($spid == null && $this->_array_vrednosti !== null) {
+ return $this->_array_vrednosti;
+ }
+
+
+ if ($this->_str_questions != '') {
+
+ $_qry_vrednosti = sisplet_query("SELECT id, spr_id, REPLACE(REPLACE(REPLACE(naslov,'\n',' '),'\r','<br>'),'|',' ') as naslov, REPLACE(REPLACE(REPLACE(naslov2,'\n',' '),'\r','<br>'),'|',' ') as naslov2, variable, vrstni_red, other, REPLACE(REPLACE(REPLACE(naslov_graf,'\n',' '),'\r','<br>'),'|',' ') as naslov_graf
+ FROM srv_vrednost
+ WHERE spr_id IN (".$this->_str_questions.")
+ ORDER BY spr_id, vrstni_red");
+ if (!$_qry_vrednosti) {
+ $this->trigerError('get_vrednosti', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ $_cnt_vrednosti = mysqli_num_rows($_qry_vrednosti);
+
+ if ($_cnt_vrednosti > 0) {
+
+ while (list($id, $spr_id, $naslov, $naslov2, $variable, $vrstni_red, $other, $naslov_graf) = mysqli_fetch_row($_qry_vrednosti)) {
+
+ $this->_array_vrednosti[(int)$spr_id][(int)$id] = array(
+ 'id' => (int)$id,
+ 'naslov' => strip_tags($naslov),
+ 'naslov2' => strip_tags($naslov2),
+ 'variable' => $variable,
+ 'vrstni_red' => (int)$vrstni_red,
+ 'other' => (int)$other,
+ 'naslov_graf' => strip_tags($naslov_graf)
+ );
+ }
+ }
+ }
+
+
+ if ($spid != null && (int)$spid > 0) {
+ return $this->_array_vrednosti[$spid];
+ }
+ else {
+ return $this->_array_vrednosti;
+ }
+ }
+
+ // Zakesiramo gride tabel vprasanj v anketi
+ private function get_gridi($grid=null) {
+
+ // Ce ze imamo podatek in iscemo za posamezno spremenljivko
+ if ($grid != null && (int)$grid > 0 && isset($this->_array_gridi[$grid])) {
+ return $this->_array_gridi[$grid];
+ }
+
+ // Vrenmo celoten array
+ if ($grid == null && $this->_array_gridi !== null) {
+ return $this->_array_gridi;
+ }
+
+
+ if ($this->_str_questions != '') {
+
+ $_qry_gridi = sisplet_query("SELECT id, spr_id, REPLACE(REPLACE(REPLACE(naslov,'\n',' '),'\r','<br>'),'|',' ') as naslov, variable, other, part, REPLACE(REPLACE(REPLACE(naslov_graf,'\n',' '),'\r','<br>'),'|',' ') as naslov_graf, vrstni_red
+ FROM srv_grid
+ WHERE spr_id IN (".$this->_str_questions.")
+ ORDER BY spr_id, vrstni_red");
+
+ if (!$_qry_gridi) {
+ $this->trigerError('get_gridi', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ $_cnt_gridi = mysqli_num_rows($_qry_gridi);
+
+ if ($_cnt_gridi > 0) {
+
+ while (list($id, $spr_id, $naslov, $variable, $other, $part, $naslov_graf) = mysqli_fetch_row($_qry_gridi)) {
+
+ $this->_array_gridi[(int)$spr_id][(int)$id] = array(
+ 'id' => (int)$id,
+ 'naslov' => strip_tags($naslov),
+ 'variable' => $variable,
+ 'other' => (int)$other,
+ 'part' => (int)$part,
+ 'naslov_graf' => strip_tags($naslov_graf)
+ );
+ }
+ }
+ }
+
+
+ if ($grid != null && (int)$grid > 0 ) {
+ return $this->_array_gridi[$grid];
+ }
+ else {
+ return $this->_array_gridi;
+ }
+ }
+
+ // Zakesiramo podatke za SPSS
+ private function get_SPSS() {
+
+ if ($this->_array_SPSS === null && $this->_str_questions != '') {
+
+ $this->_array_SPSS = array();
+
+ $_qry_SPSS = sisplet_query("SELECT dt.spr_id, MAX(LENGTH(dt.text)) AS length, MAX(LENGTH(dt.text2)) AS length2
+ FROM srv_data_text".$this->db_table." dt, srv_grupa g, srv_spremenljivka s
+ WHERE dt.spr_id = s.id AND s.gru_id=g.id AND g.ank_id=".$this->sid."
+ GROUP BY dt.spr_id");
+ while (list($spr_id, $text, $text2) = mysqli_fetch_row($_qry_SPSS)) {
+ $this->_array_SPSS[$spr_id] = array('text'=>(int)$text, 'text2'=>(int)$text2);
+ }
+
+ $_qry_SPSS1 = sisplet_query("SELECT spr_id, max(LENGTH(text)) AS length
+ FROM srv_data_textgrid".$this->db_table."
+ WHERE spr_id IN (".$this->_str_questions.")
+ GROUP BY spr_id");
+ while (list($spr_id, $text) = mysqli_fetch_row($_qry_SPSS1)) {
+ $this->_array_SPSS[$spr_id]['text2'] = $text;
+ }
+
+ // polovimo še max vrednosti za variable
+ $tmp_qry_SPSS = sisplet_query("SELECT spr_id, max(LENGTH(vrstni_red)) AS length
+ FROM srv_vrednost
+ WHERE spr_id IN (".$this->_str_questions.")
+ GROUP BY spr_id
+ ORDER BY spr_id, vrstni_red");
+ while (list($spr_id, $vrstni_red) = mysqli_fetch_row($tmp_qry_SPSS)) {
+ $this->_array_SPSS[$spr_id]['vrednost'] = $vrstni_red;
+ }
+ }
+
+ return $this->_array_SPSS;
+ }
+
+ // Zakesiramo vse bloke in vprasanja, ki imajo vklopljeno randomizacijo
+ private function get_random () {
+
+ // ce smo ze zakesirali vrednosti
+ if ($this->_array_random != null) {
+ return $this->_array_random;
+ }
+
+ $this->_array_random = array();
+
+
+ // Preberemo vsa VPRASANJA ki imajo vklopljeno randomizacijo
+ $_qry_random_spr = sisplet_query("SELECT s.id, s.variable FROM srv_spremenljivka s, srv_grupa g
+ WHERE g.ank_id='".$this->sid."' AND s.gru_id=g.id AND s.random='1'
+ ORDER BY s.vrstni_red");
+ if (!$_qry_random_spr) {
+ $this->trigerError('get_random', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ # koliko zapicov
+ $cnt_rows = mysqli_num_rows($_qry_random_spr);
+
+ // Napolnimo array z randomiziranimi vprasanji
+ if ($cnt_rows > 0) {
+ while ($row = mysqli_fetch_array($_qry_random_spr)) {
+
+ $this->_array_random[$row['id']]['id'] = $row['id'];
+ $this->_array_random[$row['id']]['variable'] = $row['variable'];
+ $this->_array_random[$row['id']]['type'] = 'spr';
+ }
+ }
+
+
+ // Preberemo vse BLOKE ki imajo vklopljeno randomizacijo
+ $_qry_random_blok = sisplet_query("SELECT i.id, i.random, i.label, i.number
+ FROM srv_if i, srv_branching b
+ WHERE b.ank_id='".$this->sid."' AND b.element_if=i.id AND (i.random>=0 OR i.random=-2) AND i.tip='1'");
+ if (!$_qry_random_blok) {
+ $this->trigerError('get_random', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ # koliko zapicov
+ $cnt_rows = mysqli_num_rows($_qry_random_blok);
+
+ // Napolnimo array z randomiziranimi bloki
+ if ($cnt_rows > 0) {
+
+ $prefix = '';
+
+ while ($row = mysqli_fetch_array($_qry_random_blok)) {
+
+ $this->_array_random[$row['id']]['id'] = $row['id'];
+ $this->_array_random[$row['id']]['variable'] = $row['label'];
+ $this->_array_random[$row['id']]['number'] = $row['number'];
+
+ // Napolnimo string z id-ji blokov
+ $this->_str_blocks .= $prefix.$row['id'];
+ $prefix = ',';
+
+ // Blok ima randomizirane bloke
+ if($row['random'] == -2){
+ $this->_array_random[$row['id']]['type'] = 'blok_blok';
+ }
+ // Blok ima randomizirana vprasanja
+ else{
+ $this->_array_random[$row['id']]['type'] = 'blok_spr';
+ }
+ }
+ }
+ }
+
+ /***** KONEC - KESIRANJE PODATKOV ANKETE (vprasanja, strani, gridi...) *****/
+
+
+
+ /***** KESIRANJE ODGOVOROV POSAMEZNEGA RESPONDENTA *****/
+
+ // Zakesiramo odgovore respondenta
+ private function cache_data_respondent($string_user){
+
+ if ($this->_str_questions != '') {
+
+ // resetiramo POINTER-je - Array-je do podatkov
+ $this->_array_user_grupa = null;
+ $this->_array_data_vrednost = null;
+ $this->_array_data_text = null;
+ $this->_array_data_grids = null;
+ $this->_array_data_check_grids = null;
+ $this->_array_data_text_grid = null;
+ $this->_array_data_rating = null;
+ $this->_array_data_text_upload = null;
+ $this->_array_data_map = null;
+ $this->_array_data_heatmap = null;
+ $this->_array_data_heatmap_regions = null;
+ $this->_array_data_vrednost_cond = null;
+ $this->_array_data_random = null;
+
+
+ // polovimo id-je strani do katerih je prišel posamezen uporabnik
+ $this->get_user_grupa($string_user);
+
+
+ // Popravimo string za omejevanje userjev
+ $_string_user = str_replace(array(' AND usr_id IN (', ')'), '', $string_user);
+ $_string_user = explode(',', $_string_user);
+ $string_user = ' AND usr_id BETWEEN '.$_string_user[0].' AND '.end($_string_user);
+
+ // Zakesiramo vse podatke - ce ni nobenega vprasanja tega tipa v anketi, ne rabimo tega izvajat
+ $this->cache_data_respondent_vrednost($string_user);
+ $this->cache_data_respondent_text($string_user);
+
+ // Kesiranje podatkov za srv_data_grid
+ if((isset($this->_cnt_questions_types['6']) && $this->_cnt_questions_types['6'] > 0)
+ || (isset($this->_cnt_questions_types['16']) && $this->_cnt_questions_types['16'] > 0)
+ || (isset($this->_cnt_questions_types['19']) && $this->_cnt_questions_types['19'] > 0)
+ || (isset($this->_cnt_questions_types['20']) && $this->_cnt_questions_types['20'] > 0)
+ || (isset($this->_cnt_questions_types['24']) && $this->_cnt_questions_types['24'] > 0)
+ )
+ $this->cache_data_respondent_grid($string_user);
+
+ // Kesiranje podatkov za srv_data_checkgrid
+ if((isset($this->_cnt_questions_types['6']) && $this->_cnt_questions_types['6'] > 0)
+ || (isset($this->_cnt_questions_types['16']) && $this->_cnt_questions_types['16'] > 0)
+ || (isset($this->_cnt_questions_types['24']) && $this->_cnt_questions_types['24'] > 0)
+ )
+ $this->cache_data_respondent_check_grid($string_user);
+
+ // Kesiranje podatkov za srv_data_textgrid
+ if((isset($this->_cnt_questions_types['19']) && $this->_cnt_questions_types['19'] > 0)
+ || (isset($this->_cnt_questions_types['20']) && $this->_cnt_questions_types['20'] > 0)
+ || (isset($this->_cnt_questions_types['24']) && $this->_cnt_questions_types['24'] > 0)
+ )
+ $this->cache_data_respondent_text_grid($string_user);
+
+ // Kesiranje podatkov za srv_data_rating
+ if(isset($this->_cnt_questions_types['17']) && $this->_cnt_questions_types['17'] > 0)
+ $this->cache_data_respondent_rating($string_user);
+
+ // Kesiranje podatkov za srv_data_text_upload
+ if(isset($this->_cnt_questions_types['21']) && $this->_cnt_questions_types['21'] > 0)
+ $this->cache_data_respondent_text_upload($string_user);
+
+ // Kesiranje podatkov za srv_data_map
+ if(isset($this->_cnt_questions_types['26']) && $this->_cnt_questions_types['26'] > 0)
+ $this->cache_data_respondent_map($string_user);
+
+ // Kesiranje podatkov za srv_data_heatmap in srv_data_heatmap_regions
+ if(isset($this->_cnt_questions_types['27']) && $this->_cnt_questions_types['27'] > 0){
+ $this->cache_data_respondent_heatmap($string_user);
+ $this->cache_data_respondent_heatmap_regions($string_user);
+ }
+
+ // Kesiranje podatkov za srv_data_vrednost_cond
+ if((isset($this->_cnt_questions_types['2']) && $this->_cnt_questions_types['2'] > 0)
+ || (isset($this->_cnt_questions_types['27']) && $this->_cnt_questions_types['27'] > 0)
+ )
+ $this->cache_data_respondent_vrednost_cond($string_user);
+
+ // Kesiranje podatkov za randomizirane vrednosti oz. randomizirana vprasanja v blokih
+ $this->cache_data_respondent_random($string_user);
+ }
+ }
+
+ // Zakesiramo case odgovorov po straneh za respondenta
+ private function get_user_grupa($string_user) {
+
+ if ($this->_str_groups != '') {
+
+ $qry = sisplet_query("SELECT gru_id, usr_id, time_edit, preskocena FROM srv_user_grupa".$this->db_table." WHERE gru_id IN (".$this->_str_groups.") ".$string_user."");
+ if (!$qry) {
+ $this->trigerError('get_user_grupa', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ $this->_array_user_grupa = array();
+
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $this->_array_user_grupa[(int)$row['usr_id']][(int)$row['gru_id']] = $row['time_edit'];
+ }
+ }
+
+ }
+
+ // Zakesiramo podatke tabele srv_data_vrednost
+ private function cache_data_respondent_vrednost($string_user){
+
+ if ($this->_array_data_vrednost === null) {
+
+ $_qry_data_vrednost = sisplet_query("SELECT spr_id, vre_id, usr_id, loop_id
+ FROM srv_data_vrednost".$this->db_table."
+ WHERE spr_id IN (".$this->_str_questions.")" . $string_user);
+ if (!$_qry_data_vrednost) {
+ $this->trigerError('cache_data_respondent_vrednost', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_vrednost) > 0) {
+
+ while (list($spr_id, $vre_id, $usr_id,$loop_id) = mysqli_fetch_row($_qry_data_vrednost)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+ $this->_array_data_vrednost[(int)$usr_id][$spr_id.'_'.$loop_id][(int)$vre_id] = (int)$vre_id;
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_vrednost
+ private function get_array_data_vrednost ($uid, $spid) {
+
+ if (isset($this->_array_data_vrednost[$uid][$spid]))
+ return $this->_array_data_vrednost[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_text
+ private function cache_data_respondent_text($string_user){
+
+ if ($this->_array_data_text === null) {
+
+ $_qry_data_text = sisplet_query("SELECT spr_id, vre_id, usr_id, REPLACE(REPLACE(REPLACE(text,'\n',' '),'\r',' '),'|',' ') as text, REPLACE(REPLACE(REPLACE(text2,'\n',' '),'\r',' '),'|',' ') as text2, loop_id
+ FROM srv_data_text".$this->db_table."
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_text) {
+ $this->trigerError('cache_data_respondent_text', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_text) > 0) {
+
+ while (list($spr_id, $vre_id, $usr_id, $text, $text2, $loop_id) = mysqli_fetch_row($_qry_data_text)) {
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+
+ // Addslashes je potreben za analize
+ $this->_array_data_text[(int)$usr_id][$spr_id.'_'.$loop_id][(int)$vre_id] = array(
+ 'text'=>trim(addslashes(strip_tags($text))),
+ 'text2'=>trim(addslashes(strip_tags($text2)))
+ );
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_text
+ private function get_array_data_text ($uid, $spid) {
+
+ if (isset($this->_array_data_text[$uid][$spid]))
+ return $this->_array_data_text[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_grid
+ private function cache_data_respondent_grid($string_user){
+
+ if ($this->_array_data_grids === null) {
+
+ $_qry_data_grids = sisplet_query("SELECT spr_id, vre_id, usr_id, grd_id, loop_id
+ FROM srv_data_grid".$this->db_table."
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_grids) {
+ $this->trigerError('cache_data_respondent_grid', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_grids) > 0) {
+
+ while (list($spr_id, $vre_id, $usr_id, $grd_id, $loop_id) = mysqli_fetch_row($_qry_data_grids)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+ $this->_array_data_grids[(int)$usr_id][$spr_id.'_'.$loop_id ][(int)$vre_id] = (int)$grd_id;
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_grids
+ private function get_array_data_grids ($uid, $spid) {
+
+ if (isset($this->_array_data_grids[$uid][$spid]))
+ return $this->_array_data_grids[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_checkgrid
+ private function cache_data_respondent_check_grid($string_user){
+
+ if ($this->_array_data_check_grids === null) {
+
+ $_qry_data_check_grids = sisplet_query("SELECT spr_id, vre_id, usr_id, grd_id, loop_id
+ FROM srv_data_checkgrid".$this->db_table."
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_check_grids) {
+ $this->trigerError('cache_data_respondent_check_grid', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_check_grids) > 0) {
+
+ while (list($spr_id, $vre_id, $usr_id, $grd_id, $loop_id) = mysqli_fetch_row($_qry_data_check_grids)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+ $this->_array_data_check_grids[(int)$usr_id][$spr_id.'_'.$loop_id][(int)$vre_id][(int)$grd_id] = (int)$grd_id;
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_checkgrid
+ private function get_array_data_check_grids ($uid, $spid) {
+
+ if (isset($this->_array_data_check_grids[$uid][$spid]))
+ return $this->_array_data_check_grids[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_textgrid
+ private function cache_data_respondent_text_grid($string_user){
+
+ if ($this->_array_data_text_grid === null) {
+
+ $_qry_data_text_grid = sisplet_query("SELECT spr_id, vre_id, usr_id, grd_id, REPLACE(REPLACE(REPLACE(REPLACE(text, '\\\\', '/'),'\n',' '),'\r','<br>'),'|',' ') as text, loop_id
+ FROM srv_data_textgrid".$this->db_table."
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_text_grid) {
+ $this->trigerError('cache_data_respondent_text_grid', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_text_grid) > 0) {
+
+ while ( list($spr_id, $vre_id, $usr_id, $grd_id, $text, $loop_id) = mysqli_fetch_row($_qry_data_text_grid)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+ $this->_array_data_text_grid[(int)$usr_id][$spr_id.'_'.$loop_id][(int)$vre_id][(int)$grd_id] = trim(strip_tags($text));
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_textgrid
+ private function get_array_data_text_grid ($uid, $spid) {
+
+ if (isset($this->_array_data_text_grid[$uid][$spid]))
+ return $this->_array_data_text_grid[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_rating
+ private function cache_data_respondent_rating($string_user){
+
+ if ($this->_array_data_rating === null) {
+
+ $_qry_data_rating = sisplet_query("SELECT spr_id, vre_id, usr_id, vrstni_red, loop_id
+ FROM srv_data_rating
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_rating) {
+ $this->trigerError('cache_data_respondent_rating', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_rating) > 0) {
+
+ while (list($spr_id, $vre_id, $usr_id, $vrstni_red, $loop_id) = mysqli_fetch_row($_qry_data_rating)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+ $this->_array_data_rating[(int)$usr_id][$spr_id.'_'.$loop_id][(int)$vre_id] = (int)$vrstni_red;
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_rating
+ private function get_array_data_rating ($uid, $spid) {
+
+ if (isset($this->_array_data_rating[$uid][$spid]))
+ return $this->_array_data_rating[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_upload
+ private function cache_data_respondent_text_upload($string_user){
+
+ if ($this->_array_data_text_upload === null) {
+
+ $_qry_data_text_upload = sisplet_query("SELECT usr_id, code, filename
+ FROM srv_data_upload
+ WHERE ank_id='".$this->sid."' ".$string_user);
+ if (!$_qry_data_text_upload) {
+ $this->trigerError('cache_data_respondent_text_upload', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_text_upload) > 0) {
+
+ while (list($usr_id, $code, $filename) = mysqli_fetch_row($_qry_data_text_upload)) {
+ $this->_array_data_text_upload[$code] = strip_tags($filename);
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za filename za posamezen code za tabelo srv_data_upload
+ private function get_array_data_text_upload ($_code) {
+
+ if (isset($this->_array_data_text_upload[$_code]))
+ return $this->_array_data_text_upload[$_code];
+ else
+ return 'Download';
+ }
+
+ // Zakesiramo podatke tabele srv_data_map
+ private function cache_data_respondent_map($string_user){
+
+ if ($this->_array_data_map === null) {
+
+ $_qry_data_map = sisplet_query("SELECT spr_id, usr_id, REPLACE(REPLACE(REPLACE(address,'\n',' '),'\r',' '),'|',' ') as address, REPLACE(REPLACE(REPLACE(text,'\n',' '),'\r',' '),'|',' ') as text, lat, lng, loop_id
+ FROM srv_data_map
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_map) {
+ $this->trigerError('cache_data_respondent_map', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ $i = 0;
+ if (mysqli_num_rows($_qry_data_map) > 0) {
+
+ while (list($spr_id, $usr_id, $address, $text, $lat, $lng, $loop_id) = mysqli_fetch_row($_qry_data_map)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+
+ // Ce respondent ni vnesel vrednosti v infowindow
+ if($text == '' || $text == null) $text = '-1';
+
+ // Addslashes je potreben za analize
+ if($this->_array_data_map[(int)$usr_id][$spr_id.'_'.$loop_id]){
+ $this->_array_data_map[(int)$usr_id][$spr_id.'_'.$loop_id]['izpis'][$i] = array(
+ 'address'=>addslashes(strip_tags($address)),
+ 'vrednost'=>addslashes(strip_tags($text)),
+ 'koordinate'=> $lat . ', ' . $lng);
+ }
+ else{
+ $this->_array_data_map[(int)$usr_id][$spr_id.'_'.$loop_id] = array(
+ 'izpis'=>array(array(
+ 'address'=>addslashes(strip_tags($address)),
+ 'vrednost'=>addslashes(strip_tags($text)),
+ 'koordinate'=>$lat . ', ' . $lng)),
+ 'spr_id' => $spr_id, 'usr_id' => $usr_id, 'loop_id' => $loop_id);
+ }
+
+ $i++;
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_map
+ private function get_array_data_map ($uid, $spid) {
+
+ if (isset($this->_array_data_map[$uid][$spid]))
+ return $this->_array_data_map[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_heatmap
+ private function cache_data_respondent_heatmap($string_user){
+
+ if ($this->_array_data_heatmap === null) {
+
+ $_qry_data_heatmap = sisplet_query("SELECT spr_id, usr_id, REPLACE(REPLACE(REPLACE(address,'\n',' '),'\r',' '),'|',' ') AS address, REPLACE(REPLACE(REPLACE(text,'\n',' '),'\r',' '),'|',' ') as text, lat, lng, loop_id
+ FROM srv_data_heatmap
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_heatmap) {
+ $this->trigerError('cache_data_respondent_heatmap', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ $i = 0;
+ if (mysqli_num_rows($_qry_data_heatmap)) {
+
+ while (list($spr_id, $usr_id, $address, $text, $lat, $lng, $loop_id) = mysqli_fetch_row($_qry_data_heatmap)) {
+
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+
+ // ce respondent ni vnesel vrednosti v infowindow
+ if($text == '' || $text == null) $text = '-1';
+
+ // adslashes je potreben za analize
+ if($this->_array_data_heatmap[(int)$usr_id][$spr_id.'_'.$loop_id]){
+ $this->_array_data_heatmap[(int)$usr_id][$spr_id.'_'.$loop_id]['izpis'][$i] = array(
+ 'address'=>addslashes(strip_tags($address)),
+ 'vrednost'=>addslashes(strip_tags($text)),
+ 'koordinate'=> $lat . ', ' . $lng);
+ }
+ else{
+ $this->_array_data_heatmap[(int)$usr_id][$spr_id.'_'.$loop_id] = array(
+ 'izpis'=>array(array(
+ 'address'=>addslashes(strip_tags($address)),
+ 'vrednost'=>addslashes(strip_tags($text)),
+ 'koordinate'=>$lat . ', ' . $lng)),
+ 'spr_id' => $spr_id, 'usr_id' => $usr_id, 'loop_id' => $loop_id);
+ }
+
+ $i++;
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_heatmap
+ private function get_array_data_heatmap ($uid, $spid) {
+
+ if (isset($this->_array_data_heatmap[$uid][$spid]))
+ return $this->_array_data_heatmap[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_heatmap_regions
+ private function cache_data_respondent_heatmap_regions($string_user){
+
+ if ($this->_array_data_heatmap_regions === null) {
+
+ $spremenljivke_id = explode(",", $this->_str_questions);
+ $_qry_data_heatmap_regions = array();
+
+ foreach ($spremenljivke_id AS $val) {
+ $str_query_regions = "SELECT id, vre_id, spr_id, region_name, region_coords FROM srv_hotspot_regions WHERE spr_id =".$val.' ';
+ array_push($_qry_data_heatmap_regions, $str_query_regions);
+ }
+
+ foreach($_qry_data_heatmap_regions as $query){
+
+ $regionsQuery = sisplet_query($query);
+ if ($regionsQuery === null) {
+ $this->trigerError('cache_data_respondent_heatmap_regions', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ $i = 0;
+ if (mysqli_num_rows($regionsQuery) > 0) {
+
+ while (list($region_id, $vre_id, $spr_id, $region_name, $region_coords) = mysqli_fetch_row($regionsQuery)) {
+
+ // adslashes je potreben za analize
+ $this->_array_data_heatmap_regions[(int)$spr_id][$i] = array(
+ 'region_name' => addslashes(strip_tags($region_name)),
+ 'region_coords' => $region_coords);
+
+ $i++;
+ }
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_heatmap_regions
+ private function get_array_data_heatmap_regions ($uid, $spid) {
+
+ if (isset($this->_array_data_heatmap_regions[$uid][$spid]))
+ return $this->_array_data_heatmap_regions[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke tabele srv_data_vrednost_cond
+ private function cache_data_respondent_vrednost_cond($string_user){
+
+ if ($this->_array_data_vrednost_cond === null) {
+
+ $_qry_data_vrednost_cond = sisplet_query("SELECT spr_id, vre_id, usr_id, text, loop_id
+ FROM srv_data_vrednost_cond
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ if (!$_qry_data_vrednost_cond) {
+ $this->trigerError('cache_data_respondent_vrednost_cond', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_vrednost_cond) > 0) {
+
+ while ( list($spr_id, $vre_id, $usr_id, $text, $loop_id) = mysqli_fetch_row($_qry_data_vrednost_cond)) {
+ $loop_id = ($loop_id == null || $loop_id == '') ? 0 : $loop_id;
+
+ // adslashes je potreben za analize
+ $this->_array_data_vrednost_cond[(int)$usr_id][$spr_id.'_'.$loop_id][(int)$vre_id] = addslashes(strip_tags($text));
+ }
+ }
+ }
+ }
+
+ // Vrnemo vrednost za uid in spr_id za tabelo srv_data_vrednost_cond
+ private function get_array_data_vrednost_cond ($uid, $spid) {
+
+ if (isset($this->_array_data_vrednost_cond[$uid][$spid]))
+ return $this->_array_data_vrednost_cond[$uid][$spid];
+ else
+ return array();
+ }
+
+ // Zakesiramo podatke randomiziranih vprasanj
+ private function cache_data_respondent_random($string_user){
+
+ // Ce smo ze zakesirali ne rabimo naprej
+ if ($this->_array_data_random === null){
+
+ // Najprej dobimo random podatke za randomizacijo znotraj vprasanj
+ $_qry_data_random = sisplet_query("SELECT spr_id, usr_id, vrstni_red
+ FROM srv_data_random_spremenljivkaContent
+ WHERE spr_id IN (".$this->_str_questions.") ".$string_user);
+ //WHERE ".$string_user);
+ if (!$_qry_data_random) {
+ $this->trigerError('cache_data_respondent_random', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_random) > 0) {
+ while($row1 = mysqli_fetch_array($_qry_data_random)){
+ $this->_array_data_random[$row1['usr_id']]['spr'][$row1['spr_id']] = $row1['vrstni_red'];
+ }
+ }
+
+
+ // Dobimo se random podatke za randomizacijo znotraj blokov
+ if($this->_str_blocks != ''){
+
+ $_qry_data_random = sisplet_query("SELECT block_id, usr_id, vrstni_red
+ FROM srv_data_random_blockContent
+ WHERE block_id IN (".$this->_str_blocks.") ".$string_user);
+ //WHERE ".$string_user);
+ if (!$_qry_data_random) {
+ $this->trigerError('cache_data_respondent_random', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($_qry_data_random) > 0) {
+
+ while($row2 = mysqli_fetch_array($_qry_data_random)){
+
+ // Zgradimo string z labelami vprasanj za prikaz v podatkih
+ $vrstni_red_string = '';
+
+ // Spremenljivke v blokih
+ if($this->_array_random[$row2['block_id']]['type'] == 'blok_spr'){
+
+ // Pridobimo imena vprasanj za izpis
+ $sqlLabele1 = sisplet_query("SELECT variable
+ FROM srv_spremenljivka
+ WHERE id IN (".$row2['vrstni_red'].")
+ ORDER BY FIND_IN_SET(id, '".$row2['vrstni_red']."')
+ ");
+
+ while($rowLabele1 = mysqli_fetch_array($sqlLabele1)){
+ $vrstni_red_string .= $rowLabele1['variable'].',';
+ }
+ }
+ // Bloki v blokih
+ else{
+ // Pridobimo imena blokov za izpis
+ $sqlLabele2 = sisplet_query("SELECT number
+ FROM srv_if
+ WHERE id IN (".$row2['vrstni_red'].")
+ ORDER BY FIND_IN_SET(id, '".$row2['vrstni_red']."')
+ ");
+
+ if($sqlLabele2){
+ while($rowLabele2 = mysqli_fetch_array($sqlLabele2)){
+ $vrstni_red_string .= 'B'.$rowLabele2['number'].',';
+ }
+ }
+ }
+
+ $vrstni_red_string = substr($vrstni_red_string, 0, -1);
+ $this->_array_data_random[$row2['usr_id']]['block'][$row2['block_id']] = $vrstni_red_string;
+ }
+ }
+ }
+ }
+ }
+
+ // Vrnemo podatke vrstnega reda za userja in element (vprasanje ali blok)
+ private function get_array_data_random ($uid, $el_id, $el_type) {
+
+ if (isset($this->_array_data_random[$uid][$el_type][$el_id]))
+ return $this->_array_data_random[$uid][$el_type][$el_id];
+ else
+ return '';
+ }
+
+ /***** KONEC - KESIRANJE ODGOVOROV POSAMEZNEGA RESPONDENTA *****/
+
+
+
+ // Iz datoteke pobrisemo response, ki so zastareli / pobrisani
+ private function deleteUsers() {
+
+ // Datoteka s podatki
+ $f1 = $this->data_file_name;
+
+ // Datoteka kam zapišemo user id-je ki jih je potrebno pobrisat
+ $f2 = $this->data_file_name.'.todel';
+
+ // Datoteka kamor začasno shranimo original
+ $f3 = $this->data_file_name.'_'.time().'.orig';
+
+ if ((int)$this->sid > 0 && file_exists($f1)) {
+
+ try {
+
+ // Preberemo max time iz datoteke in uporabimo manjšega
+ if (IS_WINDOWS) {
+ $command = 'awk -F"|" "BEGIN {max = 0} {if ('.TIME_FIELD.' > max && '.TIME_FIELD.' > 0) max='.TIME_FIELD.' } END {print max}" '.$f1;
+ }
+ else {
+ $command = 'awk -F\'|\' \'BEGIN {max = 0} {if ('.TIME_FIELD.' > max && '.TIME_FIELD.' > 0) max='.TIME_FIELD.' } END {print max}\' '.$f1;
+ }
+ $user_time_from_file = shell_exec($command);
+
+ $inkremental_user_limit = " AND u.time_edit > FROM_UNIXTIME('".max((int)$this->data_file_time,(int)$user_time_from_file)."') ";
+
+ // Za inkrementalno brisanje datotek
+ $qry_users_deleted = sisplet_query("SELECT u.id AS usr_id FROM srv_user AS u WHERE u.ank_id='".$this->sid."' ".$inkremental_user_limit);
+ if (mysqli_num_rows($qry_users_deleted) > 0) {
+
+ // Zapišemo v datoteko idje respondentov, ki jih brišemo
+ $file = fopen($f2, 'w');
+
+ while (list($usr_id) = mysqli_fetch_row($qry_users_deleted)) {
+ fwrite($file, $usr_id . "\n");
+ }
+
+ fclose($file);
+
+ if (IS_WINDOWS) {
+ $cmd = 'cp '.$f1.' '.$f3.' && awk -F"|" "NR==FNR {++a[$0]; next} { f = $1; if (!a[$1]) print $0}" '.$f2.' '.$f3.' > '.$f1;
+ }
+ else {
+ $cmd = 'cp '.$f1.' '.$f3.' && awk -F\'|\' \'NR==FNR {++a[$0]; next} { f = $1; if (!a[$1]) print $0}\' '.$f2.' '.$f3.' > '.$f1;
+ }
+
+ $out_command = shell_exec($cmd);
+ }
+
+ // Ce je vse ok, pobrišemo datoteke
+ if (file_exists($f1)) {
+
+ // Pobrišemo datoteko z userji katere smo brisali
+ if (file_exists($f2)) {
+ unlink($f2);
+ }
+
+ // Pobrišemo backup datoteko
+ if (file_exists($f3)) {
+ unlink($f3);
+ }
+ }
+ }
+ catch (Exception $e) {
+ }
+ }
+ }
+
+ // Resetiramo vse pointerje
+ private function cleanup() {
+
+ $this->noErrors = true;
+
+ $this->_HEADER = null;
+
+ $this->_str_groups = null; # cache string za strani
+ $this->_cnt_groups = 0; # cache število za strani
+
+ $this->_str_questions = null; # cache string za vprašanja
+ $this->_cnt_questions = 0; # cache za število vprašanj
+
+ $this->_qry_users = null; # cache query za vprašanja
+ $this->_str_users = null; # cache string za user_id ji
+ $this->_cnt_all_users = 0; # cache za število userjev
+
+ $this->_array_vrednosti = null; # cache array z vrednostmi
+ $this->_array_gridi = null; # cache array z gridi
+ $this->_array_random = null; # cache array z random vprasanji in bloki
+ $this->_array_SPSS = null; # zakeširamo array usergrup za uporabnika
+ $this->_array_user_grupa = null; # zakeširamo array usergrup za uporabnika
+ $this->_array_users_from_CMS = null;
+
+ $this->_array_data_vrednost = null;
+ $this->_array_data_text = null;
+ $this->_array_data_grids = null;
+ $this->_array_data_check_grids = null;
+ $this->_array_data_text_grid = null;
+ $this->_array_data_rating = null;
+ $this->_array_data_text_grid = null;
+ $this->_array_data_text_upload = null;
+ $this->_array_data_map = null;
+ $this->_array_data_heatmap = null;
+ $this->_array_data_heatmap_regions = null;
+ $this->_array_data_vrednost_cond = null;
+ $this->_array_data_random = null;
+ }
+
+
+
+ // Zakesiramo in vrnemo respondente, ki so tudi prijavljeni v 1ki (ce ima anketa to nastavitev vklopljeno)
+ private function get_user_CMS_email($user_from_cms_id) {
+
+ // če še niammo arraya z e-maili
+ if ($this->_array_users_from_CMS == null) {
+
+ // polovimo emaile uporrabnikov iz CMS
+ $this->_array_users_from_CMS = array();
+
+ $qry = sisplet_query("SELECT su.user_id, u.email
+ FROM srv_user AS su JOIN users AS u ON su.user_id = u.id
+ WHERE su.ank_id = '".$this->sid."' AND su.preview='0' AND su.deleted='0' AND su.user_id > 0");
+ while ( $row = mysqli_fetch_assoc($qry)) {
+ $this->_array_users_from_CMS[$row['user_id']] = $row['email'];
+ }
+ }
+
+ // ko smo že polovili e-maile
+ if (is_array($this->_array_users_from_CMS) && isset($this->_array_users_from_CMS[$user_from_cms_id])) {
+ return $this->_array_users_from_CMS[$user_from_cms_id];
+ }
+ else {
+ return '';
+ }
+ }
+
+ // Pripravimo missing vrednosti za anketo
+ private function setSurveyMissingValues() {
+
+ $smv = new SurveyMissingValues($sid);
+ $smv -> Init();
+
+ $_sys_missings = $smv->GetSurveyMissingValues();
+
+ if (is_array($_sys_missings) && count($_sys_missings) > 0){
+
+ foreach ($_sys_missings[1] AS $_sys_missing) {
+
+ // nastavimo mapping za rekodiranje sistemskih vrednosti
+ $this->sysMissingMap[$_sys_missing['defSysVal']] = $_sys_missing['value'];
+ }
+ }
+ }
+
+ // Prestejemo stevilo vrstic v datoteki
+ private function getLinesCnt(){
+
+ if (IS_WINDOWS) {
+ $command = 'awk "NF != 0 {++count} END {print count}" '.$this->data_file_name;
+ }
+ else {
+ $command = 'awk \'NF != 0 {++count} END {print count}\' '.$this->data_file_name;
+ }
+
+ $lines = shell_exec($command);
+
+ return (int)$lines;
+ }
+
+ // Ugotovimo do katere spremenljivke zamenjujemo vrednosti
+ private function calculateValuesToChange($uid) {
+
+ $result = 0;
+
+ if (count($this->_user_spr_answer_count['spremenljivke']) == 0) {
+ return $result;
+ }
+
+ if ($this->_user_spr_answer_count['last_seen'] == $this->_user_spr_answer_count['cnt']) {
+ return $result;
+ }
+
+ if (count($this->_user_spr_answer_count['spremenljivke']) == 0) {
+ return $result;
+ }
+
+ foreach ($this->_user_spr_answer_count['spremenljivke'] AS $cnt) {
+
+ if ($this->_user_spr_answer_count['last_seen'] > $result) {
+ $result += $cnt;
+ }
+ }
+
+ return $this->_user_spr_answer_count['cnt'] - $result;
+ }
+
+
+ // Rekodiranje odgovora
+ private function recode_answer($spr_id, $answer, $uid) {
+
+ $this->addUserSprAnswerCount($spr_id, $answer, $uid);
+
+ // Najprej preverimo ali imamo mapping za sistemske missige
+ $answer = isset($this->sysMissingMap[$answer]) && $this->sysMissingMap[$answer] != null
+ ? $this->sysMissingMap[$answer]
+ : $answer;
+
+ $_recoded = $answer;
+
+ if ( $this->_array_recode === null) {
+ $this->_array_recode = array();
+
+ // Polovimo vse spremenljivke za katere moramo rekodirat
+ $sqlSelect = sisplet_query("SELECT spr_id, search, value, operator FROM srv_recode WHERE ank_id = '".$this->sid."' AND enabled='1' ORDER BY vrstni_red");
+ if (!$sqlSelect) {
+ $this->trigerError('recode_answer', mysqli_error($GLOBALS['connect_db']));
+ }
+
+ if (mysqli_num_rows($sqlSelect)) {
+ while ($rowSelect = mysqli_fetch_assoc($sqlSelect)) {
+ $this->_array_recode[$rowSelect['spr_id']][] = array('s'=>$rowSelect['search'],'v'=>$rowSelect['value'],'o'=>$rowSelect['operator']);
+ }
+ }
+ }
+
+ if (isset($this->_array_recode[$spr_id])) {
+
+ $recoded = false;
+
+ if (isset($this->_array_recoded[$spr_id][$answer])) {
+ return $this->_array_recoded[$spr_id][$answer];
+ }
+ else if (count($this->_array_recode[$spr_id]) > 0 && $recoded == false) {
+
+ foreach ($this->_array_recode[$spr_id] AS $k => $do_recode) {
+
+ if ( $answer == $do_recode['s'] || (int)$do_recode['o'] > 0 && $recoded == false) {
+ $original = $_recoded;
+ $_recoded = $this->check_recode($_recoded,$do_recode['s'],$do_recode['v'],$do_recode['o']);
+
+ if ($original != $_recoded) {
+ $recoded = true;
+ }
+ }
+ }
+
+ $this->_array_recoded[$spr_id][$answer] = $_recoded;
+ }
+ }
+
+ // Vrnemo rezultat
+ return $_recoded;
+ }
+
+ // Rekodiranje odgovora - stejemo zadnmi veljaven odgovor
+ private function addUserSprAnswerCount($spr, $answer, $uid) {
+
+ // štejemo zadnji veljaven odgovor
+ $this->_user_spr_answer_count['cnt']++;
+
+ if ($answer != -1 && $answer != -4 && $answer !== '-2d') {
+
+ // sistemskih in skritih ne upoštevamo
+ if ($this->AllQuestionsData[$spr]['sistem'] == 1 || $this->AllQuestionsData[$spr]['visible'] == 0) {
+ // preskočimo
+ }
+ else {
+ $this->_user_spr_answer_count['last'] = $this->_user_spr_answer_count['cnt'];
+ $this->_user_spr_answer_count['last_seen'] = $this->_user_spr_answer_count['cnt'];
+ }
+ }
+
+ // Pogledamo se ce je respondent videl vprasanje (tudi ce je -1, ker ga potem ne smemo spremenit v -3)
+ if ($answer == -1 || $answer === '-2d') {
+ if (is_array($this->_array_user_grupa[$uid]) && array_key_exists($this->AllQuestionsData[$spr]['gru_id'], $this->_array_user_grupa[$uid])) {
+ $this->_user_spr_answer_count['last_seen'] = $this->_user_spr_answer_count['cnt'] - 1;
+ }
+ }
+
+ if (!isset($this->_user_spr_answer_count['spremenljivke'][$spr])) {
+ $this->_user_spr_answer_count['spremenljivke'][$spr] = 0;
+ }
+
+ $this->_user_spr_answer_count['spremenljivke'][$spr]++;
+ }
+
+ // Rekodiranje odgovora - preverimo glede na operator
+ private function check_recode ($answer, $search, $value, $operand) {
+
+ $_recoded = $answer;
+
+ switch ($operand) {
+
+ case 0: # ==
+ $_recoded = $answer == $search ? $value : $answer;
+ break;
+
+ case 1: # <>
+ $_recoded = $answer != $search ? $value : $answer;
+ break;
+
+ case 2: # <
+ $_recoded = $answer < $search ? $value : $answer;
+ break;
+
+ case 3: # >
+ $_recoded = $answer > $search ? $value : $answer;
+ break;
+
+ case 4: # <=
+ $_recoded = $answer <= $search ? $value : $answer;
+ break;
+
+ case 5: # >=
+ $_recoded = $answer >= $search ? $value : $answer;
+ break;
+
+ case 6: # >=
+ $search = explode(',',$search);
+ $s1 = (int)$search[0];
+ $s2 = (int)$search[1];
+ $_recoded = (int)$answer >= $s1 && (int)$answer <= $s2 ? $value : $answer;
+ break;
+ }
+
+ return $_recoded;
+ }
+
+
+ // Heatmap - pretvori polje s tockami obmocja v ustrezno obliko
+ private function convertPolyString($polypoints){
+
+ $poly = array();
+ $polyObjectArray = array();
+ $j = 0;
+ $poly = explode(',',$polypoints);
+
+ for($i = 0; $i<sizeof($poly); $i++){
+
+ if($i == 0 || $i%2 == 0){
+ $tmpX = (int)$poly[$i];
+ }
+ else{
+ $tmpY = (int)$poly[$i];
+
+ $polyObjectArray[$j]["x"] = $tmpX;
+ $polyObjectArray[$j]["y"] = $tmpY;
+
+ $j++;
+ }
+ }
+
+ return $polyObjectArray;
+ }
+
+ // Heatmap - preveri, ali je posamezna tocka znotraj trenutnega obmocja
+ private function insidePoly($poly, $pointx, $pointy){
+
+ $inside = false;
+
+ for ($i = 0, $j = sizeof($poly) - 1; $i < sizeof($poly); $j = $i++) {
+
+ if( (($poly[$i]["y"] > $pointy) != ($poly[$j]["y"] > $pointy)) && ($pointx < ($poly[$j]["x"]-$poly[$i]["x"]) * ($pointy-$poly[$i]["y"]) / ($poly[$j]["y"]-$poly[$i]["y"]) + $poly[$i]["x"]) )
+ $inside = !$inside;
+ }
+
+ return $inside;
+ }
+
+ // Heatmap - priprava spremenljivk za koordinate točk
+ private function preparePointCoords($answerKoo, $returnPointx, $returnPointy){
+
+ $coordsWithComma = explode('<br>',$answerKoo);
+ $pointx = array();
+ $pointy = array();
+
+ for($i = 1; $i<sizeof($coordsWithComma); $i++){
+
+ // Vecdimenzionalno polje
+ $coords[$i-1] = explode(',',$coordsWithComma[$i]);
+ }
+
+ // Loop-anje skozi vecdimenzionalno polje
+ $i = 0;
+ $j = 0;
+ foreach ($coords as $coord) {
+
+ foreach ($coord as $coo) {
+
+ if($i == 0 || $i%2 == 0){
+ $tmpX = (int)$coo;
+ }
+ else{
+ $tmpY = (int)$coo;
+ $pointx[$j]["x"] = $tmpX;
+ $pointy[$j]["y"] = $tmpY;
+ $j++;
+ }
+
+ $i++;
+ }
+ }
+
+ if ($returnPointx == 1){
+ return $pointx;
+ }
+
+ if ($returnPointy == 1){
+ return $pointy;
+ }
+ }
+
+
+ // Zapisemo error in oznacimo da imamo error
+ private function trigerError($what, $error) {
+
+ $this->noErrors = false;
+ $this->errors[][$what] = $error;
+
+ return;
+ }
+
+ // Vrnemo error
+ private function getError() {
+ return array('error'=>$this->errors);
+ }
+
+ // Shranimo checkpoint za merjenje performanca - zaenkrat onemogoceno (samo za testiranje)
+ private function setLogCheckpoint($checkpoint_name){
+ global $admin_type;
+
+ if(true || $admin_type != 0)
+ return;
+
+ $this->log[$checkpoint_name]['time'] = microtime(true);
+ $this->log[$checkpoint_name]['memory'] = memory_get_usage();
+ $this->log[$checkpoint_name]['memory_peak'] = memory_get_peak_usage();
+ }
+
+ // Zapisemo checkpointe v logfile - zaenkrat onemogoceno (samo za testiranje)
+ private function saveLogCheckpoints(){
+
+ if(true || $admin_type != 0)
+ return;
+
+ $SL = new SurveyLog();
+
+ $cnt = 0;
+ foreach($this->log as $checkpoint => $data){
+
+ $time = ($cnt == 0) ? 'Start: '.$data['time'] : 'Elapsed: '.($data['time'] - $this->log['start']['time']);
+ $memory = 'Memory: '.((int)$data['memory'] / 1024 / 1000).' MB';
+ $memory_peak = 'Memory peak: '.((int)$data['memory_peak'] / 1024 / 1000).' MB';
+
+ $message = ' TESTING data collection for survey '.$this->sid.' - checkpoint '.$checkpoint.' - '.$time.', '.$memory.', '.$memory_peak;
+
+ $SL->addMessage(SurveyLog::DEBUG, $message);
+
+ $cnt++;
+ }
+
+ $SL->write();
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyData/class.SurveyDataDisplay.php b/admin/survey/classes/surveyData/class.SurveyDataDisplay.php
new file mode 100644
index 0000000..bc50f46
--- /dev/null
+++ b/admin/survey/classes/surveyData/class.SurveyDataDisplay.php
@@ -0,0 +1,3535 @@
+<?php
+
+/**
+ *
+ * Created on 17.12.2019
+ *
+ * @author: Peter Hrvatin
+ *
+ * Class za prikaz tabele s podatki
+ *
+*/
+
+#KONSTANTE
+// spremenljivke, ki se podajajo preko GETa
+define('VAR_REC_ON_PAGE', 'rec_on_page');
+define('VAR_SPR_LIMIT', 'spr_limit');
+define('VAR_CUR_REC_PAGE', 'cur_rec_page');
+define('VAR_SPR_PAGE', 'spr_page');
+define('VAR_ORDER', 'order');
+define('VAR_EDIT', 'edit');
+define('VAR_PRINT', 'print');
+define('VAR_MONITORING', 'monitoring');
+define('VAR_CODING', 'coding');
+define('VAR_DATA', 'view_data');
+define('VAR_META', 'view_meta');
+define('VAR_CIRCLES', 'view_circles');
+define('VAR_METAFULL', 'view_fullmeta');
+define('VAR_SHOW_SYSTEM', 'view_system');
+define('VAR_SORT_SEQ', 'sort_seq');
+define('VAR_SORT_TYPE', 'sort_type');
+define('VAR_PDF_TYPE', 'type');
+define('VAR_RELEVANCE', 'view_relevance');
+define('VAR_SHOW_DATE', 'view_date', false);
+define('VAR_SHOW_NO', 'view_no', false);
+define('VAR_EMAIL', 'email');
+define('SRV_LIST_GROUP_PAGINATE', 4); # po kolko strani grupira pri paginaciji
+
+global $site_path;
+
+class SurveyDataDisplay{
+
+ static private $sid = null; # id ankete
+
+ static private $folder = ''; # pot do folderja
+ static private $headFileName = null; # pot do header fajla
+ static private $dataFileName = null; # pot do data fajla
+ static private $dataFileStatus = null; # status data datoteke
+ static private $dataFileUpdated = null; # kdaj je bilo updejtano
+
+ static private $SDF = null; # class za osnovne funkcije data fajla
+
+ static private $inited = false; # ali smo razred inicializirali
+ static private $subAction = M_COLLECT_DATA_VIEW; # ali smo v urejanju ali pregledu
+
+ static private $survey = null; # podatki ankete
+ static private $db_table = ''; # ali se uporablja aktivna tabela
+
+ static private $file_handler = null; # ali se uporablja aktivna tabela
+
+ static private $_REC_ORDER = array('recnum'=>'ASC'); // vrstni red zapisov - rekordov
+ static private $_REC_LIMIT = ' NR==1,NR==50'; # string za limiz tapisov
+
+ static private $_RECORD_COUNT = 0; # koliko zapisov dobimo po filtriranju
+ static private $_TOTAL_PAGES = 0; # koliko strani dobimo po filtriranju
+ static private $_ALL_QUESTION_COUNT = null; # koliko je vseh vprasanj
+ static private $_ALL_VARIABLES_COUNT = null; # koliko je vseh variables
+
+ static private $SSNDF = null; # Class za SN_data fajle
+ static private $is_social_network = false; # ali je anketa tipa SN (social network)
+
+ static private $_HEADERS = array();
+
+ static private $_HAS_TEST_DATA = false; # ali anketa vsebuje testne podatke
+
+ static private $do_sort = false; # ali sploh sortiramo podatke
+ static private $sort_seq = null; # po katerem stolpcu sortiramo
+ static private $sort_type = null; # na kak način sortiramo sort_asc = / sort_dsc =
+
+ static private $doCMSUserFilter = false; # ali filtriramo samo svoje ankete
+
+ static private $usr_id = null; #id respondenta za ki ga trenutno prikazujemo
+
+ static private $showItime = false; #ali prikazujemo insert time
+ static private $showLineNumber = false; #ali vrivamo line number
+ static private $lineoffset = 0; #po koliko celicah vrivamo line number
+
+ static private $displayEditIcons = array(
+ 'dataIcons_quick_view' => true,
+ 'dataIcons_edit' => false,
+ 'dataIcons_write'=>false); #ali prikazujemo ikone za urejanje
+
+ static private $displayEditIconsSettings = false; # ali prikazujemo okno s checkboxi za nastavitve tabele s podatki
+
+ static private $printPreview = false; # ali prikazujemo podatke kot print preview;
+
+ static private $canDisplayRelevance = true; # ali prikazujemo ustreznost - relevance;
+
+ static private $quickEdit_recnum = array(); # array z prejsnjim in naslednjim recnumom (za vpogled - puscici naprej,nazaj)
+
+ # LIMITI
+ static public $_VARS = array(
+ VAR_DATA => 1, # ali prikazujemo podatke
+ VAR_REC_ON_PAGE => 50,
+ VAR_CUR_REC_PAGE => 1,
+ VAR_META => 0, # ali prikazujemo meta (status)
+ VAR_METAFULL => 0, # ali prikazujemo full meta
+ VAR_SPR_LIMIT => 10,
+ VAR_SPR_PAGE => 1,
+ VAR_EDIT => 0, # ali imamo možnost urejanja (brisanje popravljanje)
+ VAR_PRINT => 0, # ali imamo možnost izpisa v PDF, RTF
+ VAR_MONITORING => 0, # ali smo v zavihku monitoring
+ VAR_CODING => 0, # ali smo v zavihku kodiranje
+ VAR_SHOW_SYSTEM => 0, # ali prikazujemo sistemske variable (telefon, email)
+ VAR_PDF_TYPE => 0, # tip izpisa pdf (0 -> kratek, 1 -> dolg, 2 -> zelo kratek)
+ VAR_SORT_SEQ => '', # po kateri sekvenci sortiramo
+ VAR_SORT_TYPE => '', # način sortiranja (naraščajoče, padajoče)
+ VAR_RELEVANCE => 1, # ali prikazujemo ustreznost
+ VAR_EMAIL => 1, # ali prikazujemo email status
+ VAR_CIRCLES => 0, # ali prikazujemo kroge antonučija
+ VAR_SHOW_DATE => 0, # ali prikazujemo kroge antonučija
+ VAR_SHOW_NO => 0, # ali prikazujemo kroge antonučija
+ );
+
+
+
+ static public $_CURRENT_STATUS_FILTER = '';
+ static public $_VARIABLE_FILTER = ''; # sed string array z prikazanimi variablami z upoštevanjem filtrov
+ static private $_SVP_PV = array(); # array z prikazanimi variablami z upoštevanjem filtrov
+
+
+ static public $_PROFILE_ID_STATUS = null;
+ static public $_PROFILE_ID_VARIABLE = null;
+ static public $_PROFILE_ID_CONDITION = null;
+
+ function __construct($anketa) {
+ self::Init($anketa);
+ }
+
+
+ /** Inicializacija
+ *
+ * @param $sid
+ */
+ static public function Init($sid) {
+
+ # nastavimo privzeto pot do folderjev
+ global $site_path, $global_user_id, $lang;
+
+ self::$folder = $site_path . EXPORT_FOLDER.'/';
+ # nastavimo id ankete
+ self::$sid = $sid;
+
+ Common::deletePreviewData($sid);
+
+ SurveySession::sessionStart(self::$sid);
+
+ # nastavimo limite
+ self::setVars();
+
+ # podakcija
+ self::$subAction = isset($_GET['m']) && $_GET['m'] != '' ? $_GET['m'] : M_COLLECT_DATA_VIEW;
+
+ # informacije ankete
+ SurveyInfo::getInstance()->SurveyInit($sid);
+ self::$survey = SurveyInfo::getInstance()->getSurveyRow();
+
+ # aktivne tabele
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ self::$db_table = '_active';
+
+ # ali je anketa tipa SN - social network
+ self::$is_social_network = (SurveyInfo::getInstance()->checkSurveyModule('social_network')) ? true : false;
+
+ # Ce imamo vklopljeno povezovanje z identifikatorji, potem prikaz identifikatorjev izklopimo
+ if(self::$survey['show_email'] == '1'){
+ self::$_VARS[VAR_SHOW_SYSTEM] = false;
+ }
+
+ # ali prikazujemo datum na začetku ankete (Če smo v identifikatorjih ne smemo zaradi povezovanja)
+ if ( (self::$_VARS[VAR_SHOW_DATE] == true || (int)SurveyInfo :: getInstance()->getSurveyColumn('showItime') == 1) && self::$_VARS[VAR_SHOW_SYSTEM] == false ) {
+ //if (self::$_VARS[VAR_SHOW_DATE] == true && self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ self::$showItime = true;
+ }
+ else {
+ self::$showItime = false;
+ }
+
+ # ali prikazujemo zaporedno številko. (Če smo v identifikatorjih ne smemo zaradi povezovanja)
+ if ( (self::$_VARS[VAR_SHOW_NO] == true || (int)SurveyInfo :: getInstance()->getSurveyColumn('showLineNumber') == 1) && self::$_VARS[VAR_SHOW_SYSTEM] == false ) {
+ //if (self::$_VARS[VAR_SHOW_NO] == true) {
+ self::$showLineNumber = true;
+ }
+ else {
+ self::$showLineNumber = false;
+ }
+
+ self::$_CURRENT_STATUS_FILTER = STATUS_FIELD.'~/6|5/';
+
+ if (self::$subAction == M_COLLECT_DATA_MONITORING)
+ $monitoring = true;
+ else
+ $monitoring = false;
+
+ SurveyStatusProfiles :: Init(self::$sid);
+ SurveyVariablesProfiles :: Init($sid, $global_user_id, true, $monitoring);
+ SurveyConditionProfiles :: Init($sid, $global_user_id);
+ SurveyTimeProfiles :: Init($sid, $global_user_id);
+ SurveyUserSetting :: getInstance()->Init($sid, $global_user_id);
+ SurveyDataSettingProfiles :: Init($sid);
+ SurveySetting::getInstance()->Init($sid);
+
+ $sdsp_displayEditIcons = SurveyDataSettingProfiles :: getSetting('dataShowIcons');
+ if ($sdsp_displayEditIcons != null && is_array($sdsp_displayEditIcons)) {
+ self::$displayEditIcons = $sdsp_displayEditIcons;
+ }
+
+ if(isset($_SESSION['sid_'.self::$sid]['dataIcons_settings']))
+ self::$displayEditIconsSettings = ($_SESSION['sid_'.self::$sid]['dataIcons_settings']);
+
+ # ali filtriramo cms usejreve datotekoe
+ session_start();
+ self::$doCMSUserFilter = $_SESSION['sid_'.$sid]['doCMSUserFilter'];
+ session_commit();
+
+
+ // Inicializiramo class za datoteke
+ self::$SDF = SurveyDataFile::get_instance();
+ self::$SDF->init($sid);
+
+ // Ce imamo urlhash gre za javno povezavo in nikoli ne prikazemo loading okna
+ $show_loading = (isset($_GET['urlhash'])) ? false : true;
+
+ self::$SDF->prepareFiles($show_loading);
+
+ self::$headFileName = self::$SDF->getHeaderFileName();
+ self::$dataFileName = self::$SDF->getDataFileName();
+ self::$dataFileStatus = self::$SDF->getStatus();
+ self::$dataFileUpdated = self::$SDF->getFileUpdated();
+
+
+ // Ce ni datoteke izpisemo samo text
+ if ( self::$dataFileStatus == FILE_STATUS_NO_DATA || self::$dataFileStatus == FILE_STATUS_SRV_DELETED) {
+ Common::noDataAlert();
+ return false;
+ }
+
+
+ // Ce smo v identifikatorjih potem ne omogočamo urejanja
+ if (self::$_VARS[VAR_SHOW_SYSTEM] == true) {
+ foreach (self::$displayEditIcons AS $key => $value) {
+ self::$displayEditIcons[$key] = false;
+ }
+ }
+
+ # nastavimo ali smo v urejanju. Po novem gledamo url - zaenkrat imamo pregled urejanje in izvoz skupaj
+
+ if(self::$subAction == M_COLLECT_DATA_VIEW){
+ self::$_VARS[VAR_PRINT] = true;
+ }
+ if (self::$subAction == M_COLLECT_DATA_EDIT && self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ self::$_VARS[VAR_EDIT] = true;
+ }
+ // gorazd, ti si nekaj spremenil tole EDIT variablo - tuki se zdej v vsakem primeru nastavi edit
+ if (self::$displayEditIcons['dataIcons_edit'] == true && self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ self::$_VARS[VAR_EDIT] = true;
+ } else {
+ self::$_VARS[VAR_EDIT] = false;
+ }
+
+ if ( self::$displayEditIcons['dataIcons_multiple'] ) {
+ self::$_VARS['spr_limit'] = 'all';
+ }
+
+ if (self::$subAction == M_COLLECT_DATA_MONITORING) {
+ self::$_VARS[VAR_MONITORING] = true;
+ self::$_VARS[VAR_PRINT] = true;
+ }
+
+ if (self::$subAction == 'coding') {
+ self::$_VARS[VAR_CODING] = true;
+ }
+
+ self::$_VARS[VAR_META] = self::$_VARS[VAR_METAFULL];
+
+ # Če so izbrani VSI vnosi, naj bo označena USTREZNOST,
+ # če pa so označeni le USTREZNI, je spoloh ni treba tega stolpca, saj so itak vsi ustrezni in je odveč.
+ $ssp_pid = SurveyStatusProfiles::getCurentProfileId();
+ if ($ssp_pid == 2) {
+ self::$canDisplayRelevance = false;
+ }
+
+ # preštejemo vsa vabila, če so vsi na ne, potem ne prikažemo vabil
+ if (IS_WINDOWS) {
+ $awk_cnt_str = 'awk -F"'.STR_DLMT.'" "'.EMAIL_FIELD.'~/1/'.' {cnt++} END {print cnt}" '.self::$dataFileName;
+ } else {
+ $awk_cnt_str = 'awk -F"'.STR_DLMT.'" \''.EMAIL_FIELD.'~/1/'.' {cnt++} END {print cnt}\' \''.self::$dataFileName.'\'';
+ }
+
+ $emailCount = shell_exec($awk_cnt_str);
+
+ #self::$_VARS[VAR_EMAIL] = self::$_VARS[VAR_RELEVANCE] && ((int)self::$survey['email'] == 1 && (int)self::$survey['user_base'] == 1);
+ if (((int)self::$survey['email'] == 0 && (int)self::$survey['user_base'] == 0) ) {
+ self::$_VARS[VAR_EMAIL] = 0;
+ }
+
+ # nastavimo način sortiranja
+ self::setUpSort();
+
+ # plovimo privzete id-je uporabniškega filtra
+ self::setUserFilters();
+
+ # nastavimo uporabniške filtere
+ self::setUpFilter();
+
+ # nastavimo SN class
+ if (self :: $is_social_network) {
+ self::$SSNDF = new SurveySNDataFile(self::$sid);
+ self::$SSNDF->setVars(self::$_VARS);
+ self::$SSNDF->setParameter('canDisplayRelevance',self::$canDisplayRelevance);
+ self::$SSNDF->setParameter('showItime',self::$showItime);
+ self::$SSNDF->setParameter('showLineNumber',self::$showLineNumber);
+ }
+
+ # nastavimo trenuten id respondenta (ce ga imamo)
+ if(isset($_GET['usr_id'])) {
+ self::$usr_id = $_GET['usr_id'];
+ }
+ }
+
+ public function ajax() {
+
+ switch ($_GET['a']) {
+ case 'displayDataPrintPreview' :
+ self :: displayDataPrintPreview();
+ break;
+ case 'setSnDisplayFullTableCheckbox' :
+ self :: setSnDisplayFullTableCheckbox();
+ break;
+ case 'set_data_search_filter' :
+ self :: setDataSearchFilter();
+ break;
+ default:
+ echo 'Error! (class: SurveyAnalysis->ajax() - missing action)';
+ break;
+ }
+ }
+
+
+
+ /** vrne število vseh vprašanj
+ *
+ */
+ public static function getQuestionCount() {
+ if (self::$_ALL_QUESTION_COUNT == null) {
+ self::$_ALL_VARIABLES_COUNT = 0;
+ self::$_ALL_QUESTION_COUNT = 0;
+
+ if (self::$headFileName != null && self::$headFileName != '') {
+ foreach (unserialize(file_get_contents(self::$headFileName)) AS $_spremenljivka) {
+ if (isset($_spremenljivka['tip']) && $_spremenljivka['tip'] != 'm' && $_spremenljivka['tip'] != 'sm') {
+ self::$_ALL_VARIABLES_COUNT += $_spremenljivka['cnt_all'];
+ self::$_ALL_QUESTION_COUNT++;
+ }
+ }
+ }
+ }
+
+ return self::$_ALL_QUESTION_COUNT;
+ }
+
+ /** vrne število vseh variabel
+ *
+ */
+ public function getVariablesCount() {
+ if (self::$_ALL_VARIABLES_COUNT == null) {
+ self::$_ALL_VARIABLES_COUNT = 0;
+ self::$_ALL_QUESTION_COUNT = 0;
+ if (self::$headFileName != null && self::$headFileName != '') {
+ foreach (unserialize(file_get_contents(self::$headFileName)) AS $_spremenljivka) {
+ if (isset($_spremenljivka['tip']) && $_spremenljivka['tip'] != 'm' && $_spremenljivka['tip'] != 'sm') {
+ self::$_ALL_VARIABLES_COUNT += $_spremenljivka['cnt_all'];
+ self::$_ALL_QUESTION_COUNT++;
+ }
+ }
+ }
+ }
+ return self::$_ALL_VARIABLES_COUNT;
+ }
+
+
+ /**
+ * @desc nastavi default vrednosti spremenljivk in prebere kar je blo GETano
+ */
+ static function setVars () {
+ // preberemo kar je GETano
+ $data_view_settings = SurveySession::get('data_view_settings');
+
+ foreach (self::$_VARS AS $var => $val) {
+ if (isset($data_view_settings[$var]))
+ {
+ $_val = $data_view_settings[$var];
+ if (is_string($_val) && $_val == 'true')
+ {
+ $_val = (int)true;
+ }
+ else if (is_string($_val) && $_val == 'false')
+ {
+ $_val = (int)false;
+ }
+ else if (is_numeric($_val))
+ {
+ if( (float)$_val != (int)$_val )
+ {
+ $_val = (float)$_val;
+ }
+ else
+ {
+ $_val = (int)$_val;
+ }
+ }
+ self::$_VARS[$var] = $_val;
+ }
+ else if (isset($_REQUEST[$var]))
+ {
+ self::$_VARS[$var] = $_REQUEST[$var];
+ }
+ }
+ }
+
+ /**
+ * @desc vrne vse spremenljivki v obliki, ki se poslje preko GETa
+ * v parametrih se poda spremenljivko, ki se bo nastavla (se prav ni taka, kot je zdej v self::$_VARS)
+ */
+ static function getVars ($new_var=null, $new_val=null) {
+ $str = '';
+ foreach (self::$_VARS AS $var => $val) {
+ if ($var == $new_var) {
+ $str .= '&'.$var.'='.$new_val;
+ } else {
+ $str .= '&'.$var.'='.$val;
+ }
+ }
+ return $str;
+ }
+ /**
+ * @desc vrne vse spremenljivki v obliki, ki se poslje preko GETa brez sorta, ker dodamo naknadno z javascriptom
+ * v parametrih se poda spremenljivko, ki se bo nastavla (se prav ni taka, kot je zdej v self::$_VARS)
+ */
+
+ static function getVarsNoSort ($new_var=null, $new_val=null) {
+ $str = '';
+ foreach (self::$_VARS AS $var => $val) {
+ if ($var != VAR_SORT_SEQ && $var != VAR_SORT_TYPE) {
+ if ($var == $new_var) {
+ $str .= '&'.$var.'='.$new_val;
+ } else {
+ $str .= '&'.$var.'='.$val;
+ }
+ }
+ }
+ return $str;
+ }
+
+ static private function setUpSort() {
+ # če smo postali sort nastavitve preko geta
+ if (isset($_GET['sort_seq']) && (int)$_GET['sort_seq'] > 0 )
+ {
+ # sortiramo
+ self::$do_sort = true;
+
+ # nastavimo po kateri sekvenci / stolpcu sortiramo
+ self::$sort_seq = (int)$_GET['sort_seq'];
+
+ if (isset($_GET['sort_type']) && $_GET['sort_type'] === 'sort_dsc' )
+ {
+ self::$sort_type = 'sort_dsc';
+ }
+ else
+ {
+ self::$sort_type = 'sort_asc';
+ }
+ }
+ else
+ {
+ # ne sortiramo
+ self::$do_sort = false;
+ }
+ }
+
+ static private function setUserFilters()
+ {
+ #SurveyStatusProfiles :: setCurentProfileId();
+ self::$_PROFILE_ID_STATUS = SurveyStatusProfiles :: getDefaultProfile();
+
+ # Nastavimo filtre variabel
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+ if ($dvp != $_currentVariableProfile) {
+ SurveyUserSetting :: getInstance()->saveSettings('default_variable_profile', $_currentVariableProfile);
+ }
+ self::$_PROFILE_ID_VARIABLE = $_currentVariableProfile;
+
+ }
+
+
+ static public function setUpFilter() {
+
+ # nastavimo filter po statusih
+
+ if (self::$headFileName != null && self::$headFileName != '' && file_exists(self::$headFileName)) {
+
+ # kadar zbiramo sistemske, moramo obvezno zbirati tudi podatke, ne smemo pa full meta
+ if (self::$_VARS[VAR_SHOW_SYSTEM]){
+ self::$_VARS[VAR_DATA] = true;
+ self::$_VARS[VAR_META] = true;
+ self::$_VARS[VAR_METAFULL] = false;
+ self::$_VARS[VAR_SHOW_DATE] = false;
+ }
+ # filtriranje po statusih
+ self::$_CURRENT_STATUS_FILTER = SurveyStatusProfiles :: getStatusAsAWKString();
+
+ if (self::$dataFileStatus >= 0) {
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ # ali imamo filter na testne podatke
+ if (isset(self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence']) && (int)self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'] > 0) {
+ $test_data_sequence = self::$_HEADERS['testdata']['grids'][0]['variables'][0]['sequence'];
+ $filter_testdata = SurveyStatusProfiles :: getStatusTestAsAWKString($test_data_sequence);
+ }
+ # filtriranje po časih
+ $_time_profile_awk = SurveyTimeProfiles :: getFilterForAWK(self::$_HEADERS['unx_ins_date']['grids']['0']['variables']['0']['sequence']);
+
+ # ali imamo filter na uporabnost
+ if (isset(self::$_HEADERS['usability']['variables'][0]['sequence']) && (int)self::$_HEADERS['usability']['variables'][0]['sequence'] > 0) {
+ $usability_data_sequence = self::$_HEADERS['usability']['variables'][0]['sequence'];
+ $filter_usability = SurveyStatusProfiles :: getStatusUsableAsAWKString($usability_data_sequence);
+ }
+
+ # če nismo v indikatorjih (sistemske)
+ if (self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ # dodamo še ife
+ SurveyConditionProfiles :: setHeader(self::$_HEADERS);
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString();
+
+ # dodamo še ife za inspect
+ $SI = new SurveyInspect(self::$sid);
+ $_inspect_condition_awk = $SI->generateAwkCondition();
+ }
+
+ # dodamo pogoj za filter prepoznave uporabnika iz cms
+ # vklopljeno more bit prepoznava userja iz cms
+ if (self::$doCMSUserFilter == true) {
+ $CMSUserCondition = self::createCMSUserFilter();
+ }
+
+ if (($_condition_profile_AWK != "" && $_condition_profile_AWK != null )
+ || ($_inspect_condition_awk != "" && $_inspect_condition_awk != null)
+ || ($_time_profile_awk != "" && $_time_profile_awk != null)
+ || ($CMSUserCondition != "" && $CMSUserCondition != null)
+ || ($filter_testdata != null)
+ || ($filter_usability != null)) {
+ self::$_CURRENT_STATUS_FILTER = '('.self::$_CURRENT_STATUS_FILTER;
+ if ($_condition_profile_AWK != "" && $_condition_profile_AWK != null ) {
+ self::$_CURRENT_STATUS_FILTER .= '&&'.$_condition_profile_AWK;
+ }
+ if ($_inspect_condition_awk != "" && $_inspect_condition_awk != null ) {
+ self::$_CURRENT_STATUS_FILTER .= ' && '.$_inspect_condition_awk;
+ }
+ if ($_time_profile_awk != "" && $_time_profile_awk != null) {
+ self::$_CURRENT_STATUS_FILTER .= '&&'.$_time_profile_awk;
+ }
+ if ($CMSUserCondition != "" && $CMSUserCondition != null) {
+ self::$_CURRENT_STATUS_FILTER .= '&&'.$CMSUserCondition;
+ }
+ if ($filter_testdata != null ) {
+ self::$_CURRENT_STATUS_FILTER .= '&&('.$filter_testdata.')';
+ }
+ if ($filter_usability != null ) {
+ self::$_CURRENT_STATUS_FILTER .= '&&('.$filter_usability.')';
+ }
+ self::$_CURRENT_STATUS_FILTER .= ')';
+ }
+
+ # preštejemo vse zapise ki ustrezajo filtru po statusu
+ if (IS_WINDOWS) {
+ $awk_string = 'awk -F"'.STR_DLMT.'" "'.self::$_CURRENT_STATUS_FILTER.' {cnt++} END {print cnt}" '.self::$dataFileName;
+ $recCount = shell_exec($awk_string);
+ if ($_GET['debug'] == 1) {
+ print_r('<br>'.$awk_string);
+ }
+
+ } else {
+ $awk_string = 'awk -F"'.STR_DLMT.'" \''.self::$_CURRENT_STATUS_FILTER.' {cnt++} END {print cnt}\' \''.self::$dataFileName.'\'';
+ $recCount = shell_exec($awk_string);
+ if ($_GET['debug'] == 1) {
+ print_r('<br>'.$awk_string);
+ }
+ }
+ if ((int)$recCount > 0 ) {
+ self::$_RECORD_COUNT = (int)$recCount;
+ }
+
+
+ if (self::$_VARS[VAR_REC_ON_PAGE] != 'all') {
+ self::$_TOTAL_PAGES = bcdiv(self::$_RECORD_COUNT, self::$_VARS[VAR_REC_ON_PAGE]);
+
+ if (bcmod(self::$_RECORD_COUNT, self::$_VARS[VAR_REC_ON_PAGE]) > 0)
+ self::$_TOTAL_PAGES += 1;
+ if (self::$_VARS[VAR_CUR_REC_PAGE] > self::$_TOTAL_PAGES ) {
+ self::$_VARS[VAR_CUR_REC_PAGE] = self::$_TOTAL_PAGES;
+ } elseif (self::$_VARS[VAR_CUR_REC_PAGE] < 1 ) {
+ self::$_VARS[VAR_CUR_REC_PAGE] = 1;
+ }
+
+ # nastavimo limit za datoteko
+
+ $up = self::$_VARS[VAR_REC_ON_PAGE] * self::$_VARS[VAR_CUR_REC_PAGE];
+ $low = $up - self::$_VARS[VAR_REC_ON_PAGE]+1;
+
+ self::$_REC_LIMIT = ' NR=='.$low.',NR=='.$up.'';
+ } else {
+ # nastavimo limit za datoteko
+ self::$_REC_LIMIT = '';
+ }
+ }
+ if (self::$_VARS[VAR_DATA]) {
+ $tmp_svp_pv = SurveyVariablesProfiles :: getProfileVariables(self::$_PROFILE_ID_VARIABLE );
+
+ # če je $svp_pv = null potem prikazujemo vse variable
+ # oziroma če je sistemski dodamo tudi vse, ker drugače lahko filter skrije telefon in email
+ if (count($tmp_svp_pv) == 0 || self::$_VARS[VAR_SHOW_SYSTEM] == true ) {
+
+ $_sv = self::$SDF->getSurveyVariables();
+ if (count($_sv) > 0) {
+ foreach ( $_sv as $vid => $variable) {
+ $tmp_svp_pv[$vid] = $vid;
+ }
+ }
+ }
+ }
+ self::$lineoffset=1;
+ # če prikazujemo sistemske ne prikazujemo recnumber
+ if (!self::$_VARS[VAR_SHOW_SYSTEM] && self::$_VARS[VAR_META] && self::$_VARS[VAR_METAFULL]) {
+ $svp_pv['recnum'] = 'recnum';
+ #$svp_pv['code'] = 'code';
+ self::$lineoffset++;
+ # za code ni ofseta
+ #self::$lineoffset++;
+ }
+
+ if (self::$_VARS[VAR_DATA] && count($tmp_svp_pv) > 0) {
+ foreach ($tmp_svp_pv AS $_svp_pv) {
+
+ # če imamo sistemski email ali telefon, ime, priimek (v header je nastavljno "hide_system" = 1)
+ # potem v odvisnosti od nastavitve prikazujemo samo navadne podatke ali pa samo te sistemske, zaradizaščite podatkov
+ $_sistemski = false;
+ if (!self::$_VARS[VAR_SHOW_SYSTEM] && self::$_HEADERS[$_svp_pv]['hide_system'] == '1') {
+ # prikazujemo samo nesistemske (nezaščitene)
+ unset(self::$_HEADERS[$_svp_pv]);
+ } else if (self::$_VARS[VAR_SHOW_SYSTEM] && self::$_HEADERS[$_svp_pv]['hide_system'] !== '1') {
+ # prikazujemo samo sistemske (zaščitene) podatke
+ unset(self::$_HEADERS[$_svp_pv]);
+ } else {
+ # če ne dodamo
+ $svp_pv[$_svp_pv] = $_svp_pv;
+ }
+ }
+ }
+
+ #status - če smo v meta ali imamo profil vse enote
+ if ( (self::$_VARS[VAR_META] && self::$_VARS[VAR_METAFULL])
+ || ( $ssp_pid = SurveyStatusProfiles::getCurentProfileId() == 1 )) {
+ $svp_pv['status'] = 'status';
+ self::$lineoffset++;
+ }
+
+ #lurker
+ if ( (self::$_VARS[VAR_META] && self::$_VARS[VAR_METAFULL])
+ || ( $ssp_pid = SurveyStatusProfiles::getCurentProfileId() == 1 )) {
+ // dodamo v array da se prikazujejo tudi ti stolpci
+ $svp_pv['lurker'] = 'lurker';
+ self::$lineoffset++;
+ }
+ # ustreznost
+ if (self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance && self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ // dodamo v array da se prikazujejo tudi ti stolpci
+ $svp_pv['relevance'] = 'relevance';
+ self::$lineoffset++;
+ }
+
+ # email tion
+ #email prikazujemo skupaj z ustreznostjo
+ if ( self::$_VARS[VAR_EMAIL] && self::$_VARS[VAR_SHOW_SYSTEM] == false ) {
+ // dodamo v array da se prikazujejo tudi ti stolpci
+ $svp_pv['invitation'] = 'invitation';
+ self::$lineoffset++;
+ }
+
+ if (isset(self::$_HEADERS['testdata'])) {
+ self::$_HAS_TEST_DATA = true;
+ $svp_pv['testdata'] = 'testdata';
+ self::$lineoffset++;
+ }
+ # $svp_pv['unx_ins_date'] = 'unx_ins_date';
+
+ if (self::$_VARS[VAR_METAFULL] && self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ # dodamo tudi special meta
+ $svp_pv['meta'] = 'meta';
+ }
+
+ if (self::$showItime == true) {
+ $svp_pv['itime'] = 'itime';
+ self::$lineoffset++;
+ }
+
+ // ce imamo vklopljene sistemske ne smemo povezovat podatkov in zato urejamo po abecedi
+ if(self::$_VARS[VAR_SHOW_SYSTEM]){
+
+ $hasEmail = false;
+
+ // Poiscemo sekvenco sistemske spremenljivke
+ foreach (self::$_HEADERS AS $spr => $spremenljivka) {
+ if (isset($spremenljivka['sistem']) && $spremenljivka['sistem'] == 1 && $spremenljivka['variable'] == 'email') {
+ $sequence = $spremenljivka['sequences'];
+ $hasEmail = true;
+ }
+ }
+
+ if($hasEmail){
+ # sortiramo
+ self::$do_sort = true;
+
+ # nastavimo po kateri sekvenci / stolpcu sortiramo
+ self::$sort_seq = $sequence;
+
+ self::$sort_type = 'sort_asc';
+ }
+ }
+
+ self::getQuestionCount();
+ if (self::$_VARS[VAR_SPR_LIMIT] > self::$_ALL_QUESTION_COUNT) {
+ self::$_VARS[VAR_SPR_LIMIT] = 'all';
+ }
+
+ $spr_cont = 0; // za paginacijo spremenljivk
+
+ if(self::$_VARS['spr_limit'] == 'all'){
+ $_spr_on_pages_start = 0;
+ $_spr_on_pages_stop = self::$_VARS['spr_page'];
+ }
+ else{
+ $_spr_on_pages_start = self::$_VARS['spr_page'] * self::$_VARS['spr_limit'] - self::$_VARS['spr_limit'];
+ $_spr_on_pages_stop = self::$_VARS['spr_page'] * self::$_VARS['spr_limit'];
+ }
+
+ # skreiramo filter variabel za podatke
+ if (count(self::$_HEADERS) > 0) {
+ // zloopamo skozi spremenljivke in sestavimo filter po stolpcih
+ $_tmp_filter = '';
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset($svp_pv[$spid])) {
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ if (count($spremenljivka['grids']) > 0 ) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_tmp_filter .= $_prfx.$variable['sequence'];
+ $_prfx = ',';
+ }
+ }
+ }
+ }
+ } // end: paginacija spremenljivk
+ $spr_cont++;
+ } else
+ # če prikazujemo samo sistemske
+ if ( self::$_VARS[VAR_SHOW_SYSTEM] && in_array($spremenljivka['variable'], array('email','ime','priimek','telefon','naziv','drugo','odnos'))) {
+ if (count($spremenljivka['grids']) > 0 ) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ $_tmp_filter .= $_prfx.$variable['sequence'];
+ $_prfx = ',';
+ }
+ }
+ }
+ }
+ $svp_pv[$spid] = $spid;
+ }
+ }
+ }
+
+ # prilagodimo array profilov variabel
+ self::$_SVP_PV = $svp_pv;
+ if ($_tmp_filter != '')
+ {
+ self::$_VARIABLE_FILTER = $_tmp_filter;
+ }
+ }
+
+ }
+
+ /** Prikaže filtre za število podatkov....
+ *
+ */
+ public static function displayFilters() {
+ global $site_url, $site_path, $lang, $global_user_id;
+
+ #debug
+ echo '<script>window.onload = function() { __vnosi = 1; }</script>';
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA) {
+ return false;
+ }
+
+ # če imamo podatke
+ if (self::$dataFileStatus != FILE_STATUS_SRV_DELETED) {
+
+ echo '<div id="dataSettingsCheckboxes" '.(self::$displayEditIconsSettings ? '' : ' style="display:none;"').'>';
+
+ echo '<div id="toggleDataCheckboxes2" onClick="toggleDataCheckboxes(\'data\');"><span class="faicon close icon-orange" style="padding-bottom:2px;"></span> '.$lang['srv_data_settings_checkboxes2'].'</div>';
+
+ if(self::$dataFileStatus != FILE_STATUS_NO_DATA){
+ echo '<div id="dataSetingsLinks" class="data noBorder">';
+ self::displayLeftFilters();
+ echo '</div>'; // konec diva za paginacijo
+ }
+
+ if (self :: $is_social_network == false || self::$_VARS[VAR_CIRCLES] == 0) {
+
+ echo '<div class="clr" id="dataIconSetingsLinks" >'.$lang['srv_dataIcons_note'].'&nbsp;&nbsp;';
+
+ if (self::$_VARS[VAR_SHOW_SYSTEM] == false ) {
+ echo '<input type="checkbox" id="dataIcons_quick_view" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_quick_view'] == true ? ' checked="checekd"' : '').'/><label for="dataIcons_quick_view">'.$lang['srv_dataIcons_quick_view'].'</label>';
+ echo '&nbsp;&nbsp;';
+ /*echo '<input type="checkbox" id="dataIcons_edit" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_edit'] == true ? ' checked="checekd"' : '').'/><label for="dataIcons_edit">'.$lang['srv_dataIcons_edit'].'</label>';
+ if (self::$displayEditIcons['dataIcons_edit'] == true) {
+ echo ' '.Help::display('srv_podatki_urejanje_inline');
+ }
+ echo '&nbsp;&nbsp;';
+ echo '<input type="checkbox" id="dataIcons_write" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_write'] == true ? ' checked="checekd"' : '').'/><label for="dataIcons_write">'.$lang['srv_dataIcons_write'].'</label>';
+ echo '&nbsp;&nbsp;';*/
+ echo '<input type="checkbox" id="dataIcons_labels" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_labels'] == true ? ' checked="checekd"' : '').'/><label for="dataIcons_labels">'.$lang['srv_dataIcons_labels'].'</label>';
+
+ if ( self::showMultiple() ) {
+ echo '&nbsp;&nbsp;';
+ echo '<input type="checkbox" id="dataIcons_multiple" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_multiple'] == true ? ' checked="checekd"' : '').' /><label for="dataIcons_multiple">'.$lang['srv_dataIcons_multiple'].'</label>';
+ }
+ } else {
+ echo '<input type="checkbox" id="dataIcons_quick_view" disabled="disabled" /><label for="dataIcons_quick_view" class="gray">'.$lang['srv_dataIcons_quick_view'].'</label>';
+ echo '&nbsp;&nbsp;';
+ /*echo '<input type="checkbox" id="dataIcons_edit" disabled="disabled" /><label for="dataIcons_edit" class="gray">'.$lang['srv_dataIcons_edit'].'</label>';
+ if (self::$displayEditIcons['dataIcons_edit'] == true) {
+ echo ' '.Help::display('srv_podatki_urejanje_inline');
+ }
+ echo '&nbsp;&nbsp;';
+ echo '<input type="checkbox" id="dataIcons_write" disabled="disabled" /><label for="dataIcons_write" class="gray">'.$lang['srv_dataIcons_write'].'</label>';
+ echo '&nbsp;&nbsp;';*/
+ echo '<input type="checkbox" id="dataIcons_labels" disabled="disabled" /><label for="dataIcons_labels" class="gray">'.$lang['srv_dataIcons_labels'].'</label>';
+
+ if ( self::showMultiple() ) {
+ echo '&nbsp;&nbsp;';
+ echo '<input type="checkbox" id="dataIcons_multiple" disabled="disabled" /><label for="dataIcons_multiple" class="gray">'.$lang['srv_dataIcons_multiple'].'</label>';
+ }
+ }
+
+ # preverimo koliko anket je dejansko uporbaniških
+ # za potrebne statuse
+ $statuses = SurveyStatusProfiles :: getStatusAsArrayString();
+
+ $lurkers = false;
+ if (is_array($statuses) && count($statuses) > 0) {
+ # najprej preverimo ali filtriramo lurkereje
+ if (isset($statuses['lurker'])) {
+ $lurkers = true;
+ unset($statuses['lurker']);
+ }
+
+ if (count($statuses) > 0) {
+ $sstring = ' AND last_status IN (';
+ foreach ($statuses AS $skey => $status) {
+ if (is_numeric($skey)) {
+ $sstring.=$prefix.$skey;
+ } else if($skey == 'null') {
+ $sstring.=$prefix.'-1';
+ }
+ $prefix = ',';
+ }
+ $sstring .=')';
+
+ }
+ }
+
+ $q = sisplet_query("SELECT count(*) FROM srv_user WHERE ank_id = '".self::$sid."' AND user_id > 0 AND deleted='0' ".$sstring);
+ list($cnt) = mysqli_fetch_row($q);
+
+ if ($cnt > 0) {
+ echo '<span class="spaceLeft">';
+ self::displayOnlyCMS();
+ echo '</span>';
+ }
+
+ echo '</div>';
+ echo '<div class="clr"></div>';
+ }
+
+ echo '</div>';
+
+
+ # ali imamo testne podatke
+ if (self::$_HAS_TEST_DATA) {
+ # izrišemo bar za testne podatke
+ $SSH = new SurveyStaticHtml(self::$sid);
+ $SSH -> displayTestDataBar();
+ }
+ }
+ else {
+ print_r("Anketa je bila izbrisana! Prikaz podatkov ni mogoč!");
+ }
+ }
+
+ public static function displayPaginacija($position='_top') {
+ global $lang, $site_url;
+
+ if ((int)self::$_RECORD_COUNT == 0) {
+ return false;
+ }
+
+ # ŠTEVILO VNOSOV NA STRAN
+ echo '<div id="div_paginacija_vnosov">';
+ echo '<label>'.$lang['srv_show_inserts'].'</label>';
+ if (self::$_VARS[VAR_REC_ON_PAGE] > self::$_RECORD_COUNT) {
+ self::$_VARS[VAR_REC_ON_PAGE] = 'all';
+ }
+
+ //$_tmp_limit = array(10,50,100,250,500,1000,2500,5000,10000);
+ $_tmp_limit = array(10,50,100,250,500);
+ $_select_records = '<select id="rec_on_page'.$position.'" onchange="setDataView(\''.VAR_REC_ON_PAGE.'\',$(\'select#rec_on_page'.$position.' option:selected\').val());" title="'.$lang['srv_data_pagination_rec_on_page'].'">';
+ foreach ($_tmp_limit AS $limit) {
+ if ($limit < self::$_RECORD_COUNT) {
+ $_select_records .= '<option '.(self::$_VARS[VAR_REC_ON_PAGE] == $limit ? ' selected="selected"' : '').' value="'.$limit.'">';
+ $_select_records .= $limit;
+ $_select_records .= '</option>';
+ }
+ }
+ // Opcija "vsi" - ni na voljo ce je vec kot 1000 responsov (drugace lahko vse zasteka)
+ if(self::$_RECORD_COUNT <= 1000){
+ $_select_records .= '<option '.(self::$_VARS[VAR_REC_ON_PAGE] == 'all' ? ' selected="selected"' : '').' value="all">';
+ $_select_records .= $lang['srv_vsi'];
+ $_select_records .= '</option>';
+ }
+
+ $_select_records .= '</select>';
+
+ echo $_select_records;
+
+
+ # KATERA STRAN
+ if (self::$_VARS[VAR_REC_ON_PAGE] != 'all' && self::$_TOTAL_PAGES > 1) {
+
+ echo '<label>';
+ echo $lang['page'];
+ echo '</label>';
+
+ // puscica levo
+ if (self::$_VARS[VAR_CUR_REC_PAGE] > 1){
+ echo '<a title="'.$lang['previous_page'].'" href="#" onclick="setDataView(\''.VAR_CUR_REC_PAGE.'\',\''.(self::$_VARS[VAR_CUR_REC_PAGE]-1).'\');"><span class="faicon arrow2_l"></span></a>';
+ }
+
+ $_records_page = '<select id="cur_rec_page'.$position.'" onchange="setDataView(\''.VAR_CUR_REC_PAGE.'\',$(\'select#cur_rec_page'.$position.' option:selected\').val());" title="'.$lang['srv_data_pagination_rec_current_page'].'">';
+ for ($i=1; $i<=self::$_TOTAL_PAGES; $i++) {
+ $_records_page .= '<option'.(self::$_VARS[VAR_CUR_REC_PAGE]==$i ? ' selected="selected"' : '' )
+ . ' value="'.$i.'" >';
+ $_records_page .= $i;
+ $_records_page .= '</option>';
+
+ }
+ $_records_page .= '</select>';
+ echo $_records_page;
+
+ // puscica desno
+ if (self::$_VARS[VAR_CUR_REC_PAGE] < self::$_TOTAL_PAGES){
+ echo '<a title="'.$lang['next_page'].'" href="#" onclick="setDataView(\''.VAR_CUR_REC_PAGE.'\',\''.(self::$_VARS[VAR_CUR_REC_PAGE]+1).'\');"><span class="faicon arrow2_r"></span></a>';
+ }
+ }
+
+ echo '</div>';
+
+
+ # ŠTEVILO SPREMENLJIVK NA STRAN
+ echo '<div id="div_paginacija_vprasanj">';
+ echo '<label>'.$lang['srv_show_questions'].'</label>';
+
+ self::getQuestionCount();
+ if (self::$_VARS[VAR_SPR_LIMIT] > self::$_ALL_QUESTION_COUNT) {
+ self::$_VARS[VAR_SPR_LIMIT] = 'all';
+ }
+
+ //$_spr_limit = array(5=>'5',10=>'10',20=>'20',30=>'30',50=>'50',100=>'100','all'=>$lang['hour_all2']);
+ $_spr_limit = array(5=>'5',10=>'10',20=>'20',30=>'30',50=>'50');
+ $_spr_on_page = '<select id="spr_on_page'.$position.'" onchange="setDataView(\''.VAR_SPR_LIMIT.'\',$(\'select#spr_on_page'.$position.' option:selected\').val());" title="'.$lang['srv_data_pagination_spr_on_page'].'">';
+ foreach ($_spr_limit AS $key => $label) {
+ if ($key < self::$_ALL_QUESTION_COUNT) {
+ $_spr_on_page .= '<option '.(self::$_VARS[VAR_SPR_LIMIT] == $key ? ' selected="selected"' : '').' value="'.$key.'">';
+ $_spr_on_page .= $label;
+ $_spr_on_page .= '</option>';
+ }
+ }
+ // Opcija "vsi" - ni na voljo ce je vec kot 50 vprasanj (drugace lahko vse zasteka)
+ if(self::$_ALL_QUESTION_COUNT <= 50){
+ $_spr_on_page .= '<option '.(self::$_VARS[VAR_SPR_LIMIT] == 'all' ? ' selected="selected"' : '').' value="all">';
+ $_spr_on_page .= $lang['hour_all2'];
+ $_spr_on_page .= '</option>';
+ }
+
+ $_spr_on_page .= '</select>';
+
+ echo $_spr_on_page;
+
+
+ # KATERA STRAN
+ // prestejemo stevilo vprasanj
+ $questions = count(self::$_SVP_PV);
+ if (self::$_VARS[VAR_SPR_LIMIT] != 'all') {
+
+ $spr_pages = bcdiv($questions, self::$_VARS[VAR_SPR_LIMIT]);
+
+ if (bcmod($questions, self::$_VARS[VAR_SPR_LIMIT]) > 0)
+ $spr_pages += 1;
+
+ if ($spr_pages > 1) {
+
+ $_spr_page = '<select id="cur_spr_page'.$position.'" onchange="setDataView(\''.VAR_SPR_PAGE.'\',$(\'select#cur_spr_page'.$position.' option:selected\').val());" title="'.$lang['srv_data_pagination_spr_current_page'].'">';
+ echo '<label>';
+ echo $lang['page'];
+ echo '</label>';
+
+ // puscica levo
+ if (self::$_VARS[VAR_SPR_PAGE] > 1){
+ echo '<a title="'.$lang['previous_page'].'" href="#" onclick="setDataView(\''.VAR_SPR_PAGE.'\',\''.(self::$_VARS[VAR_SPR_PAGE]-1).'\');"><span class="faicon arrow2_l"></span></a>';
+ }
+
+ for ($i=1; $i<=$spr_pages; $i++) {
+ $_spr_page .= '<option'.(self::$_VARS[VAR_SPR_PAGE]==$i ? ' selected="selected"' : '' )
+ .' value="'.$i.'"'
+ .'>';
+ $_spr_page .= $i;
+ $_spr_page .= '</option>';
+
+ }
+ $_spr_page .= '</select>';
+ echo $_spr_page;
+
+ // puscica desno
+ if (self::$_VARS[VAR_SPR_PAGE] < $spr_pages){
+ echo '<a title="'.$lang['next_page'].'" href="#" onclick="setDataView(\''.VAR_SPR_PAGE.'\',\''.(self::$_VARS[VAR_SPR_PAGE]+1).'\');"><span class="faicon arrow2_r"></span></a>';
+ }
+
+ }
+ }
+ echo '</div>';
+ }
+
+ public static function displayLeftFilters() {
+ global $lang, $site_url;
+
+ // število zapisov na stran
+ echo '<ul class="">';
+
+ echo '<li>'.$lang['srv_show'].':</li>';
+
+ // ustreznost
+ if (self::$canDisplayRelevance) {
+
+ echo '<li>';
+
+ if (self::$_VARS[VAR_SHOW_SYSTEM] != true) {
+ echo '<label for="var_relevance"><input type="checkbox" onchange="setDataView(\''. VAR_RELEVANCE.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_RELEVANCE] ? ' checked="checked"' : '').' id="var_relevance" />'.$lang['srv_displaydata_relevance'].'</label>';
+ }
+ else {
+ echo '<label for="var_relevance" class="gray"><input type="checkbox" disabled="disabled" />'.$lang['srv_displaydata_relevance'].'</label>';
+ }
+
+ echo '</li>';
+ }
+
+ // email prikazujemo skupaj z ustreznost
+ if ((int)self::$survey['email'] == 1 && (int)self::$survey['user_base'] == 1) {
+
+ echo '<li>';
+
+ if (self::$_VARS[VAR_SHOW_SYSTEM] != true ) {
+ echo '<label for="var_email"><input type="checkbox" onchange="setDataView(\''. VAR_EMAIL.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_EMAIL] ? ' checked="checked"' : '').' id="var_email" />'.$lang['srv_displaydata_invitation'].'</label>';
+ }
+ else {
+ echo '<label for="var_email" class="gray"><input type="checkbox" disabled="disabled" id="var_email" />'.$lang['srv_displaydata_invitation'].'</label>';
+ }
+
+ echo '</li>';
+ }
+
+ // podatki
+ echo '<li>';
+ echo ' <input type="checkbox" onclick="setDataView(\''.VAR_DATA.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_DATA] ? ' checked="checked"' : '').(self::$_VARS[VAR_SHOW_SYSTEM] ? ' disabled' : '').' id="data" /><label for="data" '.(self::$_VARS[VAR_SHOW_SYSTEM] ? ' class="gray"' : '').'>'.$lang['srv_displaydata_data'].'</label>';
+ echo '</li>';
+
+ // Preverimo ce je vklopljen modul za volitve - potem nimamo identifikatorjev
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+
+ // Parapodatki
+ echo '<li>';
+ echo ' <input type="checkbox" onclick="setDataView(\''.VAR_METAFULL.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_METAFULL] ? ' checked="checked"' : '').(self::$_VARS[VAR_SHOW_SYSTEM] ? ' disabled' : '').' id="fullmeta" /><label for="fullmeta" '.(self::$_VARS[VAR_SHOW_SYSTEM] ? ' class="gray"' : '').'>'.$lang['srv_displaydata_meta'].'</label>';
+ echo '</li>';
+
+ // če imamo sistemske podatke katere moramo prikazovati ločeno - IDENTIFIKATORJI
+ if(!isset(self::$_HEADERS['_settings']['count_system_data_variables']) || (isset(self::$_HEADERS['_settings']['count_system_data_variables']) && (int)self::$_HEADERS['_settings']['count_system_data_variables'] > 0)) {
+ echo '<li>';
+ echo ' <label><input type="checkbox" onclick="setDataView(\''.VAR_SHOW_SYSTEM.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_SHOW_SYSTEM] ? ' checked="checked"' : '').' id="showsystem" />'.$lang['srv_displaydata_system_data'].'</label>';
+ echo '</li>';
+ }
+ // Po novem vedno prikazemo checkbox identifikatorji - samo je odkljukan in disablan
+ else{
+ echo '<li>';
+ echo ' <label class="gray"><input type="checkbox" checked="checked" disabled="disabled" id="showsystem" />'.$lang['srv_displaydata_system_data'].'</label>';
+ echo '</li>';
+ }
+
+ // datum
+ echo '<li>';
+ echo '<label '.(self::$_VARS[VAR_SHOW_SYSTEM] ? ' class="gray"' : '').'><input type="checkbox" onclick="setDataView(\''.VAR_SHOW_DATE.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_SHOW_DATE] ? ' checked="checked"' : '').(self::$_VARS[VAR_SHOW_SYSTEM] ? ' disabled' : '').' id="showdate" />'.$lang['srv_data_date'].'</label>';
+ echo '</li>';
+ }
+
+ // zaporedna številka
+ echo '<li>';
+ echo '<label '.(self::$_VARS[VAR_SHOW_SYSTEM] ? ' class="gray"' : '').'><input type="checkbox" onclick="setDataView(\''.VAR_SHOW_NO.'\',$(this).is(\':checked\'))" '.( self::$_VARS[VAR_SHOW_NO] ? ' checked="checked"' : '').(self::$_VARS[VAR_SHOW_SYSTEM] ? ' disabled' : '').' id="showno" />'.$lang['srv_recnum'].'</label>';
+ echo '</li>';
+
+ // pomoč - ?
+ echo '<li>'.Help :: display('displaydata_checkboxes').'</li>';
+ echo '</ul>';
+ }
+
+ // Search po tabeli s podatki
+ public static function displayDataSearch(){
+ global $lang;
+
+ $search = isset($_SESSION['sid_'.self::$sid]['data_search_filter']) ? $_SESSION['sid_'.self::$sid]['data_search_filter'] : '';
+
+ echo '<div id="data_search_filter">';
+
+ echo '<label>'.$lang['srv_find'].':</label> <input id="data_search_value" type="text" onchange="data_search_filter(); return false;" value="'.$search.'">';
+ if($search != ''){
+ echo '<span class="bold red spaceLeft">'.$lang['srv_displayData_search'].' "'.$search.'"!</span>';
+ }
+
+ echo '</div>';
+ }
+
+ // Shranimo iskanje v session
+ private function setDataSearchFilter(){
+
+ session_start();
+
+ $search = (isset($_POST['value']) && $_POST['value'] != '') ? trim($_POST['value']) : '';
+ if($search != ''){
+ $_SESSION['sid_'.self::$sid]['data_search_filter'] = $search;
+ }
+ else{
+ $_SESSION['sid_'.self::$sid]['data_search_filter'] = '';
+ }
+
+ session_commit();
+
+ // Na koncu se popravimo paginacijo na prvo stran
+ SurveySession::sessionStart(self::$sid);
+ SurveySession::append('data_view_settings','cur_rec_page',1);
+
+ return;
+ }
+
+
+ // Prikazemo editiranje na dnu (brisanje vecih hkrati...)
+ public static function displayBottomEdit(){
+ global $lang;
+ if ((int)self::$_RECORD_COUNT > 0){
+ echo '<div id="bottom_edit" class="floatLeft'.( self::$displayEditIcons['dataIcons_quick_view'] == true ? '' : ' shifted').'">';
+
+ echo '<span class="faicon arrow_up"></span> ';
+ echo '<span id="switch_on"><a href="javascript:selectAll(1);">'.$lang['srv_select_all'].'</a></span>';
+ echo '<span id="switch_off" style="display:none;"><a href="javascript:selectAll(0);">'.$lang['srv_deselect_all'].'</a></span>';
+ echo '&nbsp;&nbsp;<a href="#" onClick="deleteMultipleData();"><span class="faicon delete_circle icon-orange" title="'.$lang['srv_delete_data_multirow'].'"/></span>&nbsp;'.$lang['srv_delete_selected'].'</a>';
+ echo '<p>'.$lang['srv_delete_infotext'].' '.Help::display('srv_delete_infotext').'</p>';
+
+ echo '</div>';
+ }
+ }
+
+ /** Naredi output podatkov v HTML tabelo
+ *
+ */
+ public static function displayVnosiHTML() {
+ global $lang;
+ global $site_path;
+ global $global_user_id;
+
+ // na vrhu in na dnu izrisemo paginacijo
+ if(self::$dataFileStatus != FILE_STATUS_NO_DATA && (int)self::$_RECORD_COUNT > 0) {
+ echo '<div id="vnosi_paginacija" class="top_paginacija">';
+ self::displayPaginacija($position='_top');
+ echo '</div>';
+
+ // Izrisemo search
+ if(!self::$_VARS[VAR_CODING])
+ self::displayDataSearch();
+
+
+ // Checkboxa za urejanje in izpise podatkov ter razpiranje dodatnih nastavitev
+ echo '<div class="dataSettingsBasic">';
+
+ echo '<input type="checkbox" id="dataIcons_edit" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_edit'] == true ? ' checked="checekd"' : '').'/><label for="dataIcons_edit">'.$lang['srv_dataIcons_edit'].'</label>';
+ if (self::$displayEditIcons['dataIcons_edit'] == true) {
+ echo ' '.Help::display('srv_podatki_urejanje_inline');
+ }
+ echo '&nbsp;&nbsp;';
+
+ // Preverimo, ce je funkcionalnost v paketu, ki ga ima uporabnik
+ $userAccess = UserAccess::getInstance($global_user_id);
+ echo '<input type="checkbox" id="dataIcons_write" onchange="changeDataIcons(); return false;"'.(self::$displayEditIcons['dataIcons_write'] == true ? ' checked="checked"' : '').' '.(!$userAccess->checkUserAccess($what='data_export') ? 'disabled="disabled"' : '').' /><label for="dataIcons_write" '.(!$userAccess->checkUserAccess($what='data_export') ? 'class="user_access_locked"' : '').'>'.$lang['srv_dataIcons_write'].'</label>';
+
+ $arrow = (isset($_SESSION['sid_' . self::$sid]['dataIcons_settings'])) ? $_SESSION['sid_' . self::$sid]['dataIcons_settings'] : 0;
+ echo '<div id="toggleDataCheckboxes" ' . $borderLeft . ' onClick="toggleDataCheckboxes(\'data\');"><span class="faicon ' . ($arrow == 1 ? ' dropup_blue' : 'dropdown_blue') . '"></span> ' . $lang['srv_extra_settings'] . '</div>';
+
+ echo '</div>';
+ }
+
+ echo '<br class="clr" />';
+
+
+ echo '<div id="displayFilterNotes">';
+
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ SurveyTimeProfiles :: printIsDefaultProfile();
+
+ # če nismo v identifikatorjih
+ if (self::$_VARS[VAR_SHOW_SYSTEM] == false) {
+ # če imamo filter ifov ga izpišemo
+ SurveyConditionProfiles:: getConditionString();
+
+ # če imamo filter ifov za inspect ga izpišemo
+ $SI = new SurveyInspect(self::$sid);
+ $SI->getConditionString();
+
+ # če imamo filter spremenljivk ga izpišemo
+ SurveyVariablesProfiles:: getProfileString();
+ }
+ else{
+ echo '<p>'.$lang['srv_data_settings_identifier_notice'].'</p>';
+ }
+ # če imamo rekodiranje
+ $SR = new SurveyRecoding(self::$sid);
+ $SR -> getProfileString();
+
+ echo '</div>';
+
+
+
+
+
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ echo '<div id="div_vnosi_data">';
+
+ if ((self::$dataFileStatus == 1 || self::$dataFileStatus == 0) && self::$dataFileName !== null) {
+ # filtri morajo prikazovat vsaj eno spremenljivko ali meta podatek
+ if (count(self::$_SVP_PV) > 0) {
+
+ # če imamo kaj podatkov za prikaz
+ if ((int)self::$_RECORD_COUNT > 0){
+
+ if (self :: $is_social_network == false) {
+ if ( self::showMultiple() && self::$displayEditIcons['dataIcons_multiple'] )
+ self::DisplayDataMultipleTable();
+ else
+ self::DisplayDataTable();
+ }
+ else {
+ # imamo SN omrežje
+ if (self::$_VARS[VAR_CIRCLES] == 0) {
+ self::DisplaySnLinks();
+ self::DisplayDataTable();
+ }
+ }
+ }
+ # ni vrstic za prikaz
+ else{
+ echo $lang['srv_data_no_data_filtred'];
+ }
+ }
+ else {
+ echo '<br /><div style="margin: 0 0 40px 0;">Ni podatkov za prikaz. Preverite filtre (Podatki, Para podatki, Polni para podatki)</div>';
+ }
+ }
+
+ if (self :: $is_social_network ) {
+ if (self::$SSNDF != null && self::$_VARS[VAR_CIRCLES] == 1) {
+ self::DisplaySnLinks();
+ self::$SSNDF->outputSNDataFile();
+ }
+ }
+
+ echo '</div>'; // id="div_vnosi_data">';
+
+
+ #izrišemo legendo statusov
+ self::displayStatusLegend();
+ self::displayMetaStatusLegend();
+ self::displayTestLegend();
+
+
+ // na vrhu in na dnu izrisemo paginacijo
+ if(self::$dataFileStatus != FILE_STATUS_NO_DATA){
+ echo '<div id="vnosi_paginacija" class="bottom_paginacija">';
+ self::displayPaginacija($position='_bottom');
+ echo '</div>';
+
+ echo '<div class="clr"></div>';
+ }
+
+ // osvetlimo stolpec s spremenljivko
+ if (isset($_GET['highlight_spr'])) {
+ ?><script>
+ highlight_spremenljivka(<?=(int)$_GET['highlight_spr']?>);
+ </script><?php
+ }
+
+ // osvetlimo vrstice s spremembami
+ if (isset($_GET['highlight_usr'])) {
+ $high = explode('-', $_GET['highlight_usr']);
+ ?><script>
+ highlight_user([<?=implode(',',$high)?>]);
+ </script><?php
+ }
+
+ // prikazujemo labele podatkov
+ if ( self::$displayEditIcons['dataIcons_labels'] ) {
+ ?><script>
+ data_show_labels();
+ </script><?php
+ }
+ }
+
+
+ public static function DisplayDataTable() {
+ global $lang, $site_path;
+
+ if ( self::$dataFileStatus == FILE_STATUS_OLD) {
+ echo "Posodobljeno: ".date("d.m.Y, H:i:s", strtotime(self::$dataFileUpdated));
+ }
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ // paginacija spremenljivk
+ if(self::$_VARS['spr_limit'] == 'all'){
+ $_spr_on_pages_start = 0;
+ $_spr_on_pages_stop = self::$_VARS['spr_page'];
+ }
+ else{
+ $_spr_on_pages_start = self::$_VARS['spr_page'] * self::$_VARS['spr_limit'] - self::$_VARS['spr_limit'];
+ $_spr_on_pages_stop = self::$_VARS['spr_page'] * self::$_VARS['spr_limit'];
+ }
+
+ #preberemo HEADERS iz datoteke
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+ // vrinemo userid na začetku ki ga potem skrivamo.
+ $_svp_pv['uid'] = 'uid';
+ //self::$_SVP_PV = array_merge($_svp_pv, self::$_SVP_PV);
+
+
+ #izpišemo tabelo
+ echo '<div style="padding-top:0px; height:5px;" class="clr">&nbsp;</div>';
+
+ echo '<div id="tableContainer" class="tableContainer">';
+
+ # div v katerem po potrebi prikazujemo gumbe za skrolanje levo in desno
+ echo '<div id="dataTableScroller">';
+ echo '<span class="faicon arrow_large2_l icon-as_link pointer" onclick="dataTableScroll(\'left\');return false;"></span>';
+ echo '&nbsp;&nbsp;&nbsp;&nbsp;';
+ echo '<span class="faicon arrow_large2_r icon-as_link pointer" onclick="dataTableScroll(\'right\');return false;"></span>';
+ echo '</div>';
+
+ $display1kaIcon = self::$displayEditIcons['dataIcons_quick_view'] ;
+
+ if (self::$printPreview == true) {
+ self::$displayEditIcons['dataIcons_edit'] = false;
+ self::$displayEditIcons['dataIcons_write'] = false;
+ $display1kaIcon = false;
+ }
+ # koliko stolpcev je colspan
+ $stolpci = ((int)self::$displayEditIcons['dataIcons_edit']*4)
+ + ((int)self::$displayEditIcons['dataIcons_write']*2)
+ + (int)$display1kaIcon;
+
+ // Evoli ikona (ce je vklopljen modul)
+ if((SurveyInfo::getInstance()->checkSurveyModule('evoli') || SurveyInfo::getInstance()->checkSurveyModule('evoli_employmeter')) && self::$displayEditIcons['dataIcons_write'] == '1')
+ $stolpci += 3;
+
+ // MFDPS ikona (ce je vklopljen modul)
+ if(SurveyInfo::getInstance()->checkSurveyModule('mfdps') && self::$displayEditIcons['dataIcons_write'] == '1')
+ $stolpci += 1;
+
+ // BORZA ikona (ce je vklopljen modul)
+ if(SurveyInfo::getInstance()->checkSurveyModule('borza') && self::$displayEditIcons['dataIcons_write'] == '1')
+ $stolpci += 1;
+
+ echo '<input type="hidden" id="tableIconColspan" value="'.($stolpci).'">';
+
+ # ali smo v edit načinu ali monitoringu
+ $cssEdit = (self::$_VARS[VAR_EDIT] || self::$_VARS[VAR_MONITORING]?' editData':'');
+ echo '<table id="dataTable" class="scrollTable no_wrap_td'.$cssEdit.'" '.(self::$_VARS[VAR_EDIT]?' title="'.$lang['srv_edit_data_title'].'"':'').'>';
+
+ // Nastavimo colgroup, da na njega vezemo vse sirine v tabeli, zaradi resizinga stolpcev
+ echo '<colgroup>';
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ echo '<col class="data_edit"'.($stolpci > 1 ? (' span="'.$stolpci.'"') : '').'>';
+ }
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset(self::$_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+ if(self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<col>';
+ }
+
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ echo '<col seq="'.$variable['sequence'].'"';
+
+ if ($spremenljivka['tip'] != 'm' && $spremenljivka['tip'] != 'sm') {
+ echo ' spr_id="'.substr($spid, 0, strpos($spid, '_')).'"';
+ } else {
+ echo ' spr_id="'.$spid.'"';
+ }
+
+ echo '>';
+ }
+ }
+ }
+ }
+ $spr_cont++;
+ }
+
+ }
+ echo '</colgroup>';
+
+ echo '<thead class="fixedHeader">';
+ echo '<tr>';
+
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ echo '<th class="data_edit"'.($stolpci > 1 ? (' colspan="'.$stolpci.'"') : '').'>&nbsp;</td>';
+ }
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+
+ if (isset(self::$_SVP_PV[$spid])) {
+ if(self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<th title="'.$lang['srv_line_number'].'" >';
+ echo '<div class="headerCell">'.$lang['srv_line_number'].'</div>';
+ echo '</th>';
+ }
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ echo '<th colspan="'.$spremenljivka['cnt_all'].'" title="'.$spremenljivka['naslov'].'">';
+ echo '<div class="headerCell">'.$spremenljivka['naslov'].'</div>';
+ echo '</th>';
+ }
+ $spr_cont++;
+
+ }
+ }
+
+ echo '</tr><tr>';
+
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ echo '<th class="data_edit"'.($stolpci > 1 ? (' colspan="'.$stolpci.'"') : '').'>&nbsp;</td>';
+ }
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset(self::$_SVP_PV[$spid]) && (count($spremenljivka['grids']) > 0 )) {
+
+ if(self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<th title="'.$lang['srv_line_number'].'" >';
+ echo '<div class="headerCell">'.$lang['srv_line_number'].'</div>';
+ echo '</th>';
+ }
+
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if($spremenljivka['tip'] == 16 || $spremenljivka['tip'] == 19 || $spremenljivka['tip'] == 20){
+ echo '<th colspan="'.$grid['cnt_vars'].'" title="'.$grid['variable'].'">';
+ echo '<div class="headerCell">'.$grid['variable'].'</div>';
+ echo '</th>';
+ }
+ else{
+ echo '<th colspan="'.$grid['cnt_vars'].'" title="'.$grid['naslov'].'">';
+ echo '<div class="headerCell">'.$grid['naslov'].'</div>';
+ echo '</th>';
+ }
+ }
+ }
+ $spr_cont++;
+ }
+
+ }
+ echo '</tr><tr>';
+
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ echo '<th class="data_edit"'.($stolpci > 1 ? (' colspan="'.$stolpci.'"') : '').'>&nbsp;</td>';
+ }
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ $system_columns = array();
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset(self::$_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+ if(self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<th title="'.$lang['srv_line_number'].'" spr_id="lineNo">';
+ echo '<div class="dataCell">'.$lang['srv_line_number'].'</div>';
+ echo '</th>';
+ }
+
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ echo '<th title="'.$variable['naslov'].($variable['other'] ? '&nbsp;(text)' : '').'"'
+ .' seq="'.$variable['sequence'].'"';
+
+ if ($spremenljivka['tip'] != 'm' && $spremenljivka['tip'] != 'sm') {
+ echo ' spr_id="'.substr($spid, 0, strpos($spid, '_')).'"';
+ } else {
+ echo ' spr_id="'.$spid.'"';
+ }
+ echo ($spremenljivka['inline_edit']?' inline_edit=1':'')
+ // .' inline_edit='.($spremenljivka['inline_edit']?$spremenljivka['inline_edit']:'0')
+ .($variable['sequence'] == self::$sort_seq && self::$sort_seq != null ? ' class="hover '.self::$sort_type.'"': '')
+ .'>';
+
+ if ($variable['sequence'] == self::$sort_seq && self::$sort_seq != null) {
+ $img_src = self::$sort_type == 'sort_dsc' ? 'sort_descending' : 'sort_ascending' ;
+ echo '<span class="sort_holder"><span class="faicon '.$img_src.'" title=""></span></span>';
+ }
+
+ // Zabelezimo sekvenco sistemskih identifikatorjev da jih pobarvamo
+ if($spremenljivka['is_system'] == 1)
+ $system_columns[] = $spremenljivka['sequences'];
+
+ echo '<div class="dataCell">'.$variable['naslov'];
+ if ($variable['other'] == 1) {
+ echo '&nbsp;(text)';
+ }
+
+ /*// urejanje kalkulacije -- izracunane vrednosti v podatkih
+ if ($spremenljivka['tip'] == 22) {
+ echo ' <a href="" onclick="calculation_editing(\'-'.substr($spid, 0, strpos($spid, '_')).'\'); return false;">('.$lang['edit3'].')</a>';
+ }*/
+
+ echo '</div>';
+
+ echo '</th>';
+ }
+ }
+ }
+ }
+ $spr_cont++;
+ }
+
+ }
+ echo'</tr>';
+ echo '</thead>';
+
+
+ # PREBEREMO PODATKE
+ $_command = '';
+
+ # najprej po potrebi presortiramo
+ # na vindowsih ne delamo sorta (zaenkrat)
+ if (self::$do_sort == true) {
+
+ $sortString = '-k '.self::$sort_seq;
+
+ #ker tekstovnih ne sortira vredu sem odstranil parameter -n
+ # iz navodil: sorting keys can be interpreted numerically (-n option) instead of alphabetically (which is the default).
+ # če bodo težave bo potrebno parameter -n dodajat po potrebi
+ # $sort_numeric =>
+ $sort_numeric = '';
+ //$sort_numeric = '-n ';
+
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (count($spremenljivka['grids']) > 0 ) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if (self::$sort_seq == $variable['sequence']) {
+
+ // za datumska polja je potrebno malo potelovadit
+ if ($variable['spss'] == 'DATETIMEw' || $variable['sortType'] == 'date') {
+ #12.09.2011
+ $sortString = '-k '.self::$sort_seq.'.7,'.self::$sort_seq.'.10 -k'.self::$sort_seq.'.4,'.self::$sort_seq.'.5 -k'.self::$sort_seq.'.1,'.self::$sort_seq.'.2';
+ }
+
+ // za numericne spremenljivke in recnum uporabimo parameter -n da ne sortira po stringu
+ if ($variable['sortType'] == 'number') {
+ $sort_numeric = '-n ';
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (IS_WINDOWS) {
+ #Cygwin Sort Command On Windows
+ # popravi pot do svojega sort-a
+ $_path_to_CygwinSort = PATH_TO_CYGWIN_FOLDER;
+ # $_command = $_path_to_CygwinSort.' -t"'.STR_DLMT.'"'.(self::$sort_type == 'sort_dsc' ? '-r' : '').' +'.(int)(self::$sort_seq-1).' '.self::$dataFileName.'';
+ $_command = $_path_to_CygwinSort.' -t"'.STR_DLMT.'" '.(self::$sort_type == 'sort_asc' ? '' : '-r ').$sort_numeric.$sortString.' '.self::$dataFileName;
+ } else {
+ # smo na linuxu
+ $_command = 'sort -t \\'.STR_DLMT.' '.(self::$sort_type == 'sort_asc' ? '' : '-r ' ).$sort_numeric.$sortString.' '.self::$dataFileName;
+ }
+ }
+ // polovimo vrstice z statusom 5,6 in jih damo v začasno datoteko
+ if (IS_WINDOWS) {
+ #$cmdLn1 = 'awk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" '.self::$dataFileName.' > '.$tmp_files['filtred_status'];
+ #$out1 = shell_exec($cmdLn1);
+ # če smo predhodno sortirali
+ if (self::$do_sort == true)
+ {
+ $_command .= ' | gawk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" ';
+ #$_command = 'awk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" '.self::$dataFileName;
+ }
+ else
+ {
+ $_command = 'gawk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" '.self::$dataFileName;
+ }
+
+ } else {
+ #$cmdLn1 = 'awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }\' '.self::$dataFileName.' > '.$tmp_files['filtred_status'];
+ #$out1 = shell_exec($cmdLn1);
+ # če smo predhodno sortirali
+ if (self::$do_sort)
+ {
+ $_command .= ' | awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }\' ';
+ }
+ else
+ {
+ $_command = 'awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }\' '.self::$dataFileName;
+ }
+
+ }
+
+ // pobrisemo vrstice ki ne vsebujejo iskalnega stringa (ce searchamo) in rdece boldamo rezultat
+ $search = isset($_SESSION['sid_'.self::$sid]['data_search_filter']) ? $_SESSION['sid_'.self::$sid]['data_search_filter'] : '';
+ if($search != ''){
+ if (IS_WINDOWS) {
+ $_command .= ' | sed "/'.$search.'/!d"';
+ $_command .= ' | sed "s*'.$search.'*<span class=\"highlighted\">'.$search.'</strong>*g"';
+ } else {
+ $_command .= ' | sed \'/'.$search.'/!d\'';
+ $_command .= ' | sed \'s*'.$search.'*<span class=\"highlighted\">'.$search.'</strong>*g\'';
+ }
+ }
+
+ // paginacija po stolpcih (spremenljivkah)
+ if (IS_WINDOWS) {
+ #$cmdLn1_1 = 'cut -d "|" -f 1,'.self::$_VARIABLE_FILTER.' '.$tmp_files['filtred_status'].' > '.$tmp_files['filtred_spr_pagination'];
+ #$out1 = shell_exec($cmdLn1_1);
+ $_command .= ' | cut -d "|" -f 1,'.self::$_VARIABLE_FILTER;
+ } else {
+ #$cmdLn1_1 = 'cut -d \'|\' -f 1,'.self::$_VARIABLE_FILTER.' '.$tmp_files['filtred_status'].' > '.$tmp_files['filtred_spr_pagination'];
+ #$out1 = shell_exec($cmdLn1_1);
+ $_command .= ' | cut -d \'|\' -f 1,'.self::$_VARIABLE_FILTER;
+ }
+
+ if (self::$_REC_LIMIT != '') {
+ #paginating
+ if (IS_WINDOWS) {
+ #$cmdLn2 = 'awk '.self::$_REC_LIMIT.' '.$tmp_files['filtred_spr_pagination'].' > '.$tmp_files['filtred_pagination'];
+ #$out2 = shell_exec($cmdLn2);
+ $_command .= ' | awk '.self::$_REC_LIMIT;
+ } else {
+ #$cmdLn2 = 'awk '.self::$_REC_LIMIT.' '.$tmp_files['filtred_spr_pagination'].' > '.$tmp_files['filtred_pagination'];
+ #$out2 = shell_exec($cmdLn2);
+ $_command .= ' | awk '.self::$_REC_LIMIT;
+ }
+ #$file_sufix = 'filtred_pagination';
+ } else {
+ #$file_sufix = 'filtred_spr_pagination';
+ }
+
+ // zamenjamo | z </td><td>
+ if (IS_WINDOWS) {
+ #$cmdLn3 = 'sed "s*'.STR_DLMT.'*</td><td>*g" '.$tmp_files[$file_sufix].' > '.$tmp_files['filtred_sed'];
+ #$out3 = shell_exec($cmdLn3);
+ $_command .= ' | sed "s*'.STR_DLMT.'*'.STR_LESS_THEN.'/td'.STR_GREATER_THEN.STR_LESS_THEN.'td'.STR_GREATER_THEN.'*g" >> '.$folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+
+ } else {
+ #$cmdLn3 = 'sed \'s*'.STR_DLMT.'*</td><td>*g\' '.$tmp_files[$file_sufix].' > '.$tmp_files['filtred_sed'];
+ #$out3 = shell_exec($cmdLn3);
+ $_command .= ' | sed \'s*'.STR_DLMT.'*</td><td>*g\' >> '
+ .$folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+ }
+
+ if (IS_WINDOWS) {
+ # ker so na WINsih težave z sortom, ga damo v bat fajl in izvedemo :D
+ $file_handler = fopen($folder.'cmd_'.self::$sid.'_to_run.bat',"w");
+ fwrite($file_handler,$_command);
+ fclose($file_handler);
+ $out_command = shell_exec($folder.'cmd_'.self::$sid.'_to_run.bat');
+ unlink($folder.'cmd_'.self::$sid.'_to_run.bat');
+ } else {
+ $out_command = shell_exec($_command);
+ }
+
+ echo '<tbody class="scrollContent'.(self::$_VARS[VAR_CODING]?' coding':'').'">';
+ #$f = fopen ($tmp_files['filtred_sed'], 'r');
+ if (file_exists($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT)) {
+
+ if(self::$_VARS[VAR_REC_ON_PAGE] == 'all'){
+ $up = 0;
+ $low = 1;
+ }
+ else{
+ $up = self::$_VARS[VAR_REC_ON_PAGE] * self::$_VARS[VAR_CUR_REC_PAGE];
+ $low = $up - self::$_VARS[VAR_REC_ON_PAGE]+1;
+ }
+
+ $cntLines=$low ;
+ $f = fopen ($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT, 'r');
+ while ($line = fgets ($f)) {
+
+ echo '<tr>';
+
+ if ((int)$display1kaIcon == 1) {
+ echo '<td class="enkaIcon" title="'.$lang['srv_view_data_row_quick'].'"><span class="faicon quick_view icon-as_link"></span></td>';
+ }
+ if ($stolpci > 0 ) {
+ if (self::$displayEditIcons['dataIcons_edit'] == true) {
+ // checkbox za brisanje vecih vrstic hkrati
+ echo '<td class="data_edit" title="'.$lang['srv_view_data_row_select'].'"><input type="checkbox" class="delete_data_row" /></td>';
+ echo '<td class="data_edit"><span class="faicon delete_circle icon-orange_link" title="'.$lang['srv_delete_data_row'].'"/></span></td>';
+ echo '<td class="data_edit"><span class="faicon edit_square icon-as_link" title="'.$lang['srv_edit_data_row'].'" /></span></td>';
+ echo '<td class="data_edit"><span class="faicon edit smaller icon-as_link" title="'.$lang['srv_edit_data_row_quick'].'" /></span></td>';
+ }
+ if (self::$displayEditIcons['dataIcons_write'] == true) {
+ echo '<td class="data_edit"><span class="faicon pdf icon-as_link" title="'.$lang['srv_view_data_row_pdf'].'"></span></td>';
+ echo '<td class="data_edit"><span class="faicon rtf icon-as_link" title="'.$lang['srv_view_data_row_word'].'"></span></td>';
+
+ // Evoli ikona (ce je vklopljen modul)
+ if(SurveyInfo::getInstance()->checkSurveyModule('evoli')) {
+ echo '<td class="data_edit"><span class="sprites evoli_16 evoli icon-as_link" title="Evoli"></span></td>';
+ echo '<td class="data_edit"><span class="sprites evoli2_16 evoli2 icon-as_link" title="Evoli - Danish"></span></td>';
+ echo '<td class="data_edit"><span class="sprites evoli3_16 evoli3 icon-as_link" title="Evoli - Slovensko"></span></td>';
+ }
+ if(SurveyInfo::getInstance()->checkSurveyModule('evoli_employmeter')) {
+ echo '<td class="data_edit"><span class="sprites evoli_16 evoliEM icon-as_link" title="Evoli EM"></span></td>';
+ echo '<td class="data_edit"><span class="sprites evoli2_16 evoliEM2 icon-as_link" title="Evoli EM - Danish"></span></td>';
+ echo '<td class="data_edit"><span class="sprites evoli3_16 evoliEM3 icon-as_link" title="Evoli EM - Slovensko"></span></td>';
+ }
+
+ // MFDPS ikona (ce je vklopljen modul)
+ if(SurveyInfo::getInstance()->checkSurveyModule('mfdps')) {
+ echo '<td class="data_edit"><span class="sprites mfdps_16 mfdps" title="MFDPS"></span></td>';
+ }
+
+ // BORZA ikona (ce je vklopljen modul)
+ if(SurveyInfo::getInstance()->checkSurveyModule('borza')) {
+ echo '<td class="data_edit"><span class="sprites borza_16 borza pointer" title="BORZA"></span></td>';
+ }
+ }
+ }
+
+ // URLje v besedilu spremenimo v __hiperlinke__
+ $line = stripslashes(self::url_to_link($line));
+
+ # po potrebi vrinemo zaporedno številko
+ if (self::$showLineNumber) {
+ $pos = self::getLineNumberCellOffset($line);
+ $line = substr_replace($line, '</td><td>'.$cntLines, $pos, 0);
+ }
+
+ echo '<td class="data_uid">'.$line.'</td>';
+
+ echo '</tr>';
+ $cntLines++;
+ }
+ } else {
+ echo 'File does not exist (err.No.1)! :'.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+ #echo $folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+ }
+ echo '</tbody>';
+ echo '</table>';
+ echo '</div>'; // end div tableContainer
+
+ /**
+ * kliki na ikonice za urejanje in izpis so definirane v script_analiza.js, analiza_init();
+ */
+
+ // JS za urejanje vnosov (click in hover) (funkciji sta definirani v postProcess.js)
+ ?>
+ <script>
+ $('#dataTableScroller').followTo($("#dataTable").position().top - $("#dataTableScroller").height()-25);
+ dataTableResize(<?=self::$sid?>);
+ $('#dataTable').bind('contextmenu', function (event) { data_preview_content(event); return false; } );
+ <?php
+ if (self::$_VARS[VAR_EDIT] || self::$_VARS[VAR_MONITORING])
+ {
+ ?>
+ $('#dataTable td').click( function (event) { edit_data(event); } );
+ $('#dataTable td').hover( function (event) { edit_data_hover(event) }, function (event) { edit_data_hoverout(event) } );
+ edit_data_inline_edit(); // manj utripne, ce takoj za tabelo poklicemo brez cakanja na dom ready
+ $('#dataTable tr:nth-child(3) th').hover( function (event) { data_header_hover(event) }, function (event) { data_header_hoverout(event) } );
+ $('#dataTable tr:nth-child(3) th').live('click', function(event) { data_header_click(event); } );
+ <?php
+ } elseif (self::$_VARS[VAR_CODING]) {
+ ?>
+ $('#dataTable tbody tr td').click( function (event) { coding_click( $(this), event ) } );
+
+ $('#dataTable tr:nth-child(3) th').hover( function (event) { data_header_hover(event) }, function (event) { data_header_hoverout(event) } );
+ $('#dataTable tr:nth-child(3) th').live('click', function(event) { data_header_click(event); } );
+ <?php
+ } else {
+ ?>
+ $('#dataTable tr:nth-child(3) th').hover( function (event) { data_header_hover(event) }, function (event) { data_header_hoverout(event) } );
+ $('#dataTable tr:nth-child(3) th').live('click', function(event) { data_header_click(event); } );
+ <?php
+ }
+
+ ?>
+ $('#dataTable td.enkaIcon span.quick_view').click( function (event) { showSurveyAnswers(event); } );
+ var sort_action_url = '<?php echo 'index.php?anketa='.self::$sid.'&a='.A_COLLECT_DATA.'&m='.self::$subAction.self::getVarsNoSort();?>'
+ <?php
+ if (self::$_VARS[VAR_META]) {
+ echo "postProcessAddLurkerTitles(".(self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance ? (4+(int)self::$_VARS[VAR_EMAIL]) : (3+(int)self::$_VARS[VAR_EMAIL])).");\n";
+ }
+
+ # pobarvamo celice in dodamo title za statuse
+ echo "postProcessAddTitles();\n";
+ echo "postProcessAddMetaTitles();\n";
+
+ // Pobarvamo sistemske identifikatorje
+ if(self::$_HEADERS['_settings']['force_show_hiden_system'] == '1')
+ echo "postProcessAddSystem(".json_encode($system_columns).");\n";
+
+ if (self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance) {
+ echo "postProcessAddRelevanceTitles();\n";
+ }
+ if (self::$_VARS[VAR_EMAIL]) {
+ echo "postProcessAddEmailTitles(".(self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance ? 3 : 2).");\n";
+ }
+
+ ?>
+ </script>
+ <?php
+ if ($f) {
+ fclose($f);
+ }
+ if (file_exists($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT)) {
+ unlink($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT);
+ }
+ if ($_GET['debug'] == 1) {
+ print_r("<pre>".$_command."</pre>");
+ }
+
+ // Editiranje na dnu - brisanje vec userjev hkrati...
+
+ if(self::$dataFileStatus != FILE_STATUS_NO_DATA && (int)self::$displayEditIcons['dataIcons_edit'] == 1){
+ self::displayBottomEdit();
+ }
+ }
+
+ static public function DisplayDataMultipleTable() {
+ global $lang, $site_path;
+
+ if ( self::$dataFileStatus == FILE_STATUS_OLD) {
+ echo "Posodobljeno: ".date("d.m.Y, H:i:s", strtotime(self::$dataFileUpdated));
+ }
+
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ // paginacija spremenljivk
+ $_spr_on_pages_stop = self::$_VARS['spr_page'] * self::$_VARS['spr_limit'];
+ $_spr_on_pages_start = self::$_VARS['spr_page'] * self::$_VARS['spr_limit'] - self::$_VARS['spr_limit'];
+
+ $sql = sisplet_query("SELECT s.id, s.tip FROM srv_spremenljivka s, srv_grupa g WHERE s.tip='24' AND s.gru_id=g.id AND g.ank_id='".self::$sid."'");
+ if ( mysqli_num_rows($sql) != 1 ) return;
+ $row = mysqli_fetch_assoc($sql);
+ $parent = $row['id'];
+
+ $childs = array();
+ $sql1 = sisplet_query("SELECT spr_id FROM srv_grid_multiple WHERE parent='$parent' AND ank_id='".self::$sid."'");
+ while ( $row1 = mysqli_fetch_assoc($sql1) ) {
+ if ( isset( self::$_SVP_PV[$row1['spr_id'].'_0'] ) )
+ $childs[] = $row1['spr_id'];
+ }
+
+ #preberemo HEADERS iz datoteke
+ self::$_HEADERS = unserialize(file_get_contents(self::$headFileName));
+
+ $multiple = array();
+
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+
+ if ( isset(self::$_SVP_PV[$spid]) && is_numeric($spremenljivka['tip']) ) {
+
+ //$spr_id = explode('_', $spid)[0]; // PHP 5.4
+ $spr_id = explode('_', $spid);
+ $spr_id = $spr_id[0];
+
+ if ( in_array($spr_id, $childs) ) {
+ $spremenljivka['seq'] = explode('_', $spremenljivka['sequences']);
+ $spremenljivka['spr_id'] = $spid;
+ $multiple[] = $spremenljivka;
+ }
+ }
+ }
+
+
+ $sequences = array(); $subseq = array(); $cols = array();
+
+ for ($spr=0; $spr<count($multiple); $spr++) {
+
+ $sequences[$spr] = explode('_', $multiple[$spr]['sequences'] ); // vsi stolpci trenutne spremenljivke (4 - 12)
+ $subseq[$spr] = count($multiple[$spr]['grids']); // stevilo vrstic v vprasanju (4 - 4) (to je za vsa vprasanja enako)
+ $cols[$spr] = round(count($sequences[$spr])/$subseq[$spr], 0); // koliko stolpcev zasede enkratna ponovitev vprasanja (1 - 3)
+
+ #echo "\n\r vars: ".count($sequences[$spr]).' '.$subseq[$spr].' '.$cols[$spr].' '.$dataoffset."\n\r";
+
+ }
+
+
+ $_svp_pv['uid'] = 'uid';
+ //self::$_SVP_PV = array_merge($_svp_pv, self::$_SVP_PV);
+ #izpišemo tabelo
+ echo '<br/>';
+ echo '<div id="tableContainer" class="tableContainer">';
+
+ # div v katerem po potrebi prikazujemo gumbe za skrolanje levo in desno
+ echo '<div id="dataTableScroller">';
+ echo '<span class="pointer halfCircleLeft" onclick="dataTableScroll(\'left\');return false;">&lt;</span>';
+ echo '&nbsp;';
+ echo '<span class="pointer halfCircleRight" onclick="dataTableScroll(\'right\');return false;">&gt;</span>';
+ echo '</div>';
+
+ $display1kaIcon = self::$displayEditIcons['dataIcons_quick_view'] ;
+
+ if (self::$printPreview == true) {
+ self::$displayEditIcons['dataIcons_edit'] = false;
+ self::$displayEditIcons['dataIcons_write'] = false;
+ $display1kaIcon = false;
+ }
+ # koliko stolpcev je colspan
+ $stolpci = ((int)self::$displayEditIcons['dataIcons_edit']*4)
+ + ((int)self::$displayEditIcons['dataIcons_write']*2)
+ + (int)$display1kaIcon ;
+
+ echo '<input type="hidden" id="tableIconColspan" value="'.($stolpci).'">';
+ # ali smo v edit načinu ali monitoringu
+ $cssEdit = (self::$_VARS[VAR_EDIT] || self::$_VARS[VAR_MONITORING]?' editData':'');
+ echo '<table id="dataTable" class="scrollTable no_wrap_td'.$cssEdit.'" '.(self::$_VARS[VAR_EDIT]?' title="'.$lang['srv_edit_data_title'].'"':'').'>';
+
+ // Nastavimo colgroup, da na njega vezemo vse sirine v tabeli, zaradi resizinga stolpcev
+ echo '<colgroup>';
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ //for ($i=0; $i<$stolpci; $i++)
+ // echo '<col class="data_edit">';
+ echo '<col class="data_edit"'.($stolpci > 1 ? (' span="'.$stolpci.'"') : '').'>';
+ }
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset(self::$_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+
+ $spr_id = explode('_', $spid);
+ $spr_id = $spr_id[0];
+
+ if ( in_array($spr_id, $childs) )
+ $repeat = false;
+ else
+ $repeat = true;
+
+ if (self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<col>';
+ }
+
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ echo '<col seq="'.$variable['sequence'].'"';
+
+ if ($spremenljivka['tip'] != 'm' && $spremenljivka['tip'] != 'sm') {
+ echo ' spr_id="'.substr($spid, 0, strpos($spid, '_')).'"';
+ } else {
+ echo ' spr_id="'.$spid.'"';
+ }
+
+ echo '>';
+ }
+ }
+
+ if (!$repeat) break;
+ }
+ }
+ $spr_cont++;
+ }
+
+ }
+ echo '</colgroup>';
+
+ echo '<thead class="fixedHeader">';
+ echo '<tr>';
+
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ echo '<th class="data_edit"'.($stolpci > 1 ? (' colspan="'.$stolpci.'"') : '').'>&nbsp;</td>';
+ }
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+
+ if (isset(self::$_SVP_PV[$spid])) {
+
+ $spr_id = explode('_', $spid);
+ $spr_id = $spr_id[0];
+
+ if ( in_array($spr_id, $childs) ) {
+ $colspan = $cols[ array_search($spr_id, $childs) ];
+ } else {
+ $colspan = $spremenljivka['cnt_all'];
+ }
+
+ if (self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<th title="'.$lang['srv_line_number'].'" >';
+ echo '<div class="headerCell">'.$lang['srv_line_number'].'</div>';
+ echo '</th>';
+ }
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ echo '<th colspan="'.$colspan.'" title="'.$spremenljivka['naslov'].'">';
+ echo '<div class="headerCell">'.$spremenljivka['naslov'].'</div>';
+ echo '</th>';
+ }
+ $spr_cont++;
+
+ }
+ }
+
+ echo '</tr><tr>';
+
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ echo '<th class="data_edit"'.($stolpci > 1 ? (' colspan="'.$stolpci.'"') : '').'>&nbsp;</td>';
+ }
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset(self::$_SVP_PV[$spid]) && (count($spremenljivka['grids']) > 0 )) {
+
+ $spr_id = explode('_', $spid);
+ $spr_id = $spr_id[0];
+
+ if ( in_array($spr_id, $childs) )
+ $repeat = false;
+ else
+ $repeat = true;
+
+ if(self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<th title="'.$lang['srv_line_number'].'" >';
+ echo '<div class="headerCell">'.$lang['srv_line_number'].'</div>';
+ echo '</th>';
+ }
+
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ echo '<th colspan="'.$grid['cnt_vars'].'" title="'.$grid['naslov'].'">';
+ echo '<div class="headerCell">'.$grid['naslov'].'</div>';
+ echo '</th>';
+
+ if (!$repeat) break;
+ }
+ }
+ $spr_cont++;
+ }
+
+ }
+ echo '</tr><tr>';
+
+ # colspan za ikonce
+ if ($stolpci > 0) {
+ //for ($i=0; $i<$stolpci; $i++)
+ // echo '<th class="data_edit">&nbsp;</th>';
+ echo '<th class="data_edit"'.($stolpci > 1 ? (' colspan="'.$stolpci.'"') : '').'>&nbsp;</th>';
+ }
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (isset(self::$_SVP_PV[$spid]) && count($spremenljivka['grids']) > 0) {
+
+ $spr_id = explode('_', $spid);
+ $spr_id = $spr_id[0];
+
+ if ( in_array($spr_id, $childs) )
+ $repeat = false;
+ else
+ $repeat = true;
+
+ if (self::$showLineNumber && $spr_cont+1 == self::$lineoffset) {
+ echo '<th title="'.$lang['srv_line_number'].'" >';
+ echo '<div class="headerCell">'.$lang['srv_line_number'].'</div>';
+ echo '</th>';
+ }
+
+ // paginacija spremenljivk
+ if (self::$_VARS['spr_limit'] == 'all' || ($spr_cont >= $_spr_on_pages_start && $spr_cont < $_spr_on_pages_stop)) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ echo '<th title="'.$variable['naslov'].($variable['other'] ? '&nbsp;(text)' : '').'"'
+ .' seq="'.$variable['sequence'].'"';
+
+ if ($spremenljivka['tip'] != 'm' && $spremenljivka['tip'] != 'sm') {
+ echo ' spr_id="'.substr($spid, 0, strpos($spid, '_')).'"';
+ } else {
+ echo ' spr_id="'.$spid.'"';
+ }
+ echo ($spremenljivka['inline_edit']?' inline_edit=1':'')
+ // .' inline_edit='.($spremenljivka['inline_edit']?$spremenljivka['inline_edit']:'0')
+ .($variable['sequence'] == self::$sort_seq && self::$sort_seq != null ? ' class="hover '.self::$sort_type.'"': '')
+ .'>';
+
+ echo '<div class="dataCell">'.$variable['naslov'];
+ if ($variable['other'] == 1) {
+ echo '&nbsp;(text)';
+ }
+ /*// urejanje kalkulacije -- izracunane vrednosti v podatkih
+ if ($spremenljivka['tip'] == 22) {
+ echo ' <a href="" onclick="calculation_editing(\'-'.substr($spid, 0, strpos($spid, '_')).'\'); return false;">('.$lang['edit3'].')</a>';
+ }*/
+ if ($variable['sequence'] == self::$sort_seq && self::$sort_seq != null) {
+ $img_src = self::$sort_type == 'sort_dsc' ? 'sort_descending' : 'sort_ascending' ;
+ echo '<span class="floatRight faicon '.$img_src.'" title=""></span>';
+ }
+ echo '</div>';
+
+ echo '</th>';
+ }
+ }
+
+ if (!$repeat) break;
+ }
+ }
+ $spr_cont++;
+ }
+
+ }
+ echo'</tr>';
+ echo '</thead>';
+
+ $_command = '';
+ #preberemo podatke
+
+ # najprej po potrebi presortiramo
+ # na vindowsih ne delamo sorta (zaenkrat) // zdej ga že? :)
+ if (self::$do_sort == true) {
+ #
+ $sortString = '-k '.self::$sort_seq;
+
+ #ker tekstovnih ne sortira vredu sem odstranil parameter -n
+ # iz navodil: sorting keys can be interpreted numerically (-n option) instead of alphabetically (which is the default).
+ # če bodo težave bo potrebno parameter -n dodajat po potrebi
+ # $sort_numeric =>
+ $sort_numeric = ''; #$sort_numeric = '-n '
+
+ # za datumska polja je potrebno malo potelovadit
+ foreach (self::$_HEADERS AS $spid => $spremenljivka) {
+ if (count($spremenljivka['grids']) > 0 ) {
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ if (count ($grid['variables']) > 0) {
+ foreach ($grid['variables'] AS $vid => $variable ){
+ if (self::$sort_seq == $variable['sequence']) {
+ if ($variable['spss'] == 'DATETIMEw' || $variable['sortType'] == 'date') {
+ #12.09.2011
+ $sortString = '-k '.self::$sort_seq.'.7,'.self::$sort_seq.'.10 -k'.self::$sort_seq.'.4,'.self::$sort_seq.'.5 -k'.self::$sort_seq.'.1,'.self::$sort_seq.'.2';
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (IS_WINDOWS) {
+ #Cygwin Sort Command On Windows
+ # popravi pot do svojega sort-a
+ $_path_to_CygwinSort = PATH_TO_CYGWIN_FOLDER;
+ # $_command = $_path_to_CygwinSort.' -t"'.STR_DLMT.'"'.(self::$sort_type == 'sort_dsc' ? '-r' : '').' +'.(int)(self::$sort_seq-1).' '.self::$dataFileName.'';
+ $_command = $_path_to_CygwinSort.' -t"'.STR_DLMT.'" '.(self::$sort_type == 'sort_asc' ? '' : '-r ').$sort_numeric.$sortString.' '.self::$dataFileName;
+ } else {
+ # smo na linuxu
+ $_command = 'sort -t \\'.STR_DLMT.' '.(self::$sort_type == 'sort_asc' ? '' : '-r ' ).$sort_numeric.$sortString.' '.self::$dataFileName;
+ }
+ }
+ // polovimo vrstice z statusom 5,6 in jih damo v začasno datoteko
+ if (IS_WINDOWS) {
+ #$cmdLn1 = 'awk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" '.self::$dataFileName.' > '.$tmp_files['filtred_status'];
+ #$out1 = shell_exec($cmdLn1);
+ # če smo predhodno sortirali
+ if (self::$do_sort == true) {
+ $_command .= ' | gawk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" ';
+ #$_command = 'awk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" '.self::$dataFileName;
+ } else {
+ $_command = 'gawk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }" '.self::$dataFileName;
+ }
+
+ } else {
+ #$cmdLn1 = 'awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }\' '.self::$dataFileName.' > '.$tmp_files['filtred_status'];
+ #$out1 = shell_exec($cmdLn1);
+ # če smo predhodno sortirali
+ if (self::$do_sort) {
+ $_command .= ' | awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }\' ';
+ } else {
+ $_command = 'awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.self::$_CURRENT_STATUS_FILTER.' { print $0 }\' '.self::$dataFileName;
+ }
+
+ }
+
+ // paginacija po stolpcih (spremenljivkah)
+ if (IS_WINDOWS) {
+ #$cmdLn1_1 = 'cut -d "|" -f 1,'.self::$_VARIABLE_FILTER.' '.$tmp_files['filtred_status'].' > '.$tmp_files['filtred_spr_pagination'];
+ #$out1 = shell_exec($cmdLn1_1);
+ $_command .= ' | cut -d "|" -f 1,'.self::$_VARIABLE_FILTER;
+ } else {
+ #$cmdLn1_1 = 'cut -d \'|\' -f 1,'.self::$_VARIABLE_FILTER.' '.$tmp_files['filtred_status'].' > '.$tmp_files['filtred_spr_pagination'];
+ #$out1 = shell_exec($cmdLn1_1);
+ $_command .= ' | cut -d \'|\' -f 1,'.self::$_VARIABLE_FILTER;
+ }
+
+ if (self::$_REC_LIMIT != '') {
+ #paginating
+ if (IS_WINDOWS) {
+ #$cmdLn2 = 'awk '.self::$_REC_LIMIT.' '.$tmp_files['filtred_spr_pagination'].' > '.$tmp_files['filtred_pagination'];
+ #$out2 = shell_exec($cmdLn2);
+ $_command .= ' | awk '.self::$_REC_LIMIT;
+ } else {
+ #$cmdLn2 = 'awk '.self::$_REC_LIMIT.' '.$tmp_files['filtred_spr_pagination'].' > '.$tmp_files['filtred_pagination'];
+ #$out2 = shell_exec($cmdLn2);
+ $_command .= ' | awk '.self::$_REC_LIMIT;
+ }
+ #$file_sufix = 'filtred_pagination';
+ } else {
+ #$file_sufix = 'filtred_spr_pagination';
+ }
+
+ // zamenjamo | z </td><td>
+ if (IS_WINDOWS) {
+ #$cmdLn3 = 'sed "s*'.STR_DLMT.'*</td><td>*g" '.$tmp_files[$file_sufix].' > '.$tmp_files['filtred_sed'];
+ #$out3 = shell_exec($cmdLn3);
+ $_command .= ' | sed "s*'.STR_DLMT.'*'.STR_LESS_THEN.'/td'.STR_GREATER_THEN.STR_LESS_THEN.'td'.STR_GREATER_THEN.'*g" >> '.$folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+
+ } else {
+ #$cmdLn3 = 'sed \'s*'.STR_DLMT.'*</td><td>*g\' '.$tmp_files[$file_sufix].' > '.$tmp_files['filtred_sed'];
+ #$out3 = shell_exec($cmdLn3);
+ $_command .= ' | sed \'s*'.STR_DLMT.'*</td><td>*g\' >> '
+ .$folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+
+ }
+ if (IS_WINDOWS) {
+ # ker so na WINsih težave z sortom, ga damo v bat fajl in izvedemo :D
+ $file_handler = fopen($folder.'cmd_'.self::$sid.'_to_run.bat',"w");
+ fwrite($file_handler,$_command);
+ fclose($file_handler);
+ $out_command = shell_exec($folder.'cmd_'.self::$sid.'_to_run.bat');
+ unlink($folder.'cmd_'.self::$sid.'_to_run.bat');
+ } else {
+ $out_command = shell_exec($_command);
+ }
+
+ echo '<tbody class="scrollContent'.(self::$_VARS[VAR_CODING]?' coding':'').'">';
+ #$f = fopen ($tmp_files['filtred_sed'], 'r');
+ if (file_exists($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT)) {
+
+ if(self::$_VARS[VAR_REC_ON_PAGE] == 'all'){
+ $up = 0;
+ $low = 1;
+ }
+ else{
+ $up = self::$_VARS[VAR_REC_ON_PAGE] * self::$_VARS[VAR_CUR_REC_PAGE];
+ $low = $up - self::$_VARS[VAR_REC_ON_PAGE]+1;
+ }
+
+ $cntLines=$low ;
+ $f = fopen ($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT, 'r');
+
+ $data = array();
+ while ($line= fgets ($f)) {
+ $data[] = explode('</td><td>', $line);
+ }
+
+
+ $dataoffset = 1;
+ $vrstni_red = array();
+ foreach (self::$_HEADERS AS $key => $val) {
+ if ($key != '_settings') {
+
+ $spr = explode('_', $key);
+ $spr = $spr[0];
+ $vrstni_red[$key] = $dataoffset;
+
+ if ( in_array($key, self::$_SVP_PV) ) { // TODO: tukaj je nekaj pocasno..
+ if (is_numeric($spr)) {
+ $dataoffset += $val['cnt_all'];
+ } else {
+ $dataoffset++;
+ }
+ }
+ }
+ }
+
+
+ $newdata = array();
+ for ($dataline=0; $dataline<count($data); $dataline++) {
+
+ $origline = $data[$dataline]; //for ($j=0; $j<count($origline); $j++) $origline[$j] = (1+$j).'_'.$origline[$j];
+ $newlines = array();
+
+ for ($i=0; $i < $subseq[0]; $i++) { // $subseq mora imeti vse vrednosti enake, cene ne bo slo, zato mamo lahko kar 0
+
+ $newlines[$i] = $origline;
+
+ $add = false; // preverjamo da niso same -3 ALI -1 (Ajda pravi da vcasih ni prikazovalo vrstic s samo -1)
+ if ($i==0) $add = true; // prvo vrstico pustimo v vsakem primeru
+ for ($spr=count($multiple)-1; $spr>=0; $spr--) {
+ for ($j=0; $j<$cols[$spr]; $j++) {
+
+ if ( ! in_array(trim($newlines[$i][ $vrstni_red[$multiple[$spr]['spr_id']] + ($cols[$spr]*($i)) + $j ]), array('-1', '-3', '-4')) ) {
+ $add = true;
+ break;
+ }
+ }
+ }
+
+ if ( $add ) { // preverjamo da niso same -3
+
+ // pri vseh, razen prvi vrstici odstranimo podvojene vrednosti
+ if ($i > 0) {
+ $leave = array();
+ for ($spr=count($multiple)-1; $spr>=0; $spr--) {
+ for ($j=0; $j<$cols[$spr]; $j++) {
+ $leave[] = $vrstni_red[$multiple[$spr]['spr_id']] + ($cols[$spr]*($i)) + $j;
+ }
+ }
+ for ($j=0; $j<count($newlines[$i]); $j++) {
+ if ( ! in_array($j, $leave) )
+ $newlines[$i][$j] = '';
+ }
+ }
+
+ for ($spr=count($multiple)-1; $spr>=0; $spr--) { // zacnemo od zadaj da si ne pokvarjamo indexov
+
+ // zbrisemo na koncu (najprej na koncu, da si ne pokvarjamo indexov)
+ array_splice($newlines[$i], $vrstni_red[$multiple[$spr]['spr_id']] + ($cols[$spr]*($i+1)), $subseq[0]*$cols[$spr] - $cols[$spr]*($i+1) );
+
+ // zbrisemo na zacetku
+ array_splice($newlines[$i], $vrstni_red[$multiple[$spr]['spr_id']], $cols[$spr]*($i));
+ }
+
+ # dodamo UID. Mitja, tole sem jaz dodal,
+ # da se na začetek vsake vrstice doda UID, kateri je potreben za postprocess JS funkcije
+ # za urejanje, ker Ajda joka da v kombinirani tabeli ne deluje urejanje za podvojene vrstice
+ # Gorazd
+ $newlines[$i][0] = $origline[0];
+
+ // dodamo v nov array
+ $newdata[] = $newlines[$i];
+
+ }
+ }
+
+ }
+
+ unset($data);
+ $data = &$newdata;
+
+
+ foreach ($data AS $line) {
+ $line = implode('</td><td>', $line);
+
+ echo '<tr>';
+
+
+ if ((int)$display1kaIcon == 1) {
+ echo '<td class="enkaIcon" title="'.$lang['srv_view_data_row_quick'].'"><span class="faicon quick_view icon-as_link"></span></td>';
+ }
+ if ($stolpci > 0 ) {
+ if (self::$displayEditIcons['dataIcons_edit'] == true) {
+ // checkbox za brisanje vecih vrstic hkrati
+ echo '<td class="data_edit" title="'.$lang['srv_view_data_row_select'].'"><input type="checkbox" class="delete_data_row" /></td>';
+ echo '<td class="data_edit"><span class="faicon delete_circle icon-orange_link" title="'.$lang['srv_delete_data_row'].'"/></span></td>';
+ echo '<td class="data_edit"><span class="faicon edit_square icon-as_link" title="'.$lang['srv_edit_data_row'].'" /></span></td>';
+ echo '<td class="data_edit"><span class="faicon edit smaller icon-as_link" title="'.$lang['srv_edit_data_row_quick'].'" /></span></td>';
+ }
+ if (self::$displayEditIcons['dataIcons_write'] == true) {
+ echo '<td class="data_edit"><span class="faicon pdf icon-as_link" title="'.$lang['srv_view_data_row_pdf'].'"></span></td>';
+ echo '<td class="data_edit"><span class="faicon rtf icon-as_link" title="'.$lang['srv_view_data_row_word'].'"></span></td>';
+ }
+ }
+
+ // URLje v besedilu spremenimo v __hiperlinke__
+ $line = stripslashes(self::url_to_link($line));
+
+ # po potrebi vrinemo zaporedno številko
+ if (self::$showLineNumber && self::$_VARS[VAR_DATA]) {
+ $pos = self::getLineNumberCellOffset($line);
+ $line = substr_replace($line, '</td><td>'.$cntLines, $pos, 0);
+ }
+
+ echo '<td class="data_uid">'.$line.'</td>';
+
+ echo '</tr>';
+ $cntLines++;
+ }
+ } else {
+ echo 'File does not exist (err.No.1)! :'.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+ #echo $folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+ }
+ echo '</tbody>';
+ echo '</table>';
+ echo '</div>'; // end div tableContainer
+
+ /**
+ * kliki na ikonice za urejanje in izpis so definirane v script_analiza.js, analiza_init();
+ */
+
+ // JS za urejanje vnosov (click in hover) (funkciji sta definirani v postProcess.js)
+ ?>
+ <script>
+ $('#dataTableScroller').followTo($("#dataTable").position().top - $("#dataTableScroller").height()-25);
+ dataTableResize(<?=self::$sid?>);
+ $('#dataTable').bind('contextmenu', function (event) { data_preview_content(event); return false; } );
+ <?php
+ if (self::$_VARS[VAR_EDIT] || self::$_VARS[VAR_MONITORING])
+ {
+ ?>
+ $('#dataTable td').click( function (event) { edit_data(event); } );
+ $('#dataTable td').hover( function (event) { edit_data_hover(event) }, function (event) { edit_data_hoverout(event) } );
+ edit_data_inline_edit(); // manj utripne, ce takoj za tabelo poklicemo brez cakanja na dom ready
+ $('#dataTable tr:nth-child(3) th').hover( function (event) { data_header_hover(event) }, function (event) { data_header_hoverout(event) } );
+ $('#dataTable tr:nth-child(3) th').live('click', function(event) { data_header_click(event); } );
+ <?php
+ } elseif (self::$_VARS[VAR_CODING]) {
+ ?>
+ $('#dataTable tbody tr td').click( function (event) { coding_click( $(this), event ) } );
+ <?php
+ } else {
+ ?>
+ $('#dataTable tr:nth-child(3) th').hover( function (event) { data_header_hover(event) }, function (event) { data_header_hoverout(event) } );
+ $('#dataTable tr:nth-child(3) th').live('click', function(event) { data_header_click(event); } );
+ <?php
+ }
+
+ ?>
+ $('#dataTable td.enkaIcon span.quick_view').click( function (event) { showSurveyAnswers(event); } );
+ var sort_action_url = '<?php echo 'index.php?anketa='.self::$sid.'&a='.A_COLLECT_DATA.'&m='.self::$subAction.self::getVarsNoSort();?>'
+ <?php
+ if (self::$_VARS[VAR_META]) {
+ echo "postProcessAddLurkerTitles(".(self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance ? (4+(int)self::$_VARS[VAR_EMAIL]) : (3+(int)self::$_VARS[VAR_EMAIL])).");\n";
+ }
+
+ # pobarvamo celice in dodamo title za statuse
+ echo "postProcessAddMetaTitles();\n";
+
+ if (self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance) {
+ echo "postProcessAddRelevanceTitles();\n";
+ }
+ if (self::$_VARS[VAR_EMAIL]) {
+ echo "postProcessAddEmailTitles(".(self::$_VARS[VAR_RELEVANCE] && self::$canDisplayRelevance ? 3 : 2).");\n";
+ }
+ ?>
+ </script>
+ <?php
+ if ($f) {
+ fclose($f);
+ }
+ if (file_exists($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT)) {
+ unlink($folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT);
+ }
+ if ($_GET['debug'] == 1) {
+ print_r("<pre>".$_command."</pre>");
+ }
+
+ // Editiranje na dnu - brisanje vec userjev hkrati...
+ if(self::$dataFileStatus != FILE_STATUS_NO_DATA && (int)self::$displayEditIcons['dataIcons_edit'] == 1){
+ self::displayBottomEdit();
+ }
+ }
+
+ public static function url_to_link($text) {
+ if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443)
+ return preg_replace('!(https://[a-z0-9_./?=&-]+)!i', '<a href="$1" target="_blank">$1</a> ', $text." ");
+ else
+ return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1" target="_blank">$1</a> ', $text." ");
+ }
+
+ /** Prikaze reseno anketo za posameznega uporabnika v hitrem nacinu
+ *
+ */
+ public static function displayQuickEdit(){
+ global $lang;
+ global $site_path;
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA
+ || self::$dataFileStatus == FILE_STATUS_NO_FILE
+ || self::$dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+ include_once('../../main/survey/app/global_function.php');
+ new \App\Controllers\SurveyController(true);
+ save('usr_id', self::$usr_id);
+
+ if (isset($_GET['quick_view']) && $_GET['quick_view'] == 0 ) {
+ $quick_view = false;
+ } else {
+ $quick_view = true;
+ }
+
+
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+ if ($quick_view) {
+ # če smo v quick_view disejblamo vse elemente forem
+ echo "<script>"."\n";
+ //echo "$(document).ready(function(){ $('#edit_survey_data input:[type=radio], #edit_survey_data input:[type=checkbox], #edit_survey_data input:[type=text], #edit_survey_data select, #edit_survey_data textarea').attr('disabled',true); })"."\n";
+ echo "$(document).ready(function(){ $('#edit_survey_data input:[type=radio], #edit_survey_data input:[type=checkbox], #edit_survey_data input:[type=text], #edit_survey_data select, #edit_survey_data textarea, #edit_survey_data input:[type=button] , ').attr('disabled',true); })"."\n";
+ echo "$(document).ready(function(){ $('#quick_view').attr('disabled',false); })"."\n";
+ echo "$(document).ready(function(){ $('.ranking').draggable({disabled:true}); })"."\n"; //disable-anje draggable
+ echo "$(document).ready(function(){ $('.dropzone, .sortzone').sortable({disabled:true}); })"."\n"; //disable-anje sortable
+ //echo "$(document).ready(function(){ $('canvas').attr('disabled'); })"."\n"; //disable-anje canvas
+ echo "$(document).ready(function(){ $('.sig').attr('disabled', true); })"."\n"; //disable-anje canvas
+
+ echo "</script>";
+ }
+ else{
+ # če urejamo dodamo prazno js funkcijo submitForm da ne mece errorja (submit izvedemo rocno)
+ echo "<script>function submitForm(){}</script>"."\n";
+ }
+
+ echo '<div id="edit_survey_data">';
+ echo '<div class="inner quick_edit">';
+
+ // title
+ echo '<div class="quick_edit_title">';
+
+ //echo $rowa['naslov'];
+ if (self::$quickEdit_recnum[3]['hasPrev'] == true) {
+ echo '<a href="#" onClick="location.href=\''.self::$quickEdit_recnum[0].'\'" title="'.$lang['srv_prev_resp'].'"><span class="faicon arrow2_l pointer"></span></a>';
+ }
+ echo 'Recnum '.self::$quickEdit_recnum[2];
+ if (self::$quickEdit_recnum[3]['hasNext'] == true) {
+ echo '<a href="#" onClick="location.href=\''.self::$quickEdit_recnum[1].'\'" title="'.$lang['srv_next_resp'].'"><span class="faicon arrow2_r pointer"></span></a>';
+ }
+
+ echo '</div>';
+
+ if ($quick_view == false) {
+ echo '<form name="vnos" id="vnos" method="post" action="../survey/index.php?anketa='.$_GET['anketa'].'&a=data&m=quick_edit&usr_id='.$_GET['usr_id'].'&quick_view=0&post=1" enctype="multipart/form-data">'."\n";
+ }
+
+ if (isset($_GET['anketa']))
+ {
+ save('anketa', $_GET['anketa']);
+ if ($quick_view == false) {
+
+ //JS potreben za branching
+ \App\Controllers\JsController::getInstance()->generateBranchingJS();
+ echo '<script>function checkBranchingDate(){checkBranching();}</script>';
+
+ // shranimo popravke v bazo
+ if(isset($_GET['post']) && $_GET['post'] == '1'){
+ \App\Models\SaveSurvey::getInstance()->posted();
+ }
+ }
+
+
+ $first_loop = 0;
+
+ // prikažemo spremenljivke - vse grupe
+ do
+ {
+ // nastavimo naslednjo grupo / loop
+ if(get('loop_AW') == 0 && get('loop_id') == null){
+ save('grupa', \App\Controllers\FindController::getInstance()->findNextGrupa());
+ } elseif (get('loop_id') != null) {
+ save('loop_id', \App\Controllers\FindController::getInstance()->findNextLoopId());
+
+ if (get('loop_id') == null)
+ save('grupa', \App\Controllers\FindController::getInstance()->findNextGrupa());
+ }
+
+ echo '<div id="container">'."\n";
+
+ // zgeneriramo sistemske spremenljivke
+ \App\Controllers\HeaderController::getInstance()->displaySistemske();;
+
+
+ $offset = 0;
+ $zaporedna = 1;
+ if (SurveyInfo::getInstance()->getSurveyCountType() > 0)
+ {
+ // Preštejemo koliko vprašanj je bilo do sedaj
+ $sqlg = sisplet_query("SELECT vrstni_red FROM srv_grupa WHERE id='".get('grupa')."'");
+ $rowg = mysqli_fetch_assoc($sqlg);
+ $vrstni_red = $rowg['vrstni_red'];
+
+ $sqlCountPast = sisplet_query("SELECT count(*) as cnt FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='".get('anketa')."' AND s.gru_id=g.id AND g.vrstni_red < '$vrstni_red' ORDER BY g.vrstni_red ASC, s.vrstni_red ASC");
+ $rowCount = mysqli_fetch_assoc($sqlCountPast);
+ $offset = $rowCount['cnt'];
+ }
+
+ // poiscemo vprasanja / spremenljivke
+ $sql = sisplet_query("SELECT id FROM srv_spremenljivka WHERE gru_id='".get('grupa')."' AND visible='1' ORDER BY vrstni_red ASC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+ //ce gre za glasovanje in smo eno vprasanje ze prikazali, ostalih ne prikazemo
+ if( (SurveyInfo::getInstance()->getSurveyType() != 0) || ($zaporedna == 1)){
+
+ // preverimo, ce je na tej strani LOOP
+ if (get('loop_id') ==null) {
+
+ // nastavimo pravi id trenutnega loopa
+ $if_id = \App\Controllers\FindController::find_parent_loop($row['id']);
+ if ($if_id > 0) {
+
+ // Ce je prva spremenljivka v loopih izpisemo warning za urejanje
+ $first_loop = ($first_loop == 0) ? 1 : 2;
+ if($first_loop == 1)
+ echo '<div class="loop_warning">'.$lang['srv_loop_warning'].'<a href="#" title="'.$lang['srv_edit_data_row'].'" onClick="quickEditAction(\'edit\', \''.self::$usr_id.'\');">'.$lang['srv_loop_warning2'].'</a>.</div>';
+
+ save('loop_id', \App\Controllers\FindController::getInstance()->findNextLoopId($if_id));
+ }
+ }
+
+ // filtriramo spremenljivke glede na profil
+ $dvp = SurveyUserSetting :: getInstance()->getSettings('default_variable_profile');
+ $_currentVariableProfile = SurveyVariablesProfiles :: checkDefaultProfile($dvp);
+
+ # V VPOGLEDU NE FILTRIRAMO SPREMENLJIVK (v.v.: 27.11.2011)
+ #$tmp_svp_pv = SurveyVariablesProfiles :: getProfileVariables($_currentVariableProfile);
+
+ # če je $svp_pv = null potem prikazujemo vse variable
+ # oziroma če je sistemski dodamo tudi vse, ker drugače lahko filter skrije telefon in email
+ if (!is_countable($tmp_svp_pv) || count($tmp_svp_pv) == 0 || self::$_VARS[VAR_SHOW_SYSTEM] == true ) {
+ $_sv = self::$SDF->getSurveyVariables();
+
+ if (count($_sv) > 0) {
+ foreach ( $_sv as $vid => $variable) {
+ $tmp_svp_pv[$vid] = substr($vid, 0, strpos($vid, '_'));
+ }
+ }
+ }
+ else{
+ foreach ( $tmp_svp_pv as $vid => $variable) {
+ $tmp_svp_pv[$vid] = substr($vid, 0, strpos($vid, '_'));
+ }
+ }
+ # V VPOGLEDU NE FILTRIRAMO SPREMENLJIVK (v.v.: 27.11.2011)
+ //if(in_array($row['id'],$tmp_svp_pv))
+ \App\Controllers\Vprasanja\VprasanjaController::getInstance()->displaySpremenljivka($row['id'], $offset, $zaporedna);
+ }
+
+ $zaporedna++;
+ }
+ if ($quick_view == false) {
+ \App\Controllers\JsController::getInstance()->generateSubmitJS();
+ }
+
+ echo '</div>'."\n";
+ }
+ while (get('grupa') != \App\Controllers\FindController::getInstance()->findNextGrupa() &&
+ (\App\Controllers\FindController::getInstance()->findNextGrupa() > 0 || (get('loop_id') != null && \App\Controllers\FindController::getInstance()->findNextLoopId() != null)));
+ }
+ if ($quick_view == false) {
+ //echo '<input type="submit" value="Shrani" /> ';<a href="#" onclick="document.forms['myFormName'].submit(); return false;">...</a>
+ echo '<span class="floatRight spaceLeft" ><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="document.forms[\'vnos\'].submit(); return false;"><span>' . $lang['save'] . '</span></a></div></span>';
+ echo '<span class="floatRight spaceRight" ><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="../survey/index.php?anketa='.self::$sid.'&a='.A_COLLECT_DATA.'"><span>Nazaj na podatke</span></a></div></span>';
+
+ #echo '</form>'."\n";
+ }
+ else{
+ echo '</form>'."\n";
+ }
+
+ echo '</div>'; # inner
+
+ echo '<div id="quick_edit_title">';
+ self::displayVnosIcons();
+ echo '</div>';
+
+ echo '<br /><br /><br /><br />';
+
+ echo '</div>';
+
+
+ // Div na desni z metapodatki
+ echo '<div id="quick_edit_meta">';
+ self::displayQuickEditMeta();
+ echo '</div>';
+
+ // Preverimo ce gre za prvo urejanje - potem avtomatsko ustvarimo arhiv podatkov
+ if ($quick_view == false && isset($_GET['post']) && $_GET['post'] == '1') {
+ ob_flush();
+
+ $sas = new SurveyAdminSettings();
+ $sas->checkFirstDataChange($inserted=true);
+ }
+ }
+
+ public static function displayQuickEditFilters(){
+ global $lang;
+ global $site_path;
+
+ //echo '<h2>'.$lang['srv_data_title_quick_view'].'</h2>';
+
+ if (self::$dataFileStatus == FILE_STATUS_NO_DATA
+ || self::$dataFileStatus == FILE_STATUS_NO_FILE
+ || self::$dataFileStatus == FILE_STATUS_SRV_DELETED){
+ return false;
+ }
+
+
+ self::displayQuickEditPagination();
+
+ echo '<div id="div_analiza_filtri_right" class="floatRight vpogled">';
+ echo '<ul>';
+ # div za filtre statusov
+ SurveyStatusProfiles::DisplayLink(false);
+ # div za profile variabel
+ SurveyVariablesProfiles::DisplayLink(false, false);
+ # filter za pogoje - ifi
+ SurveyConditionProfiles::DisplayLink(false);
+ # filter za čase
+ SurveyTimeProfiles::DisplayLink(false,false);
+ echo '</ul>';
+ echo '</div>';
+
+
+ # če ne uporabljamo privzetega časovnega profila izpišemo opozorilo
+ $doNewLine = SurveyTimeProfiles :: printIsDefaultProfile(false);
+ if ($doNewLine) {
+ echo '<br/>';
+ }
+ # če imamo filter ifov ga izpišemo
+ $doNewLine = SurveyConditionProfiles:: getConditionString($doNewLine ) || $doNewLine;
+
+ # če imamo filter ifov za inspect ga izpišemo
+ $SI = new SurveyInspect(self::$sid);
+ $SI->getConditionString();
+
+ # če imamo filter spremenljivk ga izpišemo
+ # ker v vpogledu ne filtriramo spremenljivk, ne izpisujemo obvestila
+ #$doNewLine = SurveyVariablesProfiles:: getProfileString($doNewLine ) || $doNewLine;
+
+ if ($doNewLine) {
+ echo '<br/>';
+ }
+
+ echo '<div id="quick_edit_title">';
+
+ self::displayVnosIcons();
+
+ echo '</div>';
+ }
+
+ public static function displayQuickEditPagination() {
+ global $site_url, $lang;
+
+ #Userje polovimo iz datoteke s pomočjo filtrov z AWK-jem
+ $_command = '';
+ #preberemo podatke
+
+ $tmp_file = self::$folder.'tmp_export_'.self::$sid.'_data'.TMP_EXT;
+ $file_handler = fopen($tmp_file,"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+
+ # polovimo vrstice z statusom 5,6 in jih damo v začasno datoteko
+ if (IS_WINDOWS) {
+ $_command = 'gawk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\"} '.self::$_CURRENT_STATUS_FILTER.' {print \"$uids[]=\",'.USER_ID_FIELD.',\";$uid_rec[\",'.USER_ID_FIELD.',\"]=\",'.MOD_REC_FIELD.',\";\" }" '.self::$dataFileName.' >> '.$tmp_file;
+ } else {
+ $_command = 'awk -F"'.STR_DLMT.'" \'BEGIN {OFS=""} '.self::$_CURRENT_STATUS_FILTER.' { print "$uids[]=",'.USER_ID_FIELD.',";$uid_rec[",'.USER_ID_FIELD.',"]=",'.MOD_REC_FIELD.',";"}\' '.self::$dataFileName.' >> '.$tmp_file;
+ }
+
+ if (IS_WINDOWS) {
+ $out_command = shell_exec($_command);
+ } else {
+ $out_command = shell_exec($_command);
+ }
+ include($tmp_file);
+
+ if (file_exists($tmp_file)) {
+ unlink($tmp_file);
+ }
+ # če imamo zapise
+ $all = count($uids);
+ # current nastavimo na zadnji element
+ if ( $all > 0) {
+ // Če trenutni user ni nastavljen ga nastavimo. Upoštevamo tudi filtre, zato preberemo prvega iz filtriranega seznama
+ if(self::$usr_id == 0){
+ self::$usr_id = reset($uids);
+ }
+
+
+ if (isset($_GET['quick_view']) && $_GET['quick_view'] == 0 ) {
+ $baseUrl = $site_url.'admin/survey/index.php?anketa='.self::$sid.'&a=data&m=quick_edit&quick_view='.$_GET['quick_view'].'&usr_id=';
+ } else {
+ $baseUrl = $site_url.'admin/survey/index.php?anketa='.self::$sid.'&a=data&m=quick_edit&usr_id=';
+ }
+
+ if (self::$usr_id > 0 && isset(self::$usr_id,$uids)) {
+ $current = array_search(self::$usr_id,$uids);
+
+ } else {
+ $current = count($uids)-1;
+ }
+
+ echo '<div id="pagination" class="floatLeft">';
+
+ # povezava -10
+ /*if ($all > 10) {
+ if ($current - 10 >= 0) {
+ echo('<div><a href="'.$baseUrl.$uids[$current - 10].'">-10</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">-10</div>');
+ }
+ }*/
+
+ $controls=array('hasPrev'=>true,'hasNext'=>true);
+
+ # povezava na prejšnjo stran
+ $prev_page = $uids[$current - 1] ? $uids[$current - 1] :$uids[$current];
+ if( ($current - 1) >= 0) {
+ echo('<div><a href="'.$baseUrl.$prev_page.'"><span class="faicon pagination_left icon-blue"></span></a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage"><span class="faicon pagination_left icon-blue_soft"></span></div>');
+ $controls['hasPrev'] = false;
+ }
+
+ # povezave za vmesne strani
+ $middle = $all / 2;
+ $skipped = false;
+ for($a = 0; $a < $all; $a++) {
+ if ($all < ((SRV_LIST_GROUP_PAGINATE+1) * 2) || $a <= SRV_LIST_GROUP_PAGINATE || $a > ($all-SRV_LIST_GROUP_PAGINATE)
+
+ || ( abs($a-$current) < SRV_LIST_GROUP_PAGINATE)) {
+ if ($skipped == true) {
+ echo '<div class="spacePage">.&nbsp;.&nbsp;.</div>';
+ $skipped = false;
+ }
+ if($a == $current) {
+ # brez href povezave
+ echo('<div class="currentPage">'.($a+1).'</div>');
+ } else {
+ echo('<div><a href="'.$baseUrl.$uids[$a].'">'.($a+1).'</a></div>');
+ }
+ } else {
+ $skipped = true;
+ }
+ }
+
+ # povezava na naslednjo stran
+ $next_page = ($uids[$current + 1]) ? $uids[$current + 1] : $uids[$current];
+ if(($current + 1) < $all) {
+ echo('<div><a href="'.$baseUrl.$next_page.'"><span class="faicon pagination_right icon-blue"></span></a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage"><span class="faicon pagination_right icon-blue_soft"></span></div>');
+ $controls['hasNext'] = false;
+ }
+
+ /*if ($all > 10) {
+ if ($current + 10 < $all) {
+ echo('<div><a href="'.$baseUrl.$uids[$current + 10].'">+10</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">+10</div>');
+ }
+ }*/
+
+ echo '</div>';
+
+ // vrnemo link na prejsnega, link na naslednjega in recnum trenutnega
+ //return array($baseUrl.$prev_page, $baseUrl.$next_page, $uid_rec[self::$usr_id], $controls);
+ self::$quickEdit_recnum = array($baseUrl.$prev_page, $baseUrl.$next_page, $uid_rec[self::$usr_id], $controls);
+ }
+ else {
+ // dobimo trenutnega userja - ce ni nastavljen v get-u
+ if(self::$usr_id == 0){
+ $sqlu = sisplet_query("SELECT id FROM srv_user WHERE ank_id='".self::$sid."' ORDER BY recnum DESC LIMIT 1");
+ $rowu = mysqli_fetch_array($sqlu);
+ self::$usr_id = $rowu['id'];
+ }
+ }
+ }
+
+ public static function displayQuickEditMeta(){
+ global $lang;
+ global $site_path;
+ global $admin_type;
+
+ $rowa = SurveyInfo::getInstance()->getSurveyRow();
+
+ // dobimo trenutnega userja
+ if(self::$usr_id > 0){
+ $sqlu = sisplet_query("SELECT * FROM srv_user WHERE ank_id='".self::$sid."' AND id='".self::$usr_id."' ");
+ $rowu = mysqli_fetch_array($sqlu);
+ }
+ else{
+ $sqlu = sisplet_query("SELECT * FROM srv_user WHERE ank_id='".self::$sid."' ORDER BY recnum DESC ");
+ $rowu = mysqli_fetch_array($sqlu);
+ }
+ self::$usr_id = $rowu['id'];
+
+ echo '<div class="title">'.$lang['srv_metapodatki'].'</div>';
+
+
+ echo '<table>';
+
+ echo '<tr><td class="left">'.$lang['srv_info_type'].':</td>';
+ echo '<td class="right">'.$lang['srv_vrsta_survey_type_'.SurveyInfo::getSurveyType()].'</td></tr>';
+
+ // IP
+ $ip = SurveySetting::getInstance()->getSurveyMiscSetting('survey_ip');
+ $ip_show = SurveySetting::getInstance()->getSurveyMiscSetting('survey_show_ip');
+ if($ip==0 && $ip_show==1 && ($admin_type == 0 || $admin_type == 1)){
+ echo '<tr><td class="left">'.$lang['ip'].':</td>';
+ echo '<td class="right">'.($rowu['ip'] ? $rowu['ip'] : '&nbsp;').'</td></tr>';
+ }
+
+ // recnum
+ echo '<tr><td class="left">'.$lang['srv_recnum'].':</td>';
+ echo '<td class="right">'.($rowu['recnum'] ? $rowu['recnum'] : '&nbsp;').'</td></tr>';
+
+ // Pri volitvah nimamo parapodatkov
+ if (!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+
+ // browser
+ echo '<tr><td class="left">'.$lang['browser'].':</td>';
+ echo '<td class="right">'.($rowu['useragent'] ? $rowu['useragent'] : '&nbsp;').'</td></tr>';
+
+ // javascript
+ echo '<tr><td class="left">'.$lang['javascript'].':</td>';
+ echo '<td class="right">'.(($rowu['javascript'] == 1) ? $lang['yes'] : $lang['no1']).'</td></tr>';
+
+ // jezik
+ // Dobimo vse jezike za katere obstaja jezikovna datoteka
+ include_once($site_path.'lang/jeziki.php');
+ $jeziki = $lang_all_global['ime'];
+ $jeziki['0'] = $lang['language'];
+ echo '<tr><td class="left">'.$lang['lang'].':</td>';
+ echo '<td class="right">'.$jeziki[$rowu['language']].'</td></tr>';
+ }
+
+ // status
+ echo '<tr><td class="left">'.$lang['status'].':</td>';
+ echo '<td class="right">'.($rowu['last_status'] ? $rowu['last_status'] : '&nbsp;').'</td></tr>';
+
+ // lurker
+ echo '<tr><td class="left">'.$lang['srv_data_lurker'].':</td>';
+ echo '<td class="right">'.(($rowu['lurker'] == 1) ? $lang['yes'] : $lang['no1']).'</td></tr>';
+
+ // Pri volitvah nimamo parapodatkov
+ if (!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+
+ // referer
+ echo '<tr><td class="left">'.$lang['referer'].':</td>';
+ echo '<td class="right">'.($rowu['referer'] ? $rowu['referer'] : '&nbsp;').'</td></tr>';
+
+ // email - samo forma
+ if($rowa['survey_type'] == 1){
+ echo '<tr><td class="left">'.$lang['email'].':</td>';
+ echo '<td class="right">'.($rowu['email'] ? $rowu['email'] : '&nbsp;').'</td></tr>';
+ }
+
+ // spreminjal
+ $datetime = strtotime($rowu['time_insert']);
+ $text = date("d.m.Y, H:i:s", $datetime);
+ echo '<tr><td class="left">'.$lang['timeinsert'].':</td>';
+ echo '<td class="right">'.$text.'</td></tr>';
+
+ $datetime = strtotime($rowu['time_edit']);
+ $text = date("d.m.Y, H:i:s", $datetime);
+ echo '<tr><td class="left">'.$lang['timeedit'].':</td>';
+ echo '<td class="right">'.$text.'</td></tr>';
+
+ // preberemo popravljanje po straneh
+ $sqlG = sisplet_query("SELECT ug.time_edit, g.naslov FROM srv_user_grupa".self::$db_table." ug, srv_grupa g WHERE g.ank_id = '".self::$sid."' AND ug.usr_id = '".self::$usr_id."' AND g.id = ug.gru_id ORDER BY g.vrstni_red ASC");
+ while($rowG = mysqli_fetch_array($sqlG)){
+
+ $datetime = strtotime($rowG['time_edit']);
+ $text = date("d.m.Y, H:i:s", $datetime);
+
+ echo '<tr><td class="left">'.$rowG['naslov'].':</td>';
+ echo '<td class="right">'.$text.'</td></tr>';
+ }
+
+ if ( $admin_type <= 1) {
+
+ echo '<tr><td class="left">'.$lang['srv_sc_txt1'].':</td>';
+ echo '<td class="right"><a href="#" onclick="sc_display(\''.self::$usr_id.'\'); return false;">'.$lang['srv_sc_txt2'].'</a></td></tr>';
+
+ }
+ }
+
+ # preberemo vklopljene module
+ //potrebuje se za modul MAZA, da aplikacija izpolni te hidden inpute
+ //rabi pa se to za povezavo respondenta med tebelama maza_app_users in srv_user
+ if(SurveyInfo::checkSurveyModule('maza')){
+ $maza_query = "SELECT mau.identifier, mau.deviceInfo, mau.tracking_log FROM maza_app_users as mau
+ JOIN maza_srv_users AS msu ON mau.id = msu.maza_user_id
+ JOIN srv_user AS su ON msu.srv_user_id = su.id
+ WHERE su.id = '".self::$usr_id."';";
+
+ $sql = sisplet_query($maza_query, 'array');
+
+ //it is already there
+ if(count($sql) > 0){
+ //NextPin link
+ echo '<tr><td class="left">'.$lang['srv_maza_nextpin_link'].':</td>';
+ echo '<td class="right"><a href="http://traffic.ijs.si/NextPin/?user=1KAPanel_'.$sql[0]['identifier'].'">'
+ . 'http://traffic.ijs.si/NextPin/?user=1KAPanel_'.$sql[0]['identifier'].'</a></td></tr>';
+ //Device info
+ echo '<tr><td class="left">'.$lang['srv_maza_device_info'].':</td>';
+ echo '<td class="right">'.$sql[0]['deviceInfo'].'</td></tr>';
+ //Tracking logs
+ echo '<tr><td class="left">'.$lang['srv_maza_user_app_logs'].':</td>';
+ echo '<td class="right">'.$sql[0]['tracking_log'].'</td></tr>';
+ }
+ }
+
+ echo '</table>';
+
+ echo '<div id="survey-connect-disp" style="display:none"></div>';
+ }
+
+
+ /* funkcija vrne AWK string za pogoj ali iščemo zapise trenutnega userja
+ * vklopljeno more bit prepoznava userja iz cms
+ *
+ */
+ static function createCMSUserFilter() {
+ #poiščemo sekvenco meta podatka: usr_from_cms
+ $found=false;
+ $sequence = null;
+ if (count(self::$_HEADERS['meta']['grids']) > 0 && $found==false) {
+ foreach (self::$_HEADERS['meta']['grids'] AS $gid => $grids) {
+ if (count($grids['variables']) > 0 && $found==false) {
+ foreach ($grids['variables'] AS $vids => $variables) {
+ if ($variables['variable'] == 'usr_from_cms') {
+ $sequence = $variables['sequence'];
+ $found=true;
+ }
+ }
+ }
+ }
+ }
+ if ($found == true && (int)$sequence > 0) {
+ # polovimo email
+ global $global_user_id;
+ $sqlu = sisplet_query("SELECT email FROM users WHERE id = '".$global_user_id."'");
+ list($email) = mysqli_fetch_row($sqlu);
+ if ($email != null &&trim($email) != '') {
+
+ # nardimo awk string da primerjamo email
+ if (IS_WINDOWS) {
+ # za windows
+ $awkString = '($'.$sequence.'=='."\\\"".$email."\\\"".')';
+ } else {
+ # za linux
+ $awkString = '($'.$sequence.'=='.'"'.$email.'"'.')';
+ }
+
+ return $awkString;
+ }
+ }
+ return null;
+ }
+
+ static function displayOnlyCMS() {
+ global $lang;
+ # prikažemo samo če imamo ankete uporabnika iz cms
+ echo '<label>';
+ echo '<input type="checkbox" id="doCMSUserFilterCheckbox"'.(self::$doCMSUserFilter==true?' checked="checked"':'').' onchange="changeDoCMSUserFilterCheckbox();" autocomplete="off">';
+ echo $lang['srv_data_onlyMySurvey'];
+ echo Help::display('srv_data_onlyMySurvey');
+ echo '</label>';
+ }
+
+ static function displayPublicData($properties = array()) {
+ global $lang;
+ global $site_url;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ $anketa = self::$sid;
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body style="margin:5px; padding:5px;" >';
+
+ echo '<h2>'.$lang['srv_publc_data_title_for'].self::$survey['naslov'].'</h2>';
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $anketa . '" />';
+
+ echo '<div id="analiza_data">';
+ //Izvoz v PDF / RTF / XLS
+ $_url1 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'a'=>'list_pdf',
+ 'anketa'=>$anketa)));
+ $_url2 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'a'=>'list_rtf',
+ 'anketa'=>$anketa)));
+ $_url3 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'a'=>'list_xls',
+ 'anketa'=>$anketa)));
+ echo '<div class="printHide" style="margin-top:6px; margin-bottom:60px;">';
+ echo '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url2.'" target="_blank"><span class="faicon rtf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url3.'" target="_blank"><span class="faicon xls icon-as_link"></span></a>';
+
+ if (isset($properties['profile_id_status']))
+ {
+ self::$_PROFILE_ID_STATUS = $properties['profile_id_status'];
+ SurveyStatusProfiles :: setCurentProfileId(self::$_PROFILE_ID_STATUS);
+ }
+
+ if (isset($properties['profile_id_variable']))
+ {
+ self::$_PROFILE_ID_VARIABLE = $properties['profile_id_variable'];
+
+ SurveyVariablesProfiles::setCurrentProfileId(self::$_PROFILE_ID_VARIABLE);
+ }
+ if (isset($properties['profile_id_condition']))
+ {
+ self::$_PROFILE_ID_CONDITION = $properties['profile_id_condition'];
+
+ SurveyConditionProfiles::setCurrentProfileId(self::$_PROFILE_ID_CONDITION);
+ }
+
+
+ self::$printPreview = true;
+ self::$_VARS[VAR_DATA] = 1;
+ self::$_VARS[VAR_EDIT] = 0;
+ self::$_VARS[VAR_PRINT] = 0;
+ self::$_VARS[VAR_MONITORING] = 0;
+ if (isset(self::$_SVP_PV['invitation'])) {
+ unset(self::$_SVP_PV['invitation']);
+ }
+
+
+ # ponastavimo nastavitve- filter
+ self::setUpFilter();
+ self::DisplayDataTable();
+
+ // JS ki vedno doda labele
+ ?><script>
+ data_show_labels();
+ </script><?php
+
+ echo '</div>';
+
+ echo '<div id="navigationBottom" class="printHide">';
+
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span><img src="'.$site_url.'admin/survey/icons/icons/printer.png" vartical-align="middle" /> '.$lang['hour_print2'].'</span></a></div></span>';
+ echo '<span class="spaceRight floatRight printHide" style="margin-top:6px;">';
+ echo '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url2.'" target="_blank"><span class="faicon rtf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url3.'" target="_blank"><span class="faicon xls icon-as_link"></span></a>';
+ echo '</span>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+
+ echo '</body>';
+ echo '</html>';
+ }
+
+ function displayDataPrintPreview() {
+ global $lang;
+ global $site_url;
+
+ header('Cache-Control: no-cache');
+ header('Pragma: no-cache');
+ $anketa = $_REQUEST['anketa'];
+ if ($anketa > 0) {
+ $sql = sisplet_query("SELECT lang_admin FROM srv_anketa WHERE id = '$anketa'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['lang_admin'];
+ } else {
+ $sql = sisplet_query("SELECT value FROM misc WHERE what = 'SurveyLang_admin'");
+ $row = mysqli_fetch_assoc($sql);
+ $lang_admin = $row['value'];
+ }
+
+ #izpišemo HTML
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
+ echo '<head>';
+ echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+ echo '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/script/js-lang.php?lang='.($lang_admin==1?'si':'en').'"></script>';
+ echo '<script type="text/javascript" src="'.$site_url.'admin/survey/minify/g=jsnew"></script>';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=css" media="screen" rel="stylesheet" />';
+ echo '<link type="text/css" href="'.$site_url.'admin/survey/minify/g=cssPrint" media="print" rel="stylesheet" />';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<!--[if lt IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie6hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 7]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie7hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<!--[if IE 8]>';
+ echo '<link rel="stylesheet" href="<?=$site_url?>admin/survey/css/ie8hacks.css" type="text/css" />';
+ echo '<![endif]-->';
+ echo '<style>';
+ echo '.container {margin-bottom:45px;} #navigationBottom {width: 100%; background-color: #f2f2f2; border-top: 1px solid gray; height:25px; padding: 10px 30px 10px 0px !important; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000;}';
+ echo '</style>';
+ echo '<script>';
+ echo 'function chkstate(){';
+ echo ' if(document.readyState=="complete"){';
+ echo ' window.close()';
+ echo ' }';
+ echo ' else{';
+ echo ' setTimeout("chkstate()",2000)';
+ echo ' }';
+ echo '}';
+ echo 'function print_win(){';
+ echo ' window.print();';
+ echo ' chkstate();';
+ echo '}';
+ echo 'function close_win(){';
+ echo ' window.close();';
+ echo '}';
+ echo '</script>';
+ echo '</head>';
+
+ echo '<body style="margin:5px; padding:5px;" onBlur="window.close();">';
+ echo '<input type="hidden" name="anketa_id" id="srv_meta_anketa_id" value="' . $_REQUEST['anketa'] . '" />';
+ #echo '<div id="div_analiza_single_var" class="container">';
+ echo '<div id="analiza_data">';
+ //Izvoz v PDF / RTF / XLS
+ $_url1 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'a'=>'list_pdf',
+ 'anketa'=>$anketa)));
+ $_url2 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'a'=>'list_rtf',
+ 'anketa'=>$anketa)));
+ $_url3 = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'b'=>'export',
+ 'a'=>'list_xls',
+ 'anketa'=>$anketa)));
+ echo '<div class=" printHide" style="margin-top:6px;">';
+ echo '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url2.'" target="_blank"><span class="faicon rtf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url3.'" target="_blank"><span class="faicon xls icon-as_link"></span></a>';
+
+ echo '<br class="clr"/>';
+ echo $lang['srv_data_print_preview'];
+ echo '</div>';
+
+ self::$printPreview = true;
+ self::$_VARS[VAR_DATA] = 1;
+ self::$_VARS[VAR_SPR_LIMIT] = 5;
+ self::$_VARS[VAR_META] = 0;
+ self::$_VARS[VAR_EMAIL] = 0;
+ self::$_VARS[VAR_RELEVANCE] = 0;
+ self::$_VARS[VAR_EDIT] = 0;
+ self::$_VARS[VAR_PRINT] = 0;
+ self::$_VARS[VAR_MONITORING] = 0;
+ if (isset(self::$_SVP_PV['invitation'])) {
+ unset(self::$_SVP_PV['invitation']);
+ }
+
+
+ # ponastavimo nastavitve- filter
+ self::setUpFilter();
+ self::DisplayDataTable();
+ echo '</div>';
+
+ echo '<div id="navigationBottom" class="printHide">';
+
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="close_win(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="window.print();return false;"><span class="faicon print_small icon-grey_dark_link"></span> '.$lang['hour_print2'].'</a></div></span>';
+
+ echo '<span class="spaceRight floatRight printHide" style="margin-top:6px;">';
+ echo '<a href="'.$_url1.'" target="_blank"><span class="faicon pdf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url2.'" target="_blank"><span class="faicon rtf icon-as_link"></span></a>&nbsp;&nbsp;';
+ echo '<a href="'.$_url3.'" target="_blank"><span class="faicon xls icon-as_link"></span></a>';
+ echo '</span>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+
+ echo '</body>';
+ echo '</html>';
+ }
+
+ static function displayVnosIcons() {
+ global $lang;
+ global $global_user_id;
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ // gumbi na levi (delete, edit, izvozi...)
+ echo '<div id="left_options">';
+
+ echo '<span class="faicon delete_circle large icon-orange_link" title="'.$lang['srv_delete_data_row'].'" onClick="quickEditAction(\'delete\', \''.self::$usr_id.'\');"></span>';
+ echo '<span class="faicon edit_square large icon-grey_dark_link" title="'.$lang['srv_edit_data_row'].'" onClick="quickEditAction(\'edit\', \''.self::$usr_id.'\');"></span>';
+ echo '<span class="faicon print_small large icon-grey_dark_link" title="'.$lang['PRN_Izpis'].'" onClick="printAnaliza(\'Vpogled\'); return false;"></span>';
+
+ // Ce imamo izvoze v paketu
+ if($userAccess->checkUserAccess($what='data_export')){
+ echo '<span class="faicon pdf large icon-grey_dark_link" title="'.$lang['PDF_Izpis'].'" onClick="quickEditAction(\'pdf\', \''.self::$usr_id.'\');"></span>';
+ echo '<span class="faicon rtf large icon-grey_dark_link" title="'.$lang['RTF_Izpis'].'" onClick="quickEditAction(\'rtf\', \''.self::$usr_id.'\');"></span>';
+ }
+ else{
+ echo '<span class="faicon pdf large icon-grey_dark_link user_access_locked" title="'.$lang['PDF_Izpis'].'" onClick="popupUserAccess(\'data_export\');"></span>';
+ echo '<span class="faicon rtf large icon-grey_dark_link user_access_locked" title="'.$lang['RTF_Izpis'].'" onClick="popupUserAccess(\'data_export\');"></span>';
+ }
+
+ echo '<span class="faicon copy large icon-grey_dark_link" title="'.$lang['srv_copy_data'].'" onClick="quickEditAction(\'copy\', \''.self::$usr_id.'\');"></span>';
+
+ // omogocimo/onemogocimo popravljanje vnosa
+ if(isset($_GET['quick_view']) && $_GET['quick_view'] == 0){
+ echo '<span class="faicon edit large icon-grey_dark_link_reverse" title="'.$lang['srv_quick_view_off'].'" onClick="quickEditAction(\'quick_view\', \''.self::$usr_id.'\');"></span>';
+ echo '<input type="hidden" id="quick_view" value="0">';
+ }
+ else{
+ echo '<span class="faicon edit large icon-grey_dark_link" title="'.$lang['srv_quick_view_on'].'" onClick="quickEditAction(\'quick_view\', \''.self::$usr_id.'\');"></span>';
+ echo '<input type="hidden" id="quick_view" value="1">';
+ }
+ echo '</div>';
+ }
+
+ static function displayStatusLegend (){
+
+ if (self::$dataFileStatus >= 0) {
+ #status - če smo v meta ali imamo profil vse enote
+ if ( (self::$_VARS[VAR_META] && self::$_VARS[VAR_METAFULL])
+ || ( SurveyStatusProfiles::getCurentProfileId() == 1 )) {
+ SurveyAnalysisHelper::getInstance()->displayStatusLegend();
+ }
+ }
+ }
+ static function displayTestLegend (){
+
+ if (self::$dataFileStatus >= 0) {
+ #testni vnosi - samo ce imamo testne
+ if (self::$_HAS_TEST_DATA) {
+ SurveyAnalysisHelper::getInstance()->displayTestLegend();
+ }
+ }
+ }
+ static function displayMetaStatusLegend (){
+
+ if (self::$dataFileStatus >= 0) {
+ SurveyAnalysisHelper::getInstance()->displayMissingLegend();
+ }
+ }
+
+ static function DisplaySnLinks() {
+ global $lang, $site_url;
+
+ echo '<div id="data_sn_buttons">';
+
+ // Gumb za preklop na EGO
+ echo '<span>';
+ echo '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::$sid.'&a='.A_COLLECT_DATA.'&m='.self::$subAction.self::getVars(VAR_CIRCLES, '0').'"'.((int)self::$_VARS[VAR_CIRCLES]==0?' class="red"':'').'>'.$lang['srv_lnk_ego'].'</a>';
+ echo '</span>';
+
+ // Gumb za preklop na ALTER
+ echo '<span>';
+ echo '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::$sid.'&a='.A_COLLECT_DATA.'&m='.self::$subAction.self::getVars(VAR_CIRCLES, '1').'"'.((int)self::$_VARS[VAR_CIRCLES]==1?' class="red"':'').'>'.$lang['srv_lnk_alter'].'</a>';
+ echo '</span>';
+
+ echo '</div>';
+ }
+
+ static function setSnDisplayFullTableCheckbox() {
+
+ session_start();
+
+ $_SESSION['sid_'.self::$sid]['snCreateFullTable'] = (int)$_POST['fullTable'] == 1;
+
+ session_commit();
+ }
+
+ static function getLineNumberCellOffset($line) {
+
+ $offset = 0;
+
+ // Ce nismo na prvi strani spremenljivk je offset drugacen in prikazemo stevilko na zacetku
+ if(self::$_VARS[VAR_SPR_PAGE] > 1){
+ $offset = strpos($line, '</td><td>');
+ }
+ elseif (self::$lineoffset > 0 ) {
+ for ($i = 0; $i < self::$lineoffset; $i++) {
+ $offset = strpos($line,'</td><td>',$offset+1);
+ }
+ }
+
+ return $offset;
+ }
+
+ static function showMultiple () {
+
+ $sql = sisplet_query("SELECT * FROM srv_grid_multiple WHERE ank_id = ".self::$sid." GROUP BY parent");
+ if ( mysqli_num_rows($sql) == 1 )
+ return true;
+
+ return false;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyData/class.SurveyDataFile.php b/admin/survey/classes/surveyData/class.SurveyDataFile.php
new file mode 100644
index 0000000..29482d7
--- /dev/null
+++ b/admin/survey/classes/surveyData/class.SurveyDataFile.php
@@ -0,0 +1,550 @@
+<?php
+
+/**
+ *
+ * Created on 17.12.2019
+ *
+ * @author: Peter Hrvatin
+ *
+ * Class za upravljanje z datotekami za podatke (preveri status datoteke, zaklepanje datoteke, klice kreiranje, updatanje...)
+ *
+*/
+
+class SurveyDataFile {
+
+ private static $instance;
+
+ private $anketa;
+ private $checked;
+
+ private $header_file_name; // Ime header datoteke
+ private $data_file_name; // Ime datoteke s podatki
+ private $head_file_time = 0; // Cas zadnjega kreiranja header datoteke
+ private $data_file_time = 0; // Cas zadnjega kreiranja datoteke s podatki
+
+ private $last_update = 0; // Cas zadnjega kreiranja datoteke
+ private $collect_all_status = 1; // Ali zbiramo vse ali samo ustrezne
+ private $file_status = FILE_STATUS_NO_DATA; // Status datoteke
+ private $has_test_data = false; // Ali vnosi vsebujejo testne podatke
+ private $last_response_time = null; // Ali vnosi vsebujejo testne podatke
+ private $all_user_cnt = null; // Stevilo vseh responsov
+
+ private $HEADER = NULL;
+
+
+ public static function get_instance($force_new=false) {
+
+ if(!is_object(self::$instance) || $force_new) {
+ self::$instance = new SurveyDataFile();
+ }
+
+ return self::$instance;
+ }
+
+ public function init($anketa) {
+ global $site_path;
+
+ // Nastavimo id ankete
+ $this->anketa = $anketa;
+
+ // Nastavimo folder kjer se nahajajo datoteke
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+ SurveySetting::getInstance()->Init($this->anketa);
+
+ // Nastavimo imena datotek
+ $this->header_file_name = $folder . 'export_header_'.$this->anketa.'.dat';
+ $this->data_file_name = $folder . 'export_data_'.$this->anketa.'.dat';
+
+ // Vedno ob inicializaciji preverimo status datoteke
+ if($this->checked == false)
+ $this->checkFile();
+ }
+
+
+ /**** GETTERJI ****/
+
+ // Vrnemo status datoteke s podatki
+ public function getStatus() {
+ return $this->file_status;
+ }
+
+ // Vrnemo cas zadnjega updata datoteke
+ public function getFileUpdated() {
+ return $this->last_update;
+ }
+
+ // Vrnemo ime header datoteke
+ public function getHeaderFileName() {
+ return $this->header_file_name;
+ }
+
+ // Vrnemo ime datoteke s podatki
+ public function getDataFileName() {
+ return $this->data_file_name;
+ }
+
+ // Vrnemo cas kreiranja datoteke s podatki
+ public function getDataFileTime() {
+ return $this->data_file_time;
+ }
+
+ // Vrnemo status kreiranja (ce pridobivamo vse ali samo ustrezne)
+ public function getCollectAllStatus() {
+ return $this->collect_all_status;
+ }
+
+ // Vrnemo status kreiranja (ce pridobivamo vse ali samo ustrezne)
+ public function getHasTestData() {
+ return $this->has_test_data;
+ }
+
+ // Vrnemo cas zadnjega responsa
+ public function getLastResponseTime() {
+ return $this->last_response_time;
+ }
+
+ // Vrnemo header datoteko
+ public function getHeader() {
+
+ if (!isset($this->HEADER) || $this->HEADER == null) {
+ if ($this->header_file_name != null && file_exists($this->header_file_name)) {
+ $this->HEADER = unserialize(file_get_contents($this->header_file_name));
+ }
+ }
+
+ return $this->HEADER;
+ }
+
+ public function getHeaderVariable($variable) {
+
+ $this->getHeader();
+
+ return isset($this->HEADER[$variable]) ? $this->HEADER[$variable] : null;
+ }
+
+ public function getSurveyVariables($filterTip = NULL) {
+
+ $result = array();
+
+ $this->getHeader();
+
+ if (is_countable($this->HEADER) && count($this->HEADER) > 0) {
+
+ foreach ($this->HEADER AS $_vkey => $variable) {
+
+ # dodamo samo tiste variable, ki imajo numerični tip (navadne spremenljvke)
+ if (is_numeric($variable['tip'] )
+ # ne dodamo sistemskih email, telefon, ime, priimek, naziv
+ && !( (int)$variable['hide_system'] == 1
+ && in_array($variable['variable'],unserialize (SYSTEM_VARIABLES)) )# unserialize (SYSTEM_VARIABLES) -> definition.php = array('email','telefon','ime','priimek','naziv','drugo')
+ ) {
+ # če filter ni setiran dodamo vse variable
+ if ( $filterTip == NULL ) {
+ $result[$_vkey] = $variable['sequences'];
+ }
+ else if ( is_array($filterTip) && in_array($variable['tip'],$filterTip) ) {
+ $result[$_vkey] = $variable['sequences'];
+ }
+ else if ( is_string($filterTip) && (string)$variable['tip'] == (string)$filterTip ) {
+ $result[$_vkey] = $variable['sequences'];
+ }
+ else if ( is_numeric($filterTip) && (int)$variable['tip'] == (int)$filterTip ) {
+ $result[$_vkey] = $variable['sequences'];
+ }
+ }
+ }
+ }
+
+ return $result;
+ }
+
+ public function getVariableName($variable) {
+
+ $result = '';
+ $this->getHeader();
+
+ if (isset($this->HEADER[$variable])) {
+ $result = '(' . $this->HEADER[$variable]['variable'] .') - '.$this->HEADER[$variable]['naslov'];
+ }
+
+ return $result;
+ }
+
+ /**** GETTERJI - KONEC ****/
+
+
+
+ // Preverimo status datotek s podatki
+ public function checkFile () {
+
+ // Najprej nastavimo status ni podatkov
+ $this->file_status = FILE_STATUS_NO_DATA;
+
+ // Preverimo ce ima anketa kaj responsov - če je respondentov več kot ONLY_VALID_LIMIT (5000) lovimo samo ustrezne
+ $sql_cnt_user = sisplet_query("SELECT count(*) FROM srv_user AS u WHERE u.ank_id = '".$this->anketa."' AND u.preview='0' AND u.deleted='0'");
+ list($this->all_user_cnt) = mysqli_fetch_row($sql_cnt_user);
+
+ // Imamo response
+ if((int)$this->all_user_cnt > 0) {
+
+ // Nastavimo zapise v bazi za datoteko
+ $sql = sisplet_query("SELECT UNIX_TIMESTAMP(head_file_time), UNIX_TIMESTAMP(data_file_time), DATE_FORMAT(last_update,'%d.%m.%Y %H:%i:%s'), collect_all_status
+ FROM srv_data_files
+ WHERE sid='".$this->anketa."'");
+ if(mysqli_num_rows($sql) > 0) {
+ list($this->head_file_time, $this->data_file_time, $this->last_update, $this->collect_all_status) = mysqli_fetch_row($sql);
+ }
+
+ // Ce je collect_all_status = 2 je admin nastavil da se lovijo vsi statusi, popravimo tudi čas, da se datoteka zgenerira na novo
+ if ((int)$this->all_user_cnt > ONLY_VALID_LIMIT && (int)$this->collect_all_status == 1) {
+
+ $this->collect_all_status = 0;
+
+ $updated = sisplet_query("INSERT INTO srv_data_files (sid, collect_all_status, data_file_time)
+ VALUES ('".$this->anketa."','".(int)$this->collect_all_status."', '0000-00-00')
+ ON DUPLICATE KEY UPDATE collect_all_status = '".(int)$this->collect_all_status."'");
+ }
+
+ // Nastavimo, ce imamo testne vnose
+ $_qry_cnt_testdata = sisplet_query("SELECT count(*)
+ FROM srv_user AS u
+ WHERE u.ank_id = '".$this->anketa."' AND preview='0' AND (u.testdata = '1' OR u.testdata = '2') AND u.deleted = '0'");
+ list($this->has_test_data) = mysqli_fetch_row($_qry_cnt_testdata);
+
+
+ // Ce ne belezimo parapodatka o datumu responsa, preverimo zadnji timestamp resevanja ankete
+ if(SurveySetting::getInstance()->getSurveyMiscSetting('survey_date') == 1) {
+
+ $sql_last_response_time = sisplet_query("SELECT UNIX_TIMESTAMP(last_response_time) AS last_response_time FROM srv_anketa WHERE id='".$this->anketa."'");
+ list($last_response_time) = mysqli_fetch_row($sql_last_response_time);
+
+ if($this->data_file_time < $last_response_time){
+ $this->clearFiles();
+ $this->file_status = FILE_STATUS_NO_FILE;
+ }
+ }
+
+ // Preverimo ce imamo usability stolpec v header datoteki ali ce imamo na novo testne podatke - potem pobrisemo vse datoteke, ker moramo vse generirati na novo
+ if($this->checkUsability() || $this->checkTestData()){
+ $this->clearFiles();
+
+ $this->file_status = FILE_STATUS_NO_FILE;
+ }
+ else{
+
+ // Datoteka obstaja
+ if(file_exists($this->getHeaderFileName()) && file_exists($this->data_file_name)) {
+ // Preverimo ce je datoteka up2date
+ $this->file_status = $this->isFileUp2Date();
+ }
+ // Ni datoteke
+ else {
+ $this->file_status = FILE_STATUS_NO_FILE;
+ }
+ }
+ }
+
+ // Konmcali smo preverjanje statusa datotek
+ $this->checked = true;
+
+ return $this->file_status;
+ }
+
+ // Preverimo ce je datoteka s podatki up to date
+ private function isFileUp2Date() {
+
+ // Cas zadnjega editiranja ankete (vse razen active=-1 - pobrisana)
+ $sql_survey = sisplet_query("SELECT active, UNIX_TIMESTAMP(edit_time) AS srv_edit_time FROM srv_anketa WHERE id='".$this->anketa."'");
+ list($anketa_active, $anketa_edit_time) = mysqli_fetch_row($sql_survey);
+
+ // Ce je anketa slucajno pobrisana nastavimo status na pobrisano
+ if($anketa_active != '0' && $anketa_active != '1'){
+ return FILE_STATUS_SRV_DELETED;
+ }
+
+ // Ce se cas zadnjega urejanja ankete ne ujema s tistim v bazi, moram vse kreirati na novo
+ if((int)$anketa_edit_time != (int)$this->head_file_time || (int)$anketa_edit_time <= 0) {
+ $this->clearFiles();
+
+ return FILE_STATUS_NO_FILE;
+ }
+
+ // Polovimo datum zadnjega respondenta
+ $this->setLastResponseTime();
+
+ // Preberemo max time iz datoteke s podatki in uporabimo manjšega
+ if(IS_WINDOWS) {
+ $command = 'awk -F"|" "BEGIN {max = 0} {if ($6 > max && $6 > 0) max=$6 } END {print max}" '.$this->data_file_name;
+ }
+ else {
+ $command = 'awk -F\'|\' \'BEGIN {max = 0} {if ($6 > max && $6 > 0) max=$6 } END {print max}\' '.$this->data_file_name;
+ }
+ $response_time_from_file = shell_exec($command);
+
+ if((int)$response_time_from_file > 0) {
+ $data_file_time = min((int)$this->data_file_time, (int)$response_time_from_file);
+ }
+ else{
+ $data_file_time = $this->data_file_time;
+ }
+
+ // Ce se cas dejanskega zadnjega responsa in cas zadnjega responsa v datoteki ne ujemata je datoteka zastarela
+ if((int)$this->last_response_time != (int)$data_file_time || (int)$this->last_response_time <= 0) {
+ return FILE_STATUS_OLD;
+ }
+
+
+ return FILE_STATUS_OK;
+ }
+
+ // Preverimo ce imamo vklopljen filter na uporabnost in ce imamo v headerju zapisan stolpec za usability (drugace moramo generirati datoteko na novo)
+ private function checkUsability(){
+
+ // Preverimo ce imamo vklopljen filter na usability
+ if(SurveyStatusProfiles::usabilitySettings()){
+
+ // Preverimo ce imamo usability stolpec v header datoteki
+ $usability = $this->getHeaderVariable('usability');
+ if($usability == null){
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ // Preverimo ce imamo testne podatke na novo -> potem moramo generirati datoteko na novo
+ private function checkTestData(){
+
+ // Preverimo ce prej nismo imeli testnih podatkov
+ $settings = $this->getHeaderVariable('_settings');
+ if($settings['hasTestData'] != 1 && $this->has_test_data > 0){
+ return true;
+ }
+
+ return false;
+ }
+
+ // Vrnemo text z info o datoteki
+ public function getDataFileInfo() {
+ global $admin_type, $lang;
+
+ $result = null;
+
+ if ($admin_type == '0') {
+
+ // Delamo inkremental
+ $inkremental_user_limit = '';
+ if ($this->file_status == FILE_STATUS_OLD) {
+ $inkremental_user_limit = " AND u.time_edit > FROM_UNIXTIME('".(int)$this->data_file_time."') ";
+ }
+
+ // Zbiramo samo ustrezne
+ $is_valid_user_limit = '';
+ if ((int)$this->collect_all_status == 0) {
+ $is_valid_user_limit = " AND u.last_status IN (5,6) ";
+ }
+
+ $qry_usr_cnt = sisplet_query("SELECT count(u.id)
+ FROM srv_user AS u
+ WHERE u.ank_id = '".$this->anketa."' AND u.preview='0' AND u.deleted='0' " . $is_valid_user_limit . $inkremental_user_limit);
+ list($user_cnt) = mysqli_fetch_row($qry_usr_cnt);
+
+ // Preverimo ce imamo izklopljeno belezenje parapodatka datum - potem moramo vedno generirati datoteko
+ $no_paradata_date = SurveySetting::getInstance()->getSurveyMiscSetting('survey_date');
+
+ $result = '&nbsp;&nbsp;<span class="leftSpace">';
+
+ if ($this->file_status == FILE_STATUS_NO_DATA) {
+ $result .= $lang['srv_dashboard_no_data'];
+ }
+ else if ($this->file_status == FILE_STATUS_NO_FILE) {
+ $result .= $lang['srv_dashboard_no_file'].$lang['srv_dashboard_new_units'].(int)$user_cnt;
+ }
+ else if ($this->file_status == FILE_STATUS_OLD && $no_paradata_date == 0) {
+ $result .= $lang['srv_dashboard_not_up_to_date'].'('.$this->last_update.')';
+ $result .= $lang['srv_dashboard_new_units'].(int) $user_cnt;
+ }
+ else if ($this->file_status == FILE_STATUS_OLD && $no_paradata_date == 1) {
+ $result .= $lang['srv_dashboard_up_to_date'].' ('.$this->last_update.')';
+ }
+ else if ($this->file_status == FILE_STATUS_OK) {
+ $result .= $lang['srv_dashboard_up_to_date'].' ('.$this->last_update.')';
+ }
+
+ $result .= '</span>';
+ }
+
+ return $result;
+ }
+
+ // Preverimo v bazi in nastavimo cas zadnjega respondenta
+ public function setLastResponseTime() {
+ global $admin_type, $lang;
+
+ // Zbiramo samo ustrezne
+ $is_valid_user_limit = '';
+ if ((int)$this->collect_all_status == 0) {
+ $is_valid_user_limit = " AND u.last_status IN (5,6) ";
+ }
+
+ // Polovimo datum zadnjega respondenta
+ $sql_usr_time = sisplet_query("SELECT max(UNIX_TIMESTAMP(GREATEST(u.time_insert,u.time_edit)))
+ FROM srv_user AS u
+ WHERE u.ank_id='".$this->anketa."' AND u.preview='0' AND u.deleted='0' ".$is_valid_user_limit."");
+ list($this->last_response_time) = mysqli_fetch_row($sql_usr_time);
+
+ // Ce ne belezimo parapodatka datum responsa moramo vedno generirati na novo - nastavimo, da je vedno zadnji response zdaj
+ $no_paradata_date = SurveySetting::getInstance()->getSurveyMiscSetting('survey_date');
+ if($no_paradata_date == 1)
+ $this->last_response_time = time();
+
+ return $this->last_response_time;
+ }
+
+
+ // Pripravimo datoteke s podatki
+ public function prepareFiles($show_loading=false) {
+ global $lang;
+
+ // File status ok, no data ali deleted survey - ne rabimo generirati ničesar
+ if(in_array($this->file_status, array(FILE_STATUS_OK, FILE_STATUS_NO_DATA, FILE_STATUS_SRV_DELETED))){
+ return $this->file_status;
+ }
+
+ // Ce imamo to vklopljeno in imamo vec kot 300 responsov prikazemo popup za loading in z ajaxem poklicemo generiranje
+ if($show_loading && $this->all_user_cnt > 300 && !isDebug()){
+
+ // Popup div z loading obvestilom
+ echo '<div id="collect_data_popup" class="divPopUp"><span class="faicon spinner fa-spin spaceRight"></span> '.$lang['srv_collectdata_in_progress'].' ('.$this->all_user_cnt.'). '.$lang['srv_collectdata_in_progress2'].'</div>';
+
+ echo '<script>
+ collectDataAjax();
+ </script>';
+
+ return $this->file_status;
+ }
+
+
+ // Najprej poskusimo zakleniti anekto za kreiranje
+ $lock = new ExclusiveLock( "survey_lock_".$this->anketa);
+ $locked_success = $lock->lock();
+
+ // Ce je nismo ustrezno zaklenili ne moremo poklicati generiranje datotek
+ if(!$locked_success){
+ return $this->file_status;
+ }
+
+
+ // Ce smo jo ustrezno zaklenili lahko poklicemo generiranje datotek
+ $collectData = new SurveyDataCollect($this->anketa);
+
+ // File status old - inkrementalno dodamo nove response
+ if($this->file_status == FILE_STATUS_OLD){
+ $sdc = new SurveyDataCollect($this->anketa);
+ $createdNewFile = (int)$sdc->updateFilesIncremental();
+ }
+ // Drugace generiramo vse na novo
+ else{
+ $sdc = new SurveyDataCollect($this->anketa);
+ $createdNewFile = (int)$sdc->createFiles();
+ }
+
+ // Na koncu se enkrat preverimo in nastavimo stanje datotek
+ $this->checkFile();
+
+ // Anketo odklenemo
+ $lock->unlock();
+
+ // Vrnemo zadnji status datotek
+ return $this->file_status;
+ }
+
+ // Popolnoma pobrisemo datoteke s podatki in ponastavimo vrednosti generiranja v bazi
+ public function clearFiles() {
+
+ // Najprej pobrisemo vse datoteke
+ $this->deleteFile();
+
+ // Pobrisemo vrstico za datoteke v bazi
+ $sql = sisplet_query("DELETE FROM srv_data_files WHERE sid='".$this->anketa."'");
+
+ // Pobrisemo lock ce ga imamo na datoteki
+ $key = 'survey_lock_'.$this->anketa;
+ $sqlUnlock = sisplet_query("DELETE FROM srv_lock WHERE lock_key='".$key."'");
+
+ // Na koncu ponastavimo statuse
+ $this->file_status = FILE_STATUS_NO_FILE;
+ $this->last_update = 0;
+ }
+
+ // Pobrisemo datoteke s podatki
+ public function deleteFile($filename=null) {
+ global $site_path;
+
+ // Nastavimo folder kjer se nahajajo datoteke
+ $folder = $site_path . EXPORT_FOLDER.'/';
+
+
+ // Brišemo specifično datoteko
+ if ($filename !== null && trim($filename) != '') {
+
+ if (file_exists($filename)) {
+ unlink($filename);
+ }
+ }
+ // Brisemo vse datoteke za doloceno anketo
+ else {
+
+ // Pobrišemo header datoteke
+ if (file_exists($folder . 'export_header_'.$this->anketa.'.dat')) {
+ unlink($folder . 'export_header_'.$this->anketa.'.dat');
+ }
+ // Pobrišemo data datoteko
+ if (file_exists($folder . 'export_data_'.$this->anketa.'.dat')) {
+ unlink($folder . 'export_data_'.$this->anketa.'.dat');
+ }
+
+ // Pobrišemo tmp file
+ if (file_exists($folder . 'export_data_'.$this->anketa.'.tmp')) {
+ unlink($folder . 'export_data_'.$this->anketa.'.tmp');
+ }
+ if (file_exists($folder . 'export_data_'.$this->anketa.'.dat_data1.tmp')) {
+ unlink($folder . 'export_data_'.$this->anketa.'.dat_data1.tmp');
+ }
+ if (file_exists($folder . 'export_data_'.$this->anketa.'.dat_data1_1.tmp')) {
+ unlink($folder . 'export_data_'.$this->anketa.'.dat_data1_1.tmp');
+ }
+
+ // Pobrisemo morebitne SN datoteke - header
+ $files = glob($folder.'export_sn_header_'.$this->anketa.'_*.dat');
+ if(count($files ) > 0) {
+ foreach ($files AS $file) {
+ unlink($file);
+ }
+ }
+ // Pobrisemo morebitne SN datoteke - data
+ $files = glob($folder.'export_sn_data_'.$this->anketa.'_*.dat');
+ if(count($files ) > 0) {
+ foreach ($files AS $file) {
+ unlink($file);
+ }
+ }
+ }
+ }
+
+
+ // Ajax klici
+ public function ajax() {
+
+ // Poklicemo generiranje datoteke s podatki
+ if($_GET['a'] == 'prepareFiles') {
+
+ $file_status = $this->prepareFiles($show_loading = false);
+
+ echo $file_status;
+ }
+ }
+}
+
diff --git a/admin/survey/classes/surveyData/class.SurveySNDataFile.php b/admin/survey/classes/surveyData/class.SurveySNDataFile.php
new file mode 100644
index 0000000..aba152b
--- /dev/null
+++ b/admin/survey/classes/surveyData/class.SurveySNDataFile.php
@@ -0,0 +1,641 @@
+<?php
+/**
+ * Created on Dec.2010
+ *
+ * @author: Gorazd Vesleič
+ *
+ * @desc: za kreacijo datoteke s podatki za SN (Alterji)
+ * Datoteko z alterji skreira iz obstoječe datoteke s podatki
+ *
+ * funkcije:
+ * - Init() - inicializacija
+ *
+ * CHANGELOG:
+ * - 9.12.2011
+ * Po novem bo potrebno ločit tabele za vsak SN loop. Zato se bo kreiralo tudi več datotek (koliko je pač glavnih loopov)
+ * Hkrati je potrebno navest za kateri krog atunučuja gre :)
+ * zato je na začetek dodana funkcija ki prešteje loope
+ */
+
+#KONSTANTE
+define(EXPORT_FOLDER, "admin/survey/SurveyData");
+DEFINE (STR_DLMT, "|");
+
+class SurveySNDataFile {
+
+ private $surveyId = null; # Id ankete
+ private $folder = null; # pot do datotek s podatki
+ private $_HEADERS = null; # Header podatki
+
+ private $headFileName = null; # pot do header fajla
+ private $dataFileName = null; # pot do data fajla
+ private $dataFileStatus = null; # status data datoteke
+ private $SDF = null; # class za inkrementalno dodajanje fajlov
+
+ private $sn_loop_parents = null; #glavni loopi
+ private $sn_loop_spremenljivke = null; # loopi po spremenljivkah
+ private $sn_loop_data = null; # ime loop variable, antonucci...
+ private $snCreateFullTable = true; # Ali prikazujemo celotno tabelo
+
+
+ private $_VARS = array();
+
+ function __construct ($sid) {
+ # nastavimo privzeto pot do folderjev
+ global $site_path, $global_user_id;
+
+ $this->surveyId = $sid;
+ $this->folder = $site_path . EXPORT_FOLDER.'/';
+
+ #inicializiramo class za datoteke
+ $this->SDF = SurveyDataFile::get_instance();
+ $this->SDF->init($sid);
+ $this->headFileName = $this->SDF->getHeaderFileName();
+ $this->dataFileName = $this->SDF->getDataFileName();
+ $this->dataFileStatus = $this->SDF->getStatus();
+
+ session_start();
+
+ $this->snCreateFullTable = $_SESSION['sid_'.$sid]['snCreateFullTable'];
+ if ( $this->dataFileStatus == FILE_STATUS_NO_DATA
+ || $this->dataFileStatus == FILE_STATUS_SRV_DELETED) {
+ Common::noDataAlert();
+ return false;
+ }
+ }
+
+ public function setVars($_VARS) {
+ $this->_VARS = $_VARS;
+ }
+ public function setParameter($parameter,$value) {
+ $this->{$parameter} = $value;
+ }
+ /** Preštejemo loope
+ *
+ */
+ function countLoops() {
+ if ($this->dataFileStatus >= 0 && $this->headFileName != '') {
+ $this -> _HEADERS = unserialize(file_get_contents($this->headFileName)) ;
+ # poiščemo skevence za vse variable loopa
+ #$_headers = $this -> _HEADERS;
+ $_headers = $this->getCleanHeader();
+
+ #preštejemo koliko loopov imamo
+ $this->sn_loop_parents = array();
+ $this->sn_loop_spremenljivke = array();
+
+ if (count($_headers) > 0) {
+ foreach ($_headers as $spr => $spremenljivka) {
+ if ($spremenljivka['loop_parent'] > 0) {
+ $this->sn_loop_data[$spremenljivka['loop_parent']]['antonucci'] = $spremenljivka['antonucci'];
+ $this->sn_loop_data[$spremenljivka['loop_parent']]['spr'] = $spr;
+ $this->sn_loop_data[$spremenljivka['loop_parent']]['variable'] = $spremenljivka['variable'];
+ $this->sn_loop_data[$spremenljivka['loop_parent']]['naslov'] = $spremenljivka['naslov'];
+ }
+ # spremenljivka je parent za loop, preštejemo variable
+ if (is_countable($spremenljivka['grids']) && count($spremenljivka['grids']) > 0) {
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach($grid['variables'] AS $vid => $variable) {
+ # če smo v loop parent
+ if ($spremenljivka['loop_parent'] > 0) {
+ $this->sn_loop_parents[$spremenljivka['loop_parent']][$variable['sequence']] = $variable['sequence'];
+
+ }
+ # če smo v loop spremenljivki
+ if ($spremenljivka['parent_loop_id'] > 0) {
+ $this->sn_loop_spremenljivke[$spremenljivka['parent_loop_id']][$spremenljivka['loop_id']][$variable['sequence']] = $variable['sequence'];
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /** Skreira datoteko z alterji iz obstoječe datoteke s podatki
+ *
+ */
+ function createSNDataFile($lpid, $sn_loop_parent,$_SN_head_file_name,$_sn_filename) {
+ if ($this->dataFileStatus >= 0 && $this->headFileName != '') {
+ # če kreiramo nove, pobrišemo morebitne obstoječe datoteke
+ $this->deleteOldSnFiles();
+
+
+ #popucamo headers
+ $_headers = $this->getCleanHeader();
+
+ $sn_loop_spremenljivke = $this->sn_loop_spremenljivke;
+
+ # resetiramo array za SN_HEADER
+ $_empty_name_filter = array();
+ $SN_HEADER = array();
+
+ $sequences = array(); # kam shranimo sequence
+ $loop_header_cnt = 0;
+
+ if (count($sn_loop_parent) > 0 ) {
+ foreach ($sn_loop_parent as $lsid => $loop_sequence) {
+ $loop_header_cnt ++;
+ $_new_sequence = 1;
+
+ # poiščemo variable loopa
+ if (isset($sn_loop_spremenljivke[$lpid]) && count($sn_loop_spremenljivke[$lpid]) > 0) {
+ $_loop_cnt = array_shift($sn_loop_spremenljivke[$lpid]);
+ } else {
+ $_loop_cnt = array();
+ }
+
+ $sequences[$lpid.'_'.$lsid] = array();
+
+ # Zloopamo skozi vse spremenljivke in dodamo v primerno skupino
+ if (count($_headers) > 0) {
+ foreach ($_headers as $spr => $spremenljivka) {
+
+ if ($loop_header_cnt === 1 ) {
+ $tmp_spremenljivka = $spremenljivka;
+ }
+ # odvisno ali smo v loopu ali ne dodamo primerne spremnljivke
+ if ((int)$spremenljivka['loop_parent'] > 0 || (int)$spremenljivka['parent_loop_id']) {
+ # ali smo v parent spremenljivki ali v loop spremenljivkah
+ if ((int)$spremenljivka['loop_parent'] > 0 && $lpid == (int)$spremenljivka['loop_parent']){
+
+ $_first_parent_variable = 0;
+
+ #smo v parent splemenljivki, dodamo samo variablo z primerno sekvenco
+ if (count($spremenljivka['grids']) > 0) {
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach($grid['variables'] AS $vid => $variable) {
+
+ if ($variable['sequence'] == $loop_sequence) {
+ #$sequences[$lpid.'_'.$lsid][$spr] = $variable['sequence'];
+ $sequences[$lpid.'_'.$lsid][] = $variable['sequence'];
+ # v sn imenih imamo samo 1 variablo
+ if ($loop_header_cnt === 1 && $_first_parent_variable === 0) {
+ $_empty_name_filter[] = '($'.$_new_sequence .' != -1 && $'.$_new_sequence .' != -2 && $'.$_new_sequence .' != -3 && $'.$_new_sequence .' != -4 && $'.$_new_sequence .' != -5)';
+ $tmp_spremenljivka['grids'][$gid]['variables'][$vid]['sequence'] = $_new_sequence;
+ $tmp_spremenljivka['sequences'] = $_new_sequence;
+ $tmp_spremenljivka['cnt_grids'] = 1;
+ $tmp_spremenljivka['cnt_all'] = 1;
+ $tmp_spremenljivka['grids']['0']['cnt_vars'] = 1;
+
+ $_new_sequence++;
+ $_first_parent_variable ++;
+
+ }
+ }
+ # odstranimo ostale variable
+ if ( $gid == 0 && $vid > 0) {
+ unset($tmp_spremenljivka['grids'][$gid]['variables'][$vid]);
+ } else if ( $gid > 0) {
+ unset($tmp_spremenljivka['grids'][$gid]);
+ }
+
+ }
+ }
+ }
+
+ }
+
+ # dodamo spremenljivko v nov header
+ if ($loop_header_cnt === 1) {
+ $SN_HEADER[$spr] = $tmp_spremenljivka;
+ }
+ }
+ # ali smo v spremenljivki v loopu
+ if ((int)$spremenljivka['parent_loop_id'] > 0) {
+ $add_this_spr = false;
+ $sequenceses = array();
+ # smo v loop spremenljivkah, dodamo variable s pravo frekvenco
+ if (count($spremenljivka['grids']) > 0) {
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach($grid['variables'] AS $vid => $variable) {
+ if (isset($_loop_cnt[$variable['sequence']])) {
+ $add_this_spr = true;
+ #$sequences[$lpid.'_'.$lsid][$spr] = $variable['sequence'];
+ $sequences[$lpid.'_'.$lsid][] = $variable['sequence'];
+ if ($loop_header_cnt === 1) {
+ $tmp_spremenljivka['grids'][$gid]['variables'][$vid]['sequence'] = $_new_sequence;
+ $sequenceses[] = $_new_sequence;
+ $_new_sequence++;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ # dodamo spremenljivko v nov header
+ if ($loop_header_cnt === 1 && $add_this_spr == true) {
+ $SN_HEADER[$spr] = $tmp_spremenljivka;
+ $SN_HEADER[$spr]['sequences'] = implode('_',$sequenceses);
+ }
+ }
+ } else {
+
+ # nismo v loopu
+ $sequenceses = array();
+ if (is_countable($spremenljivka['grids']) && count($spremenljivka['grids']) > 0) {
+ foreach($spremenljivka['grids'] AS $gid => $grid) {
+ if (count($grid['variables']) > 0) {
+ foreach($grid['variables'] AS $vid => $variable) {
+ #$sequences[$lpid.'_'.$lsid][$spr] = $variable['sequence'];
+ $sequences[$lpid.'_'.$lsid][] = $variable['sequence'];
+ if ($loop_header_cnt === 1) {
+ $tmp_spremenljivka['grids'][$gid]['variables'][$vid]['sequence'] = $_new_sequence;
+ $sequenceses[] = $_new_sequence;
+ $_new_sequence++;
+ }
+
+ }
+ }
+ }
+ }
+
+ # dodamo spremenljivko v nov header
+ if ($loop_header_cnt === 1) {
+ $SN_HEADER[$spr] = $tmp_spremenljivka;
+ $SN_HEADER[$spr]['sequences'] = implode('_',$sequenceses);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ # zapišemo header za SN datoteko
+ if (is_array($SN_HEADER) && count($SN_HEADER) > 0) {
+ #zapišemo SN header datoteko
+ file_put_contents($_SN_head_file_name, serialize($SN_HEADER));
+
+ }
+
+ # KREACIJA DATA DATOTEKE
+ # skreiramo fajle z potrebnimi skevencami
+ if (count($sequences) > 0) {
+ $_original_data_file = $this->dataFileName;
+ $_paste_files = '';
+
+ foreach ($sequences AS $skey => $sequence) {
+
+ if (is_array($sequence) && count($sequence)>0) {
+ $_sequence = implode(",",$sequence);
+
+ if (IS_WINDOWS) {
+ $cmdLn1 = 'cut -d "|" -f '.$_sequence.' '.$_original_data_file.' > '.$this->folder.'export_sn_data_'.$this->surveyId.'_'.$lpid.'_'.$skey.'.dat';
+ } else {
+ $cmdLn1 = 'cut -d \'|\' -f '.$_sequence.' '.$_original_data_file.' > '.$this->folder.'export_sn_data_'.$this->surveyId.'_'.$lpid.'_'.$skey.'.dat';
+ }
+ $out1 = shell_exec($cmdLn1);
+ $_paste_files .= $this->folder.'export_sn_data_'.$this->surveyId.'_'.$lpid.'_'.$skey.'.dat ';
+ }
+ }
+
+ # združimo datoteke v eno
+ $_orig_date = explode("_",$_original_data_file);
+ $_orig_date = explode(".",$_orig_date[3]);
+
+ #$_merged_file_name = $this->folder.'export_sn_data_'.$this->surveyId.'_'.$_orig_date[0].'.dat';
+ $_merged_file_name = $_sn_filename;
+ $tmp_merged_file_name = $this->folder.'tmp_export_sn_data_'.$this->surveyId.'_'.$lpid.'_'.$_orig_date[0].'.dat';
+ if (IS_WINDOWS) {
+ $cmdLn2 = 'paste -d "\n" '.$_paste_files .'> '.$tmp_merged_file_name;
+ }
+ else {
+ $cmdLn2 = 'paste -d \'\n\' '.$_paste_files. '>' .$tmp_merged_file_name;
+ }
+ $out2 = shell_exec($cmdLn2);
+
+ # pripravimo filtre, za data datoteko, da odstranimo zapise ki nimajo imen ( če je nekdo dodal samo 2 imena nekdo pa 5)
+ $_empty_name_filter = implode(' && ',$_empty_name_filter);
+
+ # sfiltriramo zapise ki nimajo imen
+ if (IS_WINDOWS) {
+ $cmdLn3 = 'awk -F"'.STR_DLMT.'" "BEGIN {OFS=\"\x7C\"} '.$_empty_name_filter.' { print $0 }" ' . $tmp_merged_file_name .' > ' . $_merged_file_name;
+ }
+ else {
+ $cmdLn3 = 'awk -F"'.STR_DLMT.'" \'BEGIN {OFS="\x7C"} '.$_empty_name_filter.' { print $0 }\' ' . $tmp_merged_file_name . ' > ' . $_merged_file_name;
+ }
+ $out3 = shell_exec($cmdLn3);
+
+ # pobrišemo odvečne datoteke
+ foreach (explode(" ",$_paste_files) as $filename_to_delete) {
+ if (trim($filename_to_delete) != '') {
+ $this->SDF->deleteFile($filename_to_delete);
+ }
+ }
+
+ if (trim($tmp_merged_file_name) != '') {
+ $this->SDF->deleteFile($tmp_merged_file_name);
+ }
+ }
+ }
+ }
+
+ function displayFullTableCheckbox() {
+ global $lang;
+ session_start();
+ echo '<label><input id="snCreateFullTable" name="snCreateFullTable" onclick="setSnDisplayFullTableCheckbox();" type="checkbox"'.($this->snCreateFullTable==true?' checked="checked"':'').'>Prikaži razširjeno tabelo</label>';
+ }
+
+
+ function outputSNDataFile() {
+ global $lang;
+ $this->countLoops();
+
+ # forsamo novo kreiranje! malo slaba rešitev - mogoče dodat enako kontrolao na zadnjega userja v SN fajlih
+ $this->deleteOldSnFiles();
+
+ $_original_head_file = $this->headFileName;
+ $_original_data_file = $this->dataFileName;
+
+ # timestam head datoteke
+ $_orig_date_h = explode("_",$_original_head_file);
+ $_orig_date_h = explode(".",$_orig_date_h[3]);
+ # združimo datoteke v eno
+ $_orig_date_d = explode("_",$_original_data_file);
+ $_orig_date_d = explode(".",$_orig_date_d[3]);
+
+
+ $this-> displayFullTableCheckbox();
+
+ # Tukaj začnemo loopat po glavnih loopih in nardimo ločene tabele za vsak loop
+
+ # zloopamo tolikokrat koliko imamo variabel za loop ( v loop_parent)
+ if (count($this->sn_loop_parents) > 0) {
+ foreach ($this->sn_loop_parents as $lpid => $sn_loop_parent) {
+
+ # head ime datoteke za loop
+ $_SN_head_file_name = $this->folder.'export_sn_header_'.$this->surveyId.'_'.$lpid.'_'.$_orig_date_h[0].'.dat';
+ # data ime datoteke za loop
+ $_sn_filename = $this->folder.'export_sn_data_'.$this->surveyId.'_'.$lpid.'_'.$_orig_date_d[0].'.dat';
+ # začasno ime datoteke za loop
+ $_sn_tmp1 = $this->folder.'tmp_1_export_sn_data_'.$this->surveyId.'_'.$lpid.'_'.$_orig_date_d[0].'.dat';
+ # če SN header in SN data datoteka obstaja
+ if (!file_exists($_SN_head_file_name) || !file_exists($_sn_filename)) {
+ $this->createSNDataFile($lpid, $sn_loop_parent,$_SN_head_file_name,$_sn_filename);
+ }
+
+ # če SN header in SN data datoteka obstaja
+ if (file_exists($_SN_head_file_name) && file_exists($_sn_filename)) {
+
+ # naložimo header
+ $SN_HEADER = unserialize(file_get_contents($_SN_head_file_name));
+ echo '<div id="tableContainer" class="tableContainer">';
+
+ echo '<h3>'.$lang['srv_loop_for_variable'].' <b>['. $this->sn_loop_data[$lpid]['variable']. '] - '. $this->sn_loop_data[$lpid]['naslov']. '</b> ('.$lang['srv_loop_antonucci_circle'].' '.$this->sn_loop_data[$lpid]['antonucci'].')</h3>';
+
+
+ // TABELA
+ echo '<table id="dataTable" border="0" cellpadding="0" cellspacing="0" width="100%" class="scrollTable no_wrap_td social_network">';
+
+
+ // COLGROUP - Nastavimo colgroup, da na njega vezemo vse sirine v tabeli, zaradi resizinga stolpcev
+ echo '<colgroup>';
+
+ $spr_cont = 0;
+ foreach ($SN_HEADER AS $spid => $spremenljivka) {
+
+ if ($spr_cont > 0 && $spid != 'uid' && count($spremenljivka['grids']) > 0) {
+
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ if (count ($grid['variables']) > 0) {
+
+ foreach ($grid['variables'] AS $vid => $variable ){
+ echo '<col>';
+ }
+ }
+ }
+ }
+ $spr_cont++;
+ }
+
+ echo '</colgroup>';
+
+
+ // THEAD
+ echo '<thead class="fixedHeader">';
+ echo '<tr>';
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach ($SN_HEADER AS $spid => $spremenljivka) {
+
+ if ($spr_cont > 0 && $spid != 'uid') {
+ echo '<th colspan="'.$spremenljivka['cnt_all'].'" title="'.$spremenljivka['naslov'].'">';
+ echo '<div class="headerCell">'.$spremenljivka['naslov'].'</div>';
+ echo '</th>';
+ }
+
+ $spr_cont++;
+ }
+
+ # nova vrstica
+ echo '</tr><tr>';
+
+ # dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach ($SN_HEADER AS $spid => $spremenljivka) {
+ if ($spr_cont > 0 && $spid != 'uid') {
+ if (count($spremenljivka['grids']) > 0) {
+
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+ echo '<th colspan="'.$grid['cnt_vars'].'" title="'.$grid['naslov'].'">';
+ echo '<div class="headerCell">'.$grid['naslov'].'</div>';
+ echo '</th>';
+ }
+ }
+ }
+
+ $spr_cont++;
+ }
+
+ # nova vrstica
+ echo '</tr><tr>';
+
+ ## dodamo skrit stolpec uid
+ echo '<th class="data_uid">&nbsp;</th>';
+
+ $spr_cont = 0;
+ foreach ($SN_HEADER AS $spid => $spremenljivka) {
+
+ if ($spr_cont > 0 && $spid != 'uid' && count($spremenljivka['grids']) > 0) {
+
+ foreach ($spremenljivka['grids'] AS $gid => $grid) {
+
+ if (count ($grid['variables']) > 0) {
+
+ foreach ($grid['variables'] AS $vid => $variable ){
+ echo '<th title="'.$variable['naslov'].($variable['other'] ? '&nbsp;(text)' : '').'">';
+ echo '<div class="dataCell">'.$variable['naslov'];
+
+ if ($variable['other'] == 1) {
+ echo '&nbsp;(text)';
+ }
+
+ echo '</div>';
+ echo '</th>';
+ }
+ }
+ }
+ }
+ $spr_cont++;
+ }
+ echo'</tr>';
+ echo '</thead>';
+
+
+ // TBODY - dodamo podatke
+ if (file_exists($_sn_filename)) {
+
+ // zamenjamo | z </td><td>
+ if (IS_WINDOWS) {
+ $cmdLn3 = 'sed "s*'.STR_DLMT.'*</td><td>*g" '.$_sn_filename.' > '.$_sn_tmp1;
+ } else {
+ $cmdLn3 = 'sed \'s*'.STR_DLMT.'*</td><td>*g\' '.$_sn_filename.' > '.$_sn_tmp1;
+ }
+ $out3 = shell_exec($cmdLn3);
+
+ echo '<tbody class="scrollContent">';
+
+ $file_handler = fopen ($_sn_tmp1, 'r');
+ while ($line = fgets ($file_handler)) {
+ echo '<tr>';
+ echo '<td class="data_uid">'.$line.'</td>';
+ echo '</tr>';
+ }
+
+ echo '</tbody>';
+
+ if ($file_handler) {
+ fclose($file_handler);
+ }
+
+ # pobrišemo tmp falj
+ if (trim($_sn_tmp1) != '') {
+ $this->SDF->deleteFile($_sn_tmp1);
+ }
+ }
+
+ echo '</table>';
+
+ echo '</div>';
+ }
+
+ }
+ }
+
+ }
+ /** Pobriše morebitne stare SN daoteke
+ *
+ */
+ function deleteOldSnFiles() {
+ if ($this->surveyId > 0) {
+
+ # odstranimo morebitne SN datoteke - header
+ $files = glob($this->folder.'export_sn_header_'.$this->surveyId.'_*.dat');
+ if(count($files ) > 0) {
+ foreach ($files AS $file) {
+ unlink($file);
+ }
+ }
+ # odstranimo morebitne SN datoteke - data
+ $files = glob($this->folder.'export_sn_data_'.$this->surveyId.'_*.dat');
+ if(count($files ) > 0) {
+ foreach ($files AS $file) {
+ unlink($file);
+ }
+ }
+
+ }
+ }
+
+ /* Tukaj pripravimo redosled in prikaz glavnih spremenljivk
+ *
+ */
+ function getCleanHeader() {
+ # poiščemo skevence za vse variable loopa
+ $header = $this -> _HEADERS;
+ $cleanHeader = array();
+ if (count($header) > 0) {
+ foreach ($header AS $spr_id => $spremenljivka) {
+
+ if ($this->_VARS[VAR_DATA] == '1') {
+ $add_data = true;
+ } else {
+ $add_data = false;
+ }
+
+ # preverimo ali delamo kompleksno tabelo al samo simpl
+ if ($this->snCreateFullTable == false) {
+ $add_data = $add_data && ((int)$spremenljivka['loop_parent'] > 0 || (int)$spremenljivka['parent_loop_id'] > 0);
+ }
+ if ( $spremenljivka['tip'] == 'm' || $spremenljivka['tip'] == 'sm') {
+ $add_data = false;
+ switch ($spremenljivka['variable']) {
+ case 'uid':
+ case 'recnum':
+ $add_data = true;
+ break;
+ case 'code':
+ # ce prikazujemo sistemske ne prikazujemo recnumber
+ if (!$this->_VARS[VAR_SHOW_SYSTEM] && $this->_VARS[VAR_META] && $this->_VARS[VAR_METAFULL]) {
+ $add_data = true;
+ }
+ break;
+ case 'status':
+ case 'lurker':
+ if ($this->_VARS[VAR_META] && $this->_VARS[VAR_METAFULL]) {
+ $add_data = true;
+ }
+ break;
+ case 'relevance':
+ if ($this->_VARS[VAR_RELEVANCE] && $this->canDisplayRelevance) {
+ $add_data = true;
+ }
+ break;
+ case 'invitation':
+ if ($this->_VARS[VAR_EMAIL]) {
+ $add_data = true;
+ }
+ break;
+ case 'testdata':
+ $header = $this->SDF->getHeader();
+ if (isset($header['testdata'])) {
+ $add_data = true;
+ }
+ break;
+ case 'smeta':
+ case 'meta':
+ if ($this->_VARS[VAR_METAFULL]) {
+ $add_data = true;
+ }
+ break;
+ case 'itime':
+ if ($this->showItime == true) {
+ $add_data = true;
+ }
+ break;
+ }
+ }
+ if ($spremenljivka['hide_system'] == '1') {
+ $add_data = false;
+ }
+ if ($add_data == true ) {
+ $cleanHeader[$spr_id] = $spremenljivka;
+ }
+ }
+ }
+ return $cleanHeader;
+ }
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyEmails/class.SurveyAlert.php b/admin/survey/classes/surveyEmails/class.SurveyAlert.php
new file mode 100644
index 0000000..d36e884
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/class.SurveyAlert.php
@@ -0,0 +1,569 @@
+<?php
+
+/*
+ * Created on 20.5.2009
+ *
+ */
+
+define("DEF_ALERT_IN_DAYS", 3); # koliko dni prez izteko aktivira alert avtomatsko
+
+class SurveyAlert
+{
+
+ static private $instance; // instanca razreda (razred kreiramo samo enkrat)
+ static private $userId = null; // user id
+ static private $surveyId = null; // id ankete
+ static private $data = array();
+
+ // konstrutor
+ protected function __construct() {}
+ // kloniranje
+ final private function __clone() {}
+
+ /** Poskrbimo za samo eno instanco razreda
+ *
+ */
+ static function getInstance()
+ {
+ if(!self::$instance)
+ {
+ self::$instance = new SurveyAlert();
+ }
+ return self::$instance;
+ }
+
+ /** Inicializacija
+ *
+ */
+ static function Init($sid, $uid) {
+ self::setSurveyId($sid);
+ self::setUserId($uid);
+
+ self::loadDataFromDB();
+ }
+ // GETTERS & SETTERS
+ static function getSurveyId() { return self::$surveyId; }
+ static function setSurveyId($sid) { self::$surveyId = $sid; }
+ static function getUserId() { return self::$userId; }
+ static function setUserId($uid) { self::$userId = $uid; }
+
+ /** Naloži podatke iz baze v klass
+ *
+ */
+ static function loadDataFromDB() {
+
+ // podatki obveščanja
+ $sqlA = sisplet_query("SELECT * FROM srv_alert WHERE ank_id = '".self::getSurveyId()."'");
+ $sqlD = sisplet_query("SELECT d.*, u.name, u.surname, u.email FROM srv_dostop AS d " .
+ "RIGHT JOIN (SELECT u.id, u.name, u.surname, u.email FROM users as u) AS u ON d.uid = u.id WHERE d.ank_id = '".self::getSurveyId()."'");
+ $rowA = mysqli_fetch_assoc($sqlA);
+
+ $result=array();
+
+ $ostala_sinhronizirana_polja = array('finish_respondent', 'finish_respondent_cms', 'finish_author', 'finish_other', 'finish_other_emails', 'finish_text', 'finish_subject', 'expire_days', 'expire_author', 'expire_other', 'expire_other_emails', 'expire_text', 'expire_subject', 'delete_author', 'delete_other', 'delete_other_emails', 'delete_text', 'delete_subject', 'active_author', 'active_other', 'active_other_emails', 'active_text0', 'active_subject0', 'active_text1', 'active_subject1');
+ foreach ($ostala_sinhronizirana_polja as $polje) {
+ $result[$polje] = $rowA[$polje];
+ }
+
+ // dodamo še podatke iz dostopa
+ while ($rowD = mysqli_fetch_assoc($sqlD)) {
+ $result['dostop'][] = $rowD;
+ }
+
+ // Še nekateri podatki ankete
+ $catch_expire_date = isset($result['expire_days']) && $result['expire_days'] != '0000-00-00' ? ", DATE_SUB(expire,INTERVAL ".$result['expire_days']." DAY) as alert_date" : "";
+ $sqlS = sisplet_query("SELECT active, naslov, insert_uid, expire ".$catch_expire_date." FROM srv_anketa WHERE id = '".self::getSurveyId()."'");
+
+ $rowS = mysqli_fetch_assoc($sqlS);
+ $result['expire'] = $rowS['expire'];
+ $result['survey_naslov'] = $rowS['naslov'];
+ $result['survey_active'] = $rowS['active'];
+ $result['author_uid'] = $rowS['insert_uid'];
+ $result['alert_date'] = $rowS['alert_date'];
+
+ self::$data = array();
+ self::$data = $result;
+
+ return $result;
+ }
+
+ /** prepareSendExpireAlerts()
+ * Funkcija v bazo surveycrontab (tabela: srv_alert) shrani podatke za pošiljanje emailov
+ * Pošiljanje emailov se izvjaja z razredom CronJobs ki
+ * se s pomočjo crontaba zaganja vsak dan samodejno.
+ */
+ static function prepareSendExpireAlerts() {
+ global $site_url, $lang, $mysql_database_name, $app_settings;
+
+ // napolnimo tabelo srv_alert v bazi surveycrontab
+ $sqlSurvey = sisplet_query("SELECT active FROM srv_anketa WHERE id='".self::getSurveyId()."'");
+ $rowSurvey = mysqli_fetch_assoc($sqlSurvey);
+
+ $oldDb = $mysql_database_name;
+
+ # ce je anketa aktivna, dodamo zapise v bazo, če je anketa neaktivna pa jih odstranimo
+ if ($rowSurvey['active'] == 1) {
+ #anketa je aktivna
+
+ // poiscemo e-maile od avtorja in userjev v dostopu
+ $emails = "";
+ $prefix = "";
+ if (self::$data['expire_author']) {
+ $sqlAuthor = sisplet_query("SELECT name, surname, id, email FROM users WHERE id='".self::$data['author_uid']."'");
+ $rowAuthor = mysqli_fetch_assoc($sqlAuthor);
+ if ($rowAuthor['email'] != "" ) {
+ $emails .= $prefix.$rowAuthor['email'];
+ $prefix = ",";
+ }
+ if (self::$data['dostop'])
+ foreach (self::$data['dostop'] as $user) {
+ if ($user['alert_expire'] == 1) {
+ $emails.=$prefix.$user['email'];
+ $prefix = ",";
+ }
+ }
+ }
+ if (self::$data['expire_other']) {
+ foreach (explode("\n",self::$data['expire_other_emails']) as $other) {
+ $emails.=$prefix.trim($other);
+ $prefix = ",";
+ }
+ }
+
+ // pripravimo vsebino e-maila
+ $pdf_url = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array('a'=>'pdf_results',
+ 'anketa'=>self::$surveyId,
+ 'usr_id'=>self::$data['author_uid'],
+ 'type'=>'0')));
+
+ $rtf_url = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'a'=>'rtf_results',
+ 'anketa'=>self::$surveyId,
+ 'b'=>'export',
+ 'usr_id'=>self::$data['author_uid'],
+ )));
+
+ // Custom podpis
+ $signature = Common::getEmailSignature();
+
+ $text = ( self::$data['expire_text'] != '' ) ? self::$data['expire_text'] : nl2br($lang['srv_alert_expire_text'].$signature);
+ $text = str_replace(
+ array(
+ '[SURVEY]',
+ '[DATE]',
+ '[SITE]',
+ '[DAYS]',
+ '[URL]',
+ '[PDF]',
+ '[RTF]',
+ '[DURATION]'),
+ array(
+ self::$data['survey_naslov'],
+ date('r'),
+ $site_url.'main/survey/index.php?anketa='.self::getSurveyId(),
+ self::$data['expire_days'],
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'">'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'</a>',
+ '<a href="'.$pdf_url.'">'.$pdf_url.'</a>',
+ '<a href="'.$rtf_url.'">'.$rtf_url.'</a>',
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'&amp;a=trajanje">'.$lang['srv_activate_duration'].'</a>')
+ , $text);
+
+ $subject = ( self::$data['expire_subject'] != '' ) ? self::$data['expire_subject'] : $lang['srv_alert_expire_subject'];
+ $subject = str_replace(
+ array(
+ '[SURVEY]',
+ '[DATE]',
+ '[SITE]',
+ '[DAYS]',
+ '[URL]',
+ '[PDF]',
+ '[RTF]',
+ '[DURATION]'),
+ array(
+ self::$data['survey_naslov'],
+ date('r'),
+ $site_url.'main/survey/index.php?anketa='.self::getSurveyId(),
+ self::$data['expire_days'],
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'">'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'</a>',
+ '<a href="'.$pdf_url.'">'.$pdf_url.'</a>',
+ '<a href="'.$rtf_url.'">'.$rtf_url.'</a>',
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'&amp;a=trajanje">'.$lang['srv_activate_duration'].'</a>')
+ ,$subject);
+
+ // pripravimo mail
+ Common::getInstance()->Init(self::getSurveyId());
+ $MailFrom = Common::getInstance()->getFromEmail();
+ $MailReply = Common::getInstance()->getReplyToEmail();
+ if ($emails != "" && $text != "" && $subject != "" && self::$data['alert_date'] != "") {
+
+ // izberemo bazo srvcrontab
+ $db = mysqli_select_db($GLOBALS['connect_db'],'surveycrontab');
+ //or die($lang['srv_alert_database_error']);
+
+ if ($db) {
+ # najprej pobrišemo stare vrendosti, ker se alerti niso spremenili ob trajni anketi
+ $del = sisplet_query("DELETE FROM srv_alert WHERE sid='".self::getSurveyId()."'");
+ // najprej preverimo ali imamo za obstojeco anketo se kaj v crontabu (status = 0) in popravimo na status = 2 (spremenjen)
+ // vsaka anketa lahko ima samo en zapis z statusom 0 (se ni slo v crontab)
+ #$sqlUpdateOld = sisplet_query("UPDATE srv_alert SET status = 2 WHERE dbname = '".$oldDb."' AND sid = '".self::getSurveyId()."' AND status = 0");
+
+ // dodamo zapis v crontab
+
+ # trajnih anket ne dodajamo
+ if (self::$data['expire'] != '2099-01-01') {
+ $sqlInsertString = "INSERT INTO srv_alert (dbname, sid, emails, text, subject, send_date, status, MailFrom, MailReply) " .
+ "VALUES ('".$oldDb."', '".self::getSurveyId()."', '".$emails."', '".$text."', '".$subject."', '".self::$data['alert_date']."', 0, '".$MailFrom."', '".$MailReply."')";
+ $sqlInsert = sisplet_query($sqlInsertString);
+ }
+ }
+
+ // uporabimo spet staro bazo
+ mysqli_select_db($GLOBALS['connect_db'],$oldDb);
+ }
+
+
+ } else {
+ # ankata je deaktivirana, vse alerte ki so še aktivni spremenimo v status 3
+ $db = mysqli_select_db($GLOBALS['connect_db'],'surveycrontab');
+
+ if ($db) {
+ // or die($lang['srv_alert_database_error']);
+ # nastavimo status na 3 - sprememba aktivnosti ankete
+ $sqlUpdateOld = sisplet_query("UPDATE srv_alert SET status = 3 WHERE dbname = '".$oldDb."' AND sid = '".self::getSurveyId()."' AND status = 0");
+ }
+
+ // uporabimo spet staro bazo
+ mysqli_select_db($GLOBALS['connect_db'],$oldDb);
+ }
+ sisplet_query("COMMIT");
+ }
+
+ /** sendMailActive()
+ * Funkcija pošlje emaile ob spremembi aktivnosti ankete
+ */
+ static function sendMailActive() {
+ global $lang, $site_url, $site_path, $app_settings;
+
+ // poiščemo vse email naslove
+ // poiscemo e-maile od avtorja in userjev v dostopu
+ $emails = array();
+ if (self::$data['active_author']) {
+ $sqlAuthor = sisplet_query("SELECT name, surname, id, email FROM users WHERE id='".self::$data['author_uid']."'");
+ $rowAuthor = mysqli_fetch_assoc($sqlAuthor);
+ if ($rowAuthor['email'] != "" ) {
+ $emails[] =$rowAuthor['email'];
+ }
+ foreach (self::$data['dostop'] as $user) {
+ if ($user['alert_active'] == 1) {
+ $emails[] = $user['email'];
+ }
+ }
+ }
+ if (self::$data['active_other']) {
+ foreach (explode("\n",self::$data['active_other_emails']) as $other) {
+ $emails[] = trim($other);
+ }
+ }
+
+ // Podpis
+ $signature = Common::getEmailSignature();
+
+ // odvisno od statuse izberemo text in subject
+ $text = ( self::$data['survey_active'] == 1 )
+ ? (( self::$data['active_text1'] != '' ) ? self::$data['active_text1'] : nl2br($lang['srv_alert_active_text1'].$signature))
+ : (( self::$data['active_text0'] != '' ) ? self::$data['active_text0'] : nl2br($lang['srv_alert_active_text0'].$signature));
+
+ $subject = ( self::$data['survey_active'] == 1 )
+ ? (( self::$data['active_subject1'] != '' ) ? self::$data['active_subject1'] : $lang['srv_alert_active_subject1'])
+ : (( self::$data['active_subject0'] != '' ) ? self::$data['active_subject0'] : $lang['srv_alert_active_subject0']);
+
+ $pdf_url = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array('a'=>'pdf_results',
+ 'anketa'=>self::$surveyId,
+ 'usr_id'=>self::$data['author_uid'],
+ 'type'=>'0')));
+
+ $rtf_url = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'a'=>'rtf_results',
+ 'anketa'=>self::$surveyId,
+ 'b'=>'export',
+ 'usr_id'=>self::$data['author_uid'],
+ )));
+ $text = str_replace(
+ array(
+ '[SURVEY]',
+ '[DATE]',
+ '[SITE]',
+ '[DAYS]',
+ '[URL]',
+ '[PDF]',
+ '[RTF]'),
+ array(
+ self::$data['survey_naslov'],
+ date('r'),
+ $site_url.'main/survey/index.php?anketa='.self::getSurveyId(),
+ self::$data['expire_days'],
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'">'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'</a>',
+ '<a href="'.$pdf_url.'">'.$pdf_url.'</a>',
+ '<a href="'.$rtf_url.'">'.$rtf_url.'</a>'),
+ $text);
+
+ $subject = str_replace(
+ array(
+ '[SURVEY]',
+ '[DATE]',
+ '[SITE]',
+ '[DAYS]',
+ '[URL]',
+ '[PDF]',
+ '[RTF]'),
+ array(
+ self::$data['survey_naslov'],
+ date('r'),
+ $site_url.'main/survey/index.php?anketa='.self::getSurveyId(),
+ self::$data['expire_days'],
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'">'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'</a>',
+ '<a href="'.$pdf_url.'">'.$pdf_url.'</a>',
+ '<a href="'.$rtf_url.'">'.$rtf_url.'</a>'),
+ $subject);
+
+
+ // preprečimo večkratno pošiljanje na iste naslove
+ array_unique($emails);
+ $spisek = "";
+ $send_success = $send_errors = array();
+
+
+ // posljemo maile
+ foreach ($emails AS $email) {
+ $email = trim($email);
+ if (strlen ($email) > 1 && strpos ($spisek, $email)===false || strlen ($spisek) == 0) {
+
+ try
+ {
+ $MA = new MailAdapter(self::getSurveyId(), $type='alert');
+ $MA->addRecipients($email);
+ $resultX = $MA->sendMail($text, $subject);
+ }
+ catch (Exception $e)
+ {
+ }
+
+ $spisek .= $email ."|";
+ if ($resultX) {
+ $send_success[] = $email;
+ } else {
+ $send_errors[] = $email;
+ }
+ }
+ }
+ }
+
+ /** sendMailDelete()
+ * Funkcija pošlje emaile ob izbrisu ankete
+ */
+ static function sendMailDelete() {
+ global $lang, $site_url, $site_path, $app_settings;
+
+ // poiščemo vse email naslove
+ // poiscemo e-maile od avtorja in userjev v dostopu
+ $emails = array();
+ if (self::$data['delete_author']) {
+ $sqlAuthor = sisplet_query("SELECT name, surname, id, email FROM users WHERE id='".self::$data['author_uid']."'");
+ $rowAuthor = mysqli_fetch_assoc($sqlAuthor);
+ if ($rowAuthor['email'] != "" ) {
+ $emails[] =$rowAuthor['email'];
+ }
+ foreach (self::$data['dostop'] as $user) {
+ if ($user['alert_delete'] == 1) {
+ $emails[] = $user['email'];
+ }
+ }
+ }
+ if (self::$data['delete_other']) {
+ foreach (explode("\n",self::$data['delete_other_emails']) as $other) {
+ $emails[] = trim($other);
+ }
+ }
+
+ // Custom podpis
+ $signature = Common::getEmailSignature();
+
+ // odvisno od statuse izberemo text in subject
+ $text = ( self::$data['delete_text'] != '' ) ? self::$data['delete_text'] : nl2br($lang['srv_alert_delete_text'].$signature);
+
+ $subject = ( self::$data['delete_subject'] != '' ) ? self::$data['delete_subject'] : $lang['srv_alert_delete_subject'];
+
+ $pdf_url = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array('a'=>'pdf_results',
+ 'anketa'=>self::$surveyId,
+ 'usr_id'=>self::$data['author_uid'],
+ 'type'=>'0')));
+
+ $rtf_url = $site_url.'admin/survey/izvoz.php?dc='.base64_encode(
+ serialize(
+ array( 'a'=>'rtf_results',
+ 'anketa'=>self::$surveyId,
+ 'b'=>'export',
+ 'usr_id'=>self::$data['author_uid']
+ )));
+
+ $text = str_replace(
+ array(
+ '[SURVEY]',
+ '[DATE]',
+ '[SITE]',
+ '[DAYS]',
+ '[URL]',
+ '[PDF]',
+ '[RTF]'),
+ array(
+ self::$data['survey_naslov'],
+ date('r'),
+ $site_url.'main/survey/index.php?anketa='.self::getSurveyId(),
+ self::$data['expire_days'],
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'">'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'</a>',
+ '<a href="'.$pdf_url.'">'.$pdf_url.'</a>',
+ '<a href="'.$rtf_url.'">'.$rtf_url.'</a>'),
+ $text);
+
+ $subject = str_replace(
+ array(
+ '[SURVEY]',
+ '[DATE]',
+ '[SITE]',
+ '[DAYS]',
+ '[URL]',
+ '[PDF]',
+ '[RTF]'),
+ array(
+ self::$data['survey_naslov'],
+ date('r'),
+ $site_url.'main/survey/index.php?anketa='.self::getSurveyId(),
+ self::$data['expire_days'],
+ '<a href="'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'">'.$site_url.'admin/survey/index.php?anketa='.self::getSurveyId().'</a>',
+ '<a href="'.$pdf_url.'">'.$pdf_url.'</a>',
+ '<a href="'.$rtf_url.'">'.$rtf_url.'</a>'),
+ $subject);
+
+ // preprečimo večkratno pošiljanje na iste naslove
+ array_unique($emails);
+ $spisek = "";
+ $send_success = $send_errors = array();
+
+ // posljemo maile
+ foreach ($emails AS $email) {
+ $email = trim($email);
+ if (strlen ($email) > 1 && strpos ($spisek, $email)===false || strlen ($spisek) == 0) {
+
+ try{
+ $MA = new MailAdapter(self::getSurveyId(), $type='alert');
+ $MA->addRecipients($email);
+ $resultX = $MA->sendMail($text, $subject);
+ }
+ catch (Exception $e)
+ {
+ }
+
+ $spisek .= $email ."|";
+
+ if ($resultX) {
+ $send_success[] = $email;
+ }
+ else {
+ $send_errors[] = $email;
+ }
+ }
+ }
+ }
+
+ static function setDefaultAlertBeforeExpire() {
+ global $lang, $site_url, $site_path, $app_settings;
+
+ $turn_on_alert = false;
+
+ # vseeno prvo preverimo ali ni zapisa za alert že v bazi
+ $sqlAlert = sisplet_query("SELECT * FROM srv_alert WHERE ank_id = '".self::getSurveyId()."'");
+ if (mysqli_num_rows($sqlAlert) > 0) {
+ # zapis je ze v bazi in ga zato ne popravljamo
+ $rowAlert = mysqli_fetch_array($sqlAlert);
+
+ if($rowAlert['expire_subject'] == '')
+ $turn_on_alert = true;
+ }
+ else{
+ $turn_on_alert = true;
+ }
+
+ if($turn_on_alert) {
+
+ // Custom podpis
+ $signature = Common::getEmailSignature();
+
+ # zapisa še ni v bazi, zato dodamo nov alert 3 dni pred koncem
+ $alert_expire_author = 1;
+ $alert_expire_other = 0;
+ $alert_expire_other_emails = '';
+ $alert_expire_text = nl2br($lang['srv_alert_expire_text'].$signature);
+ $alert_expire_subject = $lang['srv_alert_expire_subject'];
+
+ $mySqlInsert = sisplet_query("INSERT INTO srv_alert (ank_id, expire_days, expire_author, expire_other, expire_other_emails, expire_subject, expire_text) VALUES " .
+ "('".self::getSurveyId()."', '".DEF_ALERT_IN_DAYS."', '$alert_expire_author', '$alert_expire_other', '$alert_expire_other_emails', '$alert_expire_subject', '$alert_expire_text') " .
+ "ON DUPLICATE KEY UPDATE expire_days = '".DEF_ALERT_IN_DAYS."', expire_author = '$alert_expire_author', expire_other = '$alert_expire_other', expire_other_emails='$alert_expire_other_emails', expire_subject='$alert_expire_subject', expire_text='$alert_expire_text'");
+ if (!$mySqlInsert)
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ #osvežimo podatke
+ self::loadDataFromDB();
+ self::prepareSendExpireAlerts();
+
+ $sqlAlert = sisplet_query("SELECT * FROM srv_alert WHERE ank_id = '".self::getSurveyId()."'");
+
+ $rowAlert = mysqli_fetch_array($sqlAlert);
+
+ return $rowAlert;
+ }
+
+ // Nastavimo obvescanje pri aktivaciji (default ob kreiranju ankete)
+ static function setDefaultAlertActivation() {
+ global $lang;
+ global $global_user_id;
+ global $app_settings;
+
+ $anketa = self::getSurveyId();
+
+ $alert_active_author = 1;
+ $alert_active_other = 0;
+
+ // Custom podpis
+ $signature = Common::getEmailSignature();
+
+ $alert_active_subject0 = $lang['srv_alert_active_subject0'];
+ $alert_active_text0 = nl2br($lang['srv_alert_active_text0'].$signature);
+ $alert_active_subject1 = $lang['srv_alert_active_subject1'];
+ $alert_active_text1 = nl2br($lang['srv_alert_active_text1'].$signature);
+
+ $mySqlInsert = sisplet_query("INSERT INTO srv_alert (ank_id, active_author, active_other, active_other_emails, active_subject0, active_text0, active_subject1, active_text1) VALUES " .
+ "('$anketa', '$alert_active_author', '$alert_active_other', '$alert_active_other_emails', '$alert_active_subject0', '$alert_active_text0', '$alert_active_subject1', '$alert_active_text1') " .
+ "ON DUPLICATE KEY UPDATE active_author = '$alert_active_author', active_other = '$alert_active_other', active_other_emails='$alert_active_other_emails', active_subject0='$alert_active_subject0', active_text0='$alert_active_text0', active_subject1='$alert_active_subject1', active_text1='$alert_active_text1'");
+
+ if (!$mySqlInsert)
+ echo mysqli_error($GLOBALS['connect_db']);
+
+ // ponastavimo alert_admin
+ // najprej vse stare zapise postavimo na 0 nato pa setiramo na 1 kjer je potrebno
+ $mysqlUpdate = sisplet_query("UPDATE srv_dostop SET alert_active='0' WHERE ank_id = '$anketa'");
+ $sqlInsertUpdate = sisplet_query("INSERT INTO srv_dostop (ank_id, uid, alert_active) VALUES ('$anketa', '$global_user_id', 1) ON DUPLICATE KEY UPDATE alert_active=1");
+ if (!$sqlInsertUpdate)
+ echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+}
+?> \ No newline at end of file
diff --git a/admin/survey/classes/surveyEmails/class.SurveyInvitationsNew.php b/admin/survey/classes/surveyEmails/class.SurveyInvitationsNew.php
new file mode 100644
index 0000000..00ec13f
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/class.SurveyInvitationsNew.php
@@ -0,0 +1,10534 @@
+<?php
+# mysql_real_unescape_string
+/** Class ki skrbi za različna vabila
+ * Julij 2011
+ *
+ *
+ * Enter description here ...
+ * @author Gorazd_Veselic
+ *
+ */
+
+define('GROUP_PAGINATE', 4); # po kolko strani grupira pri paginaciji
+define('REC_ON_PAGE', 10); # kolko zapisov na stran pri urejanju respondentov
+define('REC_ON_SEND_PAGE', 20); # kolko zapisov na stran pri pošiljanju
+define('NOTIFY_INFO1KA', 5); # Nad koliko emaili obveščamo info@1ka.si
+
+set_time_limit(2400); # 30 minut
+
+class SurveyInvitationsNew {
+ private $sid;
+ private $count_all = 0; # koliko prejemnikov je v bazi
+ private $surveySettings; # zakeširamo nastavitve ankete
+ private $rec_send_page_limit = 20; # Koliko zapisov imamo za paginacijo
+
+ private $newTracking = false; # Ali imamo podroben tracking za anketo
+
+ private $inv_variables = array('email','password','ime','priimek','naziv','telefon','drugo','odnos');
+ private $inv_variables_link = array('email'=>'email','geslo'=>'password','ime'=>'firstname','priimek'=>'lastname','naziv'=>'salutation','telefon'=>'phone','drugo'=>'custom','odnos'=>'relation','last_status'=>'last_status','sent'=>'sent','responded'=>'responded','unsubscribed'=>'unsubscribed');
+ private $inv_variables_excel = array('email'=>'email','geslo'=>'password','ime'=>'firstname','priimek'=>'lastname','naziv'=>'salutation','telefon'=>'phone','drugo'=>'custom','odnos'=>'relation','last_status'=>'last_status','sent'=>'sent','responded'=>'responded','unsubscribed'=>'unsubscribed'
+ ,'date_inserted'=>'date_inserted','date_sent'=>'date_sent','date_responded'=>'date_responded','date_unsubscribed'=>'date_unsubscribed','list_name'=>'list_name');
+ private $inv_variables_tel_excel = array('status'=>'status','email'=>'email','geslo'=>'password','ime'=>'firstname','priimek'=>'lastname','naziv'=>'salutation','telefon'=>'phone','drugo'=>'custom','odnos'=>'relation','call_time'=>'call_time','last_status'=>'last_status'
+ ,'comment'=>'comment','date_inserted'=>'date_inserted','list_name'=>'list_name');
+
+ #private $inv_sys_db_map = array('email'=>'email','password'=>'geslo','firstname'=>'ime','lastname'=>'priimek','salutation'=>'naziv','phone'=>'telefon','custom'=>'drugo');
+
+ private $invitationAdvancedConditionId = 0;
+ private $user_inv_ids = array();
+
+ private $db_table = '';
+
+ function __construct($sid) {
+
+ $this->sid = $sid;
+
+ SurveyInfo::SurveyInit($this->sid);
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ $this->surveySettings = SurveyInfo::getInstance()->getSurveyRow();
+
+ # koliko respondentov je že v bazi
+ $sql_query_all = sisplet_query("SELECT count(*) FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0'");
+ $sql_row_all = mysqli_fetch_row($sql_query_all);
+ $this->count_all = (int)$sql_row_all[0];
+
+ # preverimo ali prikazujemo nov ali star način odvisno od nastavitve v misc
+ $sql_query = sisplet_query("SELECT count(*) FROM srv_anketa AS a WHERE id ='".$this->sid."' AND insert_time > (SELECT value FROM misc WHERE what = 'invitationTrackingStarted' LIMIT 1)");
+ list($newTracking) = mysqli_fetch_row($sql_query);
+ $this->newTracking = (int)$newTracking > 0 ? true : false;
+
+ SurveyDataSettingProfiles :: Init($this->sid);
+
+ if (isset($_SESSION['rec_on_send_page']) && (int)$_SESSION['rec_on_send_page'] > 0) {
+ $this->rec_send_page_limit = (int)$_SESSION['rec_on_send_page'];
+ } else {
+ $this->rec_send_page_limit = REC_ON_SEND_PAGE;
+ }
+
+ SurveySession::sessionStart($this->sid);
+ $this->invitationAdvancedConditionId = (int)SurveySession::get('invitationAdvancedConditionId');
+ }
+
+ function ajax() {
+
+ if (isset($_REQUEST['a']) && trim($_REQUEST['a']) != '') {
+ if (isset($_POST['recipients_list']) && $_POST['recipients_list'] != null) {
+ $_POST['recipients_list'] = mysql_real_unescape_string($_POST['recipients_list']);
+ }
+
+ if (isset($_POST['fields']) && $_POST['fields'] != null) {
+ $_POST['fields'] = mysql_real_unescape_string($_POST['fields']);
+ }
+
+ $this->action($_REQUEST['a']);
+ }
+ else {
+ echo 'Ajax error!';
+ return 'Ajax error!';
+ }
+ }
+
+ function action($action) {
+ global $lang;
+ global $site_url;
+ global $app_settings;
+ global $global_user_id;
+
+ $NoNavi = $_POST['noNavi'];
+
+ if ($action == 'inv_lists') {
+ #$NoNavi = true;
+ }
+ if ($action == 'view_archive') {
+ $NoNavi = true;
+ }
+
+ if ($NoNavi == false) {
+ echo '<div id="inv_top_navi">';
+ $this->displayNavigation();
+ echo '</div>';
+ }
+
+ // Warning za nastavitev streznika
+ $MA = new MailAdapter($this->sid, $type='invitation');
+ if(!$MA->is1KA()){
+
+ if($MA->isGoogle())
+ $mail_settings = $MA->getGoogleSettings();
+ else
+ $mail_settings = $MA->getSMTPSettings();
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $isEmail = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+ if( (empty($mail_settings) || $mail_settings['SMTPFrom'] == '' || $mail_settings['SMTPUsername'] == '')
+ && $userAccess->checkUserAccess($what='invitations')
+ && $isEmail ){
+
+ // Gorenje tega nima
+ if (!Common::checkModule('gorenje')){
+
+ // Pri ajax klicih nikoli tega ne izpišemo, ravno tako ne izpisujemo, ce imamo vklopljeno posiljanje brez emaila (navadna posta, sms)
+ $noEmailing = SurveySession::get('inv_noEmailing');
+ if($NoNavi == false && $noEmailing != 1){
+ echo '<div id="email_server_warning">';
+ echo '<span class="faicon warning icon-orange"></span> '.$lang['srv_invitation_server_warning'].'!';
+ if($action != 'inv_server')
+ echo '<span class="spaceLeft"><a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_settings">'.$lang['srv_usermailing_setting'].'</a></span>';
+ echo '</div>';
+ }
+ }
+ }
+ }
+
+ if ($action == M_INVITATIONS) {
+ $this->useRecipientsList();
+ }
+ else if ($action == 'add_recipients_view') {
+ $this->useRecipientsList();
+ }
+ else if ($action == 'add_recipients') {
+ $this->addRecipients();
+ }
+ else if ($action == 'view_recipients') {
+ $this->viewRecipients();
+ }
+ else if ($action == 'view_message') {
+ $this->viewMessage($_POST['mid']);
+ }
+ else if ($action == 'make_default') {
+ $this->makeDefaultMessage($_POST['mid']);
+ }
+ else if ($action == 'make_default_from_preview') {
+ $this->makeDefaultFromPreview($_POST['mid']);
+ }
+ else if ($action == 'save_message_simple') {
+ $this->save_message_simple();
+ }
+ else if ($action == 'save_message_simple_noEmail') {
+ $this->save_message_simple_noEmail();
+ }
+ else if ($action == 'send_message') {
+ $this->sendMessage($_POST['mid']);
+ }
+ else if ($action == 'view_archive') {
+ $this->viewAarchive($_POST['mid']);
+ }
+ else if ($action == 'view_send_recipients') {
+ if(isset($_POST['noMailing']) && $_POST['noMailing'] == '1')
+ $this->selectSendToNoEmailing();
+ else
+ $this->selectSendTo();
+ }
+ else if ($action == 'mailToSourceChange') {
+ $this->mailToSourceChange();
+ }
+ else if ($action == 'send_mail') {
+
+ // Posiljanje brez emailov (samo aktivacija prejemnikov)
+ if(isset($_GET['noemailing']) && $_GET['noemailing'] == '1'){
+ $this->sendMailNoEmailing();
+ }
+ // Klasicno posiljanje preko smtp-ja
+ else{
+ $this->sendMail();
+ }
+ }
+ else if ($action == 'upload_recipients') {
+ $this->uploadRecipients();
+ }
+ else if ($action == 'view_archive_recipients') {
+ $this->viewArchiveRecipients();
+ }
+ else if ($action == 'edit_archive_comment') {
+ $this->editArchiveComment();
+ }
+ else if ($action == 'delete_recipient_confirm') {
+ $this->deleteRecipientConfirm();
+ }
+ else if ($action == 'delete_recipient') {
+ $this->deleteRecipient();
+ }
+ else if ($action == 'delete_recipient_single') {
+ $this->deleteRecipientSingle();
+ }
+ else if ($action == 'delete_recipient_all') {
+ $this->deleteRecipientAll();
+ }
+ else if ($action == 'export_recipients') {
+ $this->exportRecipients();
+ }
+ else if ($action == 'export_recipients_all') {
+ $this->exportRecipients_all();
+ }
+ else if ($action == 'use_recipients_list') {
+ $this->useRecipientsList();
+ }
+ else if ($action == 'change_import_type') {
+ $this->changeImportType();
+ }
+ else if ($action == 'save_recipient_list') {
+ $this->saveRecipientList();
+ }
+ else if ($action == 'get_profile_name') {
+ echo "DEPRECATED!";
+ die();
+ $this->getProfileName();
+ }
+ else if ($action == 'list_get_name') {
+ $this->listGetName();
+ }
+ else if ($action == 'invListEdit') {
+ $this->invListEdit();
+ }
+ else if ($action == 'save_rec_profile') {
+ $this->saveRecProfile();
+ }
+ else if ($action == 'delete_rec_profile') {
+ $this->deleteRecProfile();
+ }
+ else if ($action == 'edit_rec_profile') {
+ $this->editRecProfile();
+ }
+ else if ($action == 'update_rec_profile') {
+ $this->updateRecProfile();
+ }
+ else if ($action == 'delete_msg_profile') {
+ $this->deleteMsgProfile();
+ }
+ else if ($action == 'message_rename') {
+ $this->messageRename();
+ }
+ else if ($action == 'show_message_rename') {
+ $this->showMessageRename();
+ }
+ else if ($action == 'edit_recipient') {
+ $this->editRecipient();
+ }
+ else if ($action == 'save_recipient') {
+ $this->saveRecipient();
+ }
+ else if ($action == 'set_recipient_filter') {
+ $this->setRecipientFilter();
+ }
+ else if ($action == 'only_this_survey') {
+ $this->onlyThisSurvey();
+ }
+ else if ($action == 'add_users_to_database') {
+ $this->add_users_to_database();
+ }
+ else if ($action == 'add_checked_users_to_database') {
+ $this->add_checked_users_to_database();
+ }
+ else if ($action == 'arch_save_comment') {
+ $this->saveArchiveComment();
+ }
+ else if ($action == 'edit_message_details') {
+ $this->editMessageDetails();
+ }
+ else if ($action == 'message_save_details') {
+ $this->messageSaveDetails();
+ }
+ else if ($action == 'message_save_forward') {
+ $this->messageSaveforward();
+ }
+ else if ($action == 'message_save_forward_noEmail') {
+ $this->messageSaveforwardNoEmail();
+ }
+ else if ($action == 'prepare_save_message') {
+ $this->prepareSaveMessage();
+ }
+ else if ($action == 'showRecipientTracking') {
+ $this->showRecipientTracking();
+ }
+ else if ($action == 'arch_show_recipients') {
+ $this->showArchiveRecipients();
+ }
+ else if ($action == 'arch_show_details') {
+ $this->showArchiveDetails();
+ }
+ else if ($action == 'arch_edit_details') {
+ $this->editArchiveDetails();
+ }
+ else if ($action == 'inv_status') {
+ $this->showInvitationStatus();
+ }
+ else if ($action == 'inv_lists') {
+ $this->showInvitationLists();
+ }
+ else if ($action == 'inv_list_save') {
+ $this->listSave();
+ }
+ else if ($action == 'invListSaveOld') {
+ $this->invListSaveOld();
+ }
+ else if ($action == 'invListEditSave') {
+ $this->invListEditSave();
+ }
+ else if ($action == 'editRecList') {
+
+ $doEdit = $_SESSION['inv_edit_rec_profile'][$this->sid] == 'true' ? true : false;
+
+ if ($doEdit) {
+ $this->showEditRecList();
+ }
+ else {
+ $this->showNoEditRecList();
+ }
+ }
+ else if ($action == 'deleteRecipientsList') {
+ $this->deleteRecipientsList();
+ }
+ else if($action == 'deleteRecipientsListMulti'){
+ $this->deleteRecipientsListMulti();
+ }
+ else if ($action == 'showInvitationListsNames') {
+ $this->showInvitationListsNames();
+ }
+ else if ($action == 'changeInvRecListEdit') {
+ $this->changeInvRecListEdit();
+ }
+ else if ($action == 'upload_list') {
+ $this->upload_list();
+ }
+ else if ($action == 'send_upload_list') {
+ $this->send_upload_list();
+ }
+ else if ($action == 'changePaginationLimit') {
+ $this->changePaginationLimit();
+ }
+ else if ($action == 'setSortField') {
+ $this->setSortField();
+ }
+ else if ($action == 'validateSysVarsMapping') {
+ $this->validateSysVarsMapping();
+ }
+ else if ($action == 'addSysVarsMapping') {
+ $this->addSysVarsMapping();
+ }
+ else if ($action == 'recipientsAddForward') {
+ $this->recipientsAddForward();
+ }
+ else if ($action == 'showAdvancedConditions') {
+ $this->showAdvancedConditions();
+ }
+ else if ($action == 'setAdvancedCondition') {
+ $this->setAdvancedCondition();
+ }
+ else if ($action == 'inv_server') {
+ $this->viewServerSettings();
+ }
+ else if ($action == 'inv_settings') {
+ $this->showInvitationSettings();
+ }
+ else if ($action == 'set_noEmailing') {
+ $this->setNoEmailing();
+ }
+ else if ($action == 'set_noEmailing_type') {
+ $this->setNoEmailingType();
+ }
+ else if ($action == 'showAAISmtpPopup') {
+ $this->showAAISmtpPopup();
+ }
+ else {
+ $sql = sisplet_query("SELECT EXISTS (SELECT 1 FROM srv_invitations_archive WHERE ank_id='".$this->sid."')");
+ $row = mysqli_fetch_array($sql);
+
+ // Ce imamo ze posiljanje je default stran "Pregled"
+ if($row[0] == 1)
+ $this->showInvitationStatus();
+ // Ce se nimamo nobenega posiljanja je default stran "Nastavitve"
+ else
+ $this->showInvitationSettings();
+ }
+ }
+
+ function addRecipients() {
+ global $lang,$global_user_id;
+ # dodamo uporabnike
+ $fields = $_POST['fields'];
+ $recipients_list = $this->getCleanString($_POST['recipients_list']);
+
+ $new_profile_id = (int)$_POST['pid'];
+
+ # če so bile spremembe v profilu ga shranimo kot novega
+ list($old_recipients_list,$old_fields) = $this->getRecipientsProfile((int)$_POST['pid']);
+ $old_recipients_list = $old_recipients_list != '' ? implode("\n", $old_recipients_list) : $old_recipients_list;
+ $new_recipients_list = str_replace("\n\r", "\n", $recipients_list);
+ $old_fields = implode(",", $old_fields);
+ $new_fields = implode(",", $fields);
+
+ if ($_POST['save_profile'] == 'true' && ($old_recipients_list !== $new_recipients_list || $old_fields !== $new_fields)) {
+
+ # shranjujemo v nov profil
+ $post_fields = str_replace('inv_field_','',implode(',',$_POST['fields']));
+ $post_recipients = $this->getCleanString($_POST['recipients_list']);
+
+ #zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ $new_name = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q)) {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles".
+ " (name,uid,fields,respondents,insert_time,comment, from_survey) ".
+ " VALUES ('$new_name', '$global_user_id', '$post_fields', '$post_recipients', NOW(), '', '".$this->sid."' )";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ echo 'Napaka!';
+ } else {
+ $new_profile_id = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+ sisplet_query("COMMIT");
+ }
+
+ #dodamo polja
+
+ $result = $this->addMassRecipients($recipients_list, $fields, $new_profile_id);
+
+
+ /*
+ # ni sprememb shranimo v sejo
+ $this->saveSessionRecipients($recipients_list, $fields, $profile_comment);
+ */
+ # prikažemo napake
+ $invalid_recipiens_array = $this->displayRecipentsErrors($result);
+
+ # po novem gremo na respondente
+ $this->viewRecipients();
+
+ return ;
+ }
+
+ function saveSessionRecipients($recipients_list, $fields, $profile_comment=null ) {
+ global $lang;
+ # polja
+ $field_list = (isset($_POST['field_list']) && trim($_POST['field_list']) != '') ? trim($_POST['field_list']) : 'email';
+
+
+ # shranimo v začasni profil
+ $new_recipients = str_replace("\n\r", "\n", $recipients_list);
+ $new_recipients = explode("\n",$new_recipients);
+
+ session_start();
+ if (is_array($_SESSION['inv_rec_profile'][$this->sid]['respondents'])) {
+ $old_recipients = str_replace("\n\r", "\n", $_SESSION['inv_rec_profile'][$this->sid]['respondents']);
+ $old_recipients = explode("\n",$old_recipients);
+ $new_recipients = array_unique(array_merge($old_recipients, $new_recipients));
+ }
+
+ if (is_array($new_recipients)) {
+ $recipients_list = implode("\n",$new_recipients);
+ } else {
+ $recipients_list = '';
+ }
+ $_SESSION['inv_rec_profile'][$this->sid] = array(
+ 'pid'=>-1,
+ 'name'=>$lang['srv_invitation_new_templist'],
+ 'fields'=>$field_list,
+ 'respondents'=>$recipients_list,
+ 'comment'=>$profile_comment
+ );
+ }
+
+ function changeImportType() {
+ $this->displayAddRecipientsView();
+ }
+
+ #prikažemo vmesnik za dodajanje respondentov
+ function addRecipientsView( $fields = array(), $recipients_list=null) {
+ global $lang;
+ global $site_url;
+
+ //echo '<h2>'.$lang['srv_inv_add_recipients_heading'].'</h2>';
+ $noEmailing = SurveySession::get('inv_noEmailing');
+
+ $row = $this->surveySettings;
+
+ echo '<h2 style="margin-left: 15px; color:#333 !important;">';
+ // Text s podatki o nastavitvah posiljanja
+ $settings_text = '<span class="bold spaceRight">'.$lang['srv_inv_message_type'].':</span>';
+
+ $individual = (int)$this->surveySettings['individual_invitation'];
+ if($individual == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($noEmailing == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($row['usercode_required'] == 0 && $individual != 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_0'];
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_0'].')</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_1'];
+
+ if($row['usercode_skip'] == 1 || $individual == 0){
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_2'].')</span>';
+ }
+ else{
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_1'].')</span>';
+ }
+ }
+
+ $settings_text .= '<span class="spaceLeft"> <a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_settings">'.$lang['edit4'].'</a></span>';
+
+ echo $settings_text;
+ echo '</h2>';
+
+
+ echo '<div id="srv_invitation_note">';
+ echo $lang['srv_invitation_num_respondents'].(int)$this->count_all;
+ echo '</div>';
+
+ echo '<div id="inv_import">';
+ $this->displayAddRecipientsView($fields, $recipients_list);
+ echo '</div>'; # id="inv_import"
+ }
+
+ function displayAddRecipientsView( $fields = array(), $recipients_list=null) {
+ global $lang, $site_path, $site_url;
+
+ $field_list = array();
+
+ # odvisno od tipa sporočil prikažemo različna polja
+ # Personalizirano e-poštno vabilo
+
+ // Ce ne posiljamo z emailom sta default polja ime in priimek
+ $noEmailing = SurveySession::get('inv_noEmailing');
+ if($noEmailing == 1){
+ $default_fields = array(
+ 'inv_field_email' => 0,
+ 'inv_field_firstname' => 1,
+ 'inv_field_lastname' => 1,
+ 'inv_field_password' => 0,
+ 'inv_field_salutation' => 0,
+ 'inv_field_phone' => 0,
+ 'inv_field_custom' => 0,
+ );
+ }
+ else{
+ $default_fields = array(
+ 'inv_field_email' => count($fields) == 0 ? 1 : 0,
+ 'inv_field_firstname' => 0,
+ 'inv_field_lastname' => 0,
+ 'inv_field_password' => 0,
+ 'inv_field_salutation' => 0,
+ 'inv_field_phone' => 0,
+ 'inv_field_custom' => 0,
+ );
+ }
+
+ // Ce imamo modul 360 imamo tudi odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ $default_fields['inv_field_relation'] = 0;
+ }
+
+ # skreiramo nov vrstni red polj
+ if (count($fields) > 0) {
+ foreach ($fields as $key=>$field) {
+ $field_list[$field] = 1;
+ if (isset($default_fields[$field])) {
+ unset($default_fields[$field]);
+ }
+ }
+ }
+
+ if (count($default_fields) > 0) {
+ foreach ($default_fields as $key =>$field) {
+ $field_list[$key] = $field;
+ unset($default_fields[$key]);
+ }
+ }
+ $import_type = isset($_POST['import_type']) ? (int)$_POST['import_type'] : 2;
+ session_start();
+ $checked = (isset($_SESSION['inv_rec_only_this_survey']) && (int)$_SESSION['inv_rec_only_this_survey'] == 1) ? '1' : '0';
+
+ # profili respondentov
+ echo '<div id="inv_recipients_profiles_holder">';
+ echo '<label><input name="inv_show_list_type" id="inv_show_list_type1" type="radio" value="0" onclick="recipientsProfileOnlyThisSurvey();"'.($checked == '0' ? ' checked="checked"':'').' autocomplete="off">'.$lang['srv_inv_list_edit_from_this_survey'].'</label><br/>';
+ echo '<label><input name="inv_show_list_type" id="inv_show_list_type2" type="radio" value="1" onclick="recipientsProfileOnlyThisSurvey();"'.($checked == '1' ? ' checked="checked"':'').' autocomplete="off">'.$lang['srv_inv_list_edit_from_all_surveys'].'</label><br/>';
+
+ echo '<span>'.$lang['srv_inv_recipient_select_list'].'</span><br/>';
+
+ $this->listRecipientsProfiles();
+ echo '</div>'; # id=inv_recipients_profiles_holder
+
+ echo '<div id="inv_import_list_container">';
+
+ $sqlSysMapping = sisplet_query("SELECT * FROM srv_invitations_mapping WHERE sid = '$this->sid'");
+ if (mysqli_num_rows($sqlSysMapping) > 0) {
+ $sysUserToAddQuery = sisplet_query("SELECT count(*) FROM srv_user where ank_id='".$this->sid."' AND inv_res_id IS NULL AND deleted='0'");
+ list($sysUserToAdd) = mysqli_fetch_row($sysUserToAddQuery);
+ }
+
+ echo '<span><input name="inv_import_type" id="inv_import_type2" type="radio" value="2" onclick="inv_change_import_type();"'.($import_type == 2 ? ' checked="checked"' : '').' autocomplete="off"><label for="inv_import_type2">'.$lang['srv_inv_recipiens_from_list'].'</label></span>';
+ echo '<span><input name="inv_import_type" id="inv_import_type1" type="radio" value="1" onclick="inv_change_import_type();"'.($import_type == 1 ? ' checked="checked"' : '').' autocomplete="off"><label for="inv_import_type1">'.$lang['srv_inv_recipiens_from_file'].'</label></span>';
+ echo '<span><input name="inv_import_type" id="inv_import_type3" type="radio" value="3" onclick="inv_change_import_type();"'.($import_type == 3 ? ' checked="checked"' : '').' autocomplete="off"><label for="inv_import_type3">'.$lang['srv_inv_recipiens_from_system']
+ .($sysUserToAdd > 0 ? ' ('.$sysUserToAdd.')' : '').'</label></span>';
+
+ echo Help::display('inv_recipiens_from_system');
+
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+
+ if ($import_type == 3) {
+ $this->createSystemVariablesMapping();
+ }
+ else {
+
+
+ # sporočilo za personalizirana e-vabila in respondente iz baze
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_field_note'].'</span>';
+
+ echo '<br >';
+
+ echo '<div id="inv_field_container">';
+
+ echo '<ul class="connectedSortable">';
+ $field_lang = array();
+ if (count($field_list ) > 0) {
+ foreach ($field_list AS $field => $checked) {
+
+ $is_selected = ($checked == 1 ) ? true : false;
+
+ # če je polje obkljukano
+ $css = $is_selected ? ' class="inv_field_enabled"' : '';
+
+ $label_for = ' for="'.$field.'_chk"';
+
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj') && $field == 'inv_field_relation')
+ echo '<br />';
+
+ echo '<li id="'.$field.'"'.$css.'>';
+ echo '<input id="'.$field.'_chk" type="checkbox" class="inv_checkbox' . $hidden_checkbox . '"'.($is_selected == true ? ' checked="checked"' : '').'>';
+ echo '<label'.$label_for.'>'.$lang['srv_'.$field].'</label>';
+ echo '</li>';
+
+ if ($is_selected == 1) {
+ $field_lang[] = $lang['srv_'.$field];
+ }
+ }
+ }
+ echo '</ul>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ echo '<script type="text/javascript">';
+ echo "$('ul.connectedSortable').sortable({update : function () { refreshFieldsList(); }, forcePlaceholderSize:'true', tolerance:'pointer', placeholder:'inv_field_placeholder', cancel:'#inv_field_relation'});";
+ echo '</script>';
+
+ # iz seznama
+ echo '<div id="inv_import_list"'.($import_type != 1 ? '' : ' class="hidden"').'>' ;
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_email_note'];
+ echo '<br class="clr" /><span class="inv_sample" >';
+ echo $lang['srv_inv_recipiens_sample'].'&nbsp;</span><span class="inv_sample">';
+ echo $lang['srv_inv_recipiens_sample1'];
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo '</span>';
+ echo '<br class="clr" />'.$lang['srv_inv_recipiens_fields'].' <span id="inv_field_list" class="inv_type_0">';
+ echo implode(',',$field_lang);
+ echo '</span>';
+
+ // Opozorilo za limit znakov pri passwordu (20)
+ echo '<span id="inv_field_list_warning" class="red" style="display:none;">';
+ echo '<br class="clr" /><br class="clr" />';
+ echo $lang['srv_inv_recipiens_pass_warning'];
+ echo '</span>';
+
+ echo '<br class="clr" /><br class="clr" />';
+
+ // delimiter
+ echo $lang['srv_inv_recipient_list_delimiter']
+ .'<label for="recipientsDelimiter1"><input id="recipientsDelimiter1" type="radio" ' .(!isset ($_POST['recipientsDelimiter']) || $_POST['recipientsDelimiter']==","?'checked="checked"':'') .' value="," name="recipientsDelimiter">' .$lang['srv_inv_recipient_delimiter_comma'] .' (,)</label>&nbsp;&nbsp;&nbsp;'
+ .'<label for="recipientsDelimiter4"><input id="recipientsDelimiter4" type="radio" ' .(isset ($_POST['recipientsDelimiter']) && $_POST['recipientsDelimiter']=="|~|"?'checked="checked"':'') .' value="|~|" name="recipientsDelimiter">' .$lang['srv_inv_recipient_delimiter_1KA'] .' (|~|)</label>&nbsp;&nbsp;&nbsp;'
+ .'<label for="recipientsDelimiter2"><input id="recipientsDelimiter2" type="radio" ' .(isset ($_POST['recipientsDelimiter']) && $_POST['recipientsDelimiter']==";"?'checked="checked"':'') .' value=";" name="recipientsDelimiter">' .$lang['srv_inv_recipient_delimiter_semicolon'] .' (;) </label>&nbsp;&nbsp;&nbsp;'
+ .'<label for="recipientsDelimiter3"><input id="recipientsDelimiter3" type="radio" ' .(isset ($_POST['recipientsDelimiter']) && $_POST['recipientsDelimiter']=="|"?'checked="checked"':'') .' value="|" name="recipientsDelimiter">' .$lang['srv_inv_recipient_delimiter_pipe'] .' (|)</label>&nbsp;&nbsp;&nbsp;';
+
+ echo '</span>';
+
+ echo '<br class="clr" /><br class="clr" />';
+
+ echo '<textarea id="inv_recipients_list" cols="50" rows="9" name="inv_recipients_list">';
+ if (is_array($recipients_list) && count($recipients_list) > 0 ) {
+ echo implode("\n",$recipients_list);
+ }
+ echo '</textarea>';
+
+ echo '<br class="clr"/>';
+
+
+ #podatki o profilu
+ echo '<br class="clr"/>';
+ $ppid = isset($_POST['pid']) ? (int)$_POST['pid'] : -1;
+
+ echo '<span class="floatLeft" style="min-width:200px;">';
+ if ((int)$ppid > 0) {
+ # polovimo podatke profila
+ $sql_string = "SELECT rp.*, u.name, u.surname FROM srv_invitations_recipients_profiles AS rp LEFT JOIN users AS u ON rp.uid = u.id WHERE rp.pid = '".(int)$ppid."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ $avtor = array();
+ if (trim($sql_row['name'])) {
+ $avtor[] = trim ($sql_row['name']);
+ }
+ if (trim($sql_row['surname'])) {
+ $avtor[] = trim ($sql_row['surname']);
+ }
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray">'.$lang['srv_inv_recipiens_list_created_by'].implode(' ',$avtor).'</div>';
+ }
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray" title="'.date("d.m.Y H:i:s",strtotime($sql_row['insert_time'])).'">'.$lang['srv_inv_recipiens_list_created_day'].date("d.m.Y",strtotime($sql_row['insert_time'])).'</div>';
+ }
+ echo '<div class="gray" title="'.$sql_row['comment'].'" style="max-width:202px;">'.$lang['srv_inv_recipiens_list_comment'].trim (strip_tags($sql_row['comment'])).'</div>';
+
+ } else {
+ echo '<div class="gray">'.$lang['srv_inv_recipiens_temporary_list'].'</div>';
+ }
+ echo '</span>';
+
+ echo '<div class="floatLeft spaceLeft">';
+
+ echo '<div>';
+ echo '<label class="spaceRight"><input type="checkbox" id="inv_recipients_add" value="1" checked="checked">'.$lang['srv_invitation_recipients_add_type4'].'</label>';
+ /*echo '<label class="spaceRight"><input type="checkbox" id="inv_recipients_rename_profile" onchange="invRenameRecipientsChange();">'.$lang['srv_inv_recipients_rename_list'].'</label>';
+ echo Help::display('srv_invitation_rename_profile');*/
+ #echo '&nbsp;';
+ #echo '<label class="spaceLeft"><input type="checkbox" id="inv_recipients_add_type2" value="2" >'.$lang['srv_invitation_recipients_add_type5'].'</label>';
+ echo '</div>';
+
+ echo '<div id="div_inv_recipients_rename_list_type" class="displayNone">';
+ $this->saveRecipientListName();
+ echo '</div>';
+
+ echo '</div>';
+
+ echo '<br />';
+
+ # če že imamo prejemnike v bazi ponudimo gumb naprej
+ echo '<span class="buttonwrapper floatRight spaceLeft spaceRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="invRecipientsForward(); return false;"><span>'.$lang['srv_invitation_forward'].'</span></a></span>';
+ echo '<br /><br />';
+
+ echo '</div>'; # id=inv_import_list
+
+ # iz datoteke
+ echo '<div id="inv_import_file"'.($import_type == 1 ? '' : ' class="hidden"').'>' ;
+ echo '<form id="inv_recipients_upload_form" name="resp_uploader" method="post" enctype="multipart/form-data" action="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=upload_recipients" autocomplete="off">';
+ echo '<input type="hidden" name="fields" id="inv_recipients_upoad_fields" value="'.implode(',',$fields).'" />';
+ echo '<input type="hidden" name="posted" value="1" />';
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_file_note_1'].'</span>';
+
+ echo '<br class="clr" />'.$lang['srv_inv_recipiens_fields'].' <span id="inv_field_list" class="inv_type_1">';
+ echo implode(',',$field_lang);
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo $lang['srv_mailing_upload_list'];
+ echo '<input type="file" name="recipientsFile" id="recipientsFile" size="42" >';
+ if (count($errors) > 0) {
+ echo '<br class="clr" />';
+ echo '<span class="inv_error_note">';
+ foreach($errors as $error) {
+ echo '* '.$error.'<br />';
+ }
+ echo '</span>';
+ }
+ echo '<br/><br/><label>'.$lang['srv_inv_recipient_import_file_delimiter'].'</label> <input type="radio" name="recipientsDelimiter" id="recipientsDelimiter1" value="," checked><label for="recipientsDelimiter1">'.$lang['srv_inv_recipient_delimiter_comma'].' (,)</label>';
+ echo ' <input type="radio" name="recipientsDelimiter" id="recipientsDelimiter2" value=";"><label for="recipientsDelimiter2">'.$lang['srv_inv_recipient_delimiter_semicolon'].' (;)</label>';
+ echo ' <input type="radio" name="recipientsDelimiter" id="recipientsDelimiter3" value="|"><label for="recipientsDelimiter3">'.$lang['srv_inv_recipient_delimiter_pipe'].' (|)</label>';
+ echo ' <input type="radio" name="recipientsDelimiter" id="recipientsDelimiter4" value="|~|"><label for="recipientsDelimiter4">'.$lang['srv_inv_recipient_delimiter_1KA'].' (|~|)</label>';
+ echo '</form>';
+ echo '<br class="clr" /><span class="inv_sample" >';
+ echo $lang['srv_inv_recipiens_sample'].'&nbsp;</span><span class="inv_sample">';
+ echo $lang['srv_inv_recipiens_sample1'];
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo '<br class="clr" />';
+ echo '<span id="inv_upload_recipients" class="buttonwrapper floatLeft spaceLeft" ><a class="ovalbutton ovalbutton_orange" ><span>'.$lang['srv_inv_btn_add_recipients_add'].'</span></a></span>';
+ echo '</div>'; # id=inv_import_file
+ }
+ echo '</div>'; # id=inv_import_list_container
+
+ echo '<br class="clr"/>';
+ }
+
+
+ /**
+ *
+ * Enter description here ...
+ * @param $_recipients - prejemniki vsak v svoji vrstici, ločeni z vejico
+ * @param $fields - array polij ki jih dodajamo
+ */
+ function addMassRecipients($_recipients = '', $fields = array(), $new_profile_id = null) {
+ global $global_user_id;
+
+ # vabila z e-maili naredimo tukaj, brez e-mailov pa s podebno funkcijo
+ if (in_array('inv_field_email',$fields)) {
+ # vabila z emaili
+ $inv_iid = $this->inv_iid;
+ # povezava imena polji iz forem, z imeni polji v bazi
+ $db_vs_form_array = array(
+ 'inv_field_email' => 'email',
+ 'inv_field_firstname' => 'firstname',
+ 'inv_field_lastname' => 'lastname',
+ 'inv_field_password' => 'password',
+ 'inv_field_cookie' => 'cookie',
+ 'inv_field_salutation' => 'salutation',
+ 'inv_field_phone' => 'phone',
+ 'inv_field_custom' => 'custom',
+ 'inv_field_relation' => 'relation',
+ );
+
+ #dodamo potrebna sistemska polja
+ $this->addSystemVariables($fields);
+
+ # dodamo ustrezne uporabnike, neustrezne izpišemo še enkrat da se lahko popravijo
+ $_recipients = str_replace("\n\r", "\n", $_recipients);
+ $recipients_list = explode("\n",$_recipients);
+ $num_recipients_list = count($recipients_list);
+
+ # katero polje je za e-mail
+ if (in_array('inv_field_email',$fields)) {
+ $user_email = true;
+ } else {
+ #za tip 0 - Personalizirano e-poštno vabilo kjer je polje e-mail obvezno
+ # dodamo polje email
+ $user_email = true;
+ $fields[] = 'inv_field_email';
+ }
+
+ # polje cookie mora bit zraven
+ if (!in_array('inv_field_cookie',$fields)) {
+ $fields[] = 'inv_field_cookie';
+ }
+
+ /* brez preverjanja unikatnosti
+ # polovimo že dodane prejemnike iz baze
+ $email_in_db = array();
+ $sql_string = "SELECT email FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0'";
+ $sql_query = sisplet_query($sql_string);
+
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $email_in_db[] = strtolower($sql_row['email']);
+ }
+ }
+ */
+
+ # katero polje je za password
+ if (in_array('inv_field_password',$fields)) {
+ $user_password = true;
+ } else {
+ $user_password = false;
+ # dodamo polje password
+ $fields[] = 'inv_field_password';
+ }
+
+ # polja za bazo
+ $db_fields = '';
+ foreach ($fields as $field) {
+ $db_fields .= ', '.$db_vs_form_array[$field];
+ }
+
+ # katera gesla (code) že imamo v bazi za to anketo
+ $password_in_db = array();
+ $sql_string = "SELECT password FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0'";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $password_in_db[$sql_row['password']] = $sql_row['password'];
+ }
+
+ $unsubscribed = array();
+ #polovimo prejemnike ki ne želijo prejemati obvestil
+ $sql_string = "SELECT email FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND unsubscribed = '1'";
+ $sql_query = sisplet_query($sql_string);
+ $unsubscribed = array();
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $unsubscribed[] = $sql_row['email'];
+ }
+ }
+
+ #polovimo prejemnike ki ne želijo prejemati obvestil i datoteje srv_survey_unsubscribed
+ $condition = (count($unsubscribed) > 0 ) ? " AND email NOT IN('".implode('\',\'',$unsubscribed)."')" : '';
+ $sql_string = "SELECT email FROM srv_survey_unsubscribe WHERE ank_id = '".$this->sid."'".$condition;
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $unsubscribed[] = $sql_row['email'];
+ }
+ }
+
+ #array z veljavnimi zapisi
+ $valid_recipiens_array = array();
+ # array z zapisi kjer so napake v geslih
+ $invalid_password_array = array();
+ #array z zapisi kjer so neveljavna gesla
+ $invalid_email_array = array();
+ #array z podvojenimi zapisi
+ $duplicate_email_array = array();
+ #aray z zapisi kjer so uporabniki izbrali da ne želijo prejemat e-mailov
+ $unsubscribed_recipiens_array = array();
+ if ( $num_recipients_list > 0 ) {
+ foreach ($recipients_list AS $recipient_line) {
+ $recipient_line = trim($recipient_line);
+ if ($recipient_line != null && $recipient_line != '') {
+
+
+ // interni delimiter in ne vejicaa!!!!
+ $line_array = explode('|~|',$recipient_line);
+
+ //$line_array = explode(',',$recipient_line);
+ # predpostavljamo da je vrstica vredu
+ $invalid_line = false;
+
+ #prilagodimo izbrana polja
+ $recipent_array = array();
+ $i = 0;
+ foreach ($fields AS $field) {
+ $recipent_array[$field] = $line_array[$i];
+ $i++;
+ }
+
+ # izvedemo validacijo posameznih polij
+
+ # najprej preverimo gesla, če niso uporabniško določena, jih dodelimo sami
+ if ( $invalid_line == false ) {
+ # če še ni bilo napake ( da ne podvajamo zapisov pri katerih je več napak)
+ if ($user_password == false) {
+ # gesla določamo avtomatsko, (ne bo problemov :] )
+
+ # Izberemo random hash, ki se ni v bazi
+ do {
+ list($code,$cookie) = $this->generateCode();
+ #} while (in_array($code,$password_in_db) && !is_numeric($code));
+ } while (in_array($code,$password_in_db)); # je bil problem kadar so same številke
+ # polje za geslo je na zadnjem mestu (smo ga dodali zgoraj)
+ $recipent_array['inv_field_password'] = $code;
+ $recipent_array['inv_field_cookie'] = $cookie;
+
+ # če je vse ok, geslo dodamo v seznam že uporabljenih
+ $password_in_db[$code] = $code;
+ } else {
+ # gesla je določil uporabnik, (dajmo ga malo preverit)
+ $user_password = trim($recipent_array['inv_field_password']);
+
+ # preverimo ali je geslo že v bazi
+ if ($user_password == null || $user_password == '' || in_array($user_password,$password_in_db)) {
+ $invalid_password_array[] = $recipient_line;
+ $invalid_line = true;
+ }
+
+ # če je vse ok, geslo dodamo v seznam že uporabljenih
+ if ($invalid_line == false) {
+ $password_in_db[$user_password] = $user_password;
+ #dodamo še piškotek
+ list($code,$cookie) = $this->generateCode();
+ $recipent_array['inv_field_cookie'] = $cookie;
+ }
+ }
+ }
+
+ # če imamo emaile naredimo validacijo, preverimo zavrnitve.. itd
+ if ($user_email == true && $invalid_line == false) {
+ # preberemo uporabniški email
+ $email_field = trim($recipent_array['inv_field_email']);
+
+ #ali je email veljaven
+ if (!$this->validEmail($email_field) && $invalid_line == false) {
+ $invalid_email_array[] = $recipient_line;
+ $invalid_line = true;
+ }
+
+ # ali je email podvojen
+ /* brez preverjanja unikatnosti
+ if (in_array(strtolower($email_field),$email_in_db) && $invalid_line == false) {
+ $duplicate_email_array[] = strtolower($recipient_line);
+ $invalid_line = true;
+ }
+ */
+
+ # ali uporabnik ne želi prejemati sporočil (opted out)
+ if (in_array($email_field,$unsubscribed) && $invalid_line == false) {
+ $unsubscribed_recipiens_array[] = $recipient_line;
+ $invalid_line = true;
+ }
+
+ # če je vse ok, email dodamo v seznam že uporabljenih
+ if ( $invalid_line == false) {
+ $email_in_db[] = strtolower($email_field);
+ }
+ }
+ # če je vse ok dodamo userja k veljavnim
+ if ( $invalid_line == false) {
+ $valid_recipiens_array[] = $recipent_array;
+ }
+ }
+ }
+ }
+
+ if ($new_profile_id == null) {
+ $list_id = (int)$_POST['pid'];
+ } else {
+ $list_id = $new_profile_id;
+ }
+
+ # pripravimo sql stavek za vstavljanje
+ if (count($valid_recipiens_array ) > 0) {
+ $sql_insert_start = "INSERT INTO srv_invitations_recipients (ank_id".$db_fields.",sent,responded,unsubscribed,deleted,date_inserted,inserted_uid,list_id) VALUES ";
+ $count = 0;
+
+ $sql_insert_array = array();
+ $cnt = 0;
+ $max_in_array = 1000; # po koliko respondentov dodajamo naenkeat
+ $array_loop = 0;
+ foreach ( $valid_recipiens_array AS $recipent_fields) {
+ $cnt++;
+ $sql_insert = "('".$this->sid."'";
+ foreach ($recipent_fields as $field) {
+ $sql_insert .= ", '" .str_replace (array('\\', "'"), array('', '&#39;'), $field) ."'";
+ }
+ $sql_insert .= ",'0','0','0','0',NOW(),'".$global_user_id."','".$list_id."')";
+ $sql_insert_array[$array_loop][] = $sql_insert;
+ if ($cnt >= $max_in_array) {
+ $array_loop++;
+ $cnt = 0;
+ }
+ }
+ $sql_insert_end = " ON DUPLICATE KEY UPDATE firstname=VALUES(firstname), lastname=VALUES(lastname), salutation=VALUES(salutation), phone=VALUES(phone), custom=VALUES(custom), relation=VALUES(relation), deleted='0', date_inserted=NOW()";
+
+ # v loopu dodamo posamezne respondente po skupinah (ker kadar je respondentov veliko mysql crkne)
+ if (count($sql_insert_array) > 0) {
+
+ foreach ($sql_insert_array AS $sub_insert_array) {
+ $query_insert = $sql_insert_start. implode(',',$sub_insert_array) .$sql_insert_end;
+ $sqlQuery = sisplet_query($query_insert);
+ $rows = mysqli_affected_rows($GLOBALS['connect_db']);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ sisplet_query("COMMIT");
+
+ }
+ }
+ return array( 'valid_recipiens' => $valid_recipiens_array,
+ 'invalid_password' => $invalid_password_array,
+ 'invalid_email' => $invalid_email_array,
+ 'duplicate_email' => $duplicate_email_array,
+ 'unsubscribed' => $unsubscribed_recipiens_array);
+ } else {
+ # vabila brez emailov
+ return $this->addMassRecipientsWithoutEmail($_recipients, $fields, $new_profile_id);
+ }
+ }
+
+
+ function addMassRecipientsWithoutEmail($_recipients='', $fields=array(), $new_profile_id=null) {
+ global $global_user_id;
+
+ $inv_iid = $this->inv_iid;
+
+ # povezava imena polji iz forem, z imeni polji v bazi
+ $db_vs_form_array = array(
+ 'inv_field_email' => 'email',
+ 'inv_field_firstname' => 'firstname',
+ 'inv_field_lastname' => 'lastname',
+ 'inv_field_password' => 'password',
+ 'inv_field_cookie' => 'cookie',
+ 'inv_field_salutation' => 'salutation',
+ 'inv_field_phone' => 'phone',
+ 'inv_field_custom' => 'custom',
+ 'inv_field_relation' => 'relation',
+ );
+
+ #dodamo potrebna sistemska polja
+ $this->addSystemVariables($fields);
+
+ # dodamo ustrezne uporabnike, neustrezne izpišemo še enkrat da se lahko popravijo
+ $_recipients = str_replace("\n\r", "\n", $_recipients);
+ $recipients_list = explode("\n",$_recipients);
+ $num_recipients_list = count($recipients_list);
+
+ # katero polje je za e-mail
+ if (in_array('inv_field_email',$fields)) {
+ $user_email = true;
+ } else {
+ }
+
+ # polje cookie mora bit zraven
+ if (!in_array('inv_field_cookie',$fields)) {
+ $fields[] = 'inv_field_cookie';
+ }
+
+ # polovimo že dodane prejemnike iz baze
+ $user_in_db = array();
+ $sql_string = "SELECT firstname,lastname,salutation,phone,custom,relation,password FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0'";
+ $sql_query = sisplet_query($sql_string);
+
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $user_in_db[] = $sql_row['firstname'].$sql_row['lastname'].$sql_row['salutation'].$sql_row['phone'].$sql_row['custom'].$sql_row['relation'].$sql_row['password'];
+ }
+ }
+ # katero polje je za password
+ if (in_array('inv_field_password',$fields)) {
+ $user_password = true;
+ } else {
+ $user_password = false;
+ # dodamo polje password
+ $fields[] = 'inv_field_password';
+ }
+
+ # polja za bazo
+ $db_fields = '';
+ foreach ($fields as $field) {
+ $db_fields .= ', '.$db_vs_form_array[$field];
+ }
+
+ # katera gesla (code) že imamo v bazi za to anketo
+ $password_in_db = array();
+ $sql_string = "SELECT password FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0'";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $password_in_db[$sql_row['password']] = $sql_row['password'];
+ }
+
+ $unsubscribed = array();
+ #polovimo prejemnike ki ne želijo prejemati obvestil
+ #
+ # $sql_string = "SELECT email FROM srv_invitations_recipients WHERE unsubscribed = '1'";
+ # $sql_query = sisplet_query($sql_string);
+ # $unsubscribed = array();
+ // if (mysqli_num_rows($sql_query) > 0 ) {
+ # while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ # $unsubscribed[] = $sql_row['email'];
+ # }
+ # }
+
+ #array z veljavnimi zapisi
+ $valid_recipiens_array = array();
+ # array z zapisi kjer so napake v geslih
+ $invalid_password_array = array();
+ #array z zapisi kjer so neveljavna gesla
+ $invalid_email_array = array();
+ #array z podvojenimi zapisi
+ $duplicate_email_array = array();
+ #aray z zapisi kjer so uporabniki izbrali da ne želijo prejemat e-mailov
+ $unsubscribed_recipiens_array = array();
+
+ if ( $num_recipients_list > 0 ) {
+ foreach ($recipients_list AS $recipient_line) {
+ $recipient_line = trim($recipient_line);
+ if ($recipient_line != null && $recipient_line != '') {
+
+ $line_array = explode('|~|',$recipient_line);
+ # predpostavljamo da je vrstica vredu
+ $invalid_line = false;
+
+ #prilagodimo izbrana polja
+ $recipent_array = array();
+ $i = 0;
+ foreach ($fields AS $field) {
+ $recipent_array[$field] = $line_array[$i];
+ $i++;
+ }
+
+ # izvedemo validacijo posameznih polij
+
+ # najprej preverimo gesla, če niso uporabniško določena, jih dodelimo sami
+ if ( $invalid_line == false ) {
+ # če še ni bilo napake ( da ne podvajamo zapisov pri katerih je več napak)
+ if ($user_password == false) {
+ # gesla določamo avtomatsko, (ne bo problemov :] )
+
+ # Izberemo random hash, ki se ni v bazi
+ do {
+ list($code,$cookie) = $this->generateCode();
+ } while (in_array($code,$password_in_db));
+ # polje za geslo je na zadnjem mestu (smo ga dodali zgoraj)
+ $recipent_array['inv_field_password'] = $code;
+ $recipent_array['inv_field_cookie'] = $cookie;
+
+ # če je vse ok, geslo dodamo v seznam že uporabljenih
+ $password_in_db[$code] = $code;
+
+ } else {
+ # gesla je določil uporabnik, (dajmo ga malo preverit)
+ $user_password = trim($recipent_array['inv_field_password']);
+
+ # preverimo ali je geslo že v bazi
+ if ($user_password == null || $user_password == '' || in_array($user_password,$password_in_db)) {
+ $invalid_password_array[] = $recipient_line;
+ $invalid_line = true;
+ }
+
+ # če je vse ok, geslo dodamo v seznam že uporabljenih
+ if ($invalid_line == false) {
+ $password_in_db[$user_password] = $user_password;
+ #dodamo še piškotek
+ list($code,$cookie) = $this->generateCode();
+ $recipent_array['inv_field_cookie'] = $cookie;
+ }
+ }
+ }
+ # če imamo emaile naredimo validacijo, preverimo zavrnitve.. itd
+ // if ($user_email == true && $invalid_line == false) {
+ if ($invalid_line == false) {
+ # # preberemo uporabniški email
+ $email_field = trim($recipent_array['inv_field_firstname'])
+ . trim($recipent_array['inv_field_lastname'])
+ . trim($recipent_array['inv_field_salutation'])
+ . trim($recipent_array['inv_field_phone'])
+ . trim($recipent_array['inv_field_custom'])
+ . trim($recipent_array['inv_field_relation'])
+ . trim($recipent_array['inv_field_password']);
+
+ #
+ # #ali je email veljaven
+ // if (!$this->validEmail($email_field) && $invalid_line == false) {
+ # $invalid_email_array[] = $recipient_line;
+ # $invalid_line = true;
+ # }
+
+ # ali je email podvojen
+ if (in_array(strtolower($email_field),$user_in_db) && $invalid_line == false) {
+ $duplicate_email_array[] = strtolower($recipient_line);
+ $invalid_line = true;
+ }
+
+ # ali uporabnik ne želi prejemati sporočil (opted out)
+ // if (in_array($email_field,$unsubscribed) && $invalid_line == false) {
+ # $unsubscribed_recipiens_array[] = $recipient_line;
+ # $invalid_line = true;
+ # }
+
+ # če je vse ok, email dodamo v seznam že uporabljenih
+ if ( $invalid_line == false) {
+ $user_in_db[] = $email_field;
+ }
+ }
+ # če je vse ok dodamo userja k veljavnim
+ if ( $invalid_line == false) {
+ $valid_recipiens_array[] = $recipent_array;
+ }
+
+ }
+ }
+ }
+
+ # pripravimo sql stavek za vstavljanje
+ if ($new_profile_id == null) {
+ $list_id = (int)$_POST['pid'];
+ }
+ else {
+ $list_id = $new_profile_id;
+ }
+
+ if (count($valid_recipiens_array ) > 0) {
+ $sql_insert_start = "INSERT INTO srv_invitations_recipients (ank_id".$db_fields.",sent,responded,unsubscribed,deleted,date_inserted,inserted_uid,list_id) VALUES ";
+ $count = 0;
+
+ $sql_insert_array = array();
+ $cnt = 0;
+ $max_in_array = 1000; # po koliko respondentov dodajamo naenkeat
+ $array_loop = 0;
+ foreach ( $valid_recipiens_array AS $recipent_fields) {
+ $cnt++;
+ $sql_insert = "('".$this->sid."'";
+ foreach ($recipent_fields as $field) {
+ $sql_insert .= ", '$field'";
+ }
+ $sql_insert .= ",'0','0','0','0',NOW(),'".$global_user_id."','".$list_id."')";
+ $sql_insert_array[$array_loop][] = $sql_insert;
+ if ($cnt >= $max_in_array) {
+ $array_loop++;
+ $cnt = 0;
+ }
+ }
+ $sql_insert_end = " ON DUPLICATE KEY UPDATE firstname=VALUES(firstname), lastname=VALUES(lastname), salutation=VALUES(salutation), phone=VALUES(phone), custom=VALUES(custom), relation=VALUES(relation), deleted='0', date_inserted=NOW()";
+
+ # v loopu dodamo posamezne respondente po skupinah (ker kadar je respondentov veliko mysql crkne)
+ if (count($sql_insert_array) > 0) {
+ foreach ($sql_insert_array AS $sub_insert_array) {
+ $query_insert = $sql_insert_start. implode(',',$sub_insert_array) .$sql_insert_end;
+ $sqlQuery = sisplet_query($query_insert);
+ $rows = mysqli_affected_rows($GLOBALS['connect_db']);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ sisplet_query("COMMIT");
+
+ }
+ }
+
+ return array( 'valid_recipiens' => $valid_recipiens_array,
+ 'invalid_password' => $invalid_password_array,
+ 'invalid_email' => $invalid_email_array,
+ 'duplicate_email' => $duplicate_email_array,
+ 'unsubscribed' => $unsubscribed_recipiens_array);
+ }
+
+ function generateCode() {
+
+ // Zgeneriramo cookie
+ $cookie = md5(mt_rand(1, mt_getrandmax()) . '@' . $_SERVER['REMOTE_ADDR']);
+
+ // Ce je prvi znak stevilka jo spremenimo v crko ker drugace vcasih izvoz v excel ne dela ok
+ $letters = array('a', 'b', 'c', 'd', 'e', 'f');
+ if(is_numeric(substr($cookie, 0, 1)))
+ $cookie = $letters[array_rand($letters)].substr($cookie, 1);
+
+ // Koda je prvi del cookija
+ $code = substr($cookie, 0, 6);
+
+ return array($code, $cookie);
+ }
+
+ #preglej prejemnike
+ function viewRecipients($errors = array(), $msgs = array()) {
+ global $lang, $site_url, $admin_type;
+
+ $noEmailing = SurveySession::get('inv_noEmailing');
+
+ $row = $this->surveySettings;
+
+ echo '<h2 style="margin-left: 15px; color:#333 !important;">';
+ // Text s podatki o nastavitvah posiljanja
+ $settings_text = '<span class="bold spaceRight">'.$lang['srv_inv_message_type'].':</span>';
+
+ $individual = (int)$this->surveySettings['individual_invitation'];
+ if($individual == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($noEmailing == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($row['usercode_required'] == 0 && $individual != 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_0'];
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_0'].')</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_1'];
+
+ if($row['usercode_skip'] == 1 || $individual == 0){
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_2'].')</span>';
+ }
+ else{
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_1'].')</span>';
+ }
+ }
+
+ $settings_text .= '<span class="spaceLeft"> <a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_settings">'.$lang['edit4'].'</a></span>';
+
+ echo $settings_text;
+ echo '</h2>';
+
+ #polovimo prejemnike ki ne želijo prejemati obvestil
+
+ # nastavimo filter
+ session_start();
+ $filter_duplicated = $_SESSION['inv_filter']['duplicated'];
+ $filter = $_SESSION['inv_filter']['value'];
+ if ($filter != '') {
+ $mysql_filter = " AND ("
+ . "i.email LIKE '%".$filter."%'"
+ . "OR i.firstname LIKE '%".$filter."%'"
+ . "OR i.lastname LIKE '%".$filter."%'"
+ . "OR i.password LIKE '%".$filter."%'"
+ . "OR i.salutation LIKE '%".$filter."%'"
+ . "OR i.phone LIKE '%".$filter."%'"
+ . "OR i.custom LIKE '%".$filter."%'"
+ . "OR i.relation LIKE '%".$filter."%'"
+ . ")";
+ }
+
+
+ if (isset($_SESSION['inv_filter_on']) && $_SESSION['inv_filter_on'] == true ) {
+
+ if (!isset($_SESSION['inv_filter']['send']) || (int)$_SESSION['inv_filter']['send'] == 0) {
+ $mysql_filter .= "";
+ } else if ($_SESSION['inv_filter']['send'] == 2) {
+ $mysql_filter .= " AND i.sent='1'";
+ } else if ($_SESSION['inv_filter']['send'] == 1) {
+ $mysql_filter .= " AND i.sent='0'";
+ }
+ if (!isset($_SESSION['inv_filter']['respondet']) || (int)$_SESSION['inv_filter']['respondet'] == 0) {
+ $mysql_filter .= "";
+ } else if ($_SESSION['inv_filter']['respondet'] == 2) {
+ $mysql_filter .= " AND i.responded='1'";
+ } else if ($_SESSION['inv_filter']['respondet'] == 1) {
+ $mysql_filter .= " AND i.responded='0'";
+ }
+ if (!isset($_SESSION['inv_filter']['unsubscribed']) || (int)$_SESSION['inv_filter']['unsubscribed'] == 0) {
+ $mysql_filter .= "";
+ } else if ($_SESSION['inv_filter']['unsubscribed'] == 2) {
+ $mysql_filter .= " AND i.unsubscribed='1'";
+ } else if ($_SESSION['inv_filter']['unsubscribed'] == 1) {
+ $mysql_filter .= " AND i.unsubscribed='0'";
+ }
+
+ if (!isset($_SESSION['inv_filter']['list']) || (int)$_SESSION['inv_filter']['list'] == -2) {
+ $mysql_filter .= "";
+ } else {
+ $mysql_filter .= " AND i.list_id='".(int)$_SESSION['inv_filter']['list']."'";
+ }
+
+ }
+ # preštejemo koliko imamo vseh respondentov in koliko jih je brez e-maila
+ $sql_query_all = sisplet_query("SELECT id FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0'");
+ $count_all = mysqli_num_rows($sql_query_all);
+
+ $sql_string_withot_email = "SELECT count(*) FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0' AND email IS NULL AND sent='0'";
+ $sql_query_without_email = sisplet_query($sql_string_withot_email);
+ $sql_row_without_email = mysqli_fetch_row($sql_query_without_email);
+ $count_without_email = $sql_row_without_email[0];
+
+
+ #koliko zapisov bi morali prikazovati
+ $sql_string_filterd_all = "SELECT i.* FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0'".$mysql_filter." ORDER BY i.id";
+ $sql_query_filterd_all = sisplet_query($sql_string_filterd_all);
+ $filtred_all = mysqli_num_rows($sql_query_filterd_all);
+
+
+ # Katera polja prikazujemo v seznamu prejemnikov
+ $default_fields = array(
+ 'sent' => 1,
+ 'email' => 1,
+ 'firstname' => 0,
+ 'lastname' => 0,
+ 'salutation' => 0,
+ 'phone' => 0,
+ 'custom' => 0,
+ );
+
+ // Volitve nimajo nekaterih polj
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ $default_fields['responded'] = 1;
+ $default_fields['unsubscribed'] = 1;
+ $default_fields['password'] = 1;
+ }
+
+ // Ce imamo modul 360 imamo tudi odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ $default_fields['relation'] = 0;
+ }
+
+ # pogledamo katera polja dejansko prikazujemo
+ $sql_select_fields = array();
+ while ($sql_row = mysqli_fetch_assoc($sql_query_filterd_all)) {
+ foreach ($default_fields AS $key => $value) {
+ # če polje še ni dodano in če ni prazno, ga dodamo
+ if ($fields[$key] == 0 && isset($sql_row[$key]) && trim($sql_row[$key]) != '') {
+ $fields[$key] = 1;
+ $sql_select_fields[] = 'i.'.$key;
+ }
+ }
+ }
+
+ // Dodamo še ostala polja
+ // Volitve nimajo nekaterih polj
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ $fields['last_status'] = 1;
+ $fields['date(date_expired)'] = 1;
+ }
+
+ $sql_select_fields[] = 'i.last_status';
+ $fields['date_inserted'] = 1;
+
+ $fields['inserted_uid'] = 1;
+ $sql_select_fields[] = 'i.inserted_uid';
+ $sql_select_fields[] = 'i.date_inserted';
+ $sql_select_fields[] = 'date(date_expired)';
+ $fields['list_id'] = 1;
+ $sql_select_fields[] = 'i.list_id';
+
+
+ #dodamo paginacijo in poiščemo zapise
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $limit_start = ($page*REC_ON_PAGE)-REC_ON_PAGE;
+
+ $sort_string = $this->getSortString();
+ $sql_string_duplicated = null;
+ if ($filter_duplicated == true)
+ {
+ $sql_string_duplicated = " JOIN(
+ SELECT email, COUNT( email ) AS email_duplicated
+ FROM srv_invitations_recipients
+ WHERE ank_id='".$this->sid."' AND deleted = '0'
+ GROUP BY email
+ HAVING email_duplicated >1
+ ) AS dup ON dup.email = i.email ";
+ }
+
+ $sql_string_filterd = "SELECT i.id,
+ ".implode(',',$sql_select_fields)."
+ FROM srv_invitations_recipients AS i
+ ".$sql_string_duplicated."
+ WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0'
+ ".$mysql_filter."
+ ".$sort_string."
+ LIMIT $limit_start,".REC_ON_PAGE;
+
+ #koliko zapisov bi morali prikazovati
+ # po potrebi upoštevamo filter pogojev
+ $this->user_inv_ids = array();
+ if ((int)$this->invitationAdvancedConditionId > 0) {
+ $this->user_inv_ids = $this->getConditionUserIds($this->invitationAdvancedConditionId);
+ if (isset($this->user_inv_ids) && is_array($this->user_inv_ids) && count($this->user_inv_ids) > 0 )
+ {
+
+ $sql_string_filterd = "SELECT i.id, ".implode(',',$sql_select_fields)." FROM srv_invitations_recipients AS i "
+ . $sql_string_duplicated
+ . " INNER JOIN srv_user AS su ON i.id = su.inv_res_id"
+ ." WHERE su.ank_id = '$this->sid' AND su.inv_res_id IS NOT NULL AND su.deleted = '0' AND su.id IN ('".(implode('\',\'',$this->user_inv_ids))."')"
+ ." AND i.ank_id = '".$this->sid."' AND i.deleted = '0'".$mysql_filter.' '.$sort_string." LIMIT $limit_start,".REC_ON_PAGE;
+ }
+ }
+
+ $sql_query_filterd = sisplet_query($sql_string_filterd);
+ # polovimo userje
+ $uids = array();
+ $sql_string_users = "SELECT DISTINCT i.inserted_uid FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0'".$mysql_filter." GROUP BY i.inserted_uid ORDER BY i.id";
+ $sql_query_users = sisplet_query($sql_string_users);
+ while ($row_users = mysqli_fetch_assoc($sql_query_users)) {
+ $uids[] = $row_users['inserted_uid'];
+ }
+
+
+ $users = array();
+ if (count($uids) > 0) {
+ $sql_string_users = "SELECT id, email FROM users WHERE id IN(".implode(',',$uids).")";
+ $sql_query_users = sisplet_query($sql_string_users);
+ while ($row_users = mysqli_fetch_assoc($sql_query_users)) {
+ $users[$row_users['id']] = array('email'=>$row_users['email']);
+ }
+ }
+
+ # polovimo sezname
+ $lids = array();
+ $sql_string_users = "SELECT i.list_id FROM srv_invitations_recipients AS i WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0'".$mysql_filter." GROUP BY i.list_id ORDER BY i.id";
+ $sql_query_users = sisplet_query($sql_string_users);
+ while ($row_users = mysqli_fetch_assoc($sql_query_users)) {
+ $lids[] = $row_users['list_id'];
+ }
+
+ #seznami
+ $lists = array();
+ $lists['-1'] = array('name'=>$lang['srv_invitation_new_templist']);
+ $lists['0'] = array('name'=>$lang['srv_invitation_new_templist_author']);
+
+ if (count($lids) > 0 ) {
+ $sql_string_lists = "SELECT * from srv_invitations_recipients_profiles WHERE pid IN(".implode(',',$lids).") ";
+ $sql_query_lists = sisplet_query($sql_string_lists);
+ while ($row_lists = mysqli_fetch_assoc($sql_query_lists)) {
+ $lists[$row_lists['pid']] = array('name'=>$row_lists['name']);
+ }
+ }
+
+ if (count($msgs) > 0) {
+ echo '<span class="inv_msg_note">';
+ foreach($msgs as $msg) {
+ echo '* '.$msg.'<br />';
+ }
+ echo '</span>';
+ }
+
+ if (count($errors) > 0) {
+ echo '<span class="inv_error_note">';
+ foreach($errors as $error) {
+ echo '* '.$error.'<br />';
+ }
+ echo '</span>';
+ }
+
+ if ($count_all > 0 ) {
+
+ # dodamo filtriranje
+
+ echo '<div id="inv_rec_filter">';
+ echo '<label>'.$lang['srv_invitation_recipients_filter'].'</label> <input id="inv_rec_filter_value" type="text" onchange="inv_filter_recipients(); return false;" value="'.$_SESSION['inv_filter']['value'].'">';
+
+ echo '&nbsp;&nbsp;&nbsp;<label><input id="inv_rec_filter_on" type="checkbox" onchange="inv_filter_recipients(); return false;"'.(isset($_SESSION['inv_filter_on']) && $_SESSION['inv_filter_on'] == true ? ' checked="true"' : '').'>';
+ echo $lang['srv_invitation_recipients_filter_advanced'].'</label>';
+
+ if (isset($_SESSION['inv_filter_on']) && $_SESSION['inv_filter_on'] == true ) {
+ echo '&nbsp;';
+ echo '&nbsp;';
+ echo '<label>'.$lang['srv_invitation_recipients_filter_sent'];
+ $selected = (int)(isset($_SESSION['inv_filter']['send']) ? (int)$_SESSION['inv_filter']['send'] : 0);
+ echo ' <select id="inv_rec_filter_send" onchange="inv_filter_recipients();">';
+ echo '<option value="0"'.((int)$selected == 0 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter0'].'</option>';
+ echo '<option value="1"'.((int)$selected == 1 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter1'].'</option>';
+ echo '<option value="2"'.((int)$selected == 2 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter2'].'</option>';
+ echo '</select></label>';
+
+ echo '&nbsp;';
+ echo '<label>'.$lang['srv_invitation_recipients_filter_answered'];
+ $selected = (int)(isset($_SESSION['inv_filter']['respondet']) ? (int)$_SESSION['inv_filter']['respondet'] : 0);
+ echo ' <select id="inv_rec_filter_respondet" onchange="inv_filter_recipients();">';
+ echo '<option value="0"'.((int)$selected == 0 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter0'].'</option>';
+ echo '<option value="1"'.((int)$selected == 1 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter1'].'</option>';
+ echo '<option value="2"'.((int)$selected == 2 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter2'].'</option>';
+ echo '</select></label>';
+
+ echo '&nbsp;';
+ echo '<label>'.$lang['srv_invitation_recipients_filter_unsubscribed'];
+ $selected = (int)(isset($_SESSION['inv_filter']['unsubscribed']) ? (int)$_SESSION['inv_filter']['unsubscribed'] : 0);
+ echo ' <select id="inv_rec_filter_unsubscribed" onchange="inv_filter_recipients();">';
+ echo '<option value="0"'.((int)$selected == 0 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter0'].'</option>';
+ echo '<option value="1"'.((int)$selected == 1 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter1'].'</option>';
+ echo '<option value="2"'.((int)$selected == 2 ? ' selected="selected"' : '').'>'.$lang['srv_invitation_filter2'].'</option>';
+ echo '</select></label>';
+
+ $this->listCondition();
+
+ $this->advancedCondition();
+ }
+
+
+ echo '</div>';
+
+
+ echo '<form id="frm_inv_rec_export" name="resp_uploader" method="post" autocomplete="off">';
+ echo '<input type="hidden" name="anketa" id="anketa" value="'.$this->sid.'">';
+ echo '<input type="hidden" name="noNavi" id="noNavi" value="true">';
+ echo '<br class="clr"/>';
+
+ if ($filter != '') {
+ echo '<span class="red strong">';
+ printf($lang['srv_inv_list_no_recipients_filter'],$filter);
+ #Podatki so filtrirani: "'.$filter.'"<br/>';
+ echo '</span>';
+ }
+
+ if ($count_all > 0 && mysqli_num_rows($sql_query_filterd) != $count_all ) {
+ echo '<div id="srv_invitation_note" class="floatLeft spaceRight">';
+ echo $lang['srv_invitation_num_respondents_filtred'].(int)mysqli_num_rows($sql_query_filterd);
+ echo '</div>';
+ } else {
+ echo '<div id="srv_invitation_note" class="floatLeft spaceRight">';
+ echo $lang['srv_invitation_num_respondents'].(int)$this->count_all;
+ echo '</div>';
+ }
+
+
+ # duplicated
+ echo '<label><input type="checkbox" id="inv_rec_filter_duplicates" onchange="inv_filter_recipients(); return false" '. ($filter_duplicated ?' checked="checked"':'') .'>' . $lang['srv_inv_recipient_show_only_duplicates'] .'</label><br class="clr"/>';
+
+ if (mysqli_num_rows($sql_query_filterd) > 0 && $count_all > 0) {
+
+ echo '<br class="clr"/>';
+
+ $this->displayPagination($filtred_all);
+
+ echo '<br class="clr"/>';
+
+
+ echo '<div style="display:inline-block; margin-right: 20px;">';
+
+ # če že imamo prejemnike v bazi več kot 20 ponudimo gumb naprej tudi zgoraj
+ if ($this->count_all > 20) {
+ echo '<span class="buttonwrapper floatRight spaceLeft" style="margin-bottom:10px;"><a class="ovalbutton ovalbutton_orange" href="'.$this->addUrl('view_message').'"><span>'.$lang['srv_invitation_forward'].'</span></a></span>';
+ }
+
+ // Izvoz vseh v excel
+ echo '<span class="floatLeft" style="line-height:45px; padding-left:10px;">';
+ echo '<a onclick="inv_recipients_form_action(\'export_all\');" href="#">';
+ echo '<span class="faicon xls" title="'.$lang['srv_invitation_recipients_export_all'].'" style="height:14px; width:16px;"></span>';
+ echo ' '.$lang['srv_invitation_recipients_export_all'];
+ echo '</a>';
+ echo '</span>';
+
+
+ echo '<table id="tbl_recipients_list">';
+
+ echo '<tr>';
+ # checkbox
+ echo '<th class="tbl_icon" colspan="'.($this->surveySettings['show_email']==1?'4':'3').'" >&nbsp;</th>';
+
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ if ($fkey == 'sent' || $fkey == 'responded' || $fkey == 'unsubscribed' ) {
+ #echo '<th class="anl_ac tbl_icon_'.$fkey.' inv_'.$fkey.'_1" title="'.$lang['srv_inv_recipients_'.$fkey].'">&nbsp;</th>';
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac pointer tbl_icon_'.$fkey.'" title="'.$lang['srv_inv_recipients_'.$fkey].'">'.$lang['srv_inv_recipients_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ } else if ($fkey == 'last_status' ) {
+ echo '<th'.$this->addSortField($fkey).' class="anl_ac pointer" title="'.$lang['srv_inv_recipients_'.$fkey].'">'.$lang['srv_inv_recipients_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ } else {
+ echo '<th'.$this->addSortField($fkey).' class="pointer" title="'.$lang['srv_inv_recipients_'.$fkey].'">'.$lang['srv_inv_recipients_'.$fkey].$this->addSortIcon($fkey).'</th>';
+ }
+ }
+ }
+ echo '</tr>';
+ while ($sql_row = mysqli_fetch_assoc($sql_query_filterd)) {
+
+ echo '<tr>';
+ # checkbox
+
+ echo '<td><input type="checkbox" name="inv_rids[]" value="'.$sql_row['id'].'"></td>';
+ #izbriši
+ #echo '<td class="tbl_inv_left"><span class="as_link rec_delete_confirm" inv_rid="'.$sql_row['id'].'">'.$lang['srv_inv_list_profiles_delete'].'</span></td>';
+ echo '<td class="tbl_inv_left"><span class="faicon delete_circle icon-orange_link" onclick="deleteRecipient_confirm(\''.$sql_row['id'].'\'); return false;" title="'.$lang['srv_inv_list_profiles_delete'].'"></span></td>';
+ #uredi
+ #echo '<td class="tbl_inv_left"><span class="as_link rec_edit" inv_rid="'.$sql_row['id'].'">'.$lang['srv_inv_list_profiles_edit'].'</span></td>';
+ echo '<td class="tbl_inv_left"><span class="faicon edit smaller icon-as_link" onclick="editRecipient(\''.$sql_row['id'].'\'); return false;" title="'.$lang['srv_inv_list_profiles_edit'].'"></span></td>';
+
+ // Skoci na urejanje odgovorov - ce imamo identifikatorje povezane s podatki
+ if($this->surveySettings['show_email'] == 1)
+ echo '<td class="tbl_inv_left"><span class="icon-grey_dark_link" onclick="window.open(\''.$site_url.'/main/survey/edit_anketa.php?anketa='.$this->sid.'&usr_id='.$sql_row['id'].'&code='.$sql_row['password'].'\', \'blank\')" title="'.$lang['srv_edit_data_row'].'"></span></td>';
+
+ foreach ($fields AS $fkey =>$field) {
+ if ($field == 1) {
+ switch ($fkey) {
+ case 'sent':
+ echo '<td class="anl_ac pointer" onclick="showRecipientTracking(\''.$sql_row['id'].'\'); return false;">';
+ echo '<span class="faicon '.((int)$sql_row['sent'] == 1 ? ('inv_sent_1') : 'inv_sent_0').' icon-as_link" title="'.((int)$sql_row['sent'] == 1 ? $lang['sent'] : $lang['not_sent']).'"></span>';
+ echo '</td>';
+ break;
+ case 'responded':
+ echo '<td class="anl_ac">';
+ echo '<span class="faicon '.((int)$sql_row['responded'] == 1 ? ('inv_responded_1') : 'inv_responded_0').' icon-orange"></span>';
+ echo '</td>';
+ break;
+ case 'unsubscribed':
+ echo '<td class="anl_ac ">';
+ echo '<span class="faicon '.((int)$sql_row['unsubscribed'] == 1 ? ('inv_unsubscribed_1') : 'inv_unsubscribed_0').'"></span>';
+ echo '</td>';
+ break;
+ case 'last_status':
+ echo '<td>('.$sql_row[$fkey].') - '.$lang['srv_userstatus_'.$sql_row[$fkey]].'</td>';
+ break;
+ case 'inserted_uid':
+ echo '<td>'.$users[$sql_row[$fkey]]['email'].'</td>';
+ break;
+ case 'email':
+ echo '<td>';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+ echo '</td>';
+ break;
+ case 'list_id':
+ echo '<td>';
+ if ((int)$sql_row[$fkey] > 0) {
+ if ($lists[$sql_row[$fkey]]['name'] != '') {
+ echo '<a href="#" onclick="$(\'#anketa_edit\').load(\'ajax.php?t=invitations&a=use_recipients_list\', {anketa:srv_meta_anketa_id, pid:'.(int)$sql_row[$fkey].' });">'.$lists[$sql_row[$fkey]]['name'].'</a>';
+ } else {
+ echo $lang['srv_inv_recipient_list_deleted'];
+ }
+ } else {
+ echo $lists[$sql_row[$fkey]]['name'];
+ }
+ echo '</td>';
+ break;
+ default:
+ echo '<td class="tbl_inv_left">';
+ if ($filter != '') {
+ echo $this->hightlight($sql_row[$fkey],$filter);
+ } else {
+ echo $sql_row[$fkey];
+ }
+
+ echo '</td>';
+ break;
+ }
+
+ }
+ }
+ echo '</tr>';
+ @ob_flush();
+ }
+ echo '</table>';
+
+ echo '<div id="inv_bottom_edit">';
+ echo '<span class="faicon arrow_up"></span> ';
+ echo '<span id="inv_switch_on"><a href="javascript:inv_selectAll(true);">'.$lang['srv_select_all'].'</a></span>';
+ echo '<span id="inv_switch_off" style="display:none;"><a href="javascript:inv_selectAll(false);">'.$lang['srv_deselect_all'].'</a></span>';
+ echo '&nbsp;&nbsp;<a href="#" onClick="inv_recipients_form_action(\'delete\');"><span class="faicon delete_circle icon-orange" title="'.$lang['srv_invitation_recipients_delete_selected'].'"></span>&nbsp;'.$lang['srv_invitation_recipients_delete_selected'].'</a>';
+ echo '&nbsp;&nbsp;<a href="#" onClick="inv_recipients_form_action(\'export\');"><span class="faicon xls delete" style="height:14px; width:16px;" title="'.$lang['srv_invitation_recipients_export_selected'].'"></span>&nbsp;'.$lang['srv_invitation_recipients_export_selected'].'</a>';
+ echo '&nbsp;&nbsp;<a href="#" onClick="inv_recipients_form_action(\'add\');">&nbsp;'.$lang['srv_invitation_recipients_activate3'].'</a>';
+
+ // Aktivira vse v seznamu (jih doda v podatke, kot da so poslani)
+ echo '<br /><span style="line-height:40px;"><a href="#" onclick="inv_add_rec_to_db(); return false;" target="_blank">'.$lang['srv_invitation_recipients_activate2'].'</a></span>';
+
+ echo '</div>';
+
+ # če že imamo prejemnike v bazi ponudimo gumb naprej
+ if ($count_all > 0) {
+ echo '<div class="buttonwrapper floatRight spaceLeft" style="margin-top:-30px;"><a class="ovalbutton ovalbutton_orange" href="'.$this->addUrl('view_message').'"><span>'.$lang['srv_invitation_forward'].'</span></a></div>';
+ echo '<br class="clr"/><br>';
+ }
+ echo '</div>';
+
+ } else {
+ echo $lang['srv_inv_list_no_recipients_filtred'].'<br class="clr">';
+ }
+ echo '</form>';
+ } else {
+ echo $lang['srv_inv_list_no_recipients'].'<br class="clr">';
+ }
+ }
+
+ function viewMessage($mid = null) {
+ global $lang, $global_user_id, $site_url;
+
+ $row = $this->surveySettings;
+
+
+ echo '<h2 style="margin-left: 15px; color:#333 !important;">';
+
+ // Text s podatki o nastavitvah posiljanja
+ $settings_text = '<span class="bold spaceRight">'.$lang['srv_inv_message_type'].':</span>';
+
+ $individual = (int)$this->surveySettings['individual_invitation'];
+ if($individual == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ $noEmailing = SurveySession::get('inv_noEmailing');
+ if($noEmailing == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($row['usercode_required'] == 0 && $individual != 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_0'];
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_0'].')</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_1'];
+
+ if($row['usercode_skip'] == 1 || $individual == 0){
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_2'].')</span>';
+ }
+ else{
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_1'].')</span>';
+ }
+ }
+
+ $settings_text .= '<span class="spaceLeft"> <a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_settings">'.$lang['edit4'].'</a></span>';
+
+ echo $settings_text;
+
+ //echo '<span style="padding-left:15px; padding-right:15px;"><input type="radio" name="inv_messages_noEmailing" id="inv_messages_noEmailing_1" '.($noEmailing == 0 ? ' checked="checked"' : '').' style="margin-bottom:4px;" onClick="noEmailingToggle(\'0\');" /> <label for="inv_messages_noEmailing_1">'.$lang['srv_inv_message_noemailing_0'].'</label></span>';
+ //echo '<span><input type="radio" name="inv_messages_noEmailing" id="inv_messages_noEmailing_2" '.($noEmailing == 1 ? ' checked="checked"' : '').' style="margin-bottom:4px;" onClick="noEmailingToggle(\'1\');" /> <label for="inv_messages_noEmailing_2">'.$lang['srv_inv_message_noemailing_1'].'</label></span>';
+
+ echo '</h2>';
+
+
+ // Ce posiljamo preko emaila
+ if($noEmailing != 1){
+ echo '<div id="inv_messages_holder">';
+
+ if ($this->checkDefaultMessage() == false) {
+ echo '<span class="inv_error_note">';
+ echo $lang['srv_invitation_note6'];
+ echo '</span>';
+ } else {
+ $sql_string = "SELECT id, naslov, subject_text, body_text, reply_to, isdefault, comment, url FROM srv_invitations_messages WHERE ank_id = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+ $array_messages = array();
+ while ( list($id, $naslov, $subject_text, $body_text, $reply_to ,$isdefault, $comment, $url) = mysqli_fetch_row($sql_query) ) {
+ $array_messages[$id] = array('id'=>$id, 'naslov' => $naslov, 'subject_text'=>$subject_text, 'body_text'=>$body_text, 'reply_to'=>$reply_to ,'isdefault'=>$isdefault, 'comment'=>$comment, 'url'=>$url);
+ if ($isdefault == '1') {
+ # če izbiramo profile in nismo postali še nobenga
+ if ( $mid == null ) {
+ $mid = $id;
+ }
+ }
+ }
+ $preview_message = $array_messages[$mid];
+
+ echo '<div id="inv_messages_profiles_holder" class="floatLeft">';
+ echo '<span>'.$lang['srv_invitation_message_choose'].':</span><br/>';
+ echo '<div id="invitation_messages" >';
+ echo '<ol>';
+ foreach ($array_messages AS $_m => $message) {
+ echo '<li mid="'.$message['id'].'" class="'
+ .($message['id'] == $mid ? ' active' : '')
+ .'" onclick="invChangeMessage(\''.$message['id'].'\')">';
+ echo $message['naslov'];
+ echo '</li>';
+ }
+ echo '</ol>';
+ echo '</div>'; #invitation_messages
+ echo '<br class="clr" />';
+ if (count($array_messages) > 1) {
+ echo '<span class="as_link" id="inv_del_msg_profile" onclick="invMessageDelete();" title="'.$lang['srv_inv_message_delete_profile'].'">'.$lang['srv_inv_message_delete_profile'].'</span><br/>';
+ }
+ echo '<span class="as_link" id="inv_ren_msg_profile" onclick="invShowMessageRename();" title="'.$lang['srv_inv_message_rename_profile'].'">'.$lang['srv_inv_message_rename_profile'].'</span>';
+ {
+ # polovimo podatke profila
+ $sql_string = "SELECT sim.*, u.name, u.surname, e.name as ename, e.surname as esurname FROM srv_invitations_messages AS sim LEFT JOIN users AS u ON sim.uid = u.id LEFT JOIN users AS e ON sim.edit_uid = e.id WHERE sim.id = '".(int)$mid."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ $avtor = array();
+ $edit = array();
+ if (trim($sql_row['name'])) {
+ $avtor[] = trim ($sql_row['name']);
+ }
+ if (trim($sql_row['surname'])) {
+ $avtor[] = trim ($sql_row['surname']);
+ }
+
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray">'.$lang['srv_invitation_author'].' '.implode(' ',$avtor).'</div>';
+ }
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray" title="'.date("d.m.Y H:i:s",strtotime($sql_row['insert_time'])).'">'.$lang['srv_invitation_author_day'].' '.date("d.m.Y",strtotime($sql_row['insert_time'])).'</div>';
+ }
+ if (trim($sql_row['ename'])) {
+ $edit[] = trim ($sql_row['ename']);
+ }
+ if (trim($sql_row['esurname'])) {
+ $edit[] = trim ($sql_row['esurname']);
+ }
+
+ if ( count($edit) > 0 && $edit != $avtor) {
+ echo '<div class="gray">'.$lang['srv_invitation_changed'].' '.implode(' ',$edit).'</div>';
+ }
+ if ($sql_row['insert_time'] != $sql_row['edit_time']) {
+ echo '<div class="gray" title="'.date("d.m.Y H:i:s",strtotime($sql_row['edit_time'])).'">'.$lang['srv_invitation_changed_day'].' '.date("d.m.Y",strtotime($sql_row['insert_time'])).'</div>';
+ }
+
+ echo '<div class="gray" style="max-width:202px">'.$lang['srv_invitation_comment'].' '. trim ($sql_row['comment']).'</div>';
+ }
+
+ echo '</div>'; #inv_messages_profiles_holder
+
+ $MA = new MailAdapter($this->sid, $type='invitation');
+ # zlistamo seznam vseh sporočil
+ # izpišemo primer besedila
+ echo '<div id="inv_msg_preview_hld" class="floatLeft">';
+ echo '<span class="h2 spaceRight floatLeft">'.$lang['srv_inv_message_draft_content_heading'].'</span> '.Help::display('srv_inv_message_title');
+
+ //echo '<span class="spaceRight floatRight"><a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_server&show_back=true">'.$lang['srv_inv_message_draft_settings'].'</a></span>';
+ echo '<br class="clr"/>';
+ echo '<div id="inv_error_note" class="hidden"></div>';
+ echo '<div id="inv_msg_preview">';
+ echo '<table>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_from'].':</th>';
+ echo '<td class="inv_bt">';
+ if($MA->getMailFrom() == '')
+ echo '<a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_settings">'.$lang['srv_usermailing_setting'].'</a>';
+ else
+ echo $MA->getMailFrom();
+ echo '<input type="hidden" id="inv_message_replyto" value="'.$MA->getMailFrom().'" autocomplete="off" readonly>';
+ echo '</td></tr>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_reply'].':</th>';
+ echo '<td class="inv_bt">';
+ echo $MA->getMailReplyTo();
+ echo '<input type="hidden" id="inv_message_replyto" value="'.$MA->getMailReplyTo().'" autocomplete="off" readonly>';
+ echo '</td></tr>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_subject'].':</th>';
+ echo '<td class="inv_bt">';
+ echo '<input type="text" id="inv_message_subject" value="'.$preview_message['subject_text'].'" autocomplete="off">';
+ echo '</td></tr>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_body'].':</th>';
+ echo '<td ><div class="msgBody">';
+ echo '<textarea id="inv_message_body" name="inv_message_body" autocomplete="off">'.($preview_message['body_text']).'</textarea>';
+ echo '</div>';
+ ?>
+ <script type="text/javascript">
+ create_inv_editor('inv_message_body', false);
+ </script><?php
+ echo '</td></tr>';
+ $urls = $this->getUrlLists();
+
+ if (count($urls) > 0) {
+ echo '<tr><th>'.$lang['srv_inv_message_draft_url'].'</th>';
+ echo '<td>';
+ echo '<select id="inv_message_url">';
+ foreach ($urls AS $url) {
+ $selected = '';
+ if ($preview_message['url'] == '') {
+ if ($preview_message['dc'] == true) {
+ $selected = ' selected="selected"';
+ }
+ } else if ($preview_message['url'] == $url['url']) {
+ $selected = ' selected="selected"';
+ }
+ echo '<option value="'.$url['url'].'"'.$selected.'>'.$url['name'].'</option>';
+ }
+ echo '</select>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '</div>';
+
+ echo '<br class="clr"/>';
+
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_forward'].'"><a class="ovalbutton" href="#" onclick="inv_message_save_forward(\''.$mid.'\'); return false;"><span>'.$lang['srv_invitation_forward'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_forward'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="if(inv_message_save_simple(\''.$mid.'\')) { window.location.reload() }; return false;"><span>'.$lang['srv_inv_message_save'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_message_saveNew'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_message_save_advanced(\''.$mid.'\'); return false;"><span>'.$lang['srv_invitation_message_saveNew'].'</span></a></span>';
+
+ echo '</div>';
+
+ echo '<div id="invitation_profile_notes"><p>';
+
+ $_indicators = $this->getAvailableIndicators();
+
+ $_sysVars = $this->getAvailableSysVars();
+
+ echo $lang['srv_inv_message_help'];
+ // Poiščemo še sistemske spremenljivke iz ankete
+ $prefix='';
+ if (count($_indicators ) > 0) {
+ echo $lang['srv_inv_message_help_identifikators'];
+
+ foreach ($_indicators AS $_identifikator) {
+ echo $prefix.'<br/>#'.strtoupper($_identifikator).'#'.$lang['srv_inv_message_help_system_'.strtolower($_identifikator)];
+ $prefix = ', ';
+ }
+
+ # preverimo ali imamo nastavljen mapping
+ $prefix = '';
+ $sqlSysMapping = sisplet_query("SELECT * FROM srv_invitations_mapping WHERE sid = '$this->sid'");
+ if (count($_sysVars ) > 0 && mysqli_num_rows($sqlSysMapping) > 0) {
+ echo '<br/><br/>'.$lang['srv_inv_message_help_systemvars'];
+ foreach ($_sysVars AS $_sys_var => $_sysLabel) {
+ echo $prefix.'<br/>#'.strtoupper($_sys_var).'#'.$lang['srv_inv_message_help_system_'.strtolower($_sys_var)];
+ $prefix = ', ';
+ }
+
+ }
+ } else {
+ echo $lang['srv_invitation_note12'];
+ }
+
+ echo '</p></div>';
+ }
+
+ echo '</div>';
+ }
+ // Ce samo dokumentiramo - navadna posta, SMS...
+ else{
+ echo '<div id="inv_messages_holder_noEmailing">';
+
+ echo $lang['srv_inv_message_noemailing_text'];
+
+ // Izbira nacina posiljanja (navadna posta, sms...) - prestavljeno pod nastavitve
+ /*echo '<div id="inv_select_noMail_type">';
+
+ $noEmailingType = SurveySession::get('inv_noEmailing_type');
+ echo '<span class="bold">'.$lang['srv_inv_message_noemailing_type'].':</span>';
+
+ echo '<span class="inv_send_span spaceLeft"><input name="noMailType" id="noMailType1" value="0" type="radio" '.($noEmailingType == 0 ? ' checked="checked"' : '').' onClick="noEmailingType(\'0\');"><label for="noMailType1">' . $lang['srv_inv_message_noemailing_type1'] . '</label></span>';
+ echo '<span class="inv_send_span spaceLeft"><input name="noMailType" id="noMailType2" value="1" type="radio" '.($noEmailingType == 1 ? ' checked="checked"' : '').' onClick="noEmailingType(\'1\');"><label for="noMailType2">' . $lang['srv_inv_message_noemailing_type2'] . '</label></span>';
+ echo '<span class="inv_send_span spaceLeft"><input name="noMailType" id="noMailType3" value="2" type="radio" '.($noEmailingType == 2 ? ' checked="checked"' : '').' onClick="noEmailingType(\'2\');"><label for="noMailType3">' . $lang['srv_inv_message_noemailing_type3'] . '</label></span>';
+
+ echo '</div>';*/
+
+ // Gumb naprej
+ /*echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_forward'].'">';
+ echo '<a class="ovalbutton ovalbutton_orange" href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=send_message&noemailing=1"><span>'.$lang['srv_invitation_forward'];
+ echo '</span></a></span>';
+
+ echo '<br class="clr"/>';*/
+
+ echo '</div>';
+
+
+ echo '<div id="inv_messages_holder">';
+
+ if ($this->checkDefaultMessage() == false) {
+ echo '<span class="inv_error_note">';
+ echo $lang['srv_invitation_note6'];
+ echo '</span>';
+ } else {
+ $sql_string = "SELECT id, naslov, subject_text, body_text, reply_to, isdefault, comment, url FROM srv_invitations_messages WHERE ank_id = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+ $array_messages = array();
+ while ( list($id, $naslov, $subject_text, $body_text, $reply_to ,$isdefault, $comment, $url) = mysqli_fetch_row($sql_query) ) {
+ $array_messages[$id] = array('id'=>$id, 'naslov' => $naslov, 'subject_text'=>$subject_text, 'body_text'=>$body_text, 'reply_to'=>$reply_to ,'isdefault'=>$isdefault, 'comment'=>$comment, 'url'=>$url);
+ if ($isdefault == '1') {
+ # če izbiramo profile in nismo postali še nobenga
+ if ( $mid == null ) {
+ $mid = $id;
+ }
+ }
+ }
+ $preview_message = $array_messages[$mid];
+
+ echo '<div id="inv_messages_profiles_holder" class="floatLeft">';
+ echo '<span>'.$lang['srv_invitation_message_choose'].':</span><br/>';
+ echo '<div id="invitation_messages" >';
+ echo '<ol>';
+ foreach ($array_messages AS $_m => $message) {
+ echo '<li mid="'.$message['id'].'" class="'
+ .($message['id'] == $mid ? ' active' : '')
+ .'" onclick="invChangeMessage(\''.$message['id'].'\')">';
+ echo $message['naslov'];
+ echo '</li>';
+ }
+ echo '</ol>';
+ echo '</div>'; #invitation_messages
+ echo '<br class="clr" />';
+ if (count($array_messages) > 1) {
+ echo '<span class="as_link" id="inv_del_msg_profile" onclick="invMessageDelete();" title="'.$lang['srv_inv_message_delete_profile'].'">'.$lang['srv_inv_message_delete_profile'].'</span><br/>';
+ }
+ echo '<span class="as_link" id="inv_ren_msg_profile" onclick="invShowMessageRename();" title="'.$lang['srv_inv_message_rename_profile'].'">'.$lang['srv_inv_message_rename_profile'].'</span>';
+ {
+ # polovimo podatke profila
+ $sql_string = "SELECT sim.*, u.name, u.surname, e.name as ename, e.surname as esurname FROM srv_invitations_messages AS sim LEFT JOIN users AS u ON sim.uid = u.id LEFT JOIN users AS e ON sim.edit_uid = e.id WHERE sim.id = '".(int)$mid."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ $avtor = array();
+ $edit = array();
+ if (trim($sql_row['name'])) {
+ $avtor[] = trim ($sql_row['name']);
+ }
+ if (trim($sql_row['surname'])) {
+ $avtor[] = trim ($sql_row['surname']);
+ }
+
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray">'.$lang['srv_invitation_author'].' '.implode(' ',$avtor).'</div>';
+ }
+ if ( count($avtor) > 0 ) {
+ echo '<div class="gray" title="'.date("d.m.Y H:i:s",strtotime($sql_row['insert_time'])).'">'.$lang['srv_invitation_author_day'].' '.date("d.m.Y",strtotime($sql_row['insert_time'])).'</div>';
+ }
+ if (trim($sql_row['ename'])) {
+ $edit[] = trim ($sql_row['ename']);
+ }
+ if (trim($sql_row['esurname'])) {
+ $edit[] = trim ($sql_row['esurname']);
+ }
+
+ if ( count($edit) > 0 && $edit != $avtor) {
+ echo '<div class="gray">'.$lang['srv_invitation_changed'].' '.implode(' ',$edit).'</div>';
+ }
+ if ($sql_row['insert_time'] != $sql_row['edit_time']) {
+ echo '<div class="gray" title="'.date("d.m.Y H:i:s",strtotime($sql_row['edit_time'])).'">'.$lang['srv_invitation_changed_day'].' '.date("d.m.Y",strtotime($sql_row['insert_time'])).'</div>';
+ }
+
+ echo '<div class="gray" style="max-width:202px">'.$lang['srv_invitation_comment'].' '. trim ($sql_row['comment']).'</div>';
+ }
+
+ echo '</div>'; #inv_messages_profiles_holder
+
+ $MA = new MailAdapter($this->sid, $type='invitation');
+ # zlistamo seznam vseh sporočil
+ # izpišemo primer besedila
+ echo '<div id="inv_msg_preview_hld" class="floatLeft">';
+ echo '<span class="h2 spaceRight floatLeft">'.$lang['srv_inv_message_draft_content_heading'].'</span> '.Help::display('srv_inv_message_title_noEmail');
+
+ //echo '<span class="spaceRight floatRight"><a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_server&show_back=true">'.$lang['srv_inv_message_draft_settings'].'</a></span>';
+ echo '<br class="clr"/>';
+ echo '<div id="inv_error_note" class="hidden"></div>';
+ echo '<div id="inv_msg_preview">';
+ echo '<table>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_subject'].':</th>';
+ echo '<td class="inv_bt">';
+ echo '<input type="text" id="inv_message_subject" value="'.$preview_message['subject_text'].'" autocomplete="off">';
+ echo '</td></tr>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_body'].':</th>';
+ echo '<td ><div class="msgBody">';
+ echo '<textarea id="inv_message_body" name="inv_message_body" autocomplete="off">'.($preview_message['body_text']).'</textarea>';
+ echo '</div>';
+ ?>
+ <script type="text/javascript">
+ create_inv_editor('inv_message_body', false);
+ </script><?php
+ echo '</td></tr>';
+
+ if (count($urls) > 0) {
+ echo '<tr><th>'.$lang['srv_inv_message_draft_url'].'</th>';
+ echo '<td>';
+ echo '<select id="inv_message_url">';
+ foreach ($urls AS $url) {
+ $selected = '';
+ if ($preview_message['url'] == '') {
+ if ($preview_message['dc'] == true) {
+ $selected = ' selected="selected"';
+ }
+ } else if ($preview_message['url'] == $url['url']) {
+ $selected = ' selected="selected"';
+ }
+ echo '<option value="'.$url['url'].'"'.$selected.'>'.$url['name'].'</option>';
+ }
+ echo '</select>';
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '</div>';
+
+ echo '<br class="clr"/>';
+
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_forward'].'"><a class="ovalbutton" href="#" onclick="inv_message_save_forward_noEmail(\''.$mid.'\'); return false;"><span>'.$lang['srv_invitation_forward'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_forward'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="if(inv_message_save_simple_noEmail(\''.$mid.'\')) { window.location.reload() }; return false;"><span>'.$lang['srv_inv_message_save'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_invitation_message_saveNew'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_message_save_advanced(\''.$mid.'\'); return false;"><span>'.$lang['srv_invitation_message_saveNew'].'</span></a></span>';
+
+ echo '</div>';
+ }
+
+ echo '</div>';
+ }
+
+ echo '<br class="clr"/>';
+ }
+
+ function checkDefaultMessage() {
+ global $lang, $global_user_id;
+
+ $sql_query = sisplet_query("SELECT id FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'");
+
+ $row = $this->surveySettings;
+
+ # če privzeto sporočilo ne obstaja ga skreiramo
+ if (mysqli_num_rows($sql_query) == 0 ) {
+
+ Common::getInstance()->Init($this->sid);
+
+ $reply_to = Common::getInstance()->getReplyToEmail();
+
+ # poiščemo ime seznama za sporočila
+ $naslov = $this->generateMessageName();
+
+ $body_text = ($row['usercode_required'] == 1) ? $lang['srv_inv_message_body_text'].$lang['srv_inv_message_body_text_pass'] : $lang['srv_inv_message_body_text'];
+
+ # skreiramo osnovno sporočilo
+ $sqlQuery = sisplet_query("INSERT INTO srv_invitations_messages (ank_id, naslov, subject_text, body_text, reply_to, isdefault, uid, insert_time, comment, edit_uid, edit_time, url ) VALUES ('$this->sid', '".$naslov."', '".$lang['srv_inv_message_subject_text']."', '".$body_text."', '".$reply_to."', '1', '".$global_user_id."', NOW(), '', '".$global_user_id."', NOW(), '')");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ $new_msg_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ((int)$new_msg_id > 0) {
+ return true;
+ }
+ else {
+ # insert ni uspel, in privzetega sporočila nimamo
+ return false;
+ }
+ }
+ else {
+ # če smo tu, imamo privzeto sporočilo
+ return true;
+ }
+ }
+
+ function makeDefaultMessage($mid = null) {
+ # preverimo kater message je trenutno privzet
+ $sql_string = "SELECT id FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'";
+ $sql_query = sisplet_query($sql_string);
+ list($def_id) = mysqli_fetch_row($sql_query);
+ if ((int)$def_id > 0 && (int)$mid > 0 && (int)$def_id != (int)$mid) {
+ # odstranimo privzet id in ga nastavimo na novo
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '0' WHERE ank_id = '$this->sid' AND isdefault='1'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ # nastavimo na nov id
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '1' WHERE ank_id = '$this->sid' AND id='$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+ sisplet_query("COMMIT");
+ }
+ $this->viewMessage($mid);
+ }
+
+ function makeDefaultFromPreview($mid = null) {
+ # preverimo kater message je trenutno privzet
+ $sql_string = "SELECT id FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'";
+ $sql_query = sisplet_query($sql_string);
+ list($def_id) = mysqli_fetch_row($sql_query);
+ if ((int)$def_id > 0 && (int)$mid > 0 && (int)$def_id != (int)$mid) {
+ # odstranimo privzet id in ga nastavimo na novo
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '0' WHERE ank_id = '$this->sid' AND isdefault='1'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ # nastavimo na nov id
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '1' WHERE ank_id = '$this->sid' AND id='$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+ sisplet_query("COMMIT");
+ }
+ $this->displayMessagePreview();
+ }
+
+ /**
+ * shranimo v obstoječ profil
+ */
+ function save_message_simple() {
+ global $lang, $global_user_id;
+ $return = array('msg'=>'', 'error'=>'0');
+
+ # shranimo vsebino
+ #če so kakšne napake jih prikažemo v float oknu
+ $mid = (int)$_POST['mid'];
+ $subject = trim($_POST['subject']);
+ $replyto = trim($_POST['replyto']);
+ $body = trim($_POST['body']);
+ $url = trim($_POST['url']);
+
+ $newline = '';
+ if ($replyto == null || $replyto == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_from'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_replyto'] = '1';
+ $newline= '<br/>';
+ } else {
+ if (!$this->validEmail($replyto)) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_from'].'"'.$lang['srv_inv_msg_3_not_valid_email'];
+ $return['inv_message_replyto'] = '1';
+ $newline= '<br/>';
+ }
+
+ }
+ if ($subject == null || $subject == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_subject'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_subject'] = '1';
+ $newline= '<br/>';
+ }
+
+ if ($body == null || $body == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_body'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_body'] = '1';
+ $newline= '<br/>';
+ }
+ # če ni napak shranim:
+ if ( $return['error'] == '0') {
+
+ if ((int)$mid > 0) {
+ # shranjujemo v obstoječ msg
+ $sql_string = "UPDATE srv_invitations_messages SET subject_text = '$subject', body_text = '$body', reply_to = '$replyto', edit_uid = '".$global_user_id."', edit_time = NOW(), url='".$url."' WHERE ank_id = '$this->sid' AND id='$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+ $return['mid'] = $mid;
+
+ if ( $sqlQuery != 1) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+ } else {
+ # mid manjka
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4']; $newline= '<br/>';
+ }
+ sisplet_query("COMMIT");
+ }
+ $return['msg'].=' '.$sql_string.$sql_insert;
+ echo json_encode($return);
+ exit;
+ }
+
+ /**
+ * shranimo v obstoječ profil
+ */
+ function save_message_simple_noEmail() {
+ global $lang, $global_user_id;
+ $return = array('msg'=>'', 'error'=>'0');
+
+ # shranimo vsebino
+ #če so kakšne napake jih prikažemo v float oknu
+ $mid = (int)$_POST['mid'];
+ $subject = trim($_POST['subject']);
+ $body = trim($_POST['body']);
+ $url = trim($_POST['url']);
+
+ $newline = '';
+ if ($subject == null || $subject == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_subject'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_subject'] = '1';
+ $newline= '<br/>';
+ }
+
+ if ($body == null || $body == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_body'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_body'] = '1';
+ $newline= '<br/>';
+ }
+ # če ni napak shranim:
+ if ( $return['error'] == '0') {
+
+ if ((int)$mid > 0) {
+ # shranjujemo v obstoječ msg
+ $sql_string = "UPDATE srv_invitations_messages SET subject_text = '$subject', body_text = '$body', edit_uid = '".$global_user_id."', edit_time = NOW(), url='".$url."' WHERE ank_id = '$this->sid' AND id='$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+ $return['mid'] = $mid;
+
+ if ( $sqlQuery != 1) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+ } else {
+ # mid manjka
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4']; $newline= '<br/>';
+ }
+ sisplet_query("COMMIT");
+ }
+ $return['msg'].=' '.$sql_string.$sql_insert;
+ echo json_encode($return);
+ exit;
+ }
+
+ function messageSaveforward() {
+ global $lang, $global_user_id;
+ $return = array('msg'=>'', 'error'=>'0');
+
+ $mid = (int)$POST['mid'];
+
+ #če so kakšne napake jih prikažemo v float oknu
+ $subject = trim($_POST['subject']);
+ $replyto = trim($_POST['replyto']);
+ $body = trim($_POST['body']);
+ $url = trim($_POST['url']);
+
+ $newline = '';
+ if ($replyto == null || $replyto == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_from'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_replyto'] = '1';
+ $newline= '<br/>';
+ } else {
+ if (!$this->validEmail($replyto)) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_from'].'"'.$lang['srv_inv_msg_3_not_valid_email'];
+ $return['inv_message_replyto'] = '1';
+ $newline= '<br/>';
+ }
+ }
+ if ($subject == null || $subject == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_subject'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_subject'] = '1';
+ $newline= '<br/>';
+ }
+
+ if ($body == null || $body == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_body'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_body'] = '1';
+ $newline= '<br/>';
+ }
+ # če ni napak shranim:
+ if ( $return['error'] == '0') {
+
+ # preverimo ali je kakšna sprememba, če je sprememba shranimo v nov profil
+ $sql_string = "SELECT subject_text, body_text, reply_to, url FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND id='".(int)$_POST['mid']."'";
+ $sql_query = sisplet_query($sql_string);
+ list($old_subject, $old_body_text, $old_reply_to, $old_url) = mysqli_fetch_row($sql_query);
+
+ if ($old_subject != $subject || $old_body_text != $body || $old_reply_to != $replyto || $old_url != $url) {
+
+ # shranjujemo v novo sporočilo
+ $naslov = $this->generateMessageName();
+ $sql_insert = "INSERT INTO srv_invitations_messages (ank_id, naslov, subject_text, body_text, reply_to, isdefault, uid, insert_time, comment, edit_uid, edit_time, url ) ".
+ "VALUES ('$this->sid', '$naslov', '$subject', '$body', '$replyto', '1', '$global_user_id', NOW(), '$comment', '$global_user_id', NOW(), '$url')";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ $newID = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($newID > 0) {
+
+ $return['mid'] = $newID;
+
+ # popravmo še isdefault pri starem zapisz
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '0' WHERE ank_id = '$this->sid' AND id != '$newID'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ } else {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+
+ }
+ sisplet_query("COMMIT");
+ }
+ $return['msg'].=' '.$sql_string.$sql_insert;
+ echo json_encode($return);
+ exit;
+ }
+
+ function messageSaveforwardNoEmail() {
+ global $lang, $global_user_id;
+ $return = array('msg'=>'', 'error'=>'0');
+
+ $mid = (int)$POST['mid'];
+
+ #če so kakšne napake jih prikažemo v float oknu
+ $subject = trim($_POST['subject']);
+ $body = trim($_POST['body']);
+ $url = trim($_POST['url']);
+
+ $newline = '';
+
+ if ($subject == null || $subject == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_subject'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_subject'] = '1';
+ $newline= '<br/>';
+ }
+
+ if ($body == null || $body == '' ) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_field'].'"'.$lang['srv_inv_message_draft_content_body'].'"'.$lang['srv_inv_msg_3_not_empty'];
+ $return['inv_message_body'] = '1';
+ $newline= '<br/>';
+ }
+ # če ni napak shranim:
+ if ( $return['error'] == '0') {
+
+ # preverimo ali je kakšna sprememba, če je sprememba shranimo v nov profil
+ $sql_string = "SELECT subject_text, body_text, reply_to, url FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND id='".(int)$_POST['mid']."'";
+ $sql_query = sisplet_query($sql_string);
+ list($old_subject, $old_body_text, $old_reply_to, $old_url) = mysqli_fetch_row($sql_query);
+
+ if ($old_subject != $subject || $old_body_text != $body || $old_url != $url) {
+
+ # shranjujemo v novo sporočilo
+ $naslov = $this->generateMessageName();
+ $sql_insert = "INSERT INTO srv_invitations_messages (ank_id, naslov, subject_text, body_text, isdefault, uid, insert_time, comment, edit_uid, edit_time, url ) ".
+ "VALUES ('$this->sid', '$naslov', '$subject', '$body', '1', '$global_user_id', NOW(), '$comment', '$global_user_id', NOW(), '$url')";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ $newID = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($newID > 0) {
+
+ $return['mid'] = $newID;
+
+ # popravmo še isdefault pri starem zapisz
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '0' WHERE ank_id = '$this->sid' AND id != '$newID'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ } else {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+
+ }
+ sisplet_query("COMMIT");
+ }
+ $return['msg'].=' '.$sql_string.$sql_insert;
+ echo json_encode($return);
+ exit;
+ }
+
+ function addUrl($what) {
+ global $site_url;
+
+ if ($what == null || trim($what) == '') {
+ $what = 'add_recipients_view';
+ }
+ $url = $site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_INVITATIONS.'&amp;m='.$what;
+
+ return $url;
+ }
+
+ /**
+ Validate an email address.
+ */
+ function validEmail($email = null) {
+ return Common::getInstance()->validEmail($email);
+ }
+
+ function displayRecipentsErrors($result) {
+ global $lang;
+ $valid_recipiens = is_array($result['valid_recipiens']) ? $result['valid_recipiens'] : array();
+ $invalid_password = is_array($result['invalid_password']) ? $result['invalid_password'] : array();
+ $invalid_email = is_array($result['invalid_email']) ? $result['invalid_email'] :array();
+ $duplicate_email = is_array($result['duplicate_email']) ? $result['duplicate_email'] : array();
+ $unsubscribed = is_array($result['unsubscribed']) ? $result['unsubscribed'] : array();
+
+ # dodani so bili nekateri uporabniki
+ if (count($valid_recipiens) > 0) {
+ echo '<div id="inv_recipiens_added">';
+ echo $lang['srv_inv_recipiens_add_success_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList1\').toggle();">'. count($valid_recipiens).'</span></span>';
+ echo '<br />';
+ echo '<div id="invRecipiensList1" class="displayNone"><br/>';
+
+ foreach ($valid_recipiens AS $fields) {
+ if (is_array($fields)) {
+
+ $text = '';
+ $text .= mb_strtolower($fields['inv_field_email']);
+
+ if (trim($fields['inv_field_firstname']) != '') {
+ $text .= ', '.str_replace("|~|", ",", mb_strtolower($fields['inv_field_firstname'], 'UTF-8'));
+ }
+ if (trim($fields['inv_field_lastname']) != '') {
+ $text .= ', '.str_replace("|~|", ",", mb_strtolower($fields['inv_field_lastname'], 'UTF-8'));
+ }
+
+ echo $text;
+ }
+ else {
+ echo mb_strtolower($fields, 'UTF-8');
+ }
+ echo '<br/>';
+ }
+
+ echo '</div>';
+ echo '</div>';
+ }
+
+ if ( (count($invalid_password) + count($invalid_email) + count($duplicate_email) + count($unsubscribed)) > 0 ) {
+ echo '<div id="inv_recipiens_rejected">';
+
+ # ni veljavnih uporabnikov
+ if (count($valid_recipiens) == 0 ) {
+ echo '<span class="red bold">'.$lang['srv_inv_recipiens_add_error'].'</span><br/>';
+ }
+ # zavrnjeni uporabniki
+ if (count($unsubscribed)> 0) {
+ echo $lang['srv_inv_recipiens_add_optedout_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList2\').toggle();">'.count($unsubscribed).'</span></span>';
+ echo '<br />';
+ echo '<div id="invRecipiensList2" class="displayNone">';
+ foreach ($unsubscribed AS $fields) {
+ if (is_array($fields)) {
+ echo strtolower($fields['inv_field_email']);
+ if (trim($fields['inv_field_firstname']) != '') {
+ echo ', '.$fields['inv_field_firstname'];
+ }
+ if (trim($fields['inv_field_lastname']) != '') {
+ echo ', '.$fields['inv_field_lastname'];
+ }
+ } else {
+ echo $fields;
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+
+ }
+
+ # podvojeni uporabniki
+ if (count($duplicate_email)> 0) {
+ echo $lang['srv_inv_recipiens_add_exist_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList3\').toggle();">'.count($duplicate_email).'</span></span>';
+ echo '<br />';
+ echo '<div id="invRecipiensList3" class="displayNone">';
+ foreach ($duplicate_email AS $fields) {
+ if (is_array($fields)) {
+ echo strtolower($fields['inv_field_email']);
+ if (trim($fields['inv_field_firstname']) != '') {
+ echo ', '.$fields['inv_field_firstname'];
+ }
+ if (trim($fields['inv_field_lastname']) != '') {
+ echo ', '.$fields['inv_field_lastname'];
+ }
+ } else {
+ echo strtolower($fields);
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+ }
+
+ # neveljaven e-mail
+ if (count($invalid_email) > 0) {
+ echo $lang['srv_inv_recipiens_add_invalid_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList4\').toggle();">'.count($invalid_email).'!</span></span>';
+ echo '<br />';
+ echo '<div id="invRecipiensList4" class="displayNone">';
+ foreach ($invalid_email AS $fields) {
+ if (is_array($fields)) {
+ echo str_replace("|~|", ",", mb_strtolower($fields['inv_field_email'], 'UTF-8'));
+ if (trim($fields['inv_field_firstname']) != '') {
+ echo ', '.str_replace("|~|", ",", $fields['inv_field_firstname']);
+ }
+ if (trim($fields['inv_field_lastname']) != '') {
+ echo ', '.str_replace("|~|", ",", $fields['inv_field_lastname']);
+ }
+ } else {
+ echo str_replace("|~|", ",", mb_strtolower($fields, 'UTF-8'));
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+ }
+
+ # neveljavena gesla
+ if (count($invalid_password) > 0) {
+ echo $lang['srv_inv_recipiens_add_invalid_password_cnt'].'<span class="inv_count"><span class="as_link" onclick="$(\'#invRecipiensList5\').toggle();">'.count($invalid_password).'!</span></span>';
+ echo '<br />';
+ echo '<div id="invRecipiensList5" class="displayNone">';
+ foreach ($invalid_password AS $fields) {
+ if (is_array($fields)) {
+ echo strtolower($fields['inv_field_email']);
+ if (trim($fields['inv_field_firstname']) != '') {
+ echo ', '.$fields['inv_field_firstname'];
+ }
+ if (trim($fields['inv_field_lastname']) != '') {
+ echo ', '.$fields['inv_field_lastname'];
+ }
+ } else {
+ echo strtolower($fields);
+ }
+ echo '<br/>';
+ }
+ echo '</div>';
+ }
+
+ if (count($invalid_email) > 0 || count($invalid_password) > 0) {
+ //echo ''.$lang['srv_inv_recipiens_add_invalid_note'];
+ echo '<br /><span class="red">'.$lang['srv_inv_recipiens_add_invalid_note2'].'!</span>';
+ echo Help::display('srv_inv_recipiens_add_invalid_note');
+ }
+ echo '</div>';
+
+ return array_merge($unsubscribed, $duplicate_email, $invalid_email, $invalid_password) ;
+ }
+ return array();
+ }
+
+ function displayNavigation() {
+ global $lang, $admin_type, $global_user_id, $app_settings;
+
+ $isEmail = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ #če ni dostopa mu ne prikažemo linkov
+ if ((int)$isEmail > 0 && $userAccess->checkUserAccess($what='invitations')) {
+ }
+ else {
+ return false;
+ }
+
+ if (!isset($_POST['noNavi']) || (isset($_POST['noNavi']) && $_POST['noNavi'] != 'true')) {
+ $_sub_action = $_GET['m'];
+
+ if ($_sub_action == null && $_GET['t'] == 'invitations') {
+ if ($_GET['a'] == 'use_recipients_list') {
+ $_sub_action = 'add_recipients_view';
+ }
+ if ($_GET['a'] == 'view_message'
+ || $_GET['a'] == 'make_default'
+ || $_GET['a'] == 'delete_msg_profile' ) {
+ $_sub_action = 'view_message';
+ }
+ if ($_GET['a'] == 'delete_recipient'
+ || $_GET['a'] == 'add_recipients'
+ || $_GET['a'] == 'view_recipients'
+ || $_GET['a'] == 'export_recipients'
+ || $_GET['a'] == 'add_checked_users_to_database'
+ || $_GET['a'] == 'setAdvancedCondition'
+ || $_GET['a'] == 'recipientsAddForward') {
+ $_sub_action = 'view_recipients';
+ }
+ if ($_GET['a'] == 'view_archive' ) {
+ $_sub_action = 'view_archive';
+ }
+ if ($_GET['a'] == 'send_mail') {
+ $_sub_action = 'send_message';
+ #$_sub_action = 'view_archive';
+ }
+ } else if( $_sub_action == 'send_mail') {
+ #$_sub_action = 'view_archive';
+ $_sub_action = 'send_message';
+ }
+
+ $active_step[] = array(1=>'',2=>'',3=>'',4=>'',5=>'',6=>'',7=>'',8=>'');
+ switch ($_sub_action) {
+ case 'inv_settings':
+ $active_step['1'] = ' active';
+ break;
+ case 'add_recipients_view':
+ $active_step['2'] = ' active';
+ break;
+ case 'view_recipients':
+ $active_step['3'] = ' active';
+ break;
+ case 'view_message':
+ $active_step['4'] = ' active';
+ break;
+ case 'send_message':
+ $active_step['5'] = ' active';
+ break;
+ case 'view_archive':
+ $active_step['6'] = ' active';
+ break;
+ case 'inv_lists':
+ $active_step['7'] = ' active';
+ break;
+ case 'inv_server':
+ $active_step['8'] = ' active';
+ break;
+ case 'inv_status':
+ $active_step['9'] = ' active';
+ break;
+
+ default:
+ $sql = sisplet_query("SELECT EXISTS (SELECT 1 FROM srv_invitations_archive WHERE ank_id='".$this->sid."')");
+ $row = mysqli_fetch_array($sql);
+
+ // Ce imamo ze posiljanje je default stran "Pregled"
+ if($row[0] == 1)
+ $active_step['9'] = ' active';
+ // Drugace je default stran "Nastavitve"
+ else
+ $active_step['1'] = ' active';
+ break;
+ }
+ if (SurveyInfo::getInstance()->checkSurveyModule('email') || SurveyInfo::getInstance()->checkSurveyModule('phone')) {
+ $disabled = false;
+ $css_disabled = '';
+ } else {
+ $disabled = true;
+ $css_disabled = '_disabled';
+ }
+
+ if($isEmail) {
+ #$spaceChar = '&#187;';
+ $spaceChar = '&nbsp;';
+ echo '<div id="inv_step_nav">';
+ echo '<div class="inv_step'.$active_step[1].'">';
+ echo '<a href="'.$this->addUrl('inv_settings').'">';
+ //echo '<span class="circle">1</span>';
+ echo '<span class="label">'.$lang['srv_inv_nav_email_settings'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+ #space
+ echo '<div class="inv_space">&nbsp;</div>';
+ echo '<div id="inv_step_nav" class="yellow">';
+
+ $class_yellow = ' yellow';
+
+ #navigacija
+ echo '<div class="inv_step'.$class_yellow.$css_disabled.$active_step[2].'">';
+ if ($disabled == false) {
+ echo '<a href="'.$this->addUrl('add_recipients_view').'">';
+ }
+ echo '<span class="circle">1</span>';
+ echo '<span class="label">'.$lang['srv_inv_nav_add_recipients'].'</span>';
+ if ($disabled == false) {
+ echo '</a>';
+ }
+ echo '</div>';
+
+ echo '<div class="inv_step_space'.$class_yellow.$css_disabled.'">'.$spaceChar.'</div>';
+ echo '<div class="inv_step'.$class_yellow.$css_disabled.$active_step[3].'">';
+ if ($disabled == false) {
+ echo '<a href="'.$this->addUrl('view_recipients').'">';
+ }
+ echo '<span class="circle">2</span>';
+ echo '<span class="label">'.$lang['srv_inv_nav_edit_recipiens'].'</span>';
+ if ($disabled == false) {
+ echo '</a>';
+ }
+ echo '</div>';
+ echo '<div class="inv_step_space'.$class_yellow.$css_disabled.'">'.$spaceChar.'</div>';
+ if ($disabled == false) {
+ echo '<a href="'.$this->addUrl('view_message').'">';
+ }
+ echo '<div class="inv_step'.$class_yellow.$css_disabled.$active_step[4].'">';
+ echo '<span class="circle">3</span>';
+ echo '<span class="label" >'.$lang['srv_inv_nav_edit_message'].'</span>';
+ if ($disabled == false) {
+ echo '</a>';
+ }
+ echo '</div>';
+ echo '<div class="inv_step_space'.$class_yellow.$css_disabled.'">'.$spaceChar.'</div>';
+ echo '<div class="inv_step'.$class_yellow.$css_disabled.$active_step[5].'">';
+ if ($disabled == false) {
+ echo '<a href="'.$this->addUrl('send_message').'">';
+ }
+ echo '<span class="circle">4</span>';
+ echo '<span class="label" >'.$lang['srv_inv_nav_send_message'].'</span>';
+ if ($disabled == false) {
+ echo '</a>';
+ }
+ echo '</div>';
+
+ echo '</div>';
+
+
+ // Pregled
+ #space
+ echo '<div class="inv_space">&nbsp;</div>';
+
+ echo '<div id="inv_step_nav">';
+ echo '<div class="inv_step'.$active_step[9].'">';
+ echo '<a href="'.$this->addUrl('inv_status').'">';
+ //echo '<span class="circle">1</span>';
+ echo '<span class="label">'.$lang['srv_inv_nav_email_review'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+
+ // Seznami
+ #space
+ echo '<div class="inv_space">&nbsp;</div>';
+
+ echo '<div id="inv_step_nav">';
+ echo '<div class="inv_step'.$active_step[7].'">';
+ echo '<a href="'.$this->addUrl('inv_lists').'">';
+ //echo '<span class="circle">1</span>';
+ echo '<span class="label">'.$lang['srv_inv_nav_email_lists'].'</span>';
+ echo '</a>';
+ echo '</div>';
+ echo '</div>';
+
+
+ echo '<br class="clr" />';
+ echo '<br class="clr" />';
+ }
+
+ }
+ echo '<input type="hidden" id="surveyConditionPage" value="invitations">';
+ }
+
+ function sendMessage() {
+ global $lang, $site_url;
+
+ // Ali posiljamo maile ali ne
+ $noEmailing = SurveySession::get('inv_noEmailing');
+
+ $row = $this->surveySettings;
+
+ # Pripravimo izbor komu lahko pošiljamo
+ echo '<h2 style="margin-left: 15px; color:#333 !important;">';
+
+ // Text s podatki o nastavitvah posiljanja
+ $settings_text = '<span class="bold spaceRight">'.$lang['srv_inv_message_type'].':</span>';
+
+ $individual = (int)$this->surveySettings['individual_invitation'];
+ if($individual == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_individual_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($noEmailing == 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_0'].'</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_noEmail_1'].'</span>';
+ }
+
+ $settings_text .= ' - ';
+
+ if($row['usercode_required'] == 0 && $individual != 0){
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_0'];
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_0'].')</span>';
+ }
+ else{
+ $settings_text .= '<span class="spaceLeft spaceRight">'.$lang['srv_inv_settings_URL_1'];
+
+ if($row['usercode_skip'] == 1 || $individual == 0){
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_2'].')</span>';
+ }
+ else{
+ $settings_text .= ' ('.$lang['srv_inv_settings_code_1'].')</span>';
+ }
+ }
+
+ $settings_text .= '<span class="spaceLeft"> <a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_settings">'.$lang['edit4'].'</a></span>';
+
+ echo $settings_text;
+ echo '</h2>';
+
+
+ if ($this->checkDefaultMessage() == false) {
+ echo '<span class="inv_error_note">';
+ echo $lang['srv_invitation_note6'];
+ echo '</span>';
+ exit();
+ }
+
+ echo '<div id="inv_send_mail">';
+
+ # damo v tabelo zaradi prilagajanja oblike levo/desno
+ echo '<table><tr>';
+
+ // Pri volitvah vedno posiljamo samo tistim, katerim se nismo poslali
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+
+ echo '<td>';
+
+ echo '<div>';
+
+ echo $lang['srv_inv_send_who_database'].'<br/>';
+ echo '<span class="floatLeft">';
+ echo '<label><input type="radio" name="mailsource" value="0" onclick="mailToSourceChange();" checked="checked">'.$lang['srv_inv_send_who_all_units'].'</label>';
+ echo '</span>';
+
+ $this->advancedCondition();
+ echo '<br class="clr"/>';
+
+ echo '<label><input type="radio" name="mailsource" value="1" onclick="mailToSourceChange();">'.$lang['srv_inv_send_who_archive'].'</label>';
+ echo '<br/><label><input type="radio" name="mailsource" value="2" onclick="mailToSourceChange();">'.$lang['srv_inv_send_who_lists'].'</label>';
+ echo '<br/>';
+
+ echo '<div id="inv_select_mail_to_source_lists">';
+ $this->displayMailToSourceLists((int)$_POST['source_type']);
+ echo '</div>'; #id="inv_select_mail_to_source_lists"
+
+ echo '</div>';
+
+ # polovimo sporočilo in prejemnike
+ $sql_query_m = sisplet_query("SELECT id, naslov, subject_text, body_text, reply_to, isdefault, comment, url FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'");
+ if (mysqli_num_rows($sql_query_m) > 0 ) {
+ $preview_message = mysqli_fetch_assoc($sql_query_m);
+ }
+ else {
+ #nimamo še vsebine sporočila skreiramo privzeto.
+ echo '<span class="inv_error_note">';
+ echo $lang['srv_invitation_note6'];
+ echo '</span>';
+
+ exit();
+ }
+
+ echo '</td>';
+ }
+
+ echo '<td>';
+
+ // Ce posiljamo preko navadne poste ali smsov, nimamo sporocila
+ if($noEmailing == 0){
+ echo '<input type="hidden" name="noMailing" value="0" />';
+
+ echo '<div id="inv_select_mail_preview">';
+ $this->displayMessagePreview();
+ echo '</div>'; // inv_select_mail_preview
+ echo '<br class="clr"/>';
+
+ echo '<div id="inv_select_mail_to_respondents">';
+ $this->selectSendTo();
+ echo '</div>'; // inv_select_mail_to_respondents
+ }
+ else{
+ echo '<input type="hidden" name="noMailing" value="1" />';
+ $noEmailingType = SurveySession::get('inv_noEmailing_type');
+ echo '<input type="hidden" name="noMailingType" value="'.$noEmailingType.'" />';
+
+ echo '<div id="inv_select_mail_to_respondents">';
+ $this->selectSendToNoEmailing();
+ echo '</div>'; // inv_select_mail_to_respondents
+ }
+
+ echo '</td>';
+
+ echo '</tr></table>';
+
+ echo '</div>'; //inv_send_mail
+ }
+
+ function displayMailToSourceLists($source_type) {
+ global $lang, $site_url;
+
+ $canShowSubOption = false;
+
+ echo '<p style="margin-left:25px;">';
+ echo $lang['srv_inv_send_who_create1'].'<a href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a=invitations&m=inv_lists">'.$lang['srv_inv_send_who_create2'].'</a><br/>';
+
+ if ((int)$source_type == 0) {
+ # vsi respondenti v bazi
+ echo $lang['srv_inv_send_who_database_note'];
+ $canShowSubOption = true;
+ }
+ elseif ((int)$source_type == 1) {
+ # Arhivi pošiljanja
+
+ # poiščemo arhiv mailingov
+ # zloopamo še po posameznih pošiljanjih
+ $sql_string_arc = "SELECT sia.*, DATE_FORMAT(sia.date_send,'%d.%m.%Y, %T') AS ds, u.name, u.surname, u.email FROM srv_invitations_archive AS sia LEFT JOIN users AS u ON sia.uid = u.id WHERE ank_id = '".$this->sid."' ORDER BY sia.date_send ASC;";
+ $sql_query_arc = sisplet_query($sql_string_arc);
+
+ if (mysqli_num_rows($sql_query_arc) > 0) {
+
+ $canShowSubOption = true;
+
+ echo $lang['srv_inv_send_who_archive_note'];
+ echo '<table id="tbl_recipients_source_list">';
+ echo '<tr>';
+ echo '<th class="tbl_icon">&nbsp;</th>';
+ echo '<th>'.$lang['srv_inv_send_who_table_address'].'</th>';
+ echo '<th>'.$lang['srv_inv_send_who_table_respondents'].'</th>';
+ echo '<th>'.$lang['srv_inv_send_who_table_date_create'].'</th>';
+ echo '</tr>';
+
+ while ($row_arc = mysqli_fetch_assoc($sql_query_arc)) {
+ echo '<tr>';
+ echo '<td class="tbl_icon"><input type="checkbox" name="mailsource_lists[]" onchange="mailToSourceCheckboxChange();" value="'.$row_arc['id'].'"></td>';
+ echo '<td>'.$row_arc['naslov'].'</td>';
+ echo '<td class="anl_ac">'.((int)$row_arc['cnt_succsess']+(int)$row_arc['cnt_error']).'</td>';
+ echo '<td>'.$row_arc['ds'].'</td>';
+ echo '</tr>';
+ }
+
+ echo '</table>';
+ }
+ else{
+ echo $lang['srv_inv_send_who_archive_no_archive'];
+ }
+ }
+ elseif ((int)$source_type == 2) {
+ # seznami respondentov
+
+ # zloopamo skozi posamezne sezname respondentov
+ $sql_string_arc ="";
+ $sql_query_arc = sisplet_query("SELECT list_id as id, COUNT(*) as cnt_succsess, list_id, sirp.name as naslov, DATE_FORMAT(sirp.insert_time,'%d.%m.%Y, %T') AS ds
+ FROM srv_invitations_recipients AS sir
+ LEFT JOIN srv_invitations_recipients_profiles AS sirp
+ ON sir.list_id = sirp.pid
+ WHERE ank_id ='".$this->sid."' AND sir.deleted ='0' group BY list_id
+ ");
+
+ if (mysqli_num_rows($sql_query_arc) > 0) {
+
+ $canShowSubOption = true;
+
+ echo $lang['srv_inv_send_who_all_units_note'];
+
+ echo '<table id="tbl_recipients_source_list">';
+ echo '<tr>';
+ echo '<th class="tbl_icon">&nbsp;</th>';
+ echo '<th>'.$lang['srv_inv_send_who_table_list_name'].'</th>';
+ echo '<th>'.$lang['srv_inv_send_who_table_respondents'].'</th>';
+ echo '<th>'.$lang['srv_inv_send_who_table_date_create'].'</th>';
+ echo '</tr>';
+ while ($row_arc = mysqli_fetch_assoc($sql_query_arc)) {
+
+ if ($row_arc['id'] > 0 && $row_arc['naslov'] == '') {
+ # če ni imena in je id < 0 je bil izbrisan
+ }
+ else {
+ if ($row_arc['id'] > 0) {
+ if ($row_arc['naslov'] != '') {
+ $_naslov = $row_arc['naslov'];
+ }
+ else {
+ $_naslov = $lang['srv_inv_send_who_table_list_deleted'];
+ }
+ }
+ else if ($row_arc['id'] == 0) {
+ $_naslov = $lang['srv_inv_send_who_table_list_temporary'];
+ }
+ else if ($row_arc['id'] < 0) {
+ $_naslov = $lang['srv_inv_send_who_table_list_noname'];
+ }
+
+ echo '<tr>';
+ echo '<td class="tbl_icon"><input type="checkbox" name="mailsource_lists[]" onchange="mailToSourceCheckboxChange();" value="'.$row_arc['id'].'"></td>';
+ echo '<td>'.$_naslov.'</td>';
+ echo '<td class="anl_ac">'.$row_arc['cnt_succsess'].'</td>';
+ echo '<td>'.$row_arc['ds'].'</td>';
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+ }
+ else{
+ echo $lang['srv_inv_send_who_no_lists'];
+ }
+ }
+ echo '</p>';
+
+ if ($canShowSubOption == true) {
+
+ echo '<span id="inv_select_mail_to">';
+ echo '<span class="bold">'.$lang['srv_inv_send_note'].'</span><br/>';
+ echo '<span class="inv_send_span"><input name="mailto" id="mailto0" value="0" type="radio" checked="checked" onclick="mailToRadioChange();"><label for="mailto0">' . $lang['srv_inv_send_recipients0'] . '</label></span><br/>';
+ echo '<span class="inv_send_span"><input name="mailto" id="mailto1" value="1" type="radio" onclick="mailToRadioChange();"><label for="mailto1">' . $lang['srv_inv_send_recipients1'] . '</label></span><br/>';
+ echo '<span class="inv_send_span"><input name="mailto" id="mailto2" value="2" type="radio" onclick="mailToRadioChange();"><label for="mailto2">' . $lang['srv_inv_send_recipients2'] . '</label></span><br/>';
+ echo '<span class="inv_send_span"><input name="mailto" id="mailto3" value="3 " type="radio" onclick="mailToRadioChange();"><label for="mailto3">' . $lang['srv_inv_send_recipients3'] . '</label></span><br/>';
+
+ echo '<span class="inv_send_span">'.$lang['srv_invitation_send_advanced'].'</span><br/>';
+ echo '<span class="inv_send_span"><input name="mailto" id="mailto4" value="4 " type="radio" onclick="mailToRadioChange();"><label for="mailto4">' . $lang['srv_inv_send_recipients4'] . '</label></span><br/>';
+ echo '<div id="inv_send_advanced_div" >';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="0" type="checkbox" id="mailto_status_0" onclick="mailTocheCheckboxChange();" disabled="disabled">0 - ' . $lang['srv_userstatus_0'] . '</label></span><br/>';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="1" type="checkbox" id="mailto_status_1" onclick="mailTocheCheckboxChange();" disabled="disabled">1 - ' . $lang['srv_userstatus_1'] . '</label></span><br/>';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="2" type="checkbox" id="mailto_status_2" onclick="mailTocheCheckboxChange();" disabled="disabled">2 - ' . $lang['srv_userstatus_2'] . '</label></span><br/>';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="3" type="checkbox" id="mailto_status_3" onclick="mailTocheCheckboxChange();" disabled="disabled">3 - ' . $lang['srv_userstatus_3'] . '</label></span><br/>';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="4" type="checkbox" id="mailto_status_4" onclick="mailTocheCheckboxChange();" disabled="disabled">4 - ' . $lang['srv_userstatus_4'] . '</label></span><br/>';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="5" type="checkbox" id="mailto_status_5" onclick="mailTocheCheckboxChange();" disabled="disabled">5 - ' . $lang['srv_userstatus_5'] . '</label></span><br/>';
+ echo '<span class="inv_send_span shift gray"><label><input name="mailto_status[]" value="6" type="checkbox" id="mailto_status_6" onclick="mailTocheCheckboxChange();" disabled="disabled">6 - ' . $lang['srv_userstatus_6'] . '</label></span><br/>';
+ echo '</div>';
+ echo '</span>'; // inv_select_mail_to
+ }
+ }
+
+ function selectSendTo($send_type = 0, $checkboxes = array()) {
+ global $lang, $site_url, $global_user_id;
+
+ if ((int)$this->surveySettings['active'] !== 1) {
+
+ $activity = SurveyInfo:: getSurveyActivity();
+ $_last_active = end($activity);
+
+ echo $lang['srv_inv_error9'];
+ echo '<a href="#" onclick="anketa_active(\'' . $this->sid . '\',\'' . (int)$this->surveySettings['active'] . '\'); return false;" title="' . $lang['srv_anketa_noactive'] . '">';
+ if ((int)$_last_active > 0 ) {
+ # anketa je zaključena
+ echo ' <span id="srv_inactive">'.$lang['srv_inv_activate_survey_here'].'</span>';
+ } else {
+ # anketa je neaktivna
+ echo ' <span id="srv_inactive">'.$lang['srv_inv_activate_survey_here'].'</span>';
+ }
+ echo '</a>';
+ }
+ # anketa je aktivna lahko pošiljamo
+ else {
+
+ // Preverimo ce je vklopljen modul za volitve - obvestilo, da ni naknadnega posiljanja
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ echo '<p class="bold red">'.$lang['srv_voting_no_duplicates'].'</p>';
+ }
+
+ $sql_string = "SELECT comment FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'";
+ $sql_query = sisplet_query($sql_string);
+ list($comment) = mysqli_fetch_row($sql_query);
+
+ $_msg = '<span>'.$lang['srv_invitation_note3'].'</span>';
+ if (isset($_POST['send_type'])) {
+ $send_type = (int)$_POST['send_type'];
+ }
+ $checkboxes = array();
+ if (isset($_POST['checkboxes']) && trim($_POST['checkboxes']) != '') {
+ $checkboxes = explode(',',$_POST['checkboxes']);
+ }
+
+ $source_type = (int)$_POST['source_type'];
+ $source_lists = trim($_POST['source_lists']);
+
+ $respondents = $this->getRespondents2Send($send_type, $checkboxes, $source_type, $source_lists);
+ #koliko strani imamp
+ $numRespondents = count($respondents);
+ $pages = ceil($numRespondents / $this->rec_send_page_limit);
+ if (count($respondents) > 0) {
+
+ echo '<div class="inv_send_mail_send_type">';
+
+ // Način pošiljanja
+ echo '<span class="bold">';
+ echo $lang['srv_inv_message_type'].': ';
+ echo $lang['email'];
+ echo '</span><br /><br />';
+
+ echo '<form id="frm_do_send" action="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=send_mail" method="post">';
+
+ // Komentar pri posiljanju
+ echo '<label>'.$lang['srv_inv_send_comment'].' '.Help::display('srv_inv_sending_comment').': ';
+ echo '<input type="text" name="comment" id="msg_comment" value="'.$comment.'">';
+ echo '</label><br class="clr"><br />';
+
+ // Pobrisi podvojene maile
+ echo '<label><input type="checkbox" id="dont_send_duplicated" name="dont_send_duplicated" checked="checked">'.$lang['srv_inv_send_remove_duplicates'].'</label></span> '.Help::display('srv_inv_sending_double').'<br />';
+
+ // Gumb Poslji
+ echo '<br /><div id="inv_send_mail_btn"><span class="buttonwrapper floatLeft"><a href="#" onclick="$(\'#fade\').fadeTo(\'slow\', 1); $(\'#inv_send_note\').fadeTo(\'slow\',1); $(\'#frm_do_send\').submit();" class="ovalbutton ovalbutton_orange" ><span>'.$lang['srv_inv_send'].'</span></a></span>';
+ echo '<br class="clr"/><br /></div>';
+
+ // Komentiram kot workaround (če ni zakomentiran, ob ajaxu tu vrine konec forme) - MISLIM DA JE TA POPRAVEK ŠE VEDNO POTREBEN (v kombinaciji z Robertovim)
+ //echo '</div>';
+
+ // Seznam mailov na katere bomo poslali
+ if ((int)$this->invitationAdvancedConditionId > 0)
+ {
+ //if (is_array($this->user_inv_ids) && count($this->user_inv_ids) > 0)
+ {
+ echo '<span class="floatLeft">';
+ $scp = new SurveyCondition($this->sid);
+ $note = $scp -> getConditionString($this->invitationAdvancedConditionId );
+ echo $note;
+ #$scp -> displayConditionNote($this->invitationAdvancedConditionId );
+ echo '</span>';
+ echo '<br/>';
+ }
+ }
+ # izpišemo seznam e-mailov in dodamo checkboxe
+ echo '<div class="strong">'.$lang['srv_inv_potencial_respondents'].'&nbsp;<span id="inv_num_recipients">'.count($respondents).'</span></div>';
+
+ # izpišemo opozorilo kadar pošiljamo na več kakor 5000 naslovov
+ $text = (Common::checkModule('gorenje')) ? $lang['srv_inv_potencial_respondents_limit_gorenje'] : $lang['srv_inv_potencial_respondents_limit'];
+ echo '<div id="inv_send_mail_limit" class="red strong'.(count($respondents) > 4999?'':' hidden').'">'.$text.'</div>';
+
+ echo '<input type="hidden" name="anketa" id="anketa" value="'.$this->sid.'">';
+ # da preprečimo večkratno pošiljanje
+ session_start();
+ list($short,$long) = $this->generateCode();
+ $_SESSION['snd_inv_token'][$this->sid] = $long;
+ echo '<input type="hidden" name="_token" id="_token" value="'.$long.'">';
+ if ($pages > 1 || $numRespondents > REC_ON_SEND_PAGE) {
+ echo '<div id="inv_pagination_content">';
+ $this->displaySendPagination($numRespondents);
+ echo '</div>';
+ }
+
+ # polovimo sezname
+ $lists = array();
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."')";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $lists[$sql_row['pid']] = $sql_row['name'];
+ }
+
+ $lists['-1'] = $lang['srv_invitation_new_templist'];
+ $lists['0'] = $lang['srv_invitation_new_templist_author'];
+
+ echo '<div id="inv_send_note">Pošiljam . . . Prosimo počakajte.</div>';
+
+ echo '<br/><table id="tbl_recipients_send_list">';
+ echo '<tr>';
+ echo '<th class="tbl_icon"><input type="checkbox" checked="checked" onclick="invTogleSend(this);">'.'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_email'].'">'.$lang['srv_inv_recipients_email'].'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_last_status'].'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_list_id'].'</th>';
+ echo '</tr>';
+ $cnt=1;
+ foreach ($respondents as $pass => $respondent) {
+ echo '<tr'.($cnt > $this->rec_send_page_limit ? ' class="displayNone"' : '').'>';
+ echo '<td><input type="checkbox" name="rids[]" value="'.$respondent['id'].'" checked="checekd"></td>';
+ echo '<td>'.$respondent['email'].'</td>';
+ echo '<td>'.$lang['srv_userstatus_'.$respondent['status']].' ('.$respondent['status'].')'.'</td>';
+ if ($lists[$respondent['list_id']] != '') {
+ echo '<td>'.$lists[$respondent['list_id']].'</td>';
+ } else {
+ echo '<td>'.$lang['srv_inv_send_who_table_list_deleted'].'</td>';
+ }
+ echo '</tr>';
+ $cnt++;
+ }
+ echo '</table>';
+ echo '</form>';
+ echo '</div>';
+ }
+ }
+ if ($cnt == 0) {
+ # ni respondentov
+ echo $_msg;
+ }
+ }
+
+ function selectSendToNoEmailing($send_type = 0, $checkboxes = array()) {
+ global $lang, $site_url, $global_user_id;
+
+ if ((int)$this->surveySettings['active'] !== 1) {
+ #anketa ni aktivna, ne pustimo pošiljanja
+ # aktivnost
+
+ $activity = SurveyInfo:: getSurveyActivity();
+ $_last_active = end($activity);
+
+ echo $lang['srv_inv_error9'];
+ echo '<a href="#" onclick="anketa_active(\'' . $this->sid . '\',\'' . (int)$this->surveySettings['active'] . '\'); return false;" title="' . $lang['srv_anketa_noactive'] . '">';
+ if ((int)$_last_active > 0 ) {
+ # anketa je zaključena
+ echo ' <span id="srv_inactive">'.$lang['srv_inv_activate_survey_here'].'</span>';
+ } else {
+ # anketa je neaktivna
+ echo ' <span id="srv_inactive">'.$lang['srv_inv_activate_survey_here'].'</span>';
+ }
+ echo '</a>';
+ } else {
+ # anketa je aktivna lahko pošiljamo
+
+ $sql_string = "SELECT comment FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'";
+ $sql_query = sisplet_query($sql_string);
+ list($comment) = mysqli_fetch_row($sql_query);
+
+ $_msg = '<span>'.$lang['srv_invitation_note3'].'</span>';
+ if (isset($_POST['send_type'])) {
+ $send_type = (int)$_POST['send_type'];
+ }
+ $checkboxes = array();
+ if (isset($_POST['checkboxes']) && trim($_POST['checkboxes']) != '') {
+ $checkboxes = explode(',',$_POST['checkboxes']);
+ }
+
+ $source_type = (int)$_POST['source_type'];
+ $source_lists = trim($_POST['source_lists']);
+
+ $respondents = $this->getRespondents2Send($send_type, $checkboxes, $source_type, $source_lists, $noEmailing=1);
+ #koliko strani imamp
+ $numRespondents = count($respondents);
+ $pages = ceil($numRespondents / $this->rec_send_page_limit);
+ if (count($respondents) > 0) {
+
+ echo '<div class="inv_send_mail_send_type">';
+
+ // Način pošiljanja
+ $noEmailingType = SurveySession::get('inv_noEmailing_type');
+ echo '<span class="bold">';
+ echo $lang['srv_inv_message_type_external'].': </span>';
+ if($noEmailingType == 1)
+ echo $lang['srv_inv_message_noemailing_type2'];
+ elseif($noEmailingType == 2)
+ echo $lang['srv_inv_message_noemailing_type3'];
+ else
+ echo $lang['srv_inv_message_noemailing_type1'];
+ echo '<br /><br />';
+
+ echo '<form id="frm_do_send" action="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=send_mail&noemailing=1" method="post">';
+
+ // Komentar pri posiljanju
+ echo '<label>'.$lang['srv_inv_send_comment'].' '.Help::display('srv_inv_sending_comment').': ';
+ echo '<input type="text" name="comment" id="msg_comment" value="'.$comment.'">';
+ echo '</label><br class="clr"><br />';
+
+ // Pobrisi podvojene maile
+ echo '<label><input type="checkbox" id="dont_send_duplicated" name="dont_send_duplicated" checked="checked">'.$lang['srv_inv_send_remove_duplicates'].'</label></span> '.Help::display('srv_inv_sending_double').'<br />';
+
+ // Gumb poslji
+ echo '<br /><div id="inv_send_mail_btn"><span class="buttonwrapper floatLeft"><a href="#" onclick="$(\'#fade\').fadeTo(\'slow\', 1); $(\'#inv_send_note\').fadeTo(\'slow\',1); $(\'#frm_do_send\').submit();" class="ovalbutton ovalbutton_orange" ><span>'.$lang['srv_inv_nav_send_noEmailing'].'</span></a></span>';
+ echo '<br class="clr"/><br /></div>';
+
+ echo '</div>';
+
+ // Seznam mailov na katere bomo poslali
+ if ((int)$this->invitationAdvancedConditionId > 0)
+ {
+ #if (is_array($this->user_inv_ids) && count($this->user_inv_ids) > 0)
+ {
+ echo '<span class="floatLeft">';
+ $scp = new SurveyCondition($this->sid);
+ $note = $scp -> getConditionString($this->invitationAdvancedConditionId );
+ echo $note;
+ #$scp -> displayConditionNote($this->invitationAdvancedConditionId );
+ echo '</span>';
+ echo '<br/>';
+ }
+ }
+ # izpišemo seznam e-mailov in dodamo checkboxe
+ echo '<div class="strong">'.$lang['srv_inv_potencial_respondents'].'&nbsp;<span id="inv_num_recipients">'.count($respondents).'</span></div>';
+
+ # izpišemo opozorilo kadar pošiljamo na več kakor 5000 naslovov
+ $text = (Common::checkModule('gorenje')) ? $lang['srv_inv_potencial_respondents_limit_gorenje'] : $lang['srv_inv_potencial_respondents_limit'];
+ echo '<div id="inv_send_mail_limit" class="red strong'.(count($respondents) > 4999?'':' hidden').'">'.$text.'</div>';
+
+ echo '<input type="hidden" name="anketa" id="anketa" value="'.$this->sid.'">';
+ # da preprečimo večkratno pošiljanje
+ session_start();
+ list($short,$long) = $this->generateCode();
+ $_SESSION['snd_inv_token'][$this->sid] = $long;
+ echo '<input type="hidden" name="_token" id="_token" value="'.$long.'">';
+ if ($pages > 1 || $numRespondents > REC_ON_SEND_PAGE) {
+ echo '<div id="inv_pagination_content">';
+ $this->displaySendPagination($numRespondents);
+ echo '</div>';
+ }
+
+ # polovimo sezname
+ $lists = array();
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."')";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $lists[$sql_row['pid']] = $sql_row['name'];
+ }
+
+ $lists['-1'] = $lang['srv_invitation_new_templist'];
+ $lists['0'] = $lang['srv_invitation_new_templist_author'];
+
+ echo '<div id="inv_send_note">Pošiljam . . . Prosimo počakajte.</div>';
+
+ echo '<br/><table id="tbl_recipients_send_list">';
+ echo '<tr>';
+ echo '<th class="tbl_icon"><input type="checkbox" checked="checked" onclick="invTogleSend(this);">'.'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_email'].'">'.$lang['srv_inv_recipients_email'].'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_firstname'].'">'.$lang['srv_inv_recipients_firstname'].'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_last_status'].'</th>';
+ echo '<th title="'.$lang['srv_inv_recipients_last_status'].'">'.$lang['srv_inv_recipients_list_id'].'</th>';
+ echo '</tr>';
+ $cnt=1;
+ foreach ($respondents as $pass => $respondent) {
+ echo '<tr'.($cnt > $this->rec_send_page_limit ? ' class="displayNone"' : '').'>';
+ echo '<td><input type="checkbox" name="rids[]" value="'.$respondent['id'].'" checked="checekd"></td>';
+ echo '<td>'.$respondent['email'].'</td>';
+ echo '<td>'.$respondent['firstname'].'</td>';
+ echo '<td>'.$lang['srv_userstatus_'.$respondent['status']].' ('.$respondent['status'].')'.'</td>';
+ if ($lists[$respondent['list_id']] != '') {
+ echo '<td>'.$lists[$respondent['list_id']].'</td>';
+ } else {
+ echo '<td>'.$lang['srv_inv_send_who_table_list_deleted'].'</td>';
+ }
+ echo '</tr>';
+ $cnt++;
+ }
+ echo '</table>';
+ echo '</form>';
+ }
+ }
+ if ($cnt == 0) {
+ # ni respondentov
+ echo $_msg;
+ }
+ }
+
+ function mailToSourceChange() {
+ $this->displayMailToSourceLists((int)$_POST['source_type']);
+ }
+
+ function viewAarchive() {
+ global $lang;
+
+ echo '<div id="div_archive_content">';
+
+ #preglej prejemnike
+ #echo '<h2>'.$lang['srv_inv_heading_step5'].$lang['srv_inv_archive_heading'].'</h2>';
+ //echo '<h2>'.$lang['srv_inv_archive_heading'].'</h2>';
+
+ # normalno pošiljanje
+ $sql_string = "SELECT sia.*, u.name, u.surname, u.email, DATE_FORMAT(sia.date_send,'%d.%m.%Y') AS ds, DATE_FORMAT(sia.date_send,'%T') AS hs FROM srv_invitations_archive AS sia LEFT JOIN users AS u ON sia.uid = u.id WHERE ank_id = '".$this->sid."' ORDER BY sia.date_send DESC;";
+ $sql_query = sisplet_query($sql_string);
+
+ # enostavno pošiljanje na posamezne maile
+ $SSMI = new SurveySimpleMailInvitation($this->sid);
+ $simple_recipents = $SSMI -> getRecipients();
+
+ if (mysqli_num_rows($sql_query) > 0 || count($simple_recipents) > 0) {
+
+ echo '<h2>'.$lang['srv_archive_invitation'].'</h2>';
+
+ echo '<table id="tbl_archive_list">';
+ echo '<tr>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_date_send'].'">'.$lang['srv_inv_archive_date_send'].'</th>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_hour_send'].'">'.$lang['srv_inv_archive_hour_send'].'</th>';
+ echo '<th title="'.$lang['srv_inv_archive_subject_text'].'">'.$lang['srv_inv_archive_naslov'].'</th>';
+ echo '<th title="'.$lang['srv_inv_archive_subject_text'].'">'.$lang['srv_inv_archive_subject_text'].'</th>';
+ #echo '<th title="'.$lang['srv_inv_archive_body_text'].'">'.$lang['srv_inv_archive_body_text'].'</th>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_message_type'].'">'.$lang['srv_inv_message_type'].'</th>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_cnt_succsess'].'">'.$lang['srv_inv_archive_cnt_succsess'].' '.Help::display('srv_inv_archive_sent').'</th>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_cnt_error'].'">'.$lang['srv_inv_archive_cnt_error'].'</th>';
+ echo '<th title="'.$lang['srv_inv_archive_sender'].'">'.$lang['srv_inv_archive_sender'].'</th>';
+ echo '<th title="'.$lang['srv_inv_archive_comment'].'">'.$lang['srv_inv_archive_comment'].'</th>';
+ #echo '<th >&nbsp;</th>';
+ echo '</tr>';
+ while ($row = mysqli_fetch_assoc($sql_query)) {
+ echo '<tr>';
+
+ // Datum
+ echo '<td class="tbl_inv_center">'.$row['ds'].'</td>';
+
+ // Ura
+ echo '<td class="tbl_inv_center">'.$row['hs'].'</td>';
+
+ // Email sporocilo
+ echo '<td class="tbl_inv_lef inv_arch_subject" title="'.$row['naslov'].'">';
+ echo '<a href="#" onclick="inv_arch_edit_details(\''.$row['id'].'\'); return false;">'.$row['naslov'].'</a>';
+ echo '</td>';
+
+ // Subject
+ echo '<td class="tbl_inv_lef inv_arch_subject" title="'.$row['naslov'].'">';
+ echo $row['subject_text'];
+ echo '</td>';
+ #echo '<td class="tbl_inv_left inv_arch_text" title="'.$row['body_text'].'">'.$row['body_text'].'</td>';
+
+ // Nacin posiljanja (email, posta, sms...)
+ echo '<td class="tbl_inv_center">';
+ if ($row['tip'] == '0')
+ echo '<span>'.$lang['srv_inv_message_noemailing_type1'].'</span>';
+ elseif($row['tip'] == '1')
+ echo '<span>'.$lang['srv_inv_message_noemailing_type2'].'</span>';
+ elseif($row['tip'] == '2')
+ echo '<span>'.$lang['srv_inv_message_noemailing_type3'].'</span>';
+ else
+ echo '<span>'.$lang['email'].'</span>';
+ echo '</td>';
+
+ # uspešno poslani
+ echo '<td class="tbl_inv_center">';
+ if ((int)$row['cnt_succsess'] > 0 ) {
+ echo '<span class="as_link as_view strong" id="inv_arch_1_'.$row['id'].'" data-archtype="succ">'.$row['cnt_succsess'].'</span>';
+ } else {
+ echo '<span>'.$row['cnt_succsess'].'</span>';
+ }
+ echo '</td>';
+
+ # neuspešno poslani
+ echo '<td class="tbl_inv_center">';
+ if ((int)$row['cnt_error'] > 0 ) {
+ echo '<span class="as_link as_view strong" id="inv_arch_0_'.$row['id'].'" data-archtype="err">'.$row['cnt_error'].'</span>';
+ } else {
+ echo '<span>'.$row['cnt_error'].'</span>';
+ }
+ echo '</td>';
+
+ # poslal
+ $avtor = array();
+ if (trim($row['name'])) {
+ $avtor[] = trim ($row['name']);
+ }
+ if (trim($row['surname'])) {
+ $avtor[] = trim ($row['surname']);
+ }
+
+ echo '<td>';
+ echo '<span title="'.(isset($row['email']) ? $row['email'] : implode(' ',$avtor)).'">'.implode(' ',$avtor).'</span>';
+ echo '</td>';
+
+ # komentar
+ echo '<td>';
+ echo '<a href="#" onclick="inv_arch_edit_details(\''.$row['id'].'\'); return false;">'.$row['comment'];
+ echo '</td>';
+
+ echo '</tr>';
+ }
+ echo '</tr>';
+ echo '</table>';
+
+ # dodamo simpl pošiljanje
+ if ( count($simple_recipents) > 0 ) {
+ if (mysqli_num_rows($sql_query) > 0) {
+ echo '<br>';
+ echo '<br>';
+ }
+ echo '<b>Prejemniki enostavnih email vabil:</b>';
+ echo '<br>';
+ echo '<br>';
+ echo '<table id="tbl_archive_list">';
+ echo '<tr>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_date_send'].'">'.$lang['srv_inv_archive_date_send'].'</th>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_email_address'].'">'.$lang['srv_inv_archive_email_address'].'</th>';
+ echo '<th class="tbl_inv_center" title="'.$lang['srv_inv_archive_status'].'">'.$lang['srv_inv_archive_status'].'</th>';
+ echo '<th title="'.$lang['srv_inv_archive_sender'].'">'.$lang['srv_inv_archive_sender'].'</th>';
+ echo '</tr>';
+ foreach ($simple_recipents as $row) {
+ echo '<tr>';
+ echo '<td>'.$row['send_time'].'</td>';
+ echo '<td>'.$row['email'].'</td>';
+ echo '<td class="tbl_inv_center">'.$row['state'].'</td>';
+ # poslal
+ $avtor = array();
+ if (trim($row['name'])) {
+ $avtor[] = trim ($row['name']);
+ }
+ if (trim($row['surname'])) {
+ $avtor[] = trim ($row['surname']);
+ }
+ echo '<td>';
+ echo '<span title="'.(isset($row['adminmail']) ? $row['adminmail'] : implode(' ',$avtor)).'">'.implode(' ',$avtor).'</span>';
+ echo '</td>';
+
+ echo '</tr>';
+ }
+ echo '</table>';
+ }
+
+ } else {
+ echo '<fieldset>';
+ echo '<legend>'.$lang['srv_archive_invitation'].'</legend>';
+
+ echo $lang['srv_invitation_note4'].'';
+
+ echo '</fieldset>';
+ }
+
+
+
+ echo '</div>'; # id="div_archive_content">';
+ echo '<br class="clr">';
+
+ }
+
+
+ // Glavno posiljanje mail vabil
+ function sendMail() {
+ global $lang, $site_path, $site_url, $global_user_id, $lastna_instalacija;
+
+ Common::getInstance()->Init($this->sid);
+
+ if (isset($_POST['rids'])) {
+
+ session_start();
+
+ # preverimo token, da ne pošiljamo večkrat
+ if (isset($_SESSION['snd_inv_token'][$this->sid])
+ && isset($_POST['_token'])
+ && $_SESSION['snd_inv_token'][$this->sid] != null
+ && $_SESSION['snd_inv_token'][$this->sid] == isset($_POST['_token'])){
+
+ // na send smo kliknili samo 1x
+ unset($_SESSION['snd_inv_token'][$this->sid]);
+
+ session_commit();
+
+ $dont_send_duplicated = false;
+ if (isset($_POST['dont_send_duplicated']) && $_POST['dont_send_duplicated'] == 'on') {
+ $dont_send_duplicated = true;
+ }
+
+ $rids = $_POST['rids'];
+
+ $return = array();
+ $return['error'] = '0';
+ $return['msg'] = '<div class="inv_send_message">'.$lang['srv_invitation_note5'].'</div>';
+
+ // Shranimo komentar h posiljanju
+ if(isset($_POST['comment']) && $_POST['comment'] != ''){
+ $comment = $_POST['comment'];
+ $sqlC = sisplet_query("UPDATE srv_invitations_messages SET comment='$comment' WHERE ank_id='$this->sid' AND isdefault='1'");
+ }
+
+ if ($this->checkDefaultMessage() == false) {
+ echo '<span class="inv_error_note">';
+ echo $lang['srv_invitation_note6'];
+ echo '</span>';
+
+ exit();
+ }
+ else {
+ // polovimo sporočilo in prejemnike
+ $sql_query_m = sisplet_query("SELECT id, subject_text, body_text, reply_to, isdefault, comment, naslov, url FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'");
+
+ if (mysqli_num_rows($sql_query_m) > 0 ) {
+ $sql_row_m = mysqli_fetch_assoc($sql_query_m);
+ }
+ else {
+ #nimamo še vsebine sporočila skreiramo privzeto.
+ echo '<span class="inv_error_note">';
+ echo $lang['srv_invitation_note6'];
+ echo '</span>';
+
+ exit();
+ }
+ }
+
+ $subject_text = $sql_row_m['subject_text'];
+ $body_text = $sql_row_m['body_text'];
+ $msg_url = $sql_row_m['url'];
+
+ // naslov za odgovor je avtor ankete
+ if ($this->validEmail($sql_row_m['reply_to'])) {
+ $reply_to = $sql_row_m['reply_to'];
+ }
+ else {
+ $reply_to = Common::getInstance()->getReplyToEmail();
+ }
+
+
+ // prejeminki besedila
+ $sql_query = sisplet_query("SELECT id, firstname, lastname, email, password, password, cookie, phone, salutation, custom, relation
+ FROM srv_invitations_recipients
+ WHERE ank_id = '".$this->sid."' AND deleted='0' AND id IN (".implode(',',$rids).")
+ ORDER BY id
+ ");
+
+ # zloopamo skozi prejemnike in personaliziramo sporočila in jih pošljemo
+ $date_sent = date ("Y-m-d H:i:s");
+
+ $numRows = mysqli_num_rows($sql_query);
+
+ # če pošiljamo na večje število reposndentov obvestimo info@1ka.si
+ if ($numRows > NOTIFY_INFO1KA && (!isset($lastna_instalacija) || $lastna_instalacija == false)) {
+
+ // Gorenje tega nima
+ if (!Common::checkModule('gorenje')){
+ global $site_url, $global_user_id;
+
+ $sqlinfo_query = sisplet_query("SELECT email, name, surname FROM users WHERE id = '".$global_user_id."'");
+ list($infoEmail,$infoName,$infoSurname) = mysqli_fetch_row($sqlinfo_query);
+
+ $infourl = '<a href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'">anketi</a>';
+ $format = $lang['srv_inv_send_finish_note'];
+
+ $info1ka_mass_email_note = sprintf($format, $infoName, $infoSurname, $infoEmail, $infourl, $numRows);
+
+ try{
+ $MA = new MailAdapter($this->sid, $type='admin');
+ $MA->addRecipients('info@1ka.si');
+ $resultX = $MA->sendMail($info1ka_mass_email_note, 'Masovno pošiljanje vabil (poslanih več kot '.NOTIFY_INFO1KA.')');
+ }
+ catch (Exception $e){
+ }
+ }
+ }
+
+ // Pripravimo arhiv pošiljanj, da dobimo arch_id
+ $sql_query_all = sisplet_query("SELECT count(*) FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0'");
+ list($count_all) = mysqli_fetch_row($sql_query_all);
+
+ $archive_naslov = 'mailing_'.date("d.m.Y").', '.date("H:i:s");
+ $sqlQuery = sisplet_query("INSERT INTO srv_invitations_archive
+ (id, ank_id, date_send, subject_text, body_text, uid, comment, naslov, rec_in_db)
+ VALUES
+ (NULL , '$this->sid', '$date_sent', '".addslashes($subject_text)."', '".addslashes($body_text)."', '$global_user_id','$comment','$archive_naslov','$count_all')
+ ");
+
+ $arch_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ // Podatki posiljatelja
+ list($name, $surname, $email) = mysqli_fetch_row(sisplet_query("SELECT name, surname, email FROM users WHERE id='$global_user_id'"));
+
+ // Podatki za posiljanje
+ $sending_data = array(
+ 'body_text' => $body_text,
+ 'subject_text' => $subject_text,
+ 'arch_id' => $arch_id,
+ 'msg_url' => $msg_url,
+ 'date_sent' => $date_sent,
+ 'from_email' => $email,
+ 'from_name' => $name.' '.$surname,
+ 'reply_to_email' => $reply_to
+ );
+
+ // Loop po prejemnikih in posiljanje mailov
+ $squalo = new SurveyInvitationsSqualo($this->sid);
+ if($squalo->getSqualoActive()){
+ $sending_results = $squalo->sendSqualoInvitations($sql_query, $sending_data);
+ }
+ else{
+ $sending_results = $this->sendMailToUsers($sql_query, $sending_data);
+ }
+
+ $send_ok = $sending_results['send_ok'];
+ $send_ok_ids = $sending_results['send_ok_ids'];
+ $send_users_data = $sending_results['send_users_data'];
+ $send_error = $sending_results['send_error'];
+ $send_error_ids = $sending_results['send_error_ids'];
+
+
+ // dodajmo še userje v povezovalno tabelo (arhiv)
+ if ($arch_id > 0) {
+
+ // updejtamo še tabelo arhivov
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_archive SET cnt_succsess='".count($send_ok_ids)."', cnt_error='".count($send_error_ids)."' WHERE id ='$arch_id'");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // za arhive
+ $_archive_recipients = array();
+
+ // za tracking
+ $_tracking = array();
+
+ if (count($send_ok_ids) > 0) {
+ foreach ( $send_ok_ids AS $id) {
+ $_archive_recipients[] = "('$arch_id','$id','1')";
+ #status 1=pošta poslana
+ $_tracking[] = "('$arch_id',NOW(),'$id','1')";
+ }
+ }
+
+ if (count($send_error_ids) > 0) {
+ foreach ( $send_error_ids AS $id) {
+ $_archive_recipients[] = "('$arch_id','$id','0')";
+ #status 2=pošta - napaka
+ $_tracking[] = "('$arch_id',NOW(),'$id','2')";
+ }
+ }
+
+ if (count($_archive_recipients) > 0) {
+ $sqlString = 'INSERT INTO srv_invitations_archive_recipients (arch_id,rec_id,success) VALUES ';
+ $sqlString .= implode(', ', $_archive_recipients);
+ $sqlQuery = sisplet_query($sqlString);
+ }
+
+ if (count($_tracking) > 0) {
+ $sqlStrTracking = "INSERT INTO srv_invitations_tracking (inv_arch_id, time_insert, res_id, status) VALUES ";
+ $sqlStrTracking .= implode(', ', $_tracking);
+ $sqlQueryTracking = sisplet_query($sqlStrTracking);
+ }
+ }
+
+
+ // Izpis rezultatov - errors and successes
+ if (count($send_error) > 0 ) {
+ $return['error'] = '1';
+
+ $return['msg'] = '<div class="inv_send_message">'.$lang['srv_invitation_note7'].count($send_error).'</div>';
+ }
+ else if (count($send_ok) > 0 ) {
+
+ $who='';
+
+ if (trim($name) != '') {
+ $who = $name;
+ }
+
+ if (trim($surname) != '') {
+ if ($who != '') {
+ $who .=' ';
+ }
+ $who .= $surname;
+ }
+
+ if ($email != '') {
+ if ($who != '') {
+ $who .=' ('.$email.')';
+ } else {
+ $who = $email;
+ }
+ }
+
+ $return['error'] = '0';
+
+ // Uspesno poslano sporocilo
+ $return['msg'] = '<br /><span class="bold" style="line-height:30px;">'.$lang['srv_invitation_note8a'].'</span><br />';
+ $return['msg'] .= '<div class="inv_send_message">';
+ $return['msg'] .= '<table id="inv_send_mail_preview">';
+ $return['msg'] .= '<tr><th><span>'.$lang['srv_inv_message_draft_content_subject'].':</span></th>';
+ $return['msg'] .= '<td class="inv_bt">';
+ $return['msg'] .= '<span>'.$sql_row_m['subject_text'].'</span>';
+ $return['msg'] .= '</td></tr>';
+ $return['msg'] .= '<tr><th>'.$lang['srv_inv_message_draft_content_body'].':</th>';
+ $return['msg'] .= '<td>';
+ $return['msg'] .= '<span class="nl2br">'.($sql_row_m['body_text']).'</span>';
+ $return['msg'] .= '</td></tr>';
+ $return['msg'] .= '</table>';
+ $return['msg'] .= '</div>';
+
+ // Je uporabnik poslal na ...
+ $return['msg'] .= sprintf($lang['srv_invitation_note8b'], $who, date("d.m.y", time()));
+ $return['msg'] .= '<span class="bold" style="line-height:30px;">'.sprintf($lang['srv_invitation_note8'], count($send_ok)).'</span><br />';
+
+ // Arhivi
+ $return['msg'] .= '<span class="bold" style="line-height:20px;">'.sprintf($lang['srv_invitation_note8c'], $site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=view_archive').'</span><br />';
+
+ // Seznam emailov...
+ $return['msg'] .= '<span class="bold" style="line-height:30px;">'.$lang['srv_invitation_note8d'].'</span><br />';
+
+ // Seznam mailov na katere je bilo uspesno poslano
+ if (count($send_ok) > 0) {
+ $return['msg'] .= '<div class="inv_send_message">';
+
+ foreach ($send_ok AS $email) {
+ $return['msg'] .= '&nbsp;'.$email.'<br/>';
+ }
+
+ $return['msg'] .= '</div>';
+ }
+ }
+ else {
+ $return['error'] = '0';
+ $return['msg'] = '<div class="inv_send_message">'.'<strong>'.$lang['srv_invitation_note9'].'</strong></div><br/>';
+ }
+ }
+ else {
+ #old session token
+ $return['msg'] = '<div class="inv_send_message"><span class="red strong">'.$lang['srv_invitation_note13'].'</span>'.'</div>';
+ }
+ }
+ else {
+ #nimamo $rids
+ $return['msg'] = '<div class="inv_send_message">'.$lang['srv_invitation_note14'].'</div>';
+ }
+
+ # popravimo timestamp za regeneracijo dashboarda
+ Common::getInstance()->Init($anketa);
+ Common::getInstance()->updateEditStamp();
+
+ #$this->viewAarchive($return['msg']);
+ $this->viewSendMailFinish($return['msg']);
+ }
+
+ // Posljemo mail userjem - loop in send
+ private function sendMailToUsers($sql_recipients_query, $sending_data){
+ global $global_user_id;
+ global $site_url;
+
+
+ // Preverimo ce je vklopljen modul za volitve
+ $voting = SurveyInfo::getInstance()->checkSurveyModule('voting');
+
+ # če mamo SEO
+ $nice_url = SurveyInfo::getSurveyLink();
+
+ // Polovimo sistemske spremenljivke
+ $sys_vars = $this->getSystemVars();
+
+ # zakeširamo user_id za datapiping
+ $arryDataPiping = array();
+ $qryDataPiping = sisplet_query("SELECT id, inv_res_id FROM srv_user WHERE ank_id='$this->sid' AND inv_res_id IS NOT NULL");
+ while (list($dpUid, $dpInvResId) = mysqli_fetch_row($qryDataPiping)) {
+
+ if ((int)$dpInvResId > 0 && (int)$dpUid > 0) {
+ $arryDataPiping[$dpInvResId] = (int)$dpUid;
+ }
+ }
+
+ $duplicated = array();
+
+ # array za rezultate
+ $send_ok = array();
+ $send_ok_ids = array();
+ $send_users_data = array();
+ $send_error = array();
+ $send_error_ids = array();
+
+ // Loop po prejemnikih
+ while ($sql_row = mysqli_fetch_assoc($sql_recipients_query)) {
+
+ $password = $sql_row['password'];
+
+ $email = $sql_row['email'];
+
+ // Preverimo ce je duplikat
+ if ($dont_send_duplicated == true && isset($duplicated[$email])) {
+ $duplicated[$email] ++;
+ continue;
+ }
+
+ $duplicated[$email] = 1;
+
+ $individual = (int)$this->surveySettings['individual_invitation'];
+
+ if ( ($individual == 1 && trim($email) != '' && trim($password) != '') || ($individual == 0 && trim($email) != '') ){
+
+ // odvisno ali imamo url za jezik.
+ if ($sending_data['msg_url'] != null && trim($sending_data['msg_url']) != '' ) {
+ $url = $sending_data['msg_url'] . ($individual == 1 ? '?code='.$password : '');
+ }
+ else {
+ $url = $nice_url . ($individual == 1 ? '&code='.$password : '');
+ }
+
+ $url .= '&ai='.(int)$sending_data['$arch_id'];
+
+ // odjava
+ $unsubscribe = $site_url . 'admin/survey/unsubscribe.php?anketa=' . $this->sid . '&code='.$password;
+
+ $user_body_text = str_replace(
+ array(
+ '#URL#',
+ '#URLLINK#',
+ '#UNSUBSCRIBE#',
+ '#FIRSTNAME#',
+ '#LASTNAME#',
+ '#EMAIL#',
+ '#CODE#',
+ '#PASSWORD#',
+ '#PHONE#',
+ '#SALUTATION#',
+ '#CUSTOM#',
+ '#RELATION#',
+ ),
+ array(
+ '<a href="' . $url . '">' . $url . '</a>',
+ $url,
+ '<a href="' . $unsubscribe . '">' . $lang['user_bye_hl'] . '</a>',
+ $sql_row['firstname'],
+ $sql_row['lastname'],
+ $sql_row['email'],
+ $sql_row['password'],
+ $sql_row['password'],
+ $sql_row['phone'],
+ $sql_row['salutation'],
+ $sql_row['custom'],
+ $sql_row['relation'],
+ ),
+ $sending_data['body_text']
+ );
+
+
+ // naredimo DataPiping;
+ if (isset($arryDataPiping[$sql_row['id']])) {
+ $user_body_text = Common::getInstance()->dataPiping($user_body_text, $arryDataPiping[$sql_row['id']], 0);
+ }
+ $resultX = null;
+
+ try{
+ $MA = new MailAdapter($this->sid, $type='invitation');
+ $MA->addRecipients($email);
+ $resultX = $MA->sendMail($user_body_text, $sending_data['subject_text']);
+
+ }
+ catch (Exception $e){
+ // todo fajn bi bilo zalogirat kaj se dogaja
+ $__error = $e->getMessage();
+ $__errStack = $e->getTraceAsString();
+ }
+
+ $_user_data = $sql_row;
+ if ($resultX) {
+ $send_ok[] = $email;
+ $send_ok_ids[] = $sql_row['id'];
+ $_user_data['status'] = 1;
+ # poslalo ok
+ }
+ else {
+ // ni poslalo
+ $send_error[] = $email;
+ $send_error_ids[] = $sql_row['id'];
+ $_user_data['status'] = 2;
+ }
+
+ $send_users_data[] = $_user_data;
+
+
+ // updejtamo userja da mu je bilo poslano - PO NOVEM TO DELAMO SPROTI
+ if ( count($send_ok_ids) > 0) {
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET sent='1', date_sent='".$sending_data['date_sent']."' WHERE id IN (".implode(',',$send_ok_ids).")");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // statuse popravimo samo če vabilo še ni bilo poslano ali je bila napaka
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET last_status='1' WHERE id IN (".implode(',',$send_ok_ids).") AND last_status IN ('0','2')");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // Pri volitvah za sabo pobrisemo podatke preko katerih bi lahko povezali prejemnike z responsi
+ if($voting){
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients
+ SET cookie='', password=''
+ WHERE id IN (".implode(',',$send_ok_ids).") AND sent='1' AND last_status='1' AND ank_id='".$this->sid."'
+ ");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+ # updejtamo status za errorje
+ if ( count($send_error_ids) > 0) {
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET last_status = GREATEST(last_status,2) WHERE id IN (".implode(',',$send_error_ids).") AND last_status IN ('0')");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ // če mamo personalizirana email vabila, userje dodamo v bazo
+ if ($individual == 1) {
+
+ // dodamo še userja v srv_user da je kompatibilno s staro logiko
+ $strInsertDataText = array();
+ $strInsertDataVrednost = array();
+
+ // Pri volitvah zaradi anonimizacije ignoriramo vse identifikatorje
+ if($voting){
+ $_r = sisplet_query("INSERT INTO srv_user
+ (ank_id, cookie, pass, last_status, inv_res_id)
+ VALUES
+ ('".$this->sid."', '".$_user_data['cookie']."', '".$_user_data['password']."', '".$_user_data['status']."', '-1') ON DUPLICATE KEY UPDATE cookie = '".$_user_data['cookie']."', pass='".$_user_data['password']."'
+ ");
+
+ // Ce ne belezimo parapodatka za cas responsa, anonimno zabelezimo cas zadnjega responsa
+ sisplet_query("UPDATE srv_anketa SET last_response_time=NOW() WHERE id='".$this->sid."'");
+ }
+ else{
+ $_r = sisplet_query("INSERT INTO srv_user
+ (ank_id, email, cookie, pass, last_status, time_insert, inv_res_id)
+ VALUES
+ ('".$this->sid."', '".$_user_data['email']."', '".$_user_data['cookie']."', '".$_user_data['password']."', '".$_user_data['status']."', NOW(), '".$_user_data['id']."') ON DUPLICATE KEY UPDATE cookie = '".$_user_data['cookie']."', pass='".$_user_data['password']."'
+ ");
+ }
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($usr_id) {
+
+ // dodamo še srv_userbase in srv userstatus
+ sisplet_query("INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ('".$usr_id."','0',NOW(),'".$global_user_id."')");
+ sisplet_query("INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ('".$usr_id."', '0', '0', NOW())");
+
+ // dodamo še podatke za posameznega userja za sistemske spremenljivke
+ foreach ($sys_vars AS $sid => $spremenljivka) {
+
+ $_user_variable = $this->inv_variables_link[$spremenljivka['variable']];
+
+ if (trim($_user_data[$_user_variable]) != '' && $_user_data[$_user_variable] != null) {
+ if($spremenljivka['variable'] == 'odnos')
+ $strInsertDataVrednost[] = "('".$sid."','".$spremenljivka['vre_id'][trim($_user_data[$_user_variable])]."','".$usr_id."')";
+ else
+ $strInsertDataText[] = "('".$sid."','".$spremenljivka['vre_id']."','".trim($_user_data[$_user_variable])."','".$usr_id."')";
+ }
+ }
+ }
+ else {
+ // lahko da user že obstaja in je šlo za duplicated keys
+ }
+
+
+ // Pri volitvah zaradi anonimizacije ne vsatvimo nicesar v sistemske spremenljivke
+ if(!$voting){
+
+ // vstavimo v srv_data_text
+ if (count($strInsertDataText) > 0) {
+ $strInsert = "INSERT INTO srv_data_text".$this->db_table." (spr_id, vre_id, text, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataText);
+ sisplet_query($strInsert);
+ }
+ // vstavimo v srv_data_vrednost
+ if (count($strInsertDataVrednost) > 0) {
+ $strInsert = "INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataVrednost);
+ sisplet_query($strInsert);
+ }
+ }
+ }
+ }
+ }
+
+ $results = array(
+ 'send_ok' => $send_ok,
+ 'send_ok_ids' => $send_ok_ids,
+ 'send_users_data' => $send_users_data,
+ 'send_error' => $send_error,
+ 'send_error_ids' => $send_error_ids,
+ );
+
+ return $results;
+ }
+
+ private function getSystemVars(){
+
+ // polovimo sistemske spremenljivke z vrednostmi
+ $qrySistemske = sisplet_query("SELECT s.id, s.naslov, s.variable
+ FROM srv_spremenljivka s, srv_grupa g
+ WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".$this->sid."' AND variable IN ("."'" . implode("','",$this->inv_variables)."')
+ ORDER BY g.vrstni_red, s.vrstni_red
+ ");
+ $sys_vars = array();
+ $sys_vars_ids = array();
+
+ while ($row = mysqli_fetch_assoc($qrySistemske)) {
+ $sys_vars[$row['id']] = array('id'=>$row['id'], 'variable'=>$row['variable'],'naslov'=>$row['naslov']);
+ $sys_vars_ids[] = $row['id'];
+ }
+
+ $sqlVrednost = sisplet_query("SELECT spr_id, id AS vre_id, vrstni_red, variable FROM srv_vrednost WHERE spr_id IN(".implode(',',$sys_vars_ids).") ORDER BY vrstni_red ASC ");
+ while ($row = mysqli_fetch_assoc($sqlVrednost)) {
+
+ // Ce gre za odnos imamo radio
+ if($sys_vars[$row['spr_id']]['variable'] == 'odnos'){
+
+ if(!isset($sys_vars[$row['spr_id']]['vre_id'][$row['vrstni_red']]))
+ $sys_vars[$row['spr_id']]['vre_id'][$row['variable']] = $row['vre_id'];
+ }
+ elseif (!isset($sys_vars[$row['spr_id']]['vre_id'])) {
+ $sys_vars[$row['spr_id']]['vre_id'] = $row['vre_id'];
+ }
+ }
+
+ return $sys_vars;
+ }
+
+ // Rocna aktivacija vabil
+ function sendMailNoEmailing() {
+ global $lang, $site_path, $site_url, $global_user_id;
+
+ Common::getInstance()->Init($this->sid);
+
+ if (isset($_POST['rids'])) {
+
+ session_start();
+
+ # preverimo token, da ne pošiljamo večkrat
+ if (isset($_SESSION['snd_inv_token'][$this->sid])
+ && isset($_POST['_token'])
+ && $_SESSION['snd_inv_token'][$this->sid] != null
+ && $_SESSION['snd_inv_token'][$this->sid] == isset($_POST['_token'])) {
+
+ # na send smo kliknili samo 1x
+ unset($_SESSION['snd_inv_token'][$this->sid]);
+
+ session_commit();
+
+ $dont_send_duplicated = false;
+ if (isset($_POST['dont_send_duplicated']) && $_POST['dont_send_duplicated'] == 'on') {
+ $dont_send_duplicated = true;
+ }
+
+ $rids = $_POST['rids'];
+
+ $return = array();
+ $return['error'] = '0';
+ $return['msg'] = '<div class="inv_send_message">'.sprintf($lang['srv_invitation_note5_noEmailing'], $site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=view_archive').'<br /><br/>';
+ $return['msg'] .= sprintf($lang['srv_invitation_note5_noEmailing2'], $site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=view_recipients').'</div>';
+
+ // Shranimo komentar h posiljanju
+ if(isset($_POST['comment']) && $_POST['comment'] != ''){
+ $comment = $_POST['comment'];
+ $sqlC = sisplet_query("UPDATE srv_invitations_messages SET comment='$comment' WHERE ank_id='$this->sid' AND isdefault='1'");
+ }
+
+ // Preberemo tip posiljanja (navadna posta, sms...)
+ $noMail_type = SurveySession::get('inv_noEmailing_type');
+
+ // Pripravimo arhiv pošiljanj, da dobimo arch_id
+ $sql_query_all = sisplet_query("SELECT count(*) FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0'");
+ list($count_all) = mysqli_fetch_row($sql_query_all);
+
+ $date_sent = date ("Y-m-d H:i:s");
+ $archive_naslov = 'mailing_'.date("d.m.Y").', '.date("H:i:s");
+
+ // Naslov in body
+ // polovimo sporočilo in prejemnike
+ $sql_query_m = sisplet_query("SELECT id, subject_text, body_text, reply_to, isdefault, comment, naslov, url FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'");
+ if (mysqli_num_rows($sql_query_m) > 0 ) {
+ $sql_row_m = mysqli_fetch_assoc($sql_query_m);
+ }
+ else {
+ $subject_text = $lang['srv_inv_message_noemailing_subject'];
+ $body_text = '';
+ }
+
+ $subject_text = $sql_row_m['subject_text'];
+ $body_text = $sql_row_m['body_text'];
+ $msg_url = $sql_row_m['url'];
+
+ // Vstavimo podatke v arhiv
+ $sqlQuery = sisplet_query("INSERT INTO srv_invitations_archive
+ (id, ank_id, date_send, subject_text, body_text, tip, uid, comment, naslov, rec_in_db)
+ VALUES
+ (NULL , '$this->sid', '$date_sent', '".addslashes($subject_text)."', '".addslashes($body_text)."', '$noMail_type', '$global_user_id', '$comment', '$archive_naslov', '$count_all')
+ ");
+
+ $arch_id = mysqli_insert_id($GLOBALS['connect_db']);
+ $duplicated = array();
+
+ // Polovimo sistemske spremenljivke
+ $sys_vars = $this->getSystemVars();
+
+ // prejeminki besedila
+ $sql_query = sisplet_query("SELECT id, firstname, lastname, email, password, cookie, phone, salutation, custom, relation
+ FROM srv_invitations_recipients
+ WHERE ank_id = '".$this->sid."' AND deleted='0' AND id IN (".implode(',',$rids).")
+ ORDER BY id
+ ");
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+
+ $password = $sql_row['password'];
+
+ $email = $sql_row['email'];
+ if ($dont_send_duplicated == true && isset($duplicated[$email]) && $email != '') {
+ $duplicated[$email] ++;
+ continue;
+ }
+
+ $duplicated[$email] = 1;
+ $individual = (int)$this->surveySettings['individual_invitation'];
+
+ $_user_data = $sql_row;
+
+ $send_ok[] = $email;
+ $send_ok_ids[] = $sql_row['id'];
+ $_user_data['status'] = 1;
+
+ $send_users_data[] = $_user_data;
+ }
+
+ // updejtamo userja da mu je bilo poslano
+ if ( count($send_ok_ids) > 0) {
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET sent = '1', date_sent = '".$date_sent."' WHERE id IN (".implode(',',$send_ok_ids).")");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // statuse popravimo samo če vabilo še ni bilo poslano ali je bila napaka
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET last_status = '1' WHERE id IN (".implode(',',$send_ok_ids).") AND last_status IN ('0','2')");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ $comment = $_POST['comment'];
+
+ // dodajmo še userje v povezovalno tabelo
+ if ($arch_id > 0) {
+
+ // updejtamo še tabelo arhivov
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_archive SET cnt_succsess='".count($send_ok_ids)."' WHERE id ='$arch_id'");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ # za arhive
+ $_archive_recipients = array();
+ # za tracking
+ $_tracking = array();
+
+ if (count($send_ok_ids) > 0) {
+ foreach ( $send_ok_ids AS $id) {
+ $_archive_recipients[] = "('$arch_id','$id','1')";
+ #status 1=pošta poslana
+ $_tracking[] = "('$arch_id',NOW(),'$id','1')";
+ }
+ }
+
+ if (count($_archive_recipients) > 0) {
+ $sqlString = 'INSERT INTO srv_invitations_archive_recipients (arch_id,rec_id,success) VALUES ';
+ $sqlString .= implode(', ', $_archive_recipients);
+ $sqlQuery = sisplet_query($sqlString);
+ }
+ if (count($_tracking) > 0) {
+ $sqlStrTracking = "INSERT INTO srv_invitations_tracking (inv_arch_id, time_insert, res_id, status) VALUES ";
+ $sqlStrTracking .= implode(', ', $_tracking);
+ $sqlQueryTracking = sisplet_query($sqlStrTracking);
+ }
+ }
+
+ sisplet_query("COMMIT");
+
+ # če mamo personalizirana email vabila, userje dodamo v bazo
+ if ($individual == 1 && count($send_users_data) > 0) {
+ # dodamo še userja v srv_user da je kompatibilno s staro logiko
+ $strInsertDataText = array();
+ $strInsertUserbase = array();
+ $strInsertUserstatus = array();
+
+ foreach ($send_users_data AS $user_data) {
+
+ $_r = sisplet_query("INSERT INTO srv_user
+ (ank_id, email, cookie, pass, last_status, time_insert, inv_res_id)
+ VALUES
+ ('".$this->sid."', '".$user_data['email']."', '".$user_data['cookie']."', '".$user_data['password']."', '".$user_data['status']."', NOW(), '".$user_data['id']."') ON DUPLICATE KEY UPDATE cookie = '".$user_data['cookie']."', pass='".$user_data['password']."'
+ ");
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+
+ if ($usr_id) {
+ # dodamo še srv_userbase in srv userstatus
+ $strInsertUserbase[] = "('".$usr_id."','0',NOW(),'".$global_user_id."')";
+ $strInsertUserstatus[] = "('".$usr_id."', '0', '0', NOW())";
+
+ # dodamo še podatke za posameznega userja za sistemske spremenljivke
+ foreach ($sys_vars AS $sid => $spremenljivka) {
+ $_user_variable = $this->inv_variables_link[$spremenljivka['variable']];
+ if (trim($user_data[$_user_variable]) != '' && $user_data[$_user_variable] != null) {
+ $strInsertDataText[] = "('".$sid."','".$spremenljivka['vre_id']."','".trim($user_data[$_user_variable])."','".$usr_id."')";
+ }
+ }
+ }
+ else {
+ // lahko da user že obstaja in je šlo za duplicated keys
+ }
+ }
+
+ // vstavimo v srv_userbase
+ if (count($strInsertUserbase) > 0) {
+ $strInsert = "INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ";
+ $strInsert .= implode(',',$strInsertUserbase);
+ sisplet_query($strInsert);
+ }
+ // vstavimo v srv_userstatus
+ if (count($strInsertUserstatus) > 0) {
+ $strInsert = "INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ";
+ $strInsert .= implode(',',$strInsertUserstatus);
+ sisplet_query($strInsert);
+ }
+ // vstavimo v srv_data_text
+ if (count($strInsertDataText) > 0) {
+ $strInsert = "INSERT INTO srv_data_text".$this->db_table." (spr_id, vre_id, text, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataText);
+ sisplet_query($strInsert);
+ }
+
+ sisplet_query("COMMIT");
+ }
+
+
+ if (count($send_ok) > 0 ) {
+
+ list($name,$surname,$email) = mysqli_fetch_row(sisplet_query("SELECT name, surname, email FROM users WHERE id='$global_user_id'"));
+ $who='';
+
+ if (trim($name) != '') {
+ $who = $name;
+ }
+
+ if (trim($surname) != '') {
+ if ($who != '') {
+ $who .=' ';
+ }
+ $who .= $surname;
+ }
+
+ if ($email != '') {
+ if ($who != '') {
+ $who .=' ('.$email.')';
+ } else {
+ $who = $email;
+ }
+ }
+
+ $return['error'] = '0';
+ }
+ else {
+ $return['error'] = '0';
+ $return['msg'] = '<div class="inv_send_message">'.'<strong>'.$lang['srv_invitation_note9'].'</strong></div><br/>';
+ }
+ }
+ else {
+ #old session token
+ $return['msg'] = '<div class="inv_send_message"><span class="red strong">'.$lang['srv_invitation_note13'].'</span>'.'</div>';
+ }
+ }
+ else {
+ #nimamo $rids
+ $return['msg'] = '<div class="inv_send_message">'.$lang['srv_invitation_note14'].'</div>';
+ }
+
+ # popravimo timestamp za regeneracijo dashboarda
+ Common::getInstance()->Init($anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $this->viewSendMailFinish($return['msg']);
+ }
+
+
+ function viewSendMailFinish($msg) {
+ global $lang, $site_url;
+
+ echo $msg;
+
+ echo '<br class="clr" />';
+ echo '<span class="floatLeft"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=inv_status"><span>'.$lang['srv_inv_nav_email_status'].'</span></a></div></span>';
+ }
+
+ function uploadRecipients() {
+ global $lang;
+
+ $errors = array();
+ $allowedExtensions = array("txt","csv","dat");
+
+ $_fields = trim($_POST['fields']);
+ if ($_fields != null && $_fields != '') {
+ $fields = explode(',',$_fields);
+ }
+ else {
+ $fields = array();
+ }
+
+ $file_name = $_FILES["recipientsFile"]["name"];
+ $file_type = $_FILES["recipientsFile"]["type"];
+ $file_size = $_FILES["recipientsFile"]["size"] > 0 ? $_FILES["recipientsFile"]["size"] / 1024 : 0;
+ $file_tmp = $_FILES["recipientsFile"]["tmp_name"];
+
+ $okFileType = ( $file_type == 'text/plain' || $file_type == 'text/csv' || $file_type == 'application/vnd.ms-excel' );
+ $okFileEnd = (pathinfo($file_name, PATHINFO_EXTENSION) != 'txt' || pathinfo($file_name, PATHINFO_EXTENSION) != 'csv');
+ # preverimo ali smo uploadali datoteko in če smo izbrali katero polje
+ if ($_POST['posted'] == '1' && count($fields) == 0) {
+ $errors[] = $lang['srv_inv_recipiens_upload_error_no_fields'];
+ }
+ #preverimo ime datoteke
+ if ( trim($file_name) == '' || $file_name == null ) {
+ $errors[] = $lang['srv_respondents_invalid_file'];
+
+ # preverimo tip:
+ } else if ( $okFileType == false ) {
+ $errors[] = $lang['srv_respondents_invalid_file_type'];
+
+ # prevermio še končnico (.txt)
+ } else if ($okFileEnd == false) {
+ $errors[] = $lang['srv_respondents_invalid_file_type'];
+ }
+
+ # preverimo velikost
+ else if ( (float)$file_size == 0 ) {
+ $errors[] = $lang['srv_respondents_invalid_file_size'];
+ }
+
+ # če so napake jih prikažemo če ne obdelamo datoteko
+ if (count($errors) > 0) {
+
+ echo '<br class="clr" />';
+
+ echo '<span class="inv_message_errors">'.$lang['srv_inv_recipiens_upload_error'].'</span>';
+
+ echo '<br class="clr" />';
+ echo '<br class="clr" />';
+
+ echo '<span class="inv_error_note">';
+ foreach($errors as $error) {
+ echo '* '.$error.'<br />';
+ }
+ echo '</span>';
+
+ $this->addRecipientsView($fields, $invalid_recipiens_array);
+ }
+ else {
+
+ $fh = @fopen($file_tmp, "rb");
+ if ($fh) {
+ $recipients_list = fread($fh, filesize($file_tmp));
+ fclose($fh);
+ }
+
+ # po potrebi zamenjamo delimiter iz (;) v (,)
+ // Vejica NI kul, ker se uporablja pri nazivih in v custom poljih Za interni delimiter naj bo recimo " | "...
+ $recipients_list = str_replace ($_POST['recipientsDelimiter'], "|~|", $recipients_list);
+
+ // Shranimo v seznam
+ $pid = $this->saveAppendRecipientList($pid=0, $fields, $recipients_list, $profileName='', $profileComment='');
+
+ // Dodamo polja
+ $result = $this->addMassRecipients($recipients_list, $fields, $pid);
+
+ // Prikažemo napake
+ $invalid_recipiens_array = $this->displayRecipentsErrors($result);
+
+ $this->addRecipientsView($fields, $invalid_recipiens_array);
+ }
+ }
+
+ function viewArchiveRecipients() {
+
+ $data = explode('_',$_POST['arch_to_view']);
+
+ $_success = (int)$data[2];
+ $_arch_id = $data[3];
+ $archType = $_POST['archType'];
+
+ # za novejše ankete prikažemo nov način
+ if ($this->newTracking) {
+ $this->showArchiveRecipients($_arch_id, $archType);
+ return;
+ }
+ global $lang,$site_url,$global_user_id;
+ echo '<div id="inv_view_arch_recipients">';
+ # polovimo sezname
+ $lists = array();
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."')";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $lists[$sql_row['pid']] = $sql_row['name'];
+ }
+
+ $lists['-1'] = $lang['srv_invitation_new_templist'];
+ $lists['0'] = $lang['srv_invitation_new_templist_author'];
+
+
+ $data = explode('_',$_POST['arch_to_view']);
+ $_success = (int)$data[2];
+ $_arch_id = $data[3];
+ $sql_string = "SELECT * FROM srv_invitations_archive WHERE id = '$_arch_id'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_a_row = mysqli_fetch_assoc($sql_query);
+
+ $sql_string = "SELECT email,firstname,lastname, password,salutation,phone,custom,relation,sent,responded,unsubscribed,deleted,last_status,list_id FROM srv_invitations_archive_recipients AS siar LEFT JOIN srv_invitations_recipients AS sir on siar.rec_id = sir.id WHERE arch_id = '$_arch_id' AND success = '$_success'";
+ $sql_query = sisplet_query($sql_string);
+
+
+ echo '<div class="inv_FS_content">';
+
+ echo '<table id="tbl_recipients_list">';
+
+ echo '<tr>';
+
+ // Pri volitvah ne prikazemo nekaterih stolpcev
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_sent'].'">'.$lang['srv_inv_recipients_sent'].'</th>';
+ echo '<th class="tbl_inv_left">'.$lang['srv_inv_recipients_email'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_firstname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_lastname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_list_id'].'</th>';
+ }
+ else{
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_sent'].'">'.$lang['srv_inv_recipients_sent'].'</th>';
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_responded'].'">'.$lang['srv_inv_recipients_responded'].'</th>';
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_unsubscribed'].'">'.$lang['srv_inv_recipients_unsubscribed'].'</th>';
+ echo '<th class="tbl_inv_left">'.$lang['srv_inv_recipients_email'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_password'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_firstname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_lastname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_last_status'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_list_id'].'</th>';
+ }
+
+ echo '</tr>';
+
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ echo '<tr>';
+
+ // Pri volitvah ne prikazemo nekaterih stolpcev
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ echo '<td><img src="'.$site_url.'admin/survey/img_0/'.((int)$sql_row['sent'] == 1 ? 'email_sent.png' : 'email_open.png').'"></td>';
+ echo '<td class="tbl_inv_left">'.$sql_row['email'].'</td>';
+ echo '<td>'.$sql_row['firstname'].'</td>';
+ echo '<td>'.$sql_row['lastname'].'</td>';
+ echo '<td>'.$lists[$sql_row['list_id']].'</td>';
+ }
+ else{
+ echo '<td><img src="'.$site_url.'admin/survey/img_0/'.((int)$sql_row['sent'] == 1 ? 'email_sent.png' : 'email_open.png').'"></td>';
+ echo '<td><img src="'.$site_url.'admin/survey/icons/icons/'.((int)$sql_row['responded'] == 1 ? 'star_on.png' : 'star_off.png').'"></td>';
+ echo '<td><img src="'.$site_url.'admin/survey/img_0/'.((int)$sql_row['unsubscribed'] == 1 ? 'opdedout_on.png' : 'opdedout_off.png').'"></td>';
+ echo '<td class="tbl_inv_left">'.$sql_row['email'].'</td>';
+ echo '<td>'.$sql_row['password'].'</td>';
+ echo '<td>'.$sql_row['firstname'].'</td>';
+ echo '<td>'.$sql_row['lastname'].'</td>';
+ echo '<td>'.$lang['srv_userstatus_'.$sql_row['last_status']].' ('.$sql_row['last_status'].')'.'</td>';
+ echo '<td>'.$lists[$sql_row['list_id']].'</td>';
+ }
+
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+ echo '</div>'; // id="arc_content"
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_arch_recipients_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function editArchiveComment() {
+ global $lang,$site_url;
+
+ echo '<div id="inv_view_arch_recipients">';
+
+ $data = explode('_',$_POST['arch_to_view']);
+ $_success = (int)$data[2];
+ $_arch_id = $data[3];
+
+ #polovimo podatke arhiva
+ $sql_string = "SELECT comment FROM srv_invitations_archive WHERE id = '".$_arch_id."'";
+ $sql_query = sisplet_query($sql_string);
+ list($comment) = mysqli_fetch_row($sql_query);
+
+ echo '<div class="inv_FS_content">';
+ echo $lang['srv_invitation_comment'];
+ echo '<input id="inv_arch_id" type="hidden" value="'.$_arch_id.'">';
+ echo '<input id="inv_arch_comment" type="text" value="'.$comment.'">';
+ echo '</div>'; // id="arc_content"
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_arch_save_comment(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_arch_recipients_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+
+ function deleteRecipientConfirm() {
+ global $lang;
+
+ if (isset($_POST['inv_rid']) && trim($_POST['inv_rid']) != '') {
+ $rid = $_POST['inv_rid'];
+ echo '<div id="inv_delete_rec_confirm">';
+
+
+ echo '<span class="h2">Ali ste prepričani da želite izbrisati respondenta:</span>';
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+
+ # polovimo podatke respondenta
+ $sql_string = "SELECT * FROM srv_invitations_recipients WHERE id = '".(int)$_POST['inv_rid']."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ echo '<div id="inv_error_note" class="hidden"/>';
+
+ echo '<input type="hidden" id="inv_rid" value="'.$sql_row['id'].'">';
+ echo '<table id="inv_edit_recipient">';
+ #email
+ if (trim($sql_row['email']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_email'].'</th><td>';
+ echo $sql_row['email'];
+ echo '</td></tr>';
+ }
+ #geslo
+ if (trim($sql_row['password']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_password'].'</th><td>';
+ echo $sql_row['password'];
+ echo '</td></tr>';
+ }
+ #ime
+ if (trim($sql_row['firstname']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_firstname'].'</th><td>';
+ echo $sql_row['firstname'];
+ echo '</td></tr>';
+ }
+ #priimek
+ if (trim($sql_row['lastname']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_lastname'].'</th><td>';
+ echo $sql_row['lastname'];
+ echo '</td></tr>';
+ }
+ #naziv
+ if (trim($sql_row['salutation']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_salutation'].'</th><td>';
+ echo $sql_row['salutation'];
+ echo '</td></tr>';
+ }
+ #telefon
+ if (trim($sql_row['phone']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_phone'].'</th><td>';
+ echo $sql_row['phone'];
+ echo '</td></tr>';
+ }
+ #drugo
+ if (trim($sql_row['custom']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_custom'].'</th><td>';
+ echo $sql_row['custom'];
+ echo '</td></tr>';
+ }
+ #odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ if (trim($sql_row['relation']) != '') {
+ echo '<tr><th>'.$lang['srv_inv_field_relation'].'</th><td>';
+ echo $sql_row['relation'];
+ echo '</td></tr>';
+ }
+ }
+ echo '</table>';
+
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+ echo '<span id="inv_delete_recipent" class="buttonwrapper floatRight" title="'.$lang['srv_inv_list_profiles_delete'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_delete_recipient();return false;" ><span>'.$lang['srv_inv_list_profiles_delete'].'</span></a></span>';
+
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<br class="clr"/>';
+
+ echo '</div>'; # id="inv_delete_rec_confirm"
+ }
+ }
+
+ function deleteRecipient() {
+ global $lang, $global_user_id, $site_url;
+
+ $return = array('success'=>'0');
+
+ #array z napakami
+ $errors = array();
+ $rids = $_POST['inv_rids'];
+ if (isset($rids) && is_array($rids) && count($rids)) {
+ $sqlString = "UPDATE srv_invitations_recipients SET deleted='1', date_deleted=NOW(), uid_deleted='".$global_user_id."' WHERE ank_id='".$this->sid."' AND id IN(".implode(',',$rids).")";
+ $sqlQuery = sisplet_query($sqlString);
+ sisplet_query("COMMIT");
+
+ if (!$sqlQuery) {
+ $errors[] = $lang['srv_inv_recipient_delete_error'];
+ } else {
+ # updejtamo še srv_users
+ $sqlString = "UPDATE srv_user SET inv_res_id=NULL WHERE ank_id='".$this->sid."' AND inv_res_id IN(".implode(',',$rids).")";
+ $sqlQuery = sisplet_query($sqlString);
+ sisplet_query("COMMIT");
+
+ $return['success'] = 2;
+ //$this->viewRecipients();
+ }
+ } else {
+ $errors[] = $lang['srv_inv_recipient_delete_error'];
+ }
+
+ header('location: ' . $site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=view_recipients');
+ }
+
+ function deleteRecipientSingle() {
+ global $lang, $global_user_id, $site_url;
+
+ $return = array('success'=>'0');
+
+ # single delete
+ $inv_rid = $_POST['inv_rid'];
+ if ((int)$inv_rid > 0) {
+ $sqlString = "UPDATE srv_invitations_recipients SET deleted='1', date_deleted=NOW(), uid_deleted='".$global_user_id."' WHERE ank_id='".$this->sid."' AND id ='$inv_rid'";
+ sisplet_query("COMMIT");
+ $sqlQuery = sisplet_query($sqlString);
+ if (!$sqlQuery) {
+ $return['error'] = $lang['srv_inv_recipient_delete_error'];
+ } else {
+ $return['success'] = 1;
+ echo json_encode($return);
+ exit;
+ }
+ } else {
+ $return['error'] = $lang['srv_inv_recipient_delete_error'];
+ }
+
+ echo json_encode($return);
+ exit;
+ }
+
+ function deleteRecipientAll() {
+ global $lang, $global_user_id, $site_url;
+
+ $return = array('success'=>'0');
+
+ # all delete
+ $sqlString = "UPDATE srv_invitations_recipients SET deleted='1', date_deleted=NOW(), uid_deleted='".$global_user_id."' WHERE ank_id='".$this->sid."' AND deleted ='0'";
+ sisplet_query("COMMIT");
+ $sqlQuery = sisplet_query($sqlString);
+ if (!$sqlQuery) {
+ $return['error'] = $lang['srv_inv_recipient_delete_error'];
+ } else {
+ $return['success'] = 1;
+ echo json_encode($return);
+ exit;
+ }
+
+ echo json_encode($return);
+ exit;
+ }
+
+ function addSystemVariables($variables) {
+ global $site_path, $lang;
+
+ // Pri modulu za volitve so responsi anonimni, zato nimamo nobenih sistemskih spremenljivk
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting'))
+ return;
+
+ $system_fields = array(
+ 'inv_field_email' => 'email',
+ 'inv_field_firstname' => 'ime',
+ 'inv_field_lastname' => 'priimek',
+ # 'inv_field_password' => 'geslo', # gesla ne dodajamo kot sistemsko spremenljivko
+ 'inv_field_salutation' => 'naziv',
+ 'inv_field_phone' => 'telefon',
+ 'inv_field_custom' => 'drugo',
+ 'inv_field_relation' => 'odnos',
+ );
+
+ $ba = new BranchingAjax($this->sid);
+
+ if (count($variables) > 0) {
+ // zakaj je bi ta reverse???
+ //$variables = array_reverse($variables,true);
+ foreach ($variables as $var) {
+ if (isset($system_fields[$var])) {
+ $spr_id = null;
+
+ $variable = $system_fields[$var];
+
+ $sqlVariable = sisplet_query("SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.variable='".$variable."' AND s.gru_id=g.id AND g.ank_id='".$this->sid."'");
+ if (mysqli_num_rows($sqlVariable) == 0 && $variable!='pass') { // če varabla še ne obstaja jo kreiramo
+ // za polje pass - Geslo ne kreiramo sistemske variable
+
+ if ($variable != 'language') $user_base = 1;
+
+ // za polje odnos (module 360 - adecco) ustvarimo radio tip spremenljivke
+ if($system_fields[$var] == 'odnos'){
+ ob_start();
+
+ $ba->ajax_spremenljivka_new(0, 0, 1, 0, 1);
+ $spr_id = $ba->spremenljivka;
+
+ ob_clean();
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET variable='".$variable."', variable_custom='1', naslov='".$variable."', sistem='1', visible='0' WHERE id='$spr_id'");
+ if (!$s) echo 'err435'.mysqli_error($GLOBALS['connect_db']);
+
+ // če gre za sistemsko "odnos" za module 360 (adecco) ustvarimo 4 vrednosti (nadrejeni, podrejeni, sodelavec, samoocenjevalec)
+ $sql = sisplet_query("UPDATE srv_vrednost SET naslov='".$lang['srv_inv_field_relation_1']."', variable='1' WHERE spr_id='".$spr_id."' AND vrstni_red='1'");
+ $sql = sisplet_query("UPDATE srv_vrednost SET naslov='".$lang['srv_inv_field_relation_2']."', variable='2' WHERE spr_id='".$spr_id."' AND vrstni_red='2'");
+ $sql = sisplet_query("UPDATE srv_vrednost SET naslov='".$lang['srv_inv_field_relation_3']."', variable='3' WHERE spr_id='".$spr_id."' AND vrstni_red='3'");
+ $sql = sisplet_query("INSERT INTO srv_vrednost (id, spr_id, naslov, variable, vrstni_red) VALUES ('', '$spr_id', '".$lang['srv_inv_field_relation_4']."', '4', '4')");
+ }
+ // dodamo novo spremenljivko na konec, tip je 21
+ else{
+ ob_start();
+
+ $ba->ajax_spremenljivka_new(0, 0, 1, 0, 21);
+ $spr_id = $ba->spremenljivka;
+
+ ob_clean();
+
+ $s = sisplet_query("UPDATE srv_spremenljivka SET variable='".$variable."', variable_custom='1', naslov='".$variable."', sistem='1', visible='0' WHERE id='$spr_id'");
+ if (!$s) echo 'err435'.mysqli_error($GLOBALS['connect_db']);
+
+ #MAPPING za povezavo podatkov
+ # če smo dodajali email, ga dodamo tudi v mapping
+ if ($variable == 'email' && (int)$spr_id > 0) {
+ $insertString = "INSERT INTO srv_invitations_mapping (sid, spr_id, field) VALUES ('$this->sid','$spr_id','email')";
+ sisplet_query($insertString);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ function listRecipientsProfiles() {
+ global $lang, $global_user_id;
+
+ $ppid = isset($_POST['pid']) ? (int)$_POST['pid'] : -1;
+
+ # polovimo vse profile
+ $array_profiles = array();
+
+ session_start();
+
+ # če obstaja seznam iz seje za to anketo
+ if (isset($_SESSION['inv_rec_profile'][$this->sid])) {
+ $array_profiles[-1] = array('name' => $_SESSION['inv_rec_profile'][$this->sid]['name']);
+ }
+ $array_profiles[0] = array('name' => $lang['srv_temp_profile_author']);
+
+
+ $onlyThisSurvey = (isset($_SESSION['inv_rec_only_this_survey']) && (int)$_SESSION['inv_rec_only_this_survey'] == 1) ? false : true;
+ if ($onlyThisSurvey == 0) {
+ #id-ji profilov do katerih lahko dostopamo
+ $sql_string = "SELECT * FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."') OR pid IN (SELECT DISTINCT pid FROM srv_invitations_recipients_profiles_access where uid = '$global_user_id')";
+ $sql_query = sisplet_query($sql_string);
+ } else {
+ # 1
+ $sql_string = "SELECT rp.* FROM srv_invitations_recipients_profiles AS rp WHERE from_survey = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+ }
+
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $array_profiles[$sql_row['pid']] = array('name' => $sql_row['name']);
+ }
+ echo '<div id="inv_import_list_profiles">';
+
+ echo '<ol>';
+ foreach ($array_profiles AS $_pid => $profile) {
+ echo '<li pid="'.$_pid.'" class="'
+ # .($_pid['isdefault'] == 1 ? ' strong' : '')
+ .($ppid === $_pid ? ' active' : '')
+ .'">';
+ echo $profile['name'];
+ echo '</li>';
+ }
+ echo '</ol>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ if ((int)$ppid > 0) {
+ # polovimo še ostale porfile
+ $sql_string = "SELECT * FROM srv_invitations_recipients_profiles WHERE pid='".(int)$ppid."' AND from_survey ='".$this->sid."' ";
+ $sql_query = sisplet_query($sql_string);
+
+ if (mysqli_num_rows($sql_query) > 0) {
+ # če je iz iste ankete, potem lahko urejamo
+ echo '<a href="#" onclick="inv_del_rec_profile();" title="'.$lang['srv_inv_recipients_delete_profile'].'">'.$lang['srv_inv_recipients_delete_profile'].'</a><br/>';
+ echo '<a href="#" onclick="inv_edit_rec_profile();" title="'.$lang['srv_inv_recipients_edit_profile'].'">'.$lang['srv_inv_recipients_edit_profile'].'</a><br/>';
+ echo '<br class="clr"/>';
+ }
+ }
+
+ echo '<br class="clr" />';
+ }
+
+ function getRecipientsProfile($pid) {
+ global $lang, $global_user_id;
+
+ session_start();
+
+ $fields = array();
+ $recipients_list = null;
+ $noEmailing = SurveySession::get('inv_noEmailing');
+
+ # če ne obstaja začasen seznam ga naredimo (praznega)
+ if (!isset($_SESSION['inv_rec_profile'][$this->sid])) {
+
+ $_SESSION['inv_rec_profile'][$this->sid] = array(
+ 'pid' => -1,
+ 'name' => $lang['srv_invitation_new_templist'],
+ 'fields' => ($noEmailing == 1 ? 'firstname,lastname' : 'email'),
+ 'respondents' => '',
+ 'comment' => $lang['srv_invitation_new_templist']
+ );
+ }
+
+ #polovimo emaile in poljaiz seznama
+ if ($pid > 0) {
+
+ # če imamo pid in je večji kot nič polovimo podatke iz tabele
+ $sql_query = sisplet_query("SELECT fields,respondents FROM srv_invitations_recipients_profiles WHERE pid = '".$pid."'");
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ if (trim($sql_row['respondents']) != '') {
+ //$recipients_list = explode("\n",trim($sql_row['respondents']));
+ // Zamenjamo 1ka delimiter z default vejico, ker drugače je v seznamih porušeno
+ $recipients_list = explode("\n",str_replace ("|~|", ",", trim($sql_row['respondents'])));
+ }
+
+ $_fields = explode(",", $sql_row['fields']);
+
+ if (count($_fields) > 0) {
+ foreach ($_fields AS $field) {
+ $fields[] = 'inv_field_'.$field;
+ }
+ }
+ }
+ else if ($pid == 0) {
+
+ # če ne je začasin porfil - avtor
+ $sql_query = sisplet_query("SELECT email, name, surname FROM users WHERE id = '".$global_user_id."'");
+ $rowEmail = mysqli_fetch_assoc($sql_query);
+
+ // default smo rekli je vejica, ane?
+ $recipients_list[] = $rowEmail['email'];
+ //$recipients_list[] = $rowEmail['email'].','.$rowEmail['name'].','.$rowEmail['surname'];
+
+ $fields[]= 'inv_field_email';
+ /*$fields[]= 'inv_field_firstname';
+ $fields[]= 'inv_field_lastname';*/
+ }
+ else if ($pid == -1) {
+ # začasen profil iz seje
+ $_fields = explode(",",$_SESSION['inv_rec_profile'][$this->sid]['fields']);
+
+ if (count($_fields) > 0) {
+ foreach ($_fields AS $field) {
+ $fields[] = 'inv_field_'.$field;
+ }
+ }
+
+ if (trim($_SESSION['inv_rec_profile'][$this->sid]['respondents']) != '') {
+ $recipients_list = explode("\n",trim($_SESSION['inv_rec_profile'][$this->sid]['respondents']));
+ }
+
+ }
+ else {
+ $recipients_list[] = '';
+ $fields[]= 'inv_field_email';
+ }
+
+ return array($recipients_list,$fields);
+
+ }
+
+ function useRecipientsList($profile_id = null) {
+ if (isset($profile_id) && !is_null($profile_id))
+ {
+ $pid = $profile_id;
+ $_POST['pid'] = $profile_id;
+ }
+ else if (isset($_POST['pid']))
+ {
+ $pid = (int)$_POST['pid'];
+ }
+ else
+ {
+ if (isset($_SESSION['inv_rec_profile'][$this->sid]))
+ {
+ $pid = -1;
+ }
+ else
+ {
+ $pid = 0;
+ }
+ }
+
+ list($recipients_list,$fields) = $this->getRecipientsProfile($pid);
+
+ $this->addRecipientsView($fields,$recipients_list);
+ }
+
+ function saveRecipientList() {
+ global $lang,$site_url, $global_user_id;
+ echo 'DEPRCATED!';
+ return false;
+ $return = array('success'=>'0');
+
+ # shranjujemo v nov profil
+ $post_fields = str_replace('inv_field_','',implode(',',$_POST['fields']));
+ $post_recipients = $this->getCleanString($_POST['recipients_list']);
+
+ $pid = (int)$_POST['pid'];
+ # če je pid < 0 shranimo v nov porfil
+ if ($pid <= 0) {
+ # dodelimo ime
+ #zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ $new_name = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q)) {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles".
+ " (name,uid,fields,respondents,insert_time,comment, from_survey) ".
+ " VALUES ('$new_name', '$global_user_id', '$post_fields', '$post_recipients', NOW(), '', '".$this->sid."' )";
+ $sqlQuery = sisplet_query($sql_insert);
+ if (!$sqlQuery) {
+ $return['success'] = '0';
+ $return['msg'] = mysqli_error($GLOBALS['connect_db']);
+ } else {
+ $return['success'] = '1';
+ $return['pid'] = mysqli_insert_id($GLOBALS['connect_db']);
+
+ }
+
+ } else {
+ # updejtamo obstoječ profil
+ $sql_update = " UPDATE srv_invitations_recipients_profiles".
+ " SET fields = '$post_fields', respondents ='$post_recipients' WHERE pid = '$pid'";
+
+ $sqlQuery = sisplet_query($sql_update);
+ if (!$sqlQuery) {
+ $return['success'] = '0';
+ $return['msg'] = mysqli_error($GLOBALS['connect_db']);
+ } else {
+ $return['success'] = '1';
+ $return['pid'] = $pid;
+ }
+ }
+ sisplet_query("COMMIT");
+ echo json_encode($return);
+ exit;
+
+ }
+
+ function getProfileName() {
+ echo 'DEPRECATED';
+ }
+
+ function saveRecProfile() {
+ global $lang, $site_url, $global_user_id;
+
+ $return = array('error'=>'0');
+ $profile_id = isset($_POST['profile_id'])? (int)$_POST['profile_id'] : -1;
+ $profile_name = (isset($_POST['profile_name']) && trim($_POST['profile_name']) != '') ? trim($_POST['profile_name']) : $lang['srv_invitation_new_templist'];
+ $profile_comment = (isset($_POST['profile_comment']) && trim($_POST['profile_comment']) != '') ? trim($_POST['profile_comment']) : '';
+ $recipients_list = trim($this->getCleanString($_POST['recipients_list']));
+ $field_list = (isset($_POST['field_list']) && trim($_POST['field_list']) != '') ? trim($_POST['field_list']) : 'email';
+
+ if ((int)$profile_id == -1) {
+ # shranimo v začasni profil
+ session_start();
+ $_SESSION['inv_rec_profile'][$this->sid] = array(
+ 'pid'=>-1,
+ 'name'=>$lang['srv_invitation_new_templist'],
+ 'fields'=>$field_list,
+ 'respondents'=>$recipients_list,
+ 'comment'=>$profile_comment
+ );
+ $return = array('error'=>'0', 'msg'=>'x0', 'pid'=>-1);
+ }
+ else if ((int)$profile_id == 0) {
+ # shranjujemo v nov profil
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles (name,uid,fields,respondents,insert_time,comment, from_survey) VALUES ('$profile_name', '$global_user_id', '$field_list', '$recipients_list', NOW(), '$profile_comment', '".$this->sid."' )";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error, 'pid'=>mysqli_insert_id($GLOBALS['connect_db']));
+ } else {
+ $return = array('error'=>'0', 'msg'=>'x1', 'pid'=>mysqli_insert_id($GLOBALS['connect_db']));
+ }
+ sisplet_query("COMMIT");
+ }
+ else {
+ # dodajamo v obstoječ profil
+ # polovimo podatke obstoječega profila
+ $sql_string = "SELECT * FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."') AND pid = '".$profile_id."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ $respondents = $sql_row['respondents']."\n".$recipients_list;
+
+ $sql_string_update = "UPDATE srv_invitations_recipients_profiles SET respondents = '".$respondents."', comment='".$profile_comment."' WHERE uid in('".$global_user_id."') AND pid = '".$profile_id."'";
+ $sqlQuery = sisplet_query($sql_string_update);
+ sisplet_query("COMMIT");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error, 'pid'=>$profile_id());
+ } else {
+ $return = array('error'=>'0', 'msg'=>'x2', 'pid'=>$profile_id);
+ }
+ }
+
+ echo json_encode($return);
+
+ exit;
+ }
+
+ function updateRecProfile() {
+ global $lang,$site_url, $global_user_id;
+
+ $return = array('error'=>'0', 'msg'=>'');
+ $pid = (int)(int)$_POST['pid'];
+ $profile_name = (isset($_POST['profile_name']) && trim($_POST['profile_name']) != '') ? trim($_POST['profile_name']) : '';
+
+ /*$profile_comment = (isset($_POST['profile_comment']) && trim($_POST['profile_comment']) != '') ? trim($_POST['profile_comment']) : '';
+ $profile_respondents = (isset($_POST['profile_respondents']) && trim($_POST['profile_respondents']) != '') ? trim($_POST['profile_respondents']) : '';*/
+
+ if ($pid > 0) {
+
+ if ($profile_name != '') {
+ //$sql_update = "UPDATE srv_invitations_recipients_profiles SET name = '$profile_name', comment = '$profile_comment', respondents = '$profile_respondents' WHERE pid = '$pid'";
+ $sql_update = "UPDATE srv_invitations_recipients_profiles SET name = '$profile_name' WHERE pid = '$pid'";
+ $sqlQuery = sisplet_query($sql_update);
+ sisplet_query("COMMIT");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error);
+ } else {
+ $return = array('error'=>'0', 'msg'=>$sql_update);
+
+ }
+ sisplet_query("COMMIT");
+ } else {
+ $return = array('error'=>'1', 'msg'=>$lang['srv_inv_msg_1']);
+ }
+
+ } else {
+ $return = array('error'=>'1', 'msg'=>$lang['srv_inv_msg_2']);
+ }
+
+ echo json_encode($return);
+
+ exit;
+ }
+
+ function deleteRecProfile() {
+ global $lang, $site_url, $global_user_id;
+
+ $return = array('error'=>'0');
+ $pid = isset($_POST['pid']) && (int)$_POST['pid'] > 0 ? (int)$_POST['pid'] : null;
+
+ if ($_POST['pid']) {
+ $sql_string = "DELETE FROM srv_invitations_recipients_profiles WHERE pid='".$pid."' AND uid='".$global_user_id."'";
+ $return['str'] = $sql_string;
+ $sqlQuery = sisplet_query($sql_string);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return['error'] = '1';
+ $return['msg'] = $error;
+ }
+ sisplet_query("COMMIT");
+ }
+
+ echo json_encode($return);
+
+ exit;
+ }
+
+ function editRecProfile() {
+ global $lang, $site_url, $global_user_id;
+
+ $return = array('error'=>'0');
+ $pid = (int)$_POST['pid'];
+
+ if ($pid > 0) {
+ $sql_string = "SELECT * FROM srv_invitations_recipients_profiles WHERE pid='".$pid."'";
+ $sqlQuery = sisplet_query($sql_string);
+ $sqlRow = mysqli_fetch_assoc($sqlQuery);
+
+ echo '<div id="inv_recipients_profile_name">';
+
+ echo '<div id="inv_error_note" class="hidden"></div>';
+
+ echo '<table>';
+ echo '<tr><td class="bold">'.$lang['srv_inv_recipient_list_name'].'</td>';
+ echo '<td>';
+ echo '<input type="text" id="rec_profile_name" value="'.$sqlRow['name'].'" autofocus="autofocus" style="width: 200px;">';
+ echo '</td></tr>';
+ echo '</table>';
+
+ echo '<input type="hidden" id="rec_profile_pid" value="'.$pid.'" >';
+
+ echo '<br class="clr" />';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_update_rec_profile(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<br class="clr" />';
+
+ echo '</div>'; # id="inv_view_arch_recipients"
+
+ sisplet_query("COMMIT");
+ }
+
+ echo json_encode($return);
+
+ exit;
+ }
+
+ function deleteMsgProfile() {
+ global $lang, $site_url, $global_user_id;
+
+ $return = array('error'=>'0');
+ $mid = isset($_POST['mid']) && (int)$_POST['mid'] > 0 ? (int)$_POST['mid'] : null;
+
+ # preštejemo koliko profilov imamo. Zadnjega ne pustimo izbrisati
+ $sql_string = "SELECT id FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND id <> '".$mid."' LIMIT 1";
+ $sql_query = sisplet_query($sql_string);
+ list($id) = mysqli_fetch_row($sql_query);
+
+ if ((int)$id > 0 ) {
+ # nastavimo na nov id
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '1' WHERE ank_id = '$this->sid' AND id='$id'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ # če imamo še kak profil pustimo zbrisat izbranega
+ if ((int)$mid > 0) {
+
+ $sql_string = "DELETE FROM srv_invitations_messages WHERE id='".$mid."'";
+ $return['str'] = $sql_string;
+ $sqlQuery = sisplet_query($sql_string);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return['error'] = '1';
+ $return['msg'] = $error;
+ }
+
+ }
+ sisplet_query("COMMIT");
+ $this->viewMessage($id);
+
+ }
+
+ #$this->viewMessage();
+ # echo json_encode($return);
+ # exit;
+ }
+
+ function showMessageRename() {
+ global $lang;
+ $mid = (int)$_POST['mid'];
+
+ echo '<div id="inv_recipients_profile_name">';
+ echo $lang['srv_inv_message_rename_new_name'].'&nbsp;';
+
+ # polovimo vsa sporočila
+ $sql_string = "SELECT naslov, comment FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND id = '$mid'";
+ list($naslov, $comment) = mysqli_fetch_row(sisplet_query($sql_string));
+
+ echo '<input type="text" id="inv_message_profile_name" value="'.$naslov.'" tabindex="1" autofocus="autofocus">';
+ echo '<br/><br/>';
+ echo $lang['srv_inv_message_draft_list_comment'];
+ echo '<textarea id="inv_message_comment" tabindex="3" rows="2" style="width:200px;">'.($comment).'</textarea>';
+
+
+ echo '<br class="clr" /><br class="clr" />';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="invMessageRename(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+ }
+
+
+ function messageRename() {
+ global $lang;
+
+ $return = array('msg'=>'', 'error'=>'0');
+
+ $mid = (int)$_POST['mid'];
+ $return['mid'] = $mid;
+
+ $name = trim($_POST['name']);
+ $comment = trim($_POST['comment']);
+
+ if ($name == '' || $name == null) {
+ $name = $this->generateMessageName();
+ }
+
+ if ($mid > 0) {
+ #updejtamo obstoječ profil
+ $sql_string = "UPDATE srv_invitations_messages SET naslov='".$name."', comment='".$comment."', edit_uid='".$global_user_id."', edit_time=NOW() WHERE ank_id = '$this->sid' AND id='$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ if ( $sqlQuery != 1) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+ sisplet_query("COMMIT");
+
+ } else {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+
+ echo json_encode($return);
+ exit;
+
+ }
+ function editRecipient() {
+ global $lang;
+
+ echo '<div id="inv_recipient_edit">';
+
+ echo '<h2>Urejanje respondenta</h2>';
+
+ if ((int)$_POST['inv_rid'] > 0) {
+ # polovimo podatke respondenta
+ $sql_string = "SELECT * FROM srv_invitations_recipients WHERE id = '".(int)$_POST['inv_rid']."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ echo '<div id="inv_error_note" class="hidden"/>';
+
+ echo '<input type="hidden" id="inv_rid" value="'.$sql_row['id'].'">';
+ echo '<table id="inv_edit_recipient">';
+ #email
+ echo '<tr><th>'.$lang['srv_inv_field_email'].'</th><td>';
+ echo '<input type="text" id="rec_email" value="'.$sql_row['email'].'" autocomplete="off" maxlength="100">';
+ echo '</td></tr>';
+ #geslo
+ echo '<tr><th>'.$lang['srv_inv_field_password'].'</th><td>';
+ echo '<input type="text" id="rec_password" value="'.$sql_row['password'].'" autocomplete="off" maxlength="45">';
+ echo '</td></tr>';
+ #ime
+ echo '<tr><th>'.$lang['srv_inv_field_firstname'].'</th><td>';
+ echo '<input type="text" id="rec_firstname" value="'.$sql_row['firstname'].'" autocomplete="off" maxlength="45">';
+ echo '</td></tr>';
+ #priimek
+ echo '<tr><th>'.$lang['srv_inv_field_lastname'].'</th><td>';
+ echo '<input type="text" id="rec_lastname" value="'.$sql_row['lastname'].'" autocomplete="off" maxlength="45">';
+ echo '</td></tr>';
+ #naziv
+ echo '<tr><th>'.$lang['srv_inv_field_salutation'].'</th><td>';
+ echo '<input type="text" id="rec_salutation" value="'.$sql_row['salutation'].'" autocomplete="off" maxlength="45">';
+ echo '</td></tr>';
+ #telefon
+ echo '<tr><th>'.$lang['srv_inv_field_phone'].'</th><td>';
+ echo '<input type="text" id="rec_phone" value="'.$sql_row['phone'].'" autocomplete="off" maxlength="45">';
+ echo '</td></tr>';
+ #drugo
+ echo '<tr><th>'.$lang['srv_inv_field_custom'].'</th><td>';
+ echo '<input type="text" id="rec_custom" value="'.$sql_row['custom'].'" autocomplete="off" maxlength="100">';
+ echo '</td></tr>';
+ #odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ echo '<tr><th>'.$lang['srv_inv_field_relation'].'</th><td>';
+ echo '<input type="text" id="rec_relation" value="'.$sql_row['relation'].'" autocomplete="off" maxlength="100">';
+ echo '</td></tr>';
+ }
+
+ echo '</table>';
+
+ echo '<br class="clr"/>';
+ echo '<br class="clr"/>';
+ echo '<span id="save_recipients" class="buttonwrapper floatRight" ><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_save_recipient();return false;" ><span>'.$lang['srv_inv_recipient_save'].'</span></a></span>';
+
+ }
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<br class="clr"/>';
+ echo '</div>';
+ }
+
+ function saveRecipient() {
+ global $lang;
+
+ $return = array('msg'=>$lang['srv_inv_error1'], 'error'=>'0');
+
+ $rid = (int)trim($_POST['inv_rid']);
+ $rec_email = trim($_POST['rec_email']);
+ $rec_password = trim($_POST['rec_password']);
+ $rec_firstname = trim($_POST['rec_firstname']);
+ $rec_lastname = trim($_POST['rec_lastname']);
+ $rec_salutation = trim($_POST['rec_salutation']);
+ $rec_phone = trim($_POST['rec_phone']);
+ $rec_custom = trim($_POST['rec_custom']);
+ $rec_relation = (int)trim($_POST['rec_relation']);
+
+ $return['rid'] = $rid;
+
+ $sql_string = "SELECT email FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND id = '".$rid."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ $newline= '<br/>';
+ # če smo imeli polje email ga preverjamo
+ if ($sql_row['email'] != null || trim($sql_row['email']) != '' || ($rec_email != null && $rec_email != '')) {
+ # email ne sme biti prazen
+ if (($sql_row['email'] != null || trim($sql_row['email']) != '') && ($rec_email == null || $rec_email == '')) {
+ $return['error'] = '1';
+
+ $return['msg'] .= $newline.$lang['srv_inv_error2'];
+ $return['error_email'] = '1';
+ $newline= '<br/>';
+ } else if (!$this->validEmail($rec_email)) {
+ # email mora biti pravilne oblike
+ $return['error'] = '1';
+
+ $return['msg'] .= $newline.$lang['srv_inv_error3'];
+ $return['error_email'] = '1';
+ $newline= '<br/>';
+ }
+ }
+ # password ne sme biti prazen
+ if ($rec_password == null || $rec_password == '') {
+ $return['error'] = '1';
+
+ $return['msg'] .= $newline.$lang['srv_inv_error4'];
+ $return['error_password'] = '1';
+ $newline= '<br/>';
+ } else {
+ #preverimo da geslo še ni uporabljeno za to anketo za katerega drugega respondenta
+ $sql_string = "SELECT * FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND password = '".$rec_password."' AND id != '".$rid."'";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) > 0) {
+ $return['error'] = '1';
+
+ $return['msg'] .= $newline.$lang['srv_inv_error5'];
+ $return['error_password'] = '1';
+ $newline= '<br/>';
+ }
+ }
+
+ # če ni napak shranimo
+ if ( $return['error'] == '0') {
+ # ali shranjujemo obstoječ msg
+ $sql_string = "UPDATE srv_invitations_recipients SET"
+ ." email = '".strtolower($rec_email)."',"
+ ." password = '$rec_password',"
+ ." firstname = '$rec_firstname',"
+ ." lastname = '$rec_lastname',"
+ ." salutation = '$rec_salutation',"
+ ." phone = '$rec_phone',"
+ ." custom = '$rec_custom',"
+ ." relation = '$rec_relation'"
+ ." WHERE ank_id = '$this->sid' AND id='$rid'";
+ $sqlQuery = sisplet_query($sql_string);
+
+ sisplet_query("COMMIT");
+ if ( $sqlQuery != 1) {
+ $return['error'] = '1';
+
+ $return['msg'] .= $newline.$lang['srv_inv_error6'];
+ }
+ }
+
+ # MAP: če imamo mapirano, updejtamo tudi pri podatkih
+ $strMap = "SELECT spr_id FROM srv_invitations_mapping WHERE sid = '".$this->sid."' AND field='email'";
+ $qryMap = sisplet_query($strMap);
+ list($mapSprId) = mysqli_fetch_row($qryMap);
+ if ((int)$mapSprId > 0) {
+ # preverimo ali ima respondent povezavo na srv_user
+ $selectUser = "SELECT id FROM srv_user where ank_id='".$this->sid."' AND inv_res_id='$rid' AND deleted='0'";
+ $qryUser = sisplet_query($selectUser);
+ list($uid) = mysqli_fetch_row($qryUser);
+
+ if ((int)$uid > 0 && $this->validEmail($rec_email)) {
+ $updateStr = "UPDATE srv_data_text".$this->db_table." SET text = '$rec_email' WHERE spr_id='$mapSprId' AND usr_id='".(int)$uid."'";
+ $qryUpdate = sisplet_query($updateStr);
+ if ((int)$qryUpdate > 0) {
+ # updejtamo še timestamp userja
+ $updateUserString = "UPDATE srv_user SET time_edit=NOW() WHERE id='".(int)$uid."'";
+ $qryUserUpdate = sisplet_query($updateUserString);
+ }
+ }
+ }
+
+ $sql_string = "SELECT * FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND id = '".$rid."'";
+ $sql_query = sisplet_query($sql_string);
+
+ $return['rec'] = mysqli_fetch_assoc($sql_query);
+
+ echo json_encode($return);
+ exit;
+ }
+
+ function setRecipientFilter(){
+
+ session_start();
+
+ if (isset($_POST['inv_filter_on']) && $_POST['inv_filter_on'] == 'true') {
+ $_SESSION['inv_filter_on'] = true;
+
+ } else {
+ $_SESSION['inv_filter_on'] = false;
+ }
+
+ $_SESSION['inv_filter']['value'] = trim($_POST['inv_filter_value']);
+ $_SESSION['inv_filter']['send'] = (int)$_POST['inv_filter_send'];
+ $_SESSION['inv_filter']['respondet'] = (int)$_POST['inv_filter_respondet'];
+ $_SESSION['inv_filter']['unsubscribed'] = (int)$_POST['inv_filter_unsubscribed'];
+
+ # če ni seznama privzeto damo na vsi
+ if (!isset($_POST['inv_filter_list']) && !isset($_SESSION['inv_filter']['list'])) {
+ $_SESSION['inv_filter']['list'] = '-2';
+ } else {
+ $_SESSION['inv_filter']['list'] = (int)$_POST['inv_filter_list'];
+ }
+ if (isset($_POST['inv_filter_duplicates']) && $_POST['inv_filter_duplicates'] == 'true') {
+ $_SESSION['inv_filter']['duplicated'] = true;
+ } else {
+ $_SESSION['inv_filter']['duplicated'] = false;
+ }
+
+ session_commit();
+ return;
+ }
+
+ function exportRecipients() {
+ global $lang;
+
+ $convertTypes = array('charSet' => 'UTF-8', # windows-1250',
+ 'delimit' => ';',
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+
+ #header('Content-Type: application/octet-stream; charset='.$convertTypes['charSet']);
+ header('Content-type: application/csv; charset='.$convertTypes['charSet']);
+ header('Content-Transfer-Encoding: binary');
+ header('Content-Disposition: attachment; filename="respondenti_anketa_'.$this->sid.'-'.date('Y-m-d').'.csv"');
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+
+ ob_clean();
+
+ # dodami boomchar za utf-8
+ echo $convertTypes['BOMchar'];
+
+ #array z napakami
+ $errors = array();
+ $inv_rids = $_POST['inv_rids'];
+ if (is_array($inv_rids) && count($inv_rids) > 0) {
+
+ // Ce delamo izvoz za telefonski modul
+ if(SurveyInfo::getInstance()->checkSurveyModule('phone')){
+ $delimit = '';
+ foreach ($this->inv_variables_tel_excel AS $vkey => $inv_variable) {
+ echo $delimit.$lang['srv_inv_recipients_'.$inv_variable];
+ $delimit = $convertTypes['delimit'];
+ }
+
+ #echo $delimit.$lang['srv_inv_recipients_count_inv'];
+ echo $convertTypes['newLine'];
+
+ $sqlString = "SELECT sir.*, IF(sirp.name IS NULL, '".$lang['srv_invitation_new_templist_author']."', sirp.name) AS list_name, scm.comment, scs.call_time, sch.status "
+ ." FROM srv_invitations_recipients AS sir"
+ ." LEFT JOIN srv_invitations_recipients_profiles AS sirp ON (sir.list_id = sirp.pid)"
+ ." LEFT JOIN srv_telephone_comment AS scm ON (scm.rec_id = sir.id)"
+ ." LEFT JOIN srv_telephone_schedule AS scs ON (scs.rec_id = sir.id)"
+ ." LEFT JOIN srv_telephone_history AS sch ON (sch.rec_id = sir.id)"
+
+ ." WHERE sir.id IN(".implode(',',$inv_rids).") ORDER BY id";
+
+ $sqlQuery = sisplet_query($sqlString);
+ if (mysqli_num_rows($sqlQuery)) {
+ while ($sql_row = mysqli_fetch_assoc($sqlQuery)) {
+ foreach ($this->inv_variables_tel_excel AS $vkey => $inv_variable) {
+ if($inv_variable == 'status' && $sql_row[$inv_variable] == '')
+ echo $lang['srv_telephone_status_'].$convertTypes['delimit'];
+ else
+ echo $sql_row[$inv_variable].$convertTypes['delimit'];
+ }
+
+ echo $convertTypes['newLine'];
+ }
+ }
+ }
+ // Izvoz za navadna vabila
+ else{
+ $delimit = '';
+ foreach ($this->inv_variables_excel AS $vkey => $inv_variable) {
+ echo $delimit.$lang['srv_inv_recipients_'.$inv_variable];
+ $delimit = $convertTypes['delimit'];
+ }
+
+ #echo $delimit.$lang['srv_inv_recipients_count_inv'];
+ echo $convertTypes['newLine'];
+
+ $sqlString = "SELECT sir.*, IF(sirp.name IS NULL, '".$lang['srv_invitation_new_templist_author']."', sirp.name) AS list_name "
+ ." FROM srv_invitations_recipients AS sir"
+ ." LEFT JOIN srv_invitations_recipients_profiles AS sirp ON (sir.list_id = sirp.pid)"
+ #." LEFT JOIN srv_invitations_archive_recipients AS siar ON (sir.id = siar.rec_id)"
+
+ ." WHERE sir.id IN(".implode(',',$inv_rids).") ORDER BY id";
+
+ /*
+ $sqlString = "SELECT sir.*, IF(sirp.name IS NULL, '".$lang['srv_invitation_new_templist_author']."', sirp.name) AS list_name, count(siar.arch_id) AS count_inv"
+ ." FROM srv_invitations_recipients AS sir"
+ ." LEFT JOIN srv_invitations_recipients_profiles AS sirp ON (sir.list_id = sirp.pid)"
+ ." LEFT JOIN srv_invitations_archive_recipients AS siar ON (sir.id = siar.rec_id)"
+ ." WHERE sir.id IN(".implode(',',$inv_rids).") GROUP BY siar.rec_id ORDER BY id";
+ */
+
+ $sqlQuery = sisplet_query($sqlString);
+ if (mysqli_num_rows($sqlQuery)) {
+ while ($sql_row = mysqli_fetch_assoc($sqlQuery)) {
+ foreach ($this->inv_variables_excel AS $vkey => $inv_variable) {
+ echo $sql_row[$inv_variable].$convertTypes['delimit'];
+ }
+
+ # echo $sql_row['count_inv'];
+ echo $convertTypes['newLine'];
+ }
+ }
+ }
+ }
+ else {
+ echo $lang['srv_inv_error7'];
+ }
+
+ ob_flush();
+ }
+
+ function exportRecipients_all() {
+ global $lang;
+
+ $convertTypes = array('charSet' => 'UTF-8', # windows-1250',
+ 'delimit' => ';',
+ 'newLine' => "\n",
+ 'BOMchar' => "\xEF\xBB\xBF");
+
+ #header('Content-Type: application/octet-stream; charset='.$convertTypes['charSet']);
+ header('Content-type: application/csv; charset='.$convertTypes['charSet']);
+ header('Content-Transfer-Encoding: binary');
+ header('Content-Disposition: attachment; filename="respondenti_anketa_'.$this->sid.'-'.date('Y-m-d').'.csv"');
+ header('Pragma: public');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+ header('Cache-Control: private',false);
+
+ ob_clean();
+ # dodami boomchar za utf-8
+ echo $convertTypes['BOMchar'];
+
+
+ // Ce delamo izvoz za telefonski modul
+ if(SurveyInfo::getInstance()->checkSurveyModule('phone')){
+ #array z napakami
+ $errors = array();
+ $delimit = '';
+ foreach ($this->inv_variables_tel_excel AS $vkey => $inv_variable) {
+ echo $delimit.$lang['srv_inv_recipients_'.$inv_variable];
+ $delimit = $convertTypes['delimit'];
+ }
+
+ #echo $delimit.$lang['srv_inv_recipients_count_inv'];
+ echo $convertTypes['newLine'];
+
+ $sqlString = "SELECT sir.*, IF(sirp.name IS NULL, '".$lang['srv_invitation_new_templist_author']."', sirp.name) AS list_name, scm.comment, scs.call_time, sch.status "
+ ." FROM srv_invitations_recipients AS sir"
+ ." LEFT JOIN srv_invitations_recipients_profiles AS sirp ON (sir.list_id = sirp.pid)"
+ ." LEFT JOIN srv_telephone_comment AS scm ON (scm.rec_id = sir.id)"
+ ." LEFT JOIN srv_telephone_schedule AS scs ON (scs.rec_id = sir.id)"
+ ." LEFT JOIN srv_telephone_history AS sch ON (sch.rec_id = sir.id)"
+
+ ." WHERE sir.ank_id = '$this->sid' AND deleted='0' ORDER BY id";
+
+ $sqlQuery = sisplet_query($sqlString);
+ if (mysqli_num_rows($sqlQuery)) {
+ while ($sql_row = mysqli_fetch_assoc($sqlQuery)) {
+ foreach ($this->inv_variables_tel_excel AS $vkey => $inv_variable) {
+ if($inv_variable == 'status' && $sql_row[$inv_variable] == '')
+ echo $lang['srv_telephone_status_'].$convertTypes['delimit'];
+ else
+ echo $sql_row[$inv_variable].$convertTypes['delimit'];
+ }
+
+ echo $convertTypes['newLine'];
+ }
+ }
+ }
+ // Izvoz za navadna vabila
+ else{
+ #array z napakami
+ $errors = array();
+ $delimit = '';
+ foreach ($this->inv_variables_excel AS $vkey => $inv_variable) {
+ echo $delimit.$lang['srv_inv_recipients_'.$inv_variable];
+ $delimit = $convertTypes['delimit'];
+ }
+
+ echo $convertTypes['newLine'];
+
+ $sqlString = "SELECT sir.*, IF(sirp.name IS NULL, '".$lang['srv_invitation_new_templist_author']."', sirp.name) AS list_name "
+ ." FROM srv_invitations_recipients AS sir"
+ ." LEFT JOIN srv_invitations_recipients_profiles AS sirp ON (sir.list_id = sirp.pid)"
+ ." WHERE sir.ank_id = '$this->sid' AND deleted='0' ORDER BY id";
+
+ $sqlQuery = sisplet_query($sqlString);
+ if (mysqli_num_rows($sqlQuery)) {
+
+ while ($sql_row = mysqli_fetch_assoc($sqlQuery)) {
+
+ foreach ($this->inv_variables_excel AS $vkey => $inv_variable) {
+ echo $sql_row[$inv_variable].$convertTypes['delimit'];
+ }
+
+ echo $convertTypes['newLine'];
+ }
+ }
+ }
+
+ ob_flush();
+ }
+
+ function onlyThisSurvey() {
+ session_start();
+ $_SESSION['inv_rec_only_this_survey'] = (isset($_POST['checked']) && $_POST['checked'] == 'true');
+ }
+
+ function hightlight($str, $keywords = '') {
+ $keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
+ $style = 'inv_high';
+ $style_i = 'inv_high_i';
+ /* Apply Style */
+ $var = '';
+
+ foreach(explode(' ', $keywords) as $keyword)
+ {
+ $replacement = "<span class='".$style."'>".$keyword."</span>";
+ $var .= $replacement." ";
+ $str = str_ireplace($keyword, $replacement, $str);
+ }
+
+ /* Apply Important Style */
+
+ $str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
+
+ return $str;
+ }
+
+ // Dodamo vse userje v bazo podatkov kot respondente
+ function add_users_to_database() {
+
+ // Preverimo ce je vklopljen modul za volitve
+ $voting = SurveyInfo::getInstance()->checkSurveyModule('voting');
+
+ # prejeminki besedila
+ $sql_query = sisplet_query("SELECT id, firstname, lastname, email, password, password, cookie, phone, salutation, custom, relation
+ FROM srv_invitations_recipients
+ WHERE ank_id = '".$this->sid."' AND deleted='0' AND sent='0'
+ ");
+
+ # polovimo sistemske spremenljivke z vrednostmi
+ $qrySistemske = sisplet_query("SELECT s.id, s.naslov, s.variable
+ FROM srv_spremenljivka s, srv_grupa g
+ WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".$this->sid."'
+ AND variable IN("."'" . implode("','",$this->inv_variables)."')
+ ORDER BY g.vrstni_red, s.vrstni_red
+ ");
+
+ $sys_vars = array();
+ $sys_vars_ids = array();
+
+ while ($row = mysqli_fetch_assoc($qrySistemske)) {
+ $sys_vars[$row['id']] = array('id'=>$row['id'], 'variable'=>$row['variable'],'naslov'=>$row['naslov']);
+ $sys_vars_ids[] = $row['id'];
+ }
+
+ $sqlVrednost = sisplet_query("SELECT spr_id, id AS vre_id, vrstni_red, variable
+ FROM srv_vrednost
+ WHERE spr_id IN(".implode(',',$sys_vars_ids).")
+ ORDER BY vrstni_red ASC
+ ");
+ while ($row = mysqli_fetch_assoc($sqlVrednost)) {
+
+ // Ce gre za odnos imamo radio
+ if($sys_vars[$row['spr_id']]['variable'] == 'odnos'){
+ if(!isset($sys_vars[$row['spr_id']]['vre_id'][$row['vrstni_red']]))
+ $sys_vars[$row['spr_id']]['vre_id'][$row['variable']] = $row['vre_id'];
+ }
+ elseif (!isset($sys_vars[$row['spr_id']]['vre_id'])) {
+ $sys_vars[$row['spr_id']]['vre_id'] = $row['vre_id'];
+ }
+ }
+
+ # array za rezultate
+ $send_users_data = array();
+
+ # zloopamo skozi prejemnike in personaliziramo sporočila in jih pošljemo
+ $date_sent = date ("Y-m-d H:i:s");
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $_user_data = $sql_row;
+ $_user_data['status'] = 1;
+ $send_users_data[] = $_user_data;
+ }
+
+ # dodamo še userja v srv_user da je kompatibilno s staro logiko
+ $strInsertDataText = array();
+ $strInsertUserbase = array();
+ $strInsertUserstatus = array();
+ foreach ($send_users_data AS $user_data) {
+
+ // Pri volitvah zaradi anonimizacije ignoriramo vse identifikatorje
+ if($voting){
+ sisplet_query("INSERT INTO srv_user
+ (ank_id, cookie, pass, last_status, inv_res_id)
+ VALUES
+ ('".$this->sid."', '".$user_data['cookie']."', '".$user_data['password']."', '".$user_data['status']."', '-1') ON DUPLICATE KEY UPDATE last_status=VALUES(last_status)
+ ");
+
+ // Ce ne belezimo parapodatka za cas responsa, anonimno zabelezimo cas zadnjega responsa
+ sisplet_query("UPDATE srv_anketa SET last_response_time=NOW() WHERE id='".$this->sid."'");
+ }
+ else{
+ sisplet_query("INSERT INTO srv_user
+ (ank_id, email, cookie, pass, last_status, time_insert, inv_res_id)
+ VALUES
+ ('".$this->sid."', '".$user_data['email']."', '".$user_data['cookie']."', '".$user_data['password']."', '".$user_data['status']."', NOW(), '".$user_data['id']."') ON DUPLICATE KEY UPDATE last_status=VALUES(last_status), inv_res_id=VALUES(inv_res_id)
+ ");
+ }
+
+
+
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($usr_id) {
+ # za update v srv_invitations_respondents
+ $send_ok_ids[] = $user_data['id'];
+ }
+ else {
+ $send_error_ids[] = $user_data;
+ }
+
+ # dodamo še srv_userbase in srv userstatus
+ $strInsertUserbase[] = "('".$usr_id."','0',NOW(),'".$global_user_id."')";
+ $strInsertUserstatus[] = "('".$usr_id."', '0', '0', NOW())";
+
+ # dodamo še podatke za posameznega userja za sistemske spremenljivke
+ foreach ($sys_vars AS $sid => $spremenljivka) {
+ $_user_variable = $this->inv_variables_link[$spremenljivka['variable']];
+ if (trim($user_data[$_user_variable]) != '' && $user_data[$_user_variable] != null) {
+ if($spremenljivka['variable'] == 'odnos')
+ $strInsertDataVrednost[] = "('".$sid."','".$spremenljivka['vre_id'][trim($user_data[$_user_variable])]."','".$usr_id."')";
+ else
+ $strInsertDataText[] = "('".$sid."','".$spremenljivka['vre_id']."','".trim($user_data[$_user_variable])."','".$usr_id."')";
+ }
+ }
+
+ sisplet_query("COMMIT");
+ }
+
+ # vstavimo v srv_userbase
+ if (count($strInsertUserbase) > 0) {
+ $strInsert = "INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ";
+ $strInsert .= implode(',',$strInsertUserbase);
+ sisplet_query($strInsert);
+ }
+ # vstavimo v srv_userstatus
+ if (count($strInsertUserstatus) > 0) {
+ $strInsert = "INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ";
+ $strInsert .= implode(',',$strInsertUserstatus);
+ sisplet_query($strInsert);
+ }
+
+ // Pri volitvah zaradi anonimizacije ne vsatvimo nicesar v sistemske spremenljivke
+ if(!$voting){
+
+ # vstavimo v srv_data_text
+ if (count($strInsertDataText) > 0) {
+ $strInsert = "INSERT INTO srv_data_text".$this->db_table." (spr_id, vre_id, text, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataText);
+ sisplet_query($strInsert);
+ }
+ # vstavimo v srv_data_vrednost
+ if (count($strInsertDataVrednost) > 0) {
+ $strInsert = "INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataVrednost);
+ sisplet_query($strInsert);
+ }
+ }
+
+ sisplet_query("COMMIT");
+
+ # zloopamo skozi prejemnike in personaliziramo sporočila in jih pošljemo
+ $date_sent = date ("Y-m-d H:i:s");
+
+ # updejtamo userja da mu je bilo poslano
+ if ( count($send_ok_ids) > 0) {
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET sent='1', date_sent = '".$date_sent."' WHERE id IN (".implode(',',$send_ok_ids).")");
+ if (!$sqlQuery)
+ $error = mysqli_error($GLOBALS['connect_db']);
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET last_status='1' WHERE id IN (".implode(',',$send_ok_ids).") AND last_status IN ('0','2')");
+ if (!$sqlQuery)
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ $msg = array($lang['srv_inv_activate_respondents']. count($send_ok_ids));
+
+ if (count($send_error_ids) > 0) {
+ print_r("<pre>");
+ print_r($lang['srv_inv_error0']);
+ print_r($send_error_ids);
+ print_r("</pre>");
+ }
+
+ # popravimo timestamp za regeneracijo dashboarda
+ Common::getInstance()->Init($anketa);
+ Common::getInstance()->updateEditStamp();
+
+ $this->viewRecipients(/*array(),$msg*/);
+ }
+
+ // Dodamo samo izbrane userje v bazo podatkov kot respondente
+ function add_checked_users_to_database() {
+ global $site_url;
+
+ // Prejemniki, ki jih ročno dodajamo med respondente
+ $inv_rids = $_POST['inv_rids'];
+
+ # prejeminki besedila
+ $sql_string = "SELECT id, firstname, lastname, email, password, cookie, phone, salutation, custom, relation FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0' AND sent='0' AND id IN(".implode(',',$inv_rids).")";
+ $sql_query = sisplet_query($sql_string);
+
+ # polovimo sistemske spremenljivke z vrednostmi
+ $strSistemske = "SELECT s.id, s.naslov, s.variable FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".$this->sid."' AND variable IN("."'" . implode("','",$this->inv_variables)."') ORDER BY g.vrstni_red, s.vrstni_red";
+ $qrySistemske = sisplet_query($strSistemske);
+ $sys_vars = array();
+ $sys_vars_ids = array();
+ while ($row = mysqli_fetch_assoc($qrySistemske)) {
+ $sys_vars[$row['id']] = array('id'=>$row['id'], 'variable'=>$row['variable'],'naslov'=>$row['naslov']);
+ $sys_vars_ids[] =$row['id'];
+ }
+ $sqlVrednost = sisplet_query("SELECT spr_id, id AS vre_id, vrstni_red, variable FROM srv_vrednost WHERE spr_id IN(".implode(',',$sys_vars_ids).") ORDER BY vrstni_red ASC ");
+ while ($row = mysqli_fetch_assoc($sqlVrednost)) {
+ // Ce gre za odnos imamo radio
+ if($sys_vars[$row['spr_id']]['variable'] == 'odnos'){
+ if(!isset($sys_vars[$row['spr_id']]['vre_id'][$row['vrstni_red']]))
+ $sys_vars[$row['spr_id']]['vre_id'][$row['variable']] = $row['vre_id'];
+ }
+ elseif (!isset($sys_vars[$row['spr_id']]['vre_id'])) {
+ $sys_vars[$row['spr_id']]['vre_id'] = $row['vre_id'];
+ }
+ }
+
+ # array za rezultate
+ $send_users_data = array();
+
+ # zloopamo skozi prejemnike in personaliziramo sporočila in jih pošljemo
+ $date_sent = date ("Y-m-d H:i:s");
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $_user_data = $sql_row;
+ $_user_data['status'] = 1;
+ $send_users_data[] = $_user_data;
+ }
+
+ # dodamo še userja v srv_user da je kompatibilno s staro logiko
+ $strInsertDataText = array();
+ $strInsertUserbase = array();
+ $strInsertUserstatus = array();
+ foreach ($send_users_data AS $user_data) {
+ $strInsert = "INSERT INTO srv_user (ank_id, email, cookie, pass, last_status, time_insert, inv_res_id) VALUES ('".$this->sid."', '".$user_data['email']."', '".$user_data['cookie']."', '".$user_data['password']."', '".$user_data['status']."', NOW(), '".$user_data['id']."') ON DUPLICATE KEY UPDATE last_status=VALUES(last_status), inv_res_id=VALUES(inv_res_id)";
+
+ sisplet_query($strInsert);
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($usr_id) {
+ # za update v srv_invitations_respondents
+ $send_ok_ids[] = $user_data['id'];
+ } else {
+ $send_error_ids[] = $user_data;
+ }
+ # dodamo še srv_userbase in srv userstatus
+ $strInsertUserbase[] = "('".$usr_id."','0',NOW(),'".$global_user_id."')";
+ $strInsertUserstatus[] = "('".$usr_id."', '0', '0', NOW())";
+
+ # dodamo še podatke za posameznega userja za sistemske spremenljivke
+ foreach ($sys_vars AS $sid => $spremenljivka) {
+ $_user_variable = $this->inv_variables_link[$spremenljivka['variable']];
+ if (trim($user_data[$_user_variable]) != '' && $user_data[$_user_variable] != null) {
+ if($spremenljivka['variable'] == 'odnos')
+ $strInsertDataVrednost[] = "('".$sid."','".$spremenljivka['vre_id'][trim($user_data[$_user_variable])]."','".$usr_id."')";
+ else
+ $strInsertDataText[] = "('".$sid."','".$spremenljivka['vre_id']."','".trim($user_data[$_user_variable])."','".$usr_id."')";
+ }
+ }
+
+ sisplet_query("COMMIT");
+ }
+
+ # vstavimo v srv_userbase
+ if (count($strInsertUserbase) > 0) {
+ $strInsert = "INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ";
+ $strInsert .= implode(',',$strInsertUserbase);
+ sisplet_query($strInsert);
+ }
+ # vstavimo v srv_userstatus
+ if (count($strInsertUserstatus) > 0) {
+ $strInsert = "INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ";
+ $strInsert .= implode(',',$strInsertUserstatus);
+ sisplet_query($strInsert);
+ }
+ # vstavimo v srv_data_text
+ if (count($strInsertDataText) > 0) {
+ $strInsert = "INSERT INTO srv_data_text".$this->db_table." (spr_id, vre_id, text, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataText);
+ sisplet_query($strInsert);
+ }
+ # vstavimo v srv_data_vrednost
+ if (count($strInsertDataVrednost) > 0) {
+ $strInsert = "INSERT INTO srv_data_vrednost".$this->db_table." (spr_id, vre_id, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataVrednost);
+ sisplet_query($strInsert);
+ }
+ sisplet_query("COMMIT");
+
+ # zloopamo skozi prejemnike in personaliziramo sporočila in jih pošljemo
+ $date_sent = date ("Y-m-d H:i:s");
+
+ # updejtamo userja da mu je bilo poslano
+ if ( count($send_ok_ids) > 0) {
+ $sqlString = "UPDATE srv_invitations_recipients SET sent = '1', date_sent = '".$date_sent."' WHERE id IN (".implode(',',$send_ok_ids).")";
+ $sqlQuery = sisplet_query($sqlString);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ $sqlString = "UPDATE srv_invitations_recipients SET last_status = '1' WHERE id IN (".implode(',',$send_ok_ids).") AND last_status IN ('0','2')";
+ $sqlQuery = sisplet_query($sqlString);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ }
+
+ $msg = array($lang['srv_inv_activate_respondents']. count($send_ok_ids));
+ if (count($send_error_ids) > 0) {
+ print_r("<pre>");
+ print_r($lang['srv_inv_error0']);
+ print_r($send_error_ids);
+ print_r("</pre>");
+ }
+ # popravimo timestamp za regeneracijo dashboarda
+ Common::getInstance()->Init($anketa);
+ Common::getInstance()->updateEditStamp();
+
+ header('location: ' . $site_url . 'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=view_recipients');
+ }
+
+ function getRespondents2Send($send_type, $checkboxes, $source_type, $source_lists, $noEmailing=0) {
+ $respondenti = array();
+
+ # če imamo dodatne omejitve source_type > 0 (arhivi, seznami) dodamo dodatno kontrolo na id-je respondentov
+ $advancedConditionJoin = '';
+ $advancedCondition = '';
+ if ($source_type == 0)
+ {
+ $this->user_inv_ids = array();
+ if ((int)$this->invitationAdvancedConditionId > 0)
+ {
+ $this->user_inv_ids = $this->getConditionUserIds($this->invitationAdvancedConditionId);
+ if (isset($this->user_inv_ids) && is_array($this->user_inv_ids) && count($this->user_inv_ids) > 0 )
+ {
+ $advancedConditionJoin = " INNER JOIN srv_user AS su ON i.id = su.inv_res_id";
+ $advancedCondition = " AND su.ank_id = '$this->sid' AND su.inv_res_id IS NOT NULL AND su.deleted = '0' AND su.id IN ('".(implode('\',\'',$this->user_inv_ids))."')";
+ }
+ }
+ }
+ else if ($source_type == 1)
+ {
+ # arhivi
+ if ($source_lists != '')
+ {
+ $sub_query = " AND i.id IN(SELECT rec_id AS id FROM srv_invitations_archive_recipients WHERE arch_id IN(".$source_lists.")) ";
+ } else {
+ $sub_query = " AND 0=1 ";
+ }
+
+ }
+ else if ($source_type == 2)
+ {
+ if ($source_lists != '')
+ {
+ $sub_query = " AND i.list_id IN(".$source_lists.") ";
+ }
+ else
+ {
+ $sub_query = " AND 0=1 ";
+ }
+ }
+ # polovimo respondente ki ustrezajo posameznemu statusu
+ if ($send_type == 0 )
+ {
+ }
+ if ($send_type == 1)
+ {
+ $sql_sub_condition = " AND i.sent = '0'";
+ }
+ if ($send_type == 2)
+ {
+ $sql_sub_condition = " AND i.sent = '1' AND i.responded = '0'";
+ }
+ if ($send_type == 3)
+ {
+ $sql_sub_condition = " AND i.sent = '1' AND i.responded = '1'";
+ }
+ if ($send_type == 4)
+ {
+ if ($_POST['checkboxes'] != null && trim($_POST['checkboxes']) != '' )
+ {
+ $sql_sub_condition = " AND i.last_status IN (".$_POST['checkboxes'].")";
+ }
+ }
+
+ // Ce imamo vklopljene volitve potem posiljamo samo tistim, katerim še nismo poslali vabila (ponovno posiljanje ni mogoce)
+ $sql_voting_condition = (SurveyInfo::getInstance()->checkSurveyModule('voting')) ? " AND i.sent = '0' AND i.cookie != '' AND i.password != ''" : "";
+
+ // Ce imamo posiljanje brez emaila, ni potrebno da je email vnesen za posameznega respondenta
+ if($noEmailing == 1){
+ $sql_fields = "SELECT DISTINCT i.password, i.id, i.email, i.firstname, i.last_status, i.list_id FROM srv_invitations_recipients AS i";
+ $sql_main_condition = " WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND i.unsubscribed = '0'";
+ $sql_sort = " ORDER BY i.id ASC";
+
+ $sql_string = $sql_fields
+ . $advancedConditionJoin
+ . $sql_main_condition
+ . $advancedCondition
+ . $sql_sub_condition
+ . $sub_query
+ . $sql_sort;
+ if ($sql_string != null) {
+ $qry = sisplet_query($sql_string);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $respondenti[$row['password']] = array('id'=>$row['id'], 'email'=>$row['email'], 'firstname'=>$row['firstname'], 'status'=>$row['last_status'], 'list_id'=>$row['list_id']);
+ }
+ }
+ }
+ else{
+ $sql_fields = "SELECT DISTINCT i.password, i.id, i.email, i.last_status, i.list_id FROM srv_invitations_recipients AS i";
+ $sql_main_condition = " WHERE i.ank_id = '".$this->sid."' AND i.deleted = '0' AND i.unsubscribed = '0' AND i.email IS NOT NULL";
+ $sql_sort = " ORDER BY i.id ASC";
+
+ $sql_string = $sql_fields
+ . $advancedConditionJoin
+ . $sql_main_condition
+ . $sql_voting_condition
+ . $advancedCondition
+ . $sql_sub_condition
+ . $sub_query
+ . $sql_sort;
+ if ($sql_string != null) {
+ $qry = sisplet_query($sql_string);
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $respondenti[$row['password']] = array('id'=>$row['id'], 'email'=>$row['email'], 'status'=>$row['last_status'], 'list_id'=>$row['list_id']);
+ }
+ }
+ }
+
+ return($respondenti);
+ }
+
+ /* Paginacija za pregled respondentov pred pošiljanjem
+ *
+ */
+ function displaySendPagination($all_records) {
+ global $lang,$site_url;
+ #trenutna stran
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $current = is_numeric($_GET['page']) && (int)$_GET['page'] > 0 ? $page : '1';
+
+ $all = ceil($all_records / $this->rec_send_page_limit);
+
+ # current nastavimo na zadnji element
+ if ( $all > 1 ) {
+ echo '<div id="pagination">';
+ # povezava na prejšnjo stran
+ # $prev_page = $current - 1 ? $current - 1 :$current;
+ # echo('<div><a href="#" onclick="invSendPage('.($prev_page).','.$this->rec_send_page_limit.')">'.$lang['previous_page_short'].'</a></div>');
+ # povezave za vmesne strani
+ for($a = 1; $a <= $all; $a++) {
+ echo('<div value="'.$a.'" '.($a == 1 ? ' class="currentPage_small"':'').'><a href="#" onclick="invSendPage('.($a).','.$this->rec_send_page_limit.')">'.($a).'</a></div>');
+ }
+ # povezava na naslednjo stran
+ # $next_page = ($current + 1) ? ($current + 1) : $current;
+ # echo('<div><a href="#" onclick="invSendPage('.($next_page).','.$this->rec_send_page_limit.')">'.$lang['next_page_short'].'</a></div>');
+
+ $rec_on_page = $all != $current ? $this->rec_send_page_limit : ( $all_records - ($all-1)*$this->rec_send_page_limit);
+
+ echo '</div>';
+ }
+ echo '<br/><div class="justtext">'.$lang['srv_inv_pagination_shown'];
+ $rec_on_page_options = array(20,50,100,200,500,1000);
+ $none_added = true;
+ $added_over = false;
+ echo '<select onchange="invSendPageChangeLimit(this,\''.$all_records.'\'); return false;">';
+ foreach ($rec_on_page_options AS $option) {
+ if ($all_records >= $option || $none_added == true || $added_over == false) {
+ echo '<option value="'.$option.'"'.($option == $this->rec_send_page_limit ? ' selected="selected"' : '').'>'.$option.'</option>';
+ $none_added = false;
+ if ($option > $all_records) {
+ $added_over = true;
+ }
+
+ }
+ #$rec_on_page;
+ }
+ echo '</select>';
+ echo $lang['srv_inv_pagination_shown_records'].'</div>';
+
+ }
+
+ /* Paginacija za pregled reposndentov
+ *
+ */
+ function displayPagination($all_records) {
+ global $lang, $site_url;
+
+ #trenutna stran
+ $page = isset($_GET['page']) ? $_GET['page'] : '1';
+ $current = is_numeric($_GET['page']) && (int)$_GET['page'] > 0 ? $page : '1';
+
+ $all = ceil($all_records / REC_ON_PAGE);
+
+ # current nastavimo na zadnji element
+ if ( $all > 1) {
+
+ echo '<div id="pagination">';
+ $baseUrl = $site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=view_recipients&page=';
+
+ # povezava -10
+ if ($all > 10) {
+ if ($current - 10 >= 0) {
+ echo('<div><a href="'.$baseUrl.($current - 10).'">-10</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">-10</div>');
+ }
+ }
+
+ # povezava na prejšnjo stran
+ $prev_page = $current - 1 ? $current - 1 :$current;
+ if( ($current - 1) >= 1) {
+ echo('<div><a href="'.$baseUrl.$prev_page.'">'.$lang['previous_page_short'].'</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">'.$lang['previous_page_short'].'</div>');
+ }
+
+ # povezave za vmesne strani
+ $middle = $all / 2;
+ $skipped = false;
+ for($a = 1; $a <= $all; $a++) {
+ if ($all < ((GROUP_PAGINATE+1) * 2) || $a <= GROUP_PAGINATE || $a > ($all-GROUP_PAGINATE)
+
+ || ( abs($a-$current) < GROUP_PAGINATE)) {
+ if ($skipped == true) {
+ echo '<div class="spacePage">.&nbsp;.&nbsp;.</div>';
+ $skipped = false;
+ }
+ if($a == $current) {
+ # brez href povezave
+ echo('<div class="currentPage">'.($a).'</div>');
+ } else {
+ echo('<div><a href="'.$baseUrl.$a.'">'.($a).'</a></div>');
+ }
+ } else {
+ $skipped = true;
+ }
+ }
+ # povezava na naslednjo stran
+ $next_page = ($current + 1) ? ($current + 1) : $current;
+ if(($current ) < $all) {
+ echo('<div><a href="'.$baseUrl.$next_page.'">'.$lang['next_page_short'].'</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">'.$lang['next_page_short'].'</div>');
+ }
+ if ($all > 10) {
+ if ($current + 10 < $all) {
+ echo('<div><a href="'.$baseUrl.($current + 10).'">+10</a></div>');
+ } else {
+ # brez href povezave
+ echo('<div class="disabledPage">+10</div>');
+ }
+ }
+
+ $rec_on_page = $all != $current ? REC_ON_PAGE : ( $all_records - ($all-1)*REC_ON_PAGE);
+ echo '<div class="justtext">'.$lang['srv_inv_pagination_shown'].$rec_on_page.$lang['srv_inv_pagination_shown_records'].'</div>';
+ echo '</div>';
+ }
+ }
+
+ function saveArchiveComment() {
+ $id = $_POST['aid'];
+ $comment = $_POST['comment'];
+ if ((int)$id > 0) {
+ $sql_string = "UPDATE srv_invitations_archive SET comment= '".$comment ."' WHERE id = '".$id."'";
+ $sqlQuery = sisplet_query($sql_string);
+ sisplet_query("COMMIT");
+ }
+ }
+
+ function generateMessageName() {
+ global $lang;
+ # poiščemo nov naslov
+ # zaporedno številčimo ime sporočilo1,2.... če slučajno ime že obstaja
+ $new_name = $lang['srv_inv_message_draft_name'];
+ $names = array();
+ $s = "SELECT naslov FROM srv_invitations_messages WHERE ank_id = '".$this->sid."' AND naslov LIKE '%".$new_name."%'";
+ $q = sisplet_query($s);
+ while (list($naslov) = mysqli_fetch_row($q)) {
+ $names[] = $naslov;
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_message_draft_name'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_message_draft_name'].$cnt;
+ }
+ return $new_name;
+ }
+
+ function editMessageDetails() {
+ global $lang;
+
+ echo '<div id="inv_recipients_profile_name">';
+ echo $lang['srv_inv_message_draft_new_save'].':&nbsp;';
+
+ # polovimo vsa sporočila
+ $sql_string = "SELECT * FROM srv_invitations_messages WHERE ank_id = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+
+ echo '<select onchange="inv_new_message_list_change(this);" autofocus="autofocus" tabindex="2">';
+ echo '<option value="0" selected="selected" class="gray bold">'.$lang['srv_inv_message_draft_new'].'</option>';
+ $messages = array();
+ while ( $row = mysqli_fetch_assoc($sql_query) ) {
+ $messages[$row['id']] = $row;
+ #'.((int)$_POST['mid'] == $row['id'] ? ' selected="selected"' : '').'
+ echo '<option value="'.$row['id'].'" comment="'.$row['comment'].'">'.$row['naslov'].'</option>';
+ }
+ echo '</select>';
+ #'.((int)$_POST['mid'] > 0 ? ' class="displayNone"' : '').'
+ echo '<span id="new_message_list_span">';
+ echo '<br><br/>';
+ echo '<label>'.$lang['srv_inv_message_rename_new_name'];
+ $newName = $this->generateMessageName();
+
+ echo '<input type="text" id="rec_profile_name" value="'.$newName.'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+ echo '<br/><br/>';
+ echo $lang['srv_inv_message_draft_list_comment'];
+ #.((int)$_POST['mid'] > 0 ? $messages[(int)$_POST['mid']]['comment'] : '').
+ echo '<textarea id="inv_message_comment" tabindex="3" rows="2" style="width:200px;"></textarea>';
+ echo '<br class="clr" /><br class="clr" />';
+ echo '<span class="buttonwrapper floatRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_message_save_details(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</div>'; # id="inv_view_arch_recipients"
+
+ }
+
+ function messageSaveDetails() {
+ global $lang, $global_user_id;
+ $return = array('msg'=>'', 'error'=>'0');
+
+ #echo json_encode($return);
+ $mid = (int)$_POST['mid'];
+ $return['mid'] = $mid;
+
+ $comment = trim($_POST['profile_comment']);
+ $naslov = trim($_POST['naslov']);
+
+ $body = $_POST['body'];
+ $subject = $_POST['subject'];
+
+ if ($mid > 0) {
+ #updejtamo obstoječ profil
+ $sql_string = "UPDATE srv_invitations_messages SET subject_text='".$subject."', body_text='".$body."', comment='".$comment."', edit_uid='".$global_user_id."', edit_time=NOW() WHERE ank_id = '$this->sid' AND id='$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+ $return['mid'] = $mid;
+
+ if ( $sqlQuery != 1) {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+ sisplet_query("COMMIT");
+
+ } else {
+ # shranimo v nov profil
+ # ali shranjujemo v novo sporočilo
+ $sql_insert = "INSERT INTO srv_invitations_messages (ank_id, naslov, isdefault, uid, insert_time, comment, edit_uid, edit_time, subject_text, body_text) "
+ ."VALUES ('$this->sid', '$naslov', '1', '$global_user_id', NOW(), '$comment', '$global_user_id', NOW(), '$subject', '$body')";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ $mid = mysqli_insert_id($GLOBALS['connect_db']);
+ if ($mid > 0) {
+ $return['mid'] = $mid;
+ # popravmo še isdefault pri starem zapisz
+ $sql_string = "UPDATE srv_invitations_messages SET isdefault = '0' WHERE ank_id = '$this->sid' AND id != '$mid'";
+ $sqlQuery = sisplet_query($sql_string);
+ } else {
+ $return['error'] = '1';
+ $return['msg'] .= $newline.$lang['srv_inv_msg_4'];
+ }
+ sisplet_query("COMMIT");
+ }
+ echo json_encode($return);
+ exit;
+ }
+
+ function prepareSaveMessage() {
+ global $lang;
+
+ echo '<div id="inv_recipients_profile_name">';
+ echo $lang['srv_inv_message_draft_new_save'].':&nbsp;';
+
+ # polovimo vsa sporočila
+ $sql_string = "SELECT * FROM srv_invitations_messages WHERE ank_id = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+
+ echo '<select onchange="inv_new_message_list_change(this);" autofocus="autofocus" tabindex="2">';
+ echo '<option value="0" class="gray bold">'.$lang['srv_inv_message_draft_new'].'</option>';
+ $messages = array();
+ while ( $row = mysqli_fetch_assoc($sql_query) ) {
+ $messages[$row['id']] = $row;
+ echo '<option value="'.$row['id'].'" comment="'.$row['comment'].'"'.((int)$_POST['mid'] == $row['id'] ? ' selected="selected"' : '').'>'.$row['naslov'].'</option>';
+ }
+ echo '</select>';
+ echo '<span id="new_message_list_span"'.((int)$_POST['mid'] > 0 ? ' class="displayNone"' : '').'>';
+ echo '<br><br/>';
+ echo '<label>'.$lang['srv_inv_message_draft_list_name'];
+ $newName = $this->generateMessageName();
+
+ echo '<input type="text" id="rec_profile_name" value="'.$newName.'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+ echo '<br/><br/>';
+ echo $lang['srv_inv_message_draft_list_comment'];
+ echo '<textarea id="inv_message_comment" tabindex="3" rows="2" style="width:200px;">'.((int)$_POST['mid'] > 0 ? $messages[(int)$_POST['mid']]['comment'] : '').'</textarea>';
+ echo '<br class="clr" /><br class="clr" />';
+ echo '<span class="buttonwrapper floatLeft spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_message_save_details(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</div>'; # id="inv_view_arch_recipients"
+
+ }
+
+ function showRecipientTracking() {
+ global $lang,$site_url,$global_user_id;
+ $_rec_id = $_POST['rid'];
+
+ # polovimo podatke o uporabniku
+ $sql_string = "SELECT firstname,lastname,email,last_status, DATE_FORMAT(date_inserted,'%d.%m.%Y, %T') AS di FROM srv_invitations_recipients WHERE id = '".(int)$_rec_id."'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_row = mysqli_fetch_assoc($sql_query);
+
+ $avtor = array();
+ if (trim($sql_row['firstname'])) {
+ $avtor[] = iconv("iso-8859-2", "utf-8",trim ($sql_row['firstname']));
+ }
+ if (trim($sql_row['lastname'])) {
+ $avtor[] = iconv("iso-8859-2", "utf-8",trim ($sql_row['lastname']));
+ }
+ $lastStatus = $sql_row['last_status'];
+
+ echo '<div id="inv_view_arch_recipients" class="singleRec">';
+
+
+ echo '<div class="inv_FS_content">';
+ echo '<div id="inv_arch_mail_preview">';
+
+ echo '<span class="strong" style="font-size: 14px;">'.$lang['srv_invitation_user_chronology_note'];
+ if ( count($avtor) > 0 ) {
+ echo '<span>';
+ echo implode(' ',$avtor);
+ if($sql_row['email'] != '')
+ echo ' ('.trim($sql_row['email']).')';
+ echo '</span>';
+ } else {
+ # izpišemo samo email
+ echo trim($sql_row['email']);
+ }
+ echo '</span>';
+
+ echo '<br/>';
+ echo $lang['srv_inv_recipients_date_inserted'].': '.$sql_row['di'];
+ # polovimo podatke uporabnikovih arhivov
+ $sql_string = "SELECT ia.*, u.name, u.surname, u.email FROM srv_invitations_archive AS ia LEFT JOIN users AS u ON ia.uid = u.id WHERE ia.id IN (SELECT inv_arch_id FROM srv_invitations_tracking WHERE res_id = '$_rec_id' ) ";
+ $sql_query = sisplet_query($sql_string);
+
+ $cnt =0;
+
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $cnt++;
+ $avtor_email = iconv("iso-8859-2", "utf-8",trim ($sql_row['email']));
+ $avtor = array();
+ if (trim($sql_row['name'])) {
+ $avtor[] = trim ($sql_row['name']);
+ }
+ if (trim($sql_row['surname'])) {
+ $avtor[] = trim ($sql_row['surname']);
+ }
+ if ( count($avtor) > 0 ) {
+ $avtor_name = implode(' ',$avtor);
+ } else {
+ $avtor_name = $avtor_email;
+ }
+
+ echo '<div style="font-weight:600; padding:5px 0px; ">';
+ echo $cnt.$lang['srv_invitation_user_chronology_sending'];
+ echo ' ('.$lang['srv_invitation_user_chronology_send_by'];
+ echo ' <span title="'.$avtor_email.'">'.$avtor_name.'</span>';
+ echo ')';
+ echo '</div>';
+
+
+ echo '<div style="margin-left:25px;margin-bottom:10px;">';
+
+ echo '<table id="tbl_respondentArchive">';
+
+ echo '<tr>';
+
+ echo '<th>'.$lang['srv_invitation_user_chronology_date'].'</th>';
+ // Volitve nimajo nekaterih polj
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting'))
+ echo '<th>'.$lang['srv_invitation_user_chronology_status'].'</th>';
+ echo '<th>'.$lang['srv_inv_message_type'].'</th>';
+
+ echo '</tr>';
+
+ $sql_string1 = "SELECT status, DATE_FORMAT(time_insert,'%d.%m.%Y, %T') AS status_time FROM srv_invitations_tracking WHERE res_id = '$_rec_id' AND inv_arch_id='".$sql_row['id']."' ORDER BY uniq ASC";
+ $sql_query1 = sisplet_query($sql_string1);
+ while ($sql_row1 = mysqli_fetch_assoc($sql_query1)) {
+ echo '<tr>';
+
+ echo '<td>'.$sql_row1['status_time'].'</td>';
+
+ // Volitve nimajo nekaterih polj
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting'))
+ echo '<td>('.$sql_row1['status'].') - '.$lang['srv_userstatus_'.$sql_row1['status']].'</td>';
+
+ echo '<td>';
+ if ($sql_row['tip'] == '0')
+ echo $lang['srv_inv_message_noemailing_type1'];
+ elseif($sql_row['tip'] == '1')
+ echo $lang['srv_inv_message_noemailing_type2'];
+ elseif($sql_row['tip'] == '2')
+ echo $lang['srv_inv_message_noemailing_type3'];
+ else
+ echo $lang['email'];
+ echo '</td>';
+
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '</div>';
+ }
+
+ // Volitve nimajo nekaterih polj
+ if(!SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ echo '<div style="padding:5px 0px;">';
+ echo '<span style="font-weight:600;">'.$lang['srv_inv_recipients_final_status'].'</span> ('.$lastStatus.') - '.$lang['srv_userstatus_'.$lastStatus];
+ echo '</div>';
+ }
+
+ echo '</div>'; // inv_select_mail_preview
+
+ echo '</div>'; // id="arc_content"
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ #echo '<span class="floatRight spaceLeft"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_arch_save_comment(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_arch_recipients_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+
+ }
+ function showArchiveRecipients($_arch_id = null, $archType = 'all') {
+ global $lang,$site_url,$global_user_id;
+ echo '<div id="inv_view_arch_recipients" class="fromArchive">';
+ if ($_arch_id == null) {
+ $_arch_id = $_POST['aid'];
+ }
+
+ #polovimo podatke arhiva
+ $sql_string = "SELECT sia.*, DATE_FORMAT(sia.date_send,'%d.%m.%Y, %T') AS ds, u.name, u.surname, u.email FROM srv_invitations_archive AS sia LEFT JOIN users AS u ON sia.uid = u.id WHERE sia.id = '".$_arch_id."'";
+ $sql_query = sisplet_query($sql_string);
+ $row = mysqli_fetch_assoc($sql_query);
+
+ # polovimo sezname
+ $lists = array();
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."')";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $lists[$sql_row['pid']] = $sql_row['name'];
+ }
+
+ $lists['-1'] = $lang['srv_invitation_new_templist'];
+ $lists['0'] = $lang['srv_invitation_new_templist_author'];
+
+ #max ststusi po userjih
+ $arch_user_max_status = array();
+ $str_max_status = "select res_id AS rid, max(status) AS usr_status from srv_invitations_tracking where inv_arch_id = '$_arch_id' GROUP BY res_id";
+ $qry_max_status = sisplet_query($str_max_status);
+ while (list($res_id,$arch_status) = mysqli_fetch_row($qry_max_status)) {
+ $arch_user_max_status[$res_id] = $arch_status;
+ }
+ #$data = explode('_',$_POST['arch_to_view']);
+ #$_success = (int)$data[2];
+ #$_arch_id = $data[3];
+ $sql_string = "SELECT * FROM srv_invitations_archive WHERE id = '$_arch_id'";
+ $sql_query = sisplet_query($sql_string);
+ $sql_a_row = mysqli_fetch_assoc($sql_query);
+
+ #$sql_string = "SELECT id as res_id,email,firstname,lastname, password,sent,responded,unsubscribed,deleted,list_id,last_status FROM srv_invitations_recipients WHERE id IN (SELECT DISTINCT res_id FROM srv_invitations_tracking WHERE inv_arch_id = '$_arch_id' )";
+ $sql_string = "SELECT DISTINCT sir.id as res_id,sir.email,sir.firstname,sir.lastname, sir.password,sir.sent,sir.responded,sir.unsubscribed,sir.deleted,"
+ ."sir.list_id,sir.last_status FROM srv_invitations_recipients AS sir INNER JOIN srv_invitations_tracking AS sit ON sir.id = sit.res_id WHERE sit.inv_arch_id = '$_arch_id'";
+
+ // prikazujemo samo napake
+ if ($archType == 'err') {
+ $sql_string = "SELECT DISTINCT sir.id as res_id,sir.email,sir.firstname,sir.lastname, sir.password,sir.sent,sir.responded,sir.unsubscribed,sir.deleted,"
+ ."sir.list_id,sir.last_status FROM srv_invitations_recipients AS sir INNER JOIN srv_invitations_tracking AS sit ON sir.id = sit.res_id "
+ ." JOIN srv_invitations_archive_recipients siar ON sir.id = siar.rec_id AND siar.arch_id = sit.inv_arch_id AND siar.success = '0'"
+ ."WHERE sit.inv_arch_id = '$_arch_id'";
+
+ }
+ // priazujemo samo ok
+ if ($archType == 'succ') {
+ $sql_string = "SELECT DISTINCT sir.id as res_id,sir.email,sir.firstname,sir.lastname, sir.password,sir.sent,sir.responded,sir.unsubscribed,sir.deleted,"
+ ."sir.list_id,sir.last_status FROM srv_invitations_recipients AS sir INNER JOIN srv_invitations_tracking AS sit ON sir.id = sit.res_id "
+ ." JOIN srv_invitations_archive_recipients siar ON sir.id = siar.rec_id AND siar.arch_id = sit.inv_arch_id AND siar.success = '1'"
+ ."WHERE sit.inv_arch_id = '$_arch_id'";
+
+ }
+
+ $sql_query = sisplet_query($sql_string);
+
+ echo '<div class="inv_FS_content">';
+
+ $avtor_email = iconv("iso-8859-2", "utf-8",trim ($row['email']));
+ $avtor = array();
+ if (trim($row['name'])) {
+ $avtor[] = trim ($row['name']);
+ }
+ if (trim($row['surname'])) {
+ $avtor[] = trim ($row['surname']);
+ }
+ if ( count($avtor) > 0 ) {
+ $avtor_name = implode(' ',$avtor);
+ } else {
+ $avtor_name = $avtor_email;
+ }
+
+ echo '<br />';
+
+ echo '<span class="inv_dashboard_sub_detail">';
+ echo $lang['srv_inv_archive_naslov'];
+ echo ': <span class="bold"><a href="#" onclick="inv_arch_edit_details(\''.$row['id'].'\'); return false;">'.$row['naslov'].'</a>';
+ echo '</span></span><br />';
+
+ echo '<span class="inv_dashboard_sub_detail">';
+ echo $lang['srv_invitation_user_chronology_send_by'];
+ echo ' <span class="bold"><span title="'.$avtor_email.'">'.$avtor_name.'</span>';
+ echo ', ';
+ echo $row['ds'];
+ echo '</span></span><br />';
+
+ echo '<span class="inv_dashboard_sub_detail">';
+ echo $lang['srv_inv_message_type'];
+ echo ': <span class="bold">';
+ if ($row['tip'] == '0')
+ echo $lang['srv_inv_message_noemailing_type1'];
+ elseif($row['tip'] == '1')
+ echo $lang['srv_inv_message_noemailing_type2'];
+ elseif($row['tip'] == '2')
+ echo $lang['srv_inv_message_noemailing_type3'];
+ else
+ echo $lang['email'];
+ echo '</span></span>';
+
+ echo '<div id="inv_arch_mail_preview">';
+
+ echo '<table id="tbl_recipients_list">';
+
+ echo '<tr>';
+
+ // Pri volitvah ne prikazemo nekaterih stolpcev
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_sent'].'">'.$lang['srv_inv_recipients_sent'].'</th>';
+ echo '<th class="tbl_inv_left">'.$lang['srv_inv_recipients_email'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_firstname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_lastname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_list_id'].'</th>';
+ }
+ else{
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_sent'].'">'.$lang['srv_inv_recipients_sent'].'</th>';
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_responded'].'">'.$lang['srv_inv_recipients_responded'].'</th>';
+ echo '<th class="tbl_icon" title="'.$lang['srv_inv_recipients_unsubscribed'].'">'.$lang['srv_inv_recipients_unsubscribed'].'</th>';
+ echo '<th class="tbl_inv_left">'.$lang['srv_inv_recipients_email'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_password'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_firstname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_lastname'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_max_archive_status'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_last_status'].'</th>';
+ echo '<th>'.$lang['srv_inv_recipients_list_id'].'</th>';
+ }
+
+ echo '</tr>';
+
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ echo '<tr>';
+
+ // Pri volitvah ne prikazemo nekaterih stolpcev
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ echo '<td><span class="as_link" onclick="showRecipientTracking(\''.$sql_row['res_id'].'\'); return false;"><img src="'.$site_url.'admin/survey/img_0/'.((int)$sql_row['sent'] == 1 ? 'email_sent.png' : 'email_open.png').'"></span></td>';
+ echo '<td class="tbl_inv_left">'.$sql_row['email'].'</td>';
+ echo '<td>'.$sql_row['firstname'].'</td>';
+ echo '<td>'.$sql_row['lastname'].'</td>';
+ echo '<td>'.$lists[$sql_row['list_id']].'</td>';
+ }
+ else{
+ echo '<td><span class="as_link" onclick="showRecipientTracking(\''.$sql_row['res_id'].'\'); return false;"><img src="'.$site_url.'admin/survey/img_0/'.((int)$sql_row['sent'] == 1 ? 'email_sent.png' : 'email_open.png').'"></span></td>';
+ echo '<td><img src="'.$site_url.'admin/survey/icons/icons/'.((int)$sql_row['responded'] == 1 ? 'star_on.png' : 'star_off.png').'"></td>';
+ echo '<td><img src="'.$site_url.'admin/survey/img_0/'.((int)$sql_row['unsubscribed'] == 1 ? 'opdedout_on.png' : 'opdedout_off.png').'"></td>';
+ echo '<td class="tbl_inv_left">'.$sql_row['email'].'</td>';
+ echo '<td>'.$sql_row['password'].'</td>';
+ echo '<td>'.$sql_row['firstname'].'</td>';
+ echo '<td>'.$sql_row['lastname'].'</td>';
+ $status = $arch_user_max_status[$sql_row['res_id']];
+ echo '<td>'.$lang['srv_userstatus_'.$status].' ('.$status.')'.'</td>';
+ echo '<td>'.$lang['srv_userstatus_'.$sql_row['last_status']].' ('.$sql_row['last_status'].')'.'</td>';
+ echo '<td>'.$lists[$sql_row['list_id']].'</td>';
+ }
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+ echo '</div>'; // inv_select_mail_preview
+
+ echo '</div>'; // id="arc_content"
+
+ echo '<br />';
+
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ #echo '<span class="floatRight spaceLeft"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_arch_save_comment(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_arch_recipients_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function editArchiveDetails() {
+ global $lang,$site_url;
+ echo '<div id="inv_view_arch_recipients">';
+
+ $_arch_id = $_POST['aid'];
+
+ #polovimo podatke arhiva
+ $sql_string = "SELECT * FROM srv_invitations_archive WHERE id = '".$_arch_id."'";
+ $sql_query = sisplet_query($sql_string);
+ $row = mysqli_fetch_assoc($sql_query);
+
+ echo '<div class="inv_FS_content">';
+ echo '<div id="inv_arch_mail_preview">';
+
+ echo '<input id="inv_arch_id" type="hidden" value="'.$_arch_id.'">';
+
+ echo '<table id="inv_arch_mail_preview">';
+ echo '<tr><td class="bold">'.$lang['srv_inv_message_draft_content_subject'].':</td>';
+ echo '<td class="inv_bt bold">';
+ echo '<span>'.$row['subject_text'].'</span>';
+ echo '</td></tr>';
+ echo '<tr><td>'.$lang['srv_inv_message_draft_content_body'].':</td>';
+ echo '<td class="inv_bt">';
+ echo '<span class="nl2br">'.($row['body_text']).'</span>';
+ echo '</td></tr>';
+ echo '<tr><td>'.$lang['srv_inv_message_draft_comment'].':</td>';
+ echo '<td>';
+ echo '<span>';
+ echo '<textarea id="inv_arch_comment" rows="2" style="width:380px;">'.$row['comment'].'</textarea>';
+ echo '</span>';
+ echo '</td></tr>';
+ echo '</table>';
+ echo '</div>'; // inv_select_mail_preview
+
+ echo '</div>'; // id="arc_content"
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ echo '<span class="floatRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_arch_save_comment(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_arch_recipients_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+ }
+ function showArchiveDetails() {
+ global $lang,$site_url;
+ echo '<div id="inv_view_arch_recipients">';
+
+ $_arch_id = $_POST['aid'];
+
+ #polovimo podatke arhiva
+ $sql_string = "SELECT * FROM srv_invitations_archive WHERE id = '".$_arch_id."'";
+ $sql_query = sisplet_query($sql_string);
+ $row = mysqli_fetch_assoc($sql_query);
+ echo '<div class="inv_FS_content">';
+ echo '<div id="inv_arch_mail_preview">';
+
+ echo '<table id="inv_arch_mail_preview">';
+ echo '<tr><td>'.$lang['srv_inv_message_draft_content_subject'].':</td>';
+ echo '<td class="inv_bt">';
+ echo '<span>'.$row['subject_text'].'</span>';
+ echo '</td></tr>';
+ echo '<tr><td>'.$lang['srv_inv_message_draft_content_body'].':</td>';
+ echo '<td class="inv_bt">';
+ echo '<span class="nl2br">'.($row['body_text']).'</span>';
+ echo '</td></tr>';
+ echo '<tr><td>'.$lang['srv_inv_message_draft_comment'].':</td>';
+ echo '<td>';
+ echo '<span>';
+ echo '<div id="inv_arch_comment" rows="2" style="width:380px;">'.$row['comment'].'</div>';
+ echo '</span>';
+ echo '</td></tr>';
+ echo '</table>';
+ echo '</div>'; // inv_select_mail_preview
+
+ echo '</div>'; // id="arc_content"
+ echo '<div class="inv_FS_btm">';
+ echo '<div id="navigationBottom" class="printHide">';
+ #echo '<span class="floatRight spaceLeft"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_arch_save_comment(); return false;"><span>'.$lang['save'].'</span></a></div></span>';
+ echo '<span class="floatRight spaceRight"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_arch_recipients_close(); return false;"><span>'.$lang['srv_zapri'].'</span></a></div></span>';
+ echo '<div class="clr" />';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function showInvitationStatus() {
+ global $admin_type, $app_settings, $global_user_id;
+
+ $isEmail = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+ $d = new Dostop();
+
+ echo '<table style="width:50%"><tr>';
+
+ // Pri volitvah prikazemo samo osnovne stevilke - zaradi anonimizacije ni trackinga
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ // Ce so izklopljena ne prikazemo leve strani
+ if((int)$isEmail > 0 && $userAccess->checkUserAccess($what='invitations')){
+ echo '<td style="padding-right:10px;vertical-align: top;">';
+ $this->displayInvitationStatusVoting();
+ echo '</td>';
+ }
+ }
+ // Nov način z trackingom
+ elseif($this->newTracking == true) {
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ // Ce so izklopljena ne prikazemo leve strani
+ if((int)$isEmail > 0 && $userAccess->checkUserAccess($what='invitations')){
+ echo '<td style="padding-right:10px;vertical-align: top;">';
+ $this->displayInvitationStatusNew();
+ echo '</td>';
+ }
+ }
+ # star način brez trackinga
+ else {
+ echo '<td style="padding-right:10px;vertical-align: top;">';
+ $this->displayInvitationStatusOld();
+ echo '</td>';
+ }
+
+ echo '</tr></table>';
+ }
+
+ function displayInvitationStatusOld() {
+ global $lang, $admin_type, $global_user_id, $site_url, $site_path;
+
+ $isEmail = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+
+ # polovimo lurkerje
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_inv_nav_email_status'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<p>';
+ if ((int)$isEmail > 0) {
+
+ # preštejemo respondente po statusu
+ $recipients_by_status = array();
+ $sql_string = "SELECT count(*) as cnt, last_status FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0' GROUP BY last_status";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) > 0) {
+ while($row = mysqli_fetch_assoc($sql_query)) {
+ $recipients_by_status['all'] += (int)$row['cnt'];
+ switch ((int)$row['last_status']) {
+ # 0 - E-pošta - ni poslana
+ case 0:
+ $recipients_by_status['not_send'] += (int)$row['cnt'];
+ break;
+ # 1 - E-pošta - neodgovor
+ case 1:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ break;
+ # 2 - E-pošta - napaka
+ case 2:
+ $recipients_by_status['not_send'] += (int)$row['cnt'];
+ $recipients_by_status['error'] += (int)$row['cnt'];
+ break;
+ # 3 - klik na nagovor
+ case 3:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ $recipients_by_status['clicked'] += (int)$row['cnt'];
+ break;
+ # 4 - klik na anketo
+ case 4:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ $recipients_by_status['clicked'] += (int)$row['cnt'];
+ break;
+ # 5 - delno prazna
+ case 5:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ $recipients_by_status['clicked'] += (int)$row['cnt'];
+ break;
+ # 6 - končana
+ case 6:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ #$recipients_by_status['clicked'] += (int)$row['cnt'];
+ $recipients_by_status['finished'] += (int)$row['cnt'];
+ break;
+ # null - neznan
+ default:
+ $recipients_by_status['unknown'] += (int)$row['cnt'];
+ break;
+ }
+ }
+ $all_rec_in_survey = (int)$recipients_by_status['all'];
+
+ echo '<table class="inv_dashboard_table">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_all'].'</th>';
+ echo '<th>'.(int)$recipients_by_status['all'].'</th>';
+ echo '<th>-</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+ #popslano enotam
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_send'].'</th>';
+ echo '<th>'.(int)$recipients_by_status['send'].'</th>';
+ echo '<th>'.((int)$recipients_by_status['send'] > 0 ? '100%' : '0%').'</th>';
+ echo '<th>'.$this->formatNumber(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['send']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</th>';
+ echo '</tr>';
+
+ #neodgovori
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unanswered'].'</td>';
+ $unanswered = ((int)$recipients_by_status['send']-(int)$recipients_by_status['clicked']-(int)$recipients_by_status['finished']);
+ echo '<td>'.$unanswered.'</td>';
+ echo '<td>'.$this->formatNumber(($unanswered > 0 ? $unanswered*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(($unanswered > 0 ? $unanswered*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_clicked'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['clicked'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['clicked'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['clicked'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ #če se slučajno pojavijo kaki neznani statusi
+ if ((int)$recipients_by_status['unknown'] > 0) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unknown'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['unknown'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['unknown'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['unknown'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_finished'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['finished'].'</td>';
+ echo '<td class="red">'.$this->formatNumber(((int)$recipients_by_status['finished'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td class="">'.$this->formatNumber(((int)$recipients_by_status['finished'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '<br>';
+ # zloopamo še po posameznih pošiljanjih
+ $sql_string_arc = "SELECT sia.*, DATE_FORMAT(sia.date_send,'%d.%m.%Y, %T') AS ds, u.name, u.surname, u.email FROM srv_invitations_archive AS sia LEFT JOIN users AS u ON sia.uid = u.id WHERE ank_id = '".$this->sid."' AND cnt_succsess > 0 ORDER BY sia.date_send ASC;";
+ $sql_query_arc = sisplet_query($sql_string_arc);
+
+ if (mysqli_num_rows($sql_query_arc) > 1) {
+ $cnt=0;
+ while($row_arc = mysqli_fetch_assoc($sql_query_arc)) {
+ $cnt++;
+ # preštejemo respondente po statusu
+ $recipients_by_status = array();
+ $sql_string = "SELECT count(*) as cnt, last_status FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted='0' AND id IN (select rec_id from srv_invitations_archive_recipients where arch_id = ".$row_arc['id']." AND success !='0') GROUP BY last_status";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) > 0) {
+ while($row = mysqli_fetch_assoc($sql_query)) {
+ $recipients_by_status['all'] += (int)$row['cnt'];
+ switch ((int)$row['last_status']) {
+ # 0 - E-pošta - ni poslana
+ case 0:
+ $recipients_by_status['not_send'] += (int)$row['cnt'];
+ break;
+ # 1 - E-pošta - neodgovor
+ case 1:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ break;
+ # 2 - E-pošta - napaka
+ case 2:
+ $recipients_by_status['not_send'] += (int)$row['cnt'];
+ $recipients_by_status['error'] += (int)$row['cnt'];
+ break;
+ # 3 - klik na nagovor
+ case 3:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ $recipients_by_status['clicked'] += (int)$row['cnt'];
+ break;
+ # 4 - klik na anketo
+ case 4:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ $recipients_by_status['clicked'] += (int)$row['cnt'];
+ break;
+ # 5 - delno prazna
+ case 5:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ $recipients_by_status['clicked'] += (int)$row['cnt'];
+ break;
+ # 6 - končana
+ case 6:
+ $recipients_by_status['send'] += (int)$row['cnt'];
+ #$recipients_by_status['clicked'] += (int)$row['cnt'];
+ $recipients_by_status['finished'] += (int)$row['cnt'];
+ break;
+ # null - neznan
+ default:
+ $recipients_by_status['unknown'] += (int)$row['cnt'];
+ break;
+ }
+ }
+ $avtor_email = iconv("iso-8859-2", "utf-8",trim ($row_arc['email']));
+ $avtor = array();
+ if (trim($row_arc['name'])) {
+ $avtor[] = trim ($row_arc['name']);
+ }
+ if (trim($row_arc['surname'])) {
+ $avtor[] = trim ($row_arc['surname']);
+ }
+ if ( count($avtor) > 0 ) {
+ $avtor_name = implode(' ',$avtor);
+ } else {
+ $avtor_name = $avtor_email;
+ }
+
+ echo '<span class="pointer span_list_archive" onClick="$(this).next().next().next().toggle(); $(this).find(\'.plus\').toggle();$(this).find(\'.minus\').toggle(); $(this).next(\'.link_archive\').toggle();">';
+ echo '<span class="inv_dashboard_sub_title as_link">';
+ echo '<span class="plus" style="color: inherit;">+ </span>';
+ echo '<span class="minus displayNone" style="color: inherit;">- </span>';
+ echo $cnt.$lang['srv_inv_dashboard_list_cnt_title'];
+ echo '</span>';
+ echo '<span class="inv_dashboard_sub_detail" title="'.$avtor_email.'">'.$avtor_name.'</span>';
+ echo ', ';
+ echo '<span class="inv_dashboard_sub_detail" >'.$row_arc['ds'].'</span>';
+ echo '</span>';
+ echo '<span class="link_archive as_link displayNone" ><a href="#" onclick="inv_arch_show_details(\''.$row_arc['id'].'\'); return false;"> arhiv </a></span>';
+ echo '<br/>';
+
+ echo '<table class="inv_dashboard_table sub displayNone">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_all'].'</th>';
+
+ echo '<th>'.(int)$all_rec_in_survey.'</th>';
+ #echo '<th>'.(int)$recipients_by_status['all'].'</th>';
+ echo '<th>&nbsp;</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+ #popslano enotam
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_send'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['send'].'</td>';
+ echo '<td>'.((int)$recipients_by_status['send'] > 0 ? '100%' : '0%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['send']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+
+
+ #neodgovori
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unanswered'].'</td>';
+ $unanswered = ((int)$recipients_by_status['send']-(int)$recipients_by_status['clicked']-(int)$recipients_by_status['finished']);
+ echo '<td>'.$unanswered.'</td>';
+ echo '<td>'.$this->formatNumber(($unanswered > 0 ? $unanswered*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(($unanswered > 0 ? $unanswered*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_clicked'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['clicked'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['clicked'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['clicked'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ #če se slučajno pojavijo kaki neznani statusi
+ if ((int)$recipients_by_status['unknown'] > 0) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unknown'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['unknown'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['unknown'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['unknown'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_finished'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['finished'].'</td>';
+ echo '<td class="red">'.$this->formatNumber(((int)$recipients_by_status['finished'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td class="">'.$this->formatNumber(((int)$recipients_by_status['finished'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ }
+
+ }
+
+ }
+ } else {
+ #Vabil še nismo pošiljali
+ echo $lang['srv_inv_dashboard_empty'].' <a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_INVITATIONS.'&amp;m=add_recipients_view">'.$lang['srv_inv_dashboard_add_link'].'</a>';
+ }
+
+ } else {
+ echo $lang['srv_inv_dashboard_not_enabled'];
+ }
+ echo '</p>';
+ echo '</div>';
+ echo '</fieldset>';
+
+ #pošiljanje po enotah
+ $cnt_by_sendings = array();
+ $all_units_count = 0;
+ # najprej koliko enotam še ni bilo poslano
+ $sel = "select count(*) FROM srv_invitations_recipients WHERE ank_id='$this->sid' AND sent = '0'";
+ $query = sisplet_query($sel);
+ list($count) = mysqli_fetch_row($query);
+ if ($count > 0) {
+ $cnt_by_sendings[0] = (int)$count;
+ }
+ $all_units_count = (int)$count;
+ $sel1 = "select count(*) as cnt, rec_id FROM srv_invitations_archive_recipients WHERE arch_id in (select id from srv_invitations_archive where ank_id = '".$this->sid."') AND success !='0' group by rec_id ORDER BY cnt ASC;";
+ $query1 = sisplet_query($sel1);
+
+ while (list($count, $rec_id) = mysqli_fetch_row($query1)) {
+ $cnt_by_sendings[(int)$count] ++;
+ $all_units_count++;
+ }
+ if (count($cnt_by_sendings) > 0) {
+ echo '<fieldset class="inv_fieldset">';
+ echo '<legend >';
+ echo '<span class="pointer legend" onClick="$(this).parent().parent().find(\'.inv_filedset_inline_div\').toggle(); $(this).find(\'.plus\').toggle();$(this).find(\'.minus\').toggle();">';
+ echo '<span class="plus red strong">+ </span>';
+ echo '<span class="minus red strong displayNone">- </span>';
+ echo $lang['srv_inv_nav_email_sending_status'];
+ echo '</span>';
+ echo Help::display('srv_inv_cnt_by_sending');
+ echo '</legend>';
+ echo '<br/>';
+ echo '<div class="inv_filedset_inline_div displayNone">';
+ echo '<table style="border-spacing: 0px;padding: 0px;margin: 0px;">';
+ echo '<colgrup>';
+ echo '<col style="min-width:150px;"/>';
+ echo '<col style="min-width:150px;"/>';
+ echo '<col style="min-width:150px;"/>';
+ echo '</colgrup>';
+ echo '<tr>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_cnt'].'</th>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_units'].'</th>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_percentage'].'</th>';
+ echo '</tr>';
+ foreach ($cnt_by_sendings AS $cnt => $units) {
+ echo '<tr>';
+ echo '<td>'.$cnt.'</td>';
+ echo '<td>'.$units.'</td>';
+ $percent = ($all_units_count > 0) ? $units / $all_units_count * 100 : 0;
+ echo '<td>'.Common::formatNumber ($percent,0,null,'%').'</td>';
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td class="anl_bt_dot red">'.$lang['srv_inv_sending_overview_sum'].'</td>';
+ echo '<td class="anl_bt_dot red">'.$all_units_count.'</td>';
+ $percent = ($all_units_count > 0) ? $all_units_count / $all_units_count * 100 : 0;
+ echo '<td class="anl_bt_dot red">'.Common::formatNumber ($percent,0,null,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+ }
+
+ // Prikaz statusov posiljanj
+ private function displayInvitationStatusNew() {
+ global $lang, $admin_type, $global_user_id, $site_url, $site_path, $app_settings;
+
+ $isEmail = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ // Email vabila so omogocena
+ if ((int)$isEmail > 0 && $userAccess->checkUserAccess($what='invitations')) {
+
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_inv_nav_email_status'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<p>';
+
+ #koliko je vseh uporabnikov v bazi
+ $sql_query = sisplet_query("SELECT count(*) as cnt FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted ='0'");
+ list($cnt_all_in_db) = mysqli_fetch_row($sql_query);
+
+ #zloopamo skozi posamezna pošiljanja in preštejemo vse potrebno
+ $sql_query = sisplet_query("SELECT sia.id, sia.tip, rec_in_db, DATE_FORMAT(sia.date_send,'%d.%m.%Y, %T') AS ds, u.name, u.surname, u.email
+ FROM srv_invitations_archive AS sia
+ INNER JOIN users AS u ON sia.uid = u.id
+ WHERE ank_id = '".$this->sid."'
+ ORDER BY sia.date_send ASC;
+ ");
+
+ $array_dashboard = array();
+ $array_archive_subdata = array();
+ $user_max_status = array();
+ $user_lurker = array();
+
+ # štetje po pošiljanjih
+ $cnt_by_user = array();
+
+ if (mysqli_num_rows($sql_query) > 0) {
+
+ #loop po vseh arhivih
+ while($row = mysqli_fetch_assoc($sql_query)) {
+ $array_archive_subdata[$row['id']] = $row;
+ $sql_subStr = "SELECT sit.res_id,sit.status FROM srv_invitations_tracking AS sit WHERE sit.inv_arch_id = '".$row['id']."' AND sit.res_id IN (SELECT id FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted ='0')";
+ $sql_subStr = "SELECT sit.res_id,sit.status, su.lurker FROM srv_invitations_tracking AS sit"
+ ." INNER JOIN srv_invitations_recipients AS sir ON sit.res_id = sir.id"
+ ." INNER join srv_user AS su ON sit.res_id = su.inv_res_id"
+ ." WHERE sir.ank_id='$this->sid' AND sir.deleted ='0' AND su.ank_id='$this->sid' AND sit.inv_arch_id = '$row[id]'";
+ $sql_subQry = sisplet_query($sql_subStr);
+ $sub_max = array();
+ #loop po vseh trackingih posameznega arhiva
+ while($subRow = mysqli_fetch_assoc($sql_subQry)) {
+ if ((int)$subRow['status'] == 2) {
+ $subRow['status'] = -2;
+
+ }
+ if ((int)$subRow['status'] == 1) {
+ $cnt_by_user[$subRow['res_id']]++;
+ }
+ #maximalni status uporabnika za posamezen arhiv
+ $sub_max[$subRow['res_id']] = max($sub_max[$subRow['res_id']],$subRow['status']);
+
+ #globalni max statusi posameznih uporabnikov
+ $_userMaxStatus = max($user_max_status[$subRow['res_id']],$subRow['status']);
+ $user_max_status[$subRow['res_id']] = $_userMaxStatus;
+ $user_lurker[$subRow['res_id']] = $subRow['lurker'];
+ }
+ #maximalni statusi uporabniak v posameznem arhivu
+ $array_dashboard[$row['id']] = $sub_max;
+ }
+ }
+
+ # preštejemo respondente po statusu
+ $recipients_by_status = array();
+ $recipients_by_status['all']=(int)$cnt_all_in_db;
+ $user_by_status_for_archive = array();
+ if (count($user_max_status) > 0) {
+
+ foreach ($user_max_status AS $uid => $status) {
+ switch ((int)$status) {
+ # 2 - E-pošta - napaka
+ case -2:
+ $recipients_by_status['not_send'] ++;
+ $recipients_by_status['error'] ++;
+ break;
+ # 0 - E-pošta - ni poslana
+ case 0:
+ $recipients_by_status['not_send'] ++;
+ break;
+ # 1 - E-pošta - neodgovor
+ case 1:
+ $recipients_by_status['send'] ++;
+ break;
+
+ # 3 - klik na nagovor
+ case 3:
+ $recipients_by_status['send'] ++;
+ $recipients_by_status['clicked'] ++;
+ break;
+ # 4 - klik na anketo
+ case 4:
+ $recipients_by_status['send'] ++;
+ $recipients_by_status['clicked'] ++;
+ break;
+ # 5 - delno prazna
+ case 5:
+ $recipients_by_status['send'] ++;
+ #$recipients_by_status['clicked'] ++;
+ if ($user_lurker[$uid] == 1) {
+ # če je lurker
+ $recipients_by_status['clicked'] ++;
+ } else {
+ $recipients_by_status['finished'] ++;
+ }
+ break;
+ # 6 - končana
+ case 6:
+ $recipients_by_status['send'] ++;
+ if ($user_lurker[$uid] == 1) {
+ # če je lurker
+ $recipients_by_status['clicked'] ++;
+ } else {
+ $recipients_by_status['finished'] ++;
+ }
+ break;
+ # null - neznan
+ default:
+ $recipients_by_status['unknown'] ++;
+ break;
+ }
+ }
+ echo '<table class="inv_dashboard_table">';
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_all'].'</th>';
+ echo '<th>'.(int)$recipients_by_status['all'].'</th>';
+ echo '<th>-</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+ #popslano enotam
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_send'].'</th>';
+ echo '<th>'.(int)$recipients_by_status['send'].'</th>';
+ echo '<th>'.((int)$recipients_by_status['send'] > 0 ? '100%' : '0%').'</th>';
+ echo '<th>'.$this->formatNumber(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['send']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</th>';
+ echo '</tr>';
+
+ #neodgovori
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unanswered'].'</td>';
+ $unanswered = ((int)$recipients_by_status['send']-(int)$recipients_by_status['clicked']-(int)$recipients_by_status['finished']);
+ echo '<td>'.$unanswered.'</td>';
+ echo '<td>'.$this->formatNumber(($unanswered > 0 ? $unanswered*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(($unanswered > 0 ? $unanswered*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_clicked'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['clicked'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['clicked'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['clicked'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ #če se slučajno pojavijo kaki neznani statusi
+ if ((int)$recipients_by_status['unknown'] > 0) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unknown'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['unknown'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['unknown'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['unknown'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_finished'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['finished'].'</td>';
+ echo '<td class="red">'.$this->formatNumber(((int)$recipients_by_status['finished'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td class="">'.$this->formatNumber(((int)$recipients_by_status['finished'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['all'] : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '<br>';
+
+
+ # POSAMEZNA pošiljanja
+ if (count($array_dashboard ) > 0) {
+ foreach ($array_dashboard AS $archive_id => $archive_data) {
+ if (count($archive_data ) > 0) {
+ foreach ($archive_data AS $uid => $status) {
+ if ((int)$status == 6 && $user_lurker[$uid] == 1) {
+ $user_by_status_for_archive[$archive_id]['6l']++;
+ } else if ((int)$status == 5 && $user_lurker[$uid] == 1) {
+ $user_by_status_for_archive[$archive_id]['5l']++;
+ } else {
+ $user_by_status_for_archive[$archive_id][$status]++;
+ }
+
+ }
+ }
+ }
+ }
+ $cnt = 0;
+ if (count($user_by_status_for_archive ) > 0) {
+ foreach ($user_by_status_for_archive AS $arch_id => $archive_data) {
+ $cnt++;
+ if (count($archive_data ) > 0) {
+ $recipients_by_status = array();
+ $recipients_by_status['all']=(int)$array_archive_subdata[$arch_id]['rec_in_db'];
+ foreach ($archive_data AS $status => $cntUsers) {
+ # 0 - E-pošta - ni poslana
+ if( $status == '0') {
+ $recipients_by_status['not_send'] +=$cntUsers;
+ # 1 - E-pošta - neodgovor'
+ } else if( $status == '1') {
+ $recipients_by_status['send'] +=$cntUsers;
+ # 2 - E-pošta - napaka
+ } else if( $status == '2') {
+ $recipients_by_status['error'] +=$cntUsers;
+ # 3 - klik na nagovor
+ } else if( $status == '3') {
+ $recipients_by_status['send'] +=$cntUsers;
+ $recipients_by_status['clicked'] +=$cntUsers;
+ # 4 - klik na anketo
+ } else if( $status == '4') {
+ $recipients_by_status['send'] +=$cntUsers;
+ $recipients_by_status['clicked'] +=$cntUsers;
+ # 5 - delno prazna
+ } else if( $status == '5') {
+ $recipients_by_status['send'] +=$cntUsers;
+ #$recipients_by_status['clicked'] +=$cntUsers;
+ $recipients_by_status['finished'] +=$cntUsers;
+
+ # 5 - delno prazna -lurker
+ } else if( $status == '5l') {
+ $recipients_by_status['send'] +=$cntUsers;
+ $recipients_by_status['clicked'] +=$cntUsers;
+
+ # 6 - končana
+ } else if( $status == '6') {
+ $recipients_by_status['send'] +=$cntUsers;
+ $recipients_by_status['finished'] +=$cntUsers;
+ # 6 - končana - lurker
+ } else if( $status == '6l') {
+ $recipients_by_status['send'] +=$cntUsers;
+ $recipients_by_status['clicked'] +=$cntUsers;
+ } else {
+ # null - neznan
+ $recipients_by_status['unknown'] +=$cntUsers;
+ }
+ }
+ $avtor_email = iconv("iso-8859-2", "utf-8",trim ($array_archive_subdata[$arch_id]['email']));
+ $avtor = array();
+ if (trim($array_archive_subdata[$arch_id]['name'])) {
+ $avtor[] = trim ($array_archive_subdata[$arch_id]['name']);
+ }
+ if (trim($array_archive_subdata[$arch_id]['surname'])) {
+ $avtor[] = trim ($array_archive_subdata[$arch_id]['surname']);
+ }
+ if ( count($avtor) > 0 ) {
+ $avtor_name = implode(' ',$avtor);
+ } else {
+ $avtor_name = $avtor_email;
+ }
+ $all_rec_in_survey = (int)$recipients_by_status['all'];
+
+ echo '<span class="pointer span_list_archive" onClick="$(this).next().next().next().toggle(); $(this).find(\'.plus\').toggle();$(this).find(\'.minus\').toggle(); $(this).next(\'.link_archive\').toggle();">';
+
+ echo '<span class="inv_dashboard_sub_title as_link">';
+ echo '<span class="plus" style="color: inherit;">+ </span>';
+ echo '<span class="minus displayNone" style="color: inherit;">- </span>';
+ echo $cnt.$lang['srv_inv_dashboard_list_cnt_title'];
+ echo '</span>';
+
+ // avtor
+ echo '<span style="font-size: 13px;" title="'.$avtor_email.'">'.$avtor_name.'</span>';
+
+ // datum
+ echo ', ';
+ echo '<span style="font-size: 13px;">'.$array_archive_subdata[$arch_id]['ds'].'</span>';
+
+ // nacin posiljanja
+ echo ', ';
+ echo '<span style="font-size: 13px;">';
+ if ($array_archive_subdata[$arch_id]['tip'] == '0')
+ echo '<span>'.$lang['srv_inv_message_noemailing_type1'].'</span>';
+ elseif($array_archive_subdata[$arch_id]['tip'] == '1')
+ echo '<span>'.$lang['srv_inv_message_noemailing_type2'].'</span>';
+ elseif($array_archive_subdata[$arch_id]['tip'] == '2')
+ echo '<span>'.$lang['srv_inv_message_noemailing_type3'].'</span>';
+ else
+ echo '<span>'.$lang['email'].'</span>';
+ echo '</span>';
+
+ echo '</span>';
+
+ // arhiv
+ echo '<span class="link_archive as_link displayNone" style="margin-left:10px;"><a href="#" onclick="inv_arch_show_recipients(\''.$array_archive_subdata[$arch_id]['id'].'\'); return false;"> arhiv </a></span>';
+ echo '<br/>';
+
+
+ echo '<table class="inv_dashboard_table sub displayNone">';
+
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_all'].'</th>';
+ echo '<th>'.(int)$all_rec_in_survey.'</th>';
+ #echo '<th>'.(int)$recipients_by_status['all'].'</th>';
+ echo '<th>&nbsp;</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+
+ # poslano enotam
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_send'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['send'].'</td>';
+ echo '<td>'.((int)$recipients_by_status['send'] > 0 ? '100%' : '0%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$all_rec_in_survey > 0 ? (int)$recipients_by_status['send']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ # neodgovori
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unanswered'].'</td>';
+ $unanswered = ((int)$recipients_by_status['send']-(int)$recipients_by_status['clicked']-(int)$recipients_by_status['finished']);
+ echo '<td>'.$unanswered.'</td>';
+ echo '<td>'.$this->formatNumber(($recipients_by_status['send'] > 0 ? $unanswered*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(($all_rec_in_survey > 0 ? $unanswered*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_clicked'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['clicked'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['clicked']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$all_rec_in_survey > 0 ? (int)$recipients_by_status['clicked']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ #če se slučajno pojavijo kaki neznani statusi
+ if ((int)$recipients_by_status['unknown'] > 0) {
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_unknown'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['unknown'].'</td>';
+ echo '<td>'.$this->formatNumber(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['unknown']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$all_rec_in_survey > 0 ? (int)$recipients_by_status['unknown']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_finished'].'</td>';
+ echo '<td>'.(int)$recipients_by_status['finished'].'</td>';
+ echo '<td class="red">'.$this->formatNumber(((int)$recipients_by_status['send'] > 0 ? (int)$recipients_by_status['finished']*100/(int)$recipients_by_status['send'] : 0),0,'%').'</td>';
+ echo '<td class="">'.$this->formatNumber(((int)$all_rec_in_survey > 0 ? (int)$recipients_by_status['finished']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ #napake
+ if ((int)$recipients_by_status['error'] > 0) {
+ echo '<tr>';
+ echo '<td class="anl_bt">'.$lang['srv_inv_dashboard_tbl_error'].'</td>';
+
+ echo '<td class="anl_bt">'.(int)$recipients_by_status['error'].'</td>';
+ echo '<td class="anl_bt">&nbsp;</td>';
+ echo '<td class="anl_bt">'.$this->formatNumber(((int)$recipients_by_status['error'] > 0 ? (int)$recipients_by_status['error']*100/(int)$all_rec_in_survey : 0),0,'%').'</td>';
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+ }
+ }
+ }
+ } else {
+ // Imamo sezname, ni pa poslanih vabil
+ if ((int)$cnt_all_in_db > 0){
+ echo $lang['srv_inv_dashboard_has_list2'];
+
+ //echo '<p class="spaceLeft bold"><a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_INVITATIONS.'&amp;m=add_recipients_view">'.$lang['srv_inv_dashboard_add_list'].'</a></p>';
+ echo '<div class="buttonwrapper"><a class="ovalbutton floatLeft spaceLeft" href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=add_recipients_view">'.$lang['srv_adding_email_respondents'].'</a></div>';
+ echo '<div class="buttonwrapper"><a class="ovalbutton floatLeft spaceLeft" href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=send_message">'.$lang['srv_inv_message_draft_send'].'</a></div>';
+ echo '<br />';
+
+ //echo '<p class="spaceLeft bold"><a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_INVITATIONS.'&amp;m=view_recipients">'.$lang['srv_inv_dashboard_view_list'].'</a></p>';
+ }
+ // Ni seznamov in ni poslanih vabil
+ else{
+ echo $lang['srv_inv_dashboard_empty'];
+
+ //echo '<p class="spaceLeft bold"><a href="'.$site_url . 'admin/survey/index.php?anketa='.$this->sid.'&amp;a='.A_INVITATIONS.'&amp;m=add_recipients_view">'.$lang['srv_inv_dashboard_add_list'].'</a></p>';
+ echo '<div class="buttonwrapper"><a class="ovalbutton floatLeft spaceLeft" href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=add_recipients_view">'.$lang['srv_adding_email_respondents'].'</a></div>';
+ echo '<br /><br />';
+ }
+ }
+
+ echo '</p>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+ // Email vabila niso omogocena
+ else {
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_inv_nav_email_status'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<p>';
+
+ echo $lang['srv_inv_dashboard_not_enabled'];
+
+ # uporabnik nima pravic omogočit vabil
+ if (!$userAccess->checkUserAccess($what='invitations')) {
+ echo '<br/>'.$lang['srv_inv_dashboard_no_permissions'];
+ }
+ # uporabnik lahko vklopi email vabila
+ else {
+ echo '&nbsp;<a href="#" onclick="enableEmailInvitation(this);">'.$lang['srv_omogoci'].'</a>';
+ }
+
+ echo '</p>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+
+
+ // predpripravimo podatke za vsa pošiljanja
+ $cnt_by_sendings = array();
+
+ $all_units_count = count($cnt_by_user);
+ if ($all_units_count > 0) {
+ foreach ($cnt_by_user AS $uid => $ucnt) {
+ $cnt_by_sendings[$ucnt]++;
+ }
+
+ echo '<br/>';
+
+ #pregled po pošiljanjih
+ echo '<fieldset class="inv_fieldset">';
+
+ echo '<legend>';
+ echo '<span class="pointer" onClick="$(this).parent().parent().find(\'.inv_filedset_inline_div\').toggle(); $(this).find(\'.plus\').toggle();$(this).find(\'.minus\').toggle();">';
+ echo '<span class="plus strong displayNone blue">+ </span>';
+ echo '<span class="minus strong blue">- </span>';
+ echo '<span class="legend blue">'.$lang['srv_inv_nav_email_sending_status'].'</span>';
+ echo '</span>';
+ echo Help::display('srv_inv_cnt_by_sending');
+ echo '</legend>';
+
+ echo '<br/>';
+
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<table style="border-spacing:0px; padding:0px; margin:0 0 20px 15px;">';
+ echo '<colgrup>';
+ echo '<col style="min-width:150px;"/>';
+ echo '<col style="min-width:150px;"/>';
+ echo '<col style="min-width:150px;"/>';
+ echo '</colgrup>';
+ echo '<tr>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_cnt'].'</th>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_units'].'</th>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_percentage'].'</th>';
+ echo '</tr>';
+ if ($cnt_by_sendings > 0) {
+ foreach ($cnt_by_sendings AS $cnt => $units) {
+ echo '<tr>';
+ echo '<td>'.$cnt.'</td>';
+ echo '<td>'.$units.'</td>';
+ $percent = ($all_units_count > 0) ? $units / $all_units_count * 100 : 0;
+ echo '<td>'.Common::formatNumber ($percent,0,null,'%').'</td>';
+ echo '</tr>';
+ }
+ }
+ echo '<tr>';
+ echo '<td class="anl_bt_dot red">'.$lang['srv_inv_sending_overview_sum'].'</td>';
+ echo '<td class="anl_bt_dot red">'.$all_units_count.'</td>';
+ $percent = ($all_units_count > 0) ? $all_units_count / $all_units_count * 100 : 0;
+ echo '<td class="anl_bt_dot red">'.Common::formatNumber ($percent,0,null,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+ }
+
+ // Prikaz statusov posiljanj pri volitvah
+ private function displayInvitationStatusVoting() {
+ global $lang, $admin_type, $global_user_id, $site_url, $site_path, $app_settings;
+
+ $isEmail = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ // Email vabila so omogocena
+ if ((int)$isEmail > 0 && $userAccess->checkUserAccess($what='invitations')) {
+
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_inv_nav_email_status'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<p>';
+
+ #koliko je vseh uporabnikov v bazi in kolkim je bil mail poslan
+ $sql_count = sisplet_query("SELECT count(id) as cnt, sent
+ FROM srv_invitations_recipients
+ WHERE ank_id='".$this->sid."' AND deleted ='0'
+ GROUP BY sent
+ ");
+
+ $cnt_all_in_db = 0;
+ $cnt_sent_in_db = 0;
+ while($row_count = mysqli_fetch_array($sql_count)){
+
+ $cnt_all_in_db += (int)$row_count['cnt'];
+
+ if($row_count['sent'] == '1'){
+ $cnt_sent_in_db += (int)$row_count['cnt'];
+ }
+ }
+
+
+ echo '<table class="inv_dashboard_table">';
+
+ // Vsi v bazi
+ echo '<tr>';
+ echo '<th>'.$lang['srv_inv_dashboard_tbl_all'].'</th>';
+ echo '<th>'.(int)$cnt_all_in_db.'</th>';
+ echo '<th>-</th>';
+ echo '<th>100%</th>';
+ echo '</tr>';
+
+ // Poslani
+ echo '<tr>';
+ echo '<td>'.$lang['srv_inv_dashboard_tbl_send'].'</td>';
+ echo '<td>'.(int)$cnt_sent_in_db.'</td>';
+ echo '<td>'.((int)$cnt_sent_in_db > 0 ? '100%' : '0%').'</td>';
+ echo '<td>'.$this->formatNumber(((int)$cnt_sent_in_db > 0 ? (int)$cnt_sent_in_db*100/(int)$cnt_all_in_db : 0),0,'%').'</td>';
+ echo '</tr>';
+
+ echo '</table>';
+
+ echo '</p>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+ // Email vabila niso omogocena
+ else {
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_inv_nav_email_status'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<p>';
+
+ echo $lang['srv_inv_dashboard_not_enabled'];
+
+ # uporabnik nima pravic omogočit vabil
+ if (!$userAccess->checkUserAccess($what='invitations')) {
+ echo '<br/>'.$lang['srv_inv_dashboard_no_permissions'];
+ }
+ # uporabnik lahko vklopi email vabila
+ else {
+ echo '&nbsp;<a href="#" onclick="enableEmailInvitation(this);">'.$lang['srv_omogoci'].'</a>';
+ }
+
+ echo '</p>';
+ echo '</div>';
+ echo '</fieldset>';
+ }
+
+
+ // predpripravimo podatke za vsa pošiljanja
+ /*$cnt_by_sendings = array();
+
+ $all_units_count = count($cnt_by_user);
+ if ($all_units_count > 0) {
+ foreach ($cnt_by_user AS $uid => $ucnt) {
+ $cnt_by_sendings[$ucnt]++;
+ }
+
+ echo '<br/>';
+
+ #pregled po pošiljanjih
+ echo '<fieldset class="inv_fieldset">';
+
+ echo '<legend>';
+ echo '<span class="pointer" onClick="$(this).parent().parent().find(\'.inv_filedset_inline_div\').toggle(); $(this).find(\'.plus\').toggle();$(this).find(\'.minus\').toggle();">';
+ echo '<span class="plus strong displayNone blue">+ </span>';
+ echo '<span class="minus strong blue">- </span>';
+ echo '<span class="legend blue">'.$lang['srv_inv_nav_email_sending_status'].'</span>';
+ echo '</span>';
+ echo Help::display('srv_inv_cnt_by_sending');
+ echo '</legend>';
+
+ echo '<br/>';
+
+ echo '<div class="inv_filedset_inline_div">';
+ echo '<table style="border-spacing:0px; padding:0px; margin:0 0 20px 15px;">';
+ echo '<colgrup>';
+ echo '<col style="min-width:150px;"/>';
+ echo '<col style="min-width:150px;"/>';
+ echo '<col style="min-width:150px;"/>';
+ echo '</colgrup>';
+ echo '<tr>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_cnt'].'</th>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_units'].'</th>';
+ echo '<th class="anl_al">'.$lang['srv_inv_sending_overview_percentage'].'</th>';
+ echo '</tr>';
+ if ($cnt_by_sendings > 0) {
+ foreach ($cnt_by_sendings AS $cnt => $units) {
+ echo '<tr>';
+ echo '<td>'.$cnt.'</td>';
+ echo '<td>'.$units.'</td>';
+ $percent = ($all_units_count > 0) ? $units / $all_units_count * 100 : 0;
+ echo '<td>'.Common::formatNumber ($percent,0,null,'%').'</td>';
+ echo '</tr>';
+ }
+ }
+ echo '<tr>';
+ echo '<td class="anl_bt_dot red">'.$lang['srv_inv_sending_overview_sum'].'</td>';
+ echo '<td class="anl_bt_dot red">'.$all_units_count.'</td>';
+ $percent = ($all_units_count > 0) ? $all_units_count / $all_units_count * 100 : 0;
+ echo '<td class="anl_bt_dot red">'.Common::formatNumber ($percent,0,null,'%').'</td>';
+ echo '</tr>';
+ echo '</table>';
+ echo '</div>';
+ echo '</fieldset>';
+ }*/
+ }
+
+
+ function showInvitationSettings() {
+ global $lang, $admin_type, $global_user_id, $site_url, $site_path, $app_settings;
+
+ $row = $this->surveySettings;
+ $_email = (int)SurveyInfo::getInstance()->checkSurveyModule('email');
+
+ $sqlu = sisplet_query("SELECT email FROM users WHERE id='".$global_user_id."'");
+ $rowu = mysqli_fetch_array($sqlu);
+ if ($rowu['email'] == '') {
+ $sqlm = sisplet_query("SELECT * FROM misc WHERE what = 'AlertFrom'");
+ $rowm = mysqli_fetch_array($sqlm);
+ $rowu['email'] = $rowm['value'];
+ }
+
+ $userAccess = UserAccess::getInstance($global_user_id);
+
+ $noEmailing = SurveySession::get('inv_noEmailing');
+
+ # Admini, managerji in Clani, ki imajo odobren dostop - lahko vklopijo vabila
+ if ($userAccess->checkUserAccess($what='invitations')) {
+
+ // Vklop vabil
+ if ($_email == 0) {
+
+ echo '<fieldset class="inv_fieldset" style="max-width:800px; padding-bottom:15px;"><legend>'.$lang['srv_invitation_nonActivated_title'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+
+ echo '<p>';
+ echo $lang['srv_invitation_nonActivated_text1'];
+ echo '</p>';
+
+ echo '<p>';
+ if($lang['id'] == '1')
+ echo sprintf($lang['srv_invitation_nonActivated_text2'], 'https://www.1ka.si/d/sl/pomoc/prirocniki/posiljanje-email-vabil-pridobitev-dovoljenja?from1ka=1');
+ else
+ echo sprintf($lang['srv_invitation_nonActivated_text2'], 'https://www.1ka.si/d/en/help/manuals/sending-email-invitations-and-obtaining-authorization?from1ka=1');
+ echo '</p>';
+
+ echo '<p>';
+ // Za gorenje popravimo text
+ $text3 = (Common::checkModule('gorenje')) ? str_replace('1KA', 'ESurvey', $lang['srv_invitation_nonActivated_text3']) : $lang['srv_invitation_nonActivated_text3'];
+ echo $text3;
+ echo '</p>';
+
+ // Gumb OMOGOCI VABILA
+ $text_button = (Common::checkModule('gorenje')) ? str_replace('1KA', 'ESurvey', $lang['srv_invitation_nonActivated_button_activate']) : $lang['srv_invitation_nonActivated_button_activate'];
+ echo '<span class="buttonwrapper floatLeft spaceRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="enableEmailInvitation(\'1\');">'.$text_button.'</a></span>';
+ //echo '<span class="spaceLeft bold" style="line-height:25px;"><a href="https://www.1ka.si/c/804/Email_vabila/?preid=793&from1ka=1">'.$lang['srv_invitation_nonActivated_more'].'</a></span>';
+ echo '<br />';
+
+ echo '</div>';
+ echo '</fieldset>';
+ }
+ // Vabila so vklopljena - NASTAVITVE
+ else{
+
+ if($noEmailing == 1){
+ echo '<table class="invitations_settings" style="width:50%;">';
+ }
+ else{
+ echo '<table class="invitations_settings" style="width:100%;">';
+ echo '<colgroup style="width:48%;"></colgroup>';
+ echo '<colgroup style="width:48%;"></colgroup>';
+ }
+
+ echo '<tr>';
+
+
+ // Leva stran - navadne nastavitve
+ echo '<td style="padding-right:20px;vertical-align: top;">';
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_inv_nav_invitations_settings_general'].' '.Help::display('srv_inv_general_settings').'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+
+ echo '<div id="surveyInvitationSetting">';
+
+ // Preverimo ce je vklopljen modul za volitve - potem ne pustimo nobenih preklopov
+ $voting_disabled = '';
+ if(SurveyInfo::getInstance()->checkSurveyModule('voting')){
+ $voting_disabled = ' disabled';
+
+ // Warning za volitve
+ echo '<p class="red bold">'.$lang['srv_voting_warning'].'</p>';
+ }
+
+ $individual = (int)$this->surveySettings['individual_invitation'];
+
+ // Individualizirana vabila - GLAVNA NASTAVITEV
+ echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['srv_user_base_individual_invitaition'];
+ if($individual == 0)
+ echo ' '.Help::display('srv_user_base_individual_invitaition_note2').' </label>';
+ else
+ echo ' '.Help::display('srv_user_base_individual_invitaition_note').' </label>';
+ echo '<label><input type="radio" name="individual_invitation" value="0" id="individual_invitation_0"'.($individual == 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="surveyBaseSettingRadio(\'individual_invitation\',true);"/>'.$lang['no1'].'</label>';
+ echo '<label><input type="radio" name="individual_invitation" value="1" id="individual_invitation_1"'.($individual == 1 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="surveyBaseSettingRadio(\'individual_invitation\',true);"/>'.$lang['yes'].'</label>';
+ echo '</p>';
+
+ // Ce niso indvidualizirana imamo samo nacin posiljanja
+ if ($individual == 0) {
+
+ // Nacin posiljanja (email, posta, sms...)
+ echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['srv_inv_message_type'].': '.Help::display('srv_inv_sending_type').'</label>';
+ echo '<label><input type="radio" name="inv_messages_noEmailing" value="0" id="inv_messages_noEmailing_1"'.($noEmailing == 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="noEmailingToggle(\'0\');"/>'.$lang['srv_inv_message_noemailing_0'].'</label>';
+ echo '<label><input type="radio" name="inv_messages_noEmailing" value="1" id="inv_messages_noEmailing_1"'.($noEmailing == 1 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="noEmailingToggle(\'1\');"/>'.$lang['srv_inv_message_noemailing_1'].'</label>';
+ echo '</p>';
+
+ // Nacin dokumentiranja (posta, sms, drugo)
+ if($noEmailing == 1){
+ $noEmailingType = SurveySession::get('inv_noEmailing_type');
+ echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['srv_inv_message_type_external'].':</label>';
+ echo '<label><input type="radio" name="noMailType" value="0" id="noMailType1"'.($noEmailingType == 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onClick="noEmailingType(\'0\');" />'.$lang['srv_inv_message_noemailing_type1'].'</label>';
+ echo '<label><input type="radio" name="noMailType" value="1" id="noMailType2"'.($noEmailingType == 1 ? ' checked="checked"' : '').' '.$voting_disabled.' onClick="noEmailingType(\'1\');" />'.$lang['srv_inv_message_noemailing_type2'].'</label>';
+ echo '<label><input type="radio" name="noMailType" value="2" id="noMailType3"'.($noEmailingType == 2 ? ' checked="checked"' : '').' '.$voting_disabled.' onClick="noEmailingType(\'2\');" />'.$lang['srv_inv_message_noemailing_type3'].'</label>';
+ echo '</p>';
+ }
+ }
+ # Normalna vabila z unikatinim URL
+ else {
+
+ // Nacin posiljanja (email, posta, sms...)
+ echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['srv_inv_message_type'].': '.Help::display('srv_inv_sending_type').'</label>';
+ echo '<label><input type="radio" name="inv_messages_noEmailing" value="0" id="inv_messages_noEmailing_1"'.($noEmailing == 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="noEmailingToggle(\'0\');"/>'.$lang['srv_inv_message_noemailing_0'].'</label>';
+ echo '<label><input type="radio" name="inv_messages_noEmailing" value="1" id="inv_messages_noEmailing_1"'.($noEmailing == 1 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="noEmailingToggle(\'1\');"/>'.$lang['srv_inv_message_noemailing_1'].'</label>';
+ echo '</p>';
+
+ // Nacin dokumentiranja (posta, sms, drugo)
+ if($noEmailing == 1){
+ $noEmailingType = SurveySession::get('inv_noEmailing_type');
+ echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['srv_inv_message_type_external'].':</label>';
+ echo '<label><input type="radio" name="noMailType" value="0" id="noMailType1"'.($noEmailingType == 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onClick="noEmailingType(\'0\');" />'.$lang['srv_inv_message_noemailing_type1'].'</label>';
+ echo '<label><input type="radio" name="noMailType" value="1" id="noMailType2"'.($noEmailingType == 1 ? ' checked="checked"' : '').' '.$voting_disabled.' onClick="noEmailingType(\'1\');" />'.$lang['srv_inv_message_noemailing_type2'].'</label>';
+ echo '<label><input type="radio" name="noMailType" value="2" id="noMailType3"'.($noEmailingType == 2 ? ' checked="checked"' : '').' '.$voting_disabled.' onClick="noEmailingType(\'2\');" />'.$lang['srv_inv_message_noemailing_type3'].'</label>';
+ echo '</p>';
+ }
+
+ // Vnos kode - samo ce je email (drugace itak vedno rocni vnos)
+ if($noEmailing != 1){
+ echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['usercode_required1'].':'.Help::display('usercode_required').'</label>';
+ echo '<label><input type="radio" name="usercode_required" value="0" id="usercode_required_0"'.($row['usercode_required'] == 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="surveyBaseSettingRadio(\'usercode_required\',true);"/>'.$lang['usercode_required2'].'</label>';
+ echo '<label><input type="radio" name="usercode_required" value="1" id="usercode_required_1"'.($row['usercode_required'] == 1 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="surveyBaseSettingRadio(\'usercode_required\',true);"/>'.$lang['usercode_required3'].'</label>';
+ echo '</p>';
+ }
+
+ if ($row['usercode_required'] != 0) {
+ echo '<p>';
+ if($noEmailing == 1)
+ echo '<label class="lbl_email_setting">'.$lang['usercode_text2'].': </label><br />';
+ else
+ echo '<label class="lbl_email_setting">'.$lang['usercode_text'].': </label><br />';
+ $nagovorText = ($row['usercode_text'] && $row['usercode_text'] != null && $row['usercode_text'] != "") ? $row['usercode_text'] : $lang['srv_basecode'];
+ echo '<textarea style="width:430px; margin-left:15px; margin-top:5px;" name="usercode_text" onblur="surveyBaseSettingText(\'usercode_text\',false);return false;">'.$nagovorText.'</textarea>';
+ echo '</p>';
+ }
+
+ // Dostop brez kode
+
+
+ echo '<p><label for="usercode_skip_0" class="lbl_email_setting">';
+ echo $lang['srv_user_base_access_check'].' '.Help::display('srv_inv_no_code');
+ echo '<input type="checkbox" name="usercode_skip_checkbox" value="0" id="usercode_skip_0"'.($row['usercode_skip'] != 0 ? ' checked="checked"' : '').' '.$voting_disabled.' onChange="surveyBaseSettingRadio(\'usercode_skip\',true);" />';
+ echo '</label></p>';
+ if($row['usercode_skip'] > 0){
+ echo '<div style="float: left; margin: -10px 0 0 15px;">';
+ echo '<label class="lbl_email_setting">'.$lang['srv_user_base_access'].Help::display('usercode_skip').' </label>';
+ echo '<label><input type="radio" name="usercode_skip" value="1" id="usercode_skip_1"'.($row['usercode_skip'] == 1 ? ' checked="checked"' : '').' onChange="surveyBaseSettingRadio(\'usercode_skip\',true);"/>'.$lang['srv_vsi'].'</label>';
+ echo '<label><input type="radio" name="usercode_skip" value="2" id="usercode_skip_2"'.($row['usercode_skip'] == 2 ? ' checked="checked"' : '').' onChange="surveyBaseSettingRadio(\'usercode_skip\',true);"/>'.$lang['srv_setting_onlyAuthor'].'</label>';
+ echo '</div>';
+ }
+
+ /*echo '<p>';
+ echo '<label class="lbl_email_setting">'.$lang['srv_user_base_access'].Help::display('usercode_skip').' </label>';
+ echo '<label><input type="radio" name="usercode_skip" value="0" id="usercode_skip_0"'.($row['usercode_skip'] == 0 ? ' checked="checked"' : '').' onChange="surveyBaseSettingRadio(\'usercode_skip\',true);"/>'.$lang['no1'].'</label>';
+ echo '<label><input type="radio" name="usercode_skip" value="1" id="usercode_skip_1"'.($row['usercode_skip'] == 1 ? ' checked="checked"' : '').' onChange="surveyBaseSettingRadio(\'usercode_skip\',true);"/>'.$lang['yes'].'</label>';
+ echo '<label><input type="radio" name="usercode_skip" value="2" id="usercode_skip_2"'.($row['usercode_skip'] == 2 ? ' checked="checked"' : '').' onChange="surveyBaseSettingRadio(\'usercode_skip\',true);"/>'.$lang['srv_setting_onlyAuthor'].'</label>';
+ echo '<br/><i class="small">* '.$lang['srv_user_base_access_alert_'.$row['usercode_skip'].''].'</i>';
+ echo '</p>';*/
+ }
+
+ echo '<br />';
+
+ // Gumb shrani - samo provizorično
+ echo '<div class="buttonwrapper"><a class="ovalbutton floatRight" href="#" title="'.$lang['save'].'">'.$lang['save'].'</a></div>';
+ echo '<div class="buttonwrapper"><a class="ovalbutton floatRight spaceRight" href="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=add_recipients_view">'.$lang['srv_adding_email_respondents'].'</a></div>';
+
+
+ echo '</div>';
+
+ echo '</div>';
+ echo '</fieldset>';
+ echo '</td>';
+
+
+ // desna stran - nastavitve streznika - samo ce imamo posiljanje preko emaila
+ if($noEmailing != 1){
+
+ // Gorenje tega nima
+ if (!Common::checkModule('gorenje')){
+
+ echo '<td style="padding-right:10px;vertical-align: top;">';
+ echo '<fieldset class="inv_fieldset"><legend>'.$lang['srv_email_setting_title'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+
+ echo '<div id="surveyInvitationSettingServer">';
+ $this->viewServerSettings();
+ echo '</div>';
+
+ echo '</div>';
+ echo '</fieldset>';
+ echo '</td>';
+ }
+ }
+
+
+ echo '</tr></table>';
+ }
+ }
+ # navadni uporabniki, ki nimajo dostopa - text kako lahko pridobijo dostop
+ else {
+ echo '<fieldset class="inv_fieldset" style="max-width:800px; padding-bottom: 15px;"><legend>'.$lang['srv_invitation_nonActivated_title'].'</legend>';
+ echo '<div class="inv_filedset_inline_div">';
+
+ echo '<p>';
+ echo $lang['srv_invitation_nonActivated_text1'];
+ echo '</p>';
+
+ echo '<p>';
+ if($lang['id'] == '1')
+ echo sprintf($lang['srv_invitation_nonActivated_text2'], 'https://www.1ka.si/d/sl/pomoc/prirocniki/posiljanje-email-vabil-pridobitev-dovoljenja?from1ka=1');
+ else
+ echo sprintf($lang['srv_invitation_nonActivated_text2'], 'https://www.1ka.si/d/en/help/manuals/sending-email-invitations-and-obtaining-authorization?from1ka=1');
+
+ echo '</p>';
+
+ echo '<p>';
+ echo $lang['srv_invitation_nonActivated_text3'];
+ echo '</p>';
+
+ // Gumb ZAPROSI ZA DOSTOP DO VABIL
+ echo '<span class="buttonwrapper floatLeft spaceRight"><a class="ovalbutton ovalbutton_orange" href="https://www.1ka.si/d/sl/pomoc/vodic-za-uporabnike/objava/1ka-vabila/?from1ka=1">'.$lang['srv_invitation_nonActivated_button_details'].'</a></span>';
+ //echo '<span class="spaceLeft bold" style="line-height:25px;"><a href="https://www.1ka.si/c/804/Email_vabila/?preid=793&from1ka=1">'.$lang['srv_invitation_nonActivated_more'].'</a></span>';
+ echo '<br />';
+
+ echo '</div>';
+ echo '</fieldset>';
+ }
+ }
+
+ function formatNumber ($value, $digit = 0, $sufix = "") {
+ if ($value <> 0 && $value != null)
+ $result = round($value, $digit);
+ else
+ $result = "0";
+
+ # polovimo decimalna mesta in vejice za tisočice
+
+ $decimal_point = SurveyDataSettingProfiles :: getSetting('decimal_point');
+ $thousands = SurveyDataSettingProfiles :: getSetting('thousands');
+
+ $result = number_format($result, $digit, $decimal_point, $thousands) . $sufix;
+
+ return $result;
+ }
+
+ function showInvitationLists($profile_id=null) {
+ global $lang,$global_user_id;
+
+ echo '<h2>'.$lang['srv_inv_list_edit_header'].'</h2>';
+
+ echo '<table>';
+ echo '<tr>';
+ echo '<td style="vertical-align:top;min-height:500px; min-width:550px;">';
+ echo '<div style="height:25px; width:100%; ">';
+ echo '<label><input name="inv_show_list_type" id="inv_show_list_type1" type="radio" value="1" onclick="showInvitationListsNames();" checked="checked" autocomplete="off">'.$lang['srv_inv_list_edit_from_this_survey'].'</label>';
+ echo '<label><input name="inv_show_list_type" id="inv_show_list_type2" type="radio" value="0" onclick="showInvitationListsNames();" autocomplete="off">'.$lang['srv_inv_list_edit_from_all_surveys'].'</label>';
+ echo '<label><input name="inv_show_list_type" id="inv_show_list_type3" type="radio" value="2" onclick="showInvitationListsNames();" autocomplete="off">'.$lang['srv_inv_list_edit_from_archive'].'</label>';
+ echo '<label class="as_link spaceLeft" onclick="inv_upload_list();">'.$lang['srv_inv_list_upload_file'].'</label>';
+ echo '</div>';
+ echo '<div id="inv_edit_rec_list">';
+ $this->showInvitationListsNames($profile_id);
+ echo '</div>';
+ echo '</td><td style="padding-left:20px; vertical-align:top;">';
+ echo '<div id="inv_selected_rec_list">';
+ $doEdit = $_SESSION['inv_edit_rec_profile'][$this->sid] == 'true' ? true : false;
+ if ($doEdit) {
+ $this->showEditRecList($profile_id);
+ } else {
+ $this->showNoEditRecList($profile_id);
+ }
+ echo '</div>';
+ echo '</td></tr>';
+ echo '</table>';
+ }
+
+ function showInvitationListsNames($profile_id=null) {
+ global $lang,$global_user_id;
+
+ $onlyThisSurvey = isset($_POST['onlyThisSurvey']) ? (int)$_POST['onlyThisSurvey'] : 1;
+ if ($profile_id == null) {
+ $pids = explode(',',$_POST['pids']);
+ } else {
+ $pids = explode(',',$profile_id);
+ }
+
+ if ($onlyThisSurvey == 0) {
+ #id-ji profilov do katerih lahko dostopamo
+ $accPid = '';
+ $accStr = "SELECT DISTINCT pid FROM srv_invitations_recipients_profiles_access where uid = '$global_user_id'";
+ $accQry = sisplet_query($accStr);
+ while (list($pid) = mysqli_fetch_row($accQry)) {
+ $accPid .= $prefix ."'".$pid."'";
+ $prefix = ',';
+ }
+
+ # polovimo še ostale porfile
+ $sql_string = "SELECT rp.*,DATE_FORMAT(rp.insert_time,'%d.%m.%Y, %T') AS ds, u.name as firstname, u.surname, u.email FROM srv_invitations_recipients_profiles AS rp LEFT JOIN users AS u ON rp.uid = u.id WHERE rp.uid in('".$global_user_id."')".($accPid != '' ? ' OR pid IN ('.$accPid.')':'');
+
+ $sql_query = sisplet_query($sql_string);
+ } else if ($onlyThisSurvey == 2) {
+ $sql_string = "SELECT sia.*,sia.id as pid, sia.naslov AS name, DATE_FORMAT(sia.date_send,'%d.%m.%Y, %T') AS ds, u.name as firstname, u.surname, u.email FROM srv_invitations_archive AS sia LEFT JOIN users AS u ON sia.uid = u.id WHERE ank_id = '".$this->sid."' ORDER BY sia.date_send DESC;";
+ $sql_query = sisplet_query($sql_string);
+ } else {
+ # 1
+ $sql_string = "SELECT rp.*, DATE_FORMAT(rp.insert_time,'%d.%m.%Y, %T') AS ds , u.name as firstname, u.surname, u.email FROM srv_invitations_recipients_profiles AS rp LEFT JOIN users AS u ON rp.uid = u.id WHERE from_survey = '$this->sid'";
+ $sql_query = sisplet_query($sql_string);
+ }
+
+ if (mysqli_num_rows($sql_query)>0) {
+ echo '<table class="inv_edit_rec_list">';
+ echo '<tr>';
+ echo '<th>&nbsp;</th>';
+ if ($onlyThisSurvey != 2) {
+ echo '<th>&nbsp;</th>';
+ echo '<th>&nbsp;</th>';
+ }
+ echo '<th>';
+ echo $lang['srv_inv_list_table_name'];
+ echo '</th>';
+ echo '<th>';
+ echo $lang['srv_inv_list_table_cnt_receive'];
+ echo '</th>';
+ echo '<th>';
+ echo $lang['srv_inv_list_table_comment'];
+ echo '</th>';
+ echo '<th>';
+ echo $lang['srv_inv_list_table_date_create'];
+ echo '</th>';
+ echo '<th>';
+ echo $lang['srv_inv_list_table_author'];
+ echo '</th>';
+ echo '</tr>';
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ echo '<tr>';
+ echo '<td>';
+ echo '<input type="checkbox" class="test_checkAll" id="inv_list_chck_'.$sql_row['pid'].'" onclick="changeInvRecListCheckbox();" value="'.$sql_row['pid'].'" '.(in_array($sql_row['pid'],$pids) ? ' checked="checked"' : '').'autocomplete="off">';
+ echo '</td>';
+ if ($onlyThisSurvey != 2) {
+ echo '<td>';
+ echo '<span class="faicon delete_circle icon-orange_link" onclick="deleteRecipientsList_confirm(\''.$sql_row['pid'].'\'); return false;" title="'.$lang['srv_inv_list_profiles_delete'].'"></span>';
+ echo '</td>';
+ echo '<td>';
+ echo '<span class="faicon quick_edit user smaller icon-as_link" onclick="inv_list_edit(\''.$sql_row['pid'].'\'); return false;" title="'.$lang['srv_inv_list_profiles_edit_access'].'"></span>';
+ echo '</td>';
+ }
+ echo '<td>';
+ echo '<label for="inv_list_chck_'.$sql_row['pid'].'">';
+ echo $sql_row['name'];
+ echo '</label>';
+ echo '</td>';
+ echo '<td>';
+ if (isset($sql_row['respondents'])) {
+ $_recipients = str_replace("\n\r", "\n", $sql_row['respondents']);
+ $_recipients = explode("\n",$_recipients);
+ echo count($_recipients);
+ } else if (isset($sql_row['cnt_succsess']) || isset($sql_row['cnt_error'])) {
+ echo (int)$sql_row['cnt_succsess']+(int)$sql_row['cnt_error'];
+ }
+ echo '</td>';
+ #echo '<td>';
+ #$_fields = explode(",",$sql_row['fields']);
+ #$_fields_lang = array();
+ #foreach ($_fields as $_field) {
+ # $_fields_lang[] = $lang['srv_inv_field_'.$_field];
+ #}
+ #echo implode(',',$_fields_lang);
+ #echo '</td>';
+ echo '<td>';
+ echo $sql_row['comment'];
+ echo '</td>';
+ echo '<td>';
+ echo $sql_row['ds'];
+ echo '</td>';
+ echo '<td title="'.$sql_row['email'].'">';
+ echo $sql_row['firstname'];
+ echo ' '.$sql_row['surname'];
+ echo '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ /*
+ * Osznačevanje vseh seznamov in brisanje le teh*/
+ echo '<div id="inv_bottom_edit">';
+ echo '<span class="faicon arrow_up"></span> ';
+ echo '<span id="inv_switch_on"><a href="#" onClick="inv_list_selectAll(true)">'.$lang['srv_select_all'].'</a></span>';
+ echo '<span id="inv_switch_off" style="display:none;"><a href="#" onClick="inv_list_selectAll(false)">'.$lang['srv_deselect_all'].'</a></span>';
+ echo '&nbsp;&nbsp;<a href="#" onclick="inv_recipients_list_action(\'delete\');"><span class="faicon delete_circle icon-orange" title="'.$lang['srv_invitation_recipients_delete_selected'].'"/></span>&nbsp;'.$lang['srv_invitation_recipients_delete_selected'].'</a>';
+ //echo '&nbsp;&nbsp;<a href="#" onclick="inv_recipients_form_action(\'export\');"><span class="sprites xls delete" style="height:14px; width:16px;" title="'.$lang['srv_invitation_recipients_export_selected'].'"/></span>&nbsp;'.$lang['srv_invitation_recipients_export_selected'].'</a>';
+ echo '</div>';
+ } else {
+ echo $lang['srv_inv_list_no_lists'];
+ }
+ return (int)mysqli_num_rows($sql_query);
+ }
+
+ function showNoEditRecList($profile_id = null) {
+ global $lang;
+ $pids=array();
+ $onlyThisSurvey = (int)$_POST['onlyThisSurvey'];
+ if ($profile_id == null)
+ {
+ # preberemo id-je profilov in respondente
+ if ($_POST['pids'] != '')
+ {
+ $pids = explode(',',$_POST['pids']);
+ }
+ } else
+ {
+ # preberemo id-je profilov in respondente
+ if ($profile_id != '')
+ {
+ $pids = explode(',',$profile_id);
+ }
+ }
+
+ if (empty($pids))
+ {
+ echo $lang['srv_inv_list_choose_left'].'<br>';
+ }
+
+ session_start();
+ $infoBox = null;
+ if (is_array($pids) && count($pids) > 0)
+ {
+ echo '<div style="width:100%; height:25px;"><label><input name="inv_show_list_edit" id="inv_show_list_edit" type="checkbox" value="1" onclick="changeInvRecListEdit();" autocomplete="off">'.$lang['srv_inv_list_edit'].'</label></div>';
+ $respondents = array();
+ $fields = array();
+ # info box prikazujemo samo ko imamo izbran 1 seznam
+ if ($onlyThisSurvey <= 1)
+ {
+ # če imamo normalne sezname
+
+ if (is_array($pids) && count($pids) == 1) {
+ $sql_string = "SELECT rp.respondents, fields,rp.name, rp.comment, u.email AS iemail, DATE_FORMAT(rp.insert_time,'%d.%m.%Y, %T') AS fitime, e.email AS eemail, DATE_FORMAT(rp.edit_time,'%d.%m.%Y, %T') AS fetime FROM srv_invitations_recipients_profiles AS rp LEFT JOIN users AS u ON rp.uid = u.id LEFT JOIN users AS e ON rp.uid = e.id WHERE rp.pid IN(".(implode(',',$pids)).")";
+ } else {
+ $sql_string = "SELECT rp.respondents, fields FROM srv_invitations_recipients_profiles AS rp WHERE rp.pid IN(".(implode(',',$pids)).")";
+ }
+
+ $sql_query = sisplet_query($sql_string);
+
+ while ($sql_row = mysqli_fetch_assoc($sql_query))
+ {
+ # info box prikazujemo samo ko imamo izbran 1 seznam
+ if (is_array($pids) && count($pids) == 1)
+ {
+ $infoBox .= '<span class="gray" style="display:inline-block; margin:10px;5px;">';
+ $infoBox .= $lang['srv_inv_list_edit_added'];
+ $infoBox .= trim($sql_row['iemail']) != '' ? $sql_row['iemail'] : $lang['srv_inv_list_edit_1kasi'];
+ $infoBox .= $lang['srv_inv_list_edit_date'].$sql_row['fitime'];
+ if ($sql_row['fitime'] != $sql_row['fetime']) {
+ $infoBox .= '<br/>'.$lang['srv_inv_list_edit_changed'];
+ $infoBox .= trim($sql_row['eemail']) != '' ? $sql_row['eemail'] : $lang['srv_inv_list_edit_1kasi'];
+ $infoBox .= $lang['srv_inv_list_edit_date'].$sql_row['fetime'];
+ }
+
+ $infoBox .= '<br/><label>'.$lang['srv_inv_list_edit_name'].$sql_row['name'].'</label>';
+ $infoBox .= '<br/><label>'.$lang['srv_inv_list_edit_comment'].$sql_row['comment'].'</label>';
+
+ }
+ #$array_profiles[$sql_row['pid']] = array('name' => $sql_row['name']);
+
+ $respondents_list = str_replace("\n\r", "\n", $sql_row['respondents']);
+ $respondents_list = explode("\n",$respondents_list);
+ $respondents = array_merge($respondents,$respondents_list);
+
+ $_fields = explode(",",$sql_row['fields']);
+ foreach ($_fields as $_field)
+ {
+ if (!in_array($_field,$fields)) {
+ $fields[] = $_field;
+ }
+ }
+ } # end-while
+ }
+ else
+ {
+ # imamo arhive
+ $fields = array();
+ $_recipients = array();
+ $sql_string = "SELECT email,firstname,lastname,salutation,phone,custom,relation FROM srv_invitations_recipients AS sir WHERE sir.id IN (SELECT siar.rec_id FROM srv_invitations_archive_recipients siar WHERE siar.arch_id IN (".(implode(',',$pids))."))";
+ $sql_query = sisplet_query($sql_string);
+ while ($row = mysqli_fetch_assoc($sql_query) ) {
+ $_recipients[] = $row;
+ foreach ($row AS $key => $value) {
+ if ($value !== null && !in_array($key,$fields)) {
+ $fields[] = $key;
+ }
+ }
+ }
+
+ # pripravimo respondente
+ foreach ($_recipients AS $_recipient) {
+ $recipient = '';
+ $prefix='';
+ foreach ($fields AS $field) {
+ $recipient.=$prefix.$_recipient[$field];
+ $prefix=',';
+ }
+ if ($recipient != '') {
+ $respondents[] = $recipient;
+ }
+ }
+
+ }
+
+ # pohandlamo polja
+ $field_list = array();
+ $default_fields = array(
+ 'inv_field_email' => count($fields) == 0 ? 1 : 0,
+ 'inv_field_firstname' => 0,
+ 'inv_field_lastname' => 0,
+ 'inv_field_password' => 0,
+ 'inv_field_salutation' => 0,
+ 'inv_field_phone' => 0,
+ 'inv_field_custom' => 0,
+ );
+
+ // Ce imamo modul 360 imamo tudi odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ $default_fields['inv_field_relation'] = 0;
+ }
+
+ # skreiramo nov vrstni red polj
+ if (count($fields) > 0) {
+ foreach ($fields as $field) {
+ $field_list['inv_field_'.$field] = 1;
+ if (isset($default_fields['inv_field_'.$field])) {
+ unset($default_fields['inv_field_'.$field]);
+ }
+ }
+ }
+
+ if (count($default_fields) > 0)
+ {
+ foreach ($default_fields as $key =>$field) {
+ $field_list[$key] = $field;
+ unset($default_fields[$key]);
+ }
+ }
+ $respondents = array_unique($respondents);
+ echo '<table class="inv_edit_rec_list">';
+ echo '<tr>';
+ $fields_cnt = 0;
+ foreach ($field_list AS $field => $checked)
+ {
+ if ($checked == 1) {
+ $fields_cnt++;
+ echo '<th title="'.$lang['srv_inv_recipients_'.$field].'">'.$lang['srv_'.$field].'</th>';
+ }
+ }
+ echo '</tr>';
+ if (is_array($respondents) && count($respondents) > 0 )
+ {
+ foreach ($respondents AS $respondent_data) {
+ $row_cnt = 0;
+ echo '<tr>';
+ $respondent_data_array = explode('|~|',$respondent_data);
+ if (count($respondent_data_array) > 0) {
+ foreach ($respondent_data_array AS $tekst) {
+ if ($row_cnt < $fields_cnt) {
+ echo '<td>'.str_replace ("|~|", ",", $tekst).'</td>';
+ $row_cnt++;
+ }
+ }
+ }
+ echo '</tr>';
+ }
+ }
+ echo '</table>';
+ }
+ echo $infoBox;
+ }
+
+ function showEditRecList($profile_id = null)
+ {
+ global $lang;
+ $pids=array();
+ $onlyThisSurvey = (int)$_POST['onlyThisSurvey'];
+ if ($profile_id == null) {
+ # preberemo id-je profilov in respondente
+ if ($_POST['pids'] != '') {
+ $pids = explode(',',$_POST['pids']);
+ }
+ } else {
+ # preberemo id-je profilov in respondente
+ if ($profile_id != '') {
+ $pids = explode(',',$profile_id);
+ }
+ }
+ if (is_array($pids) && count($pids) == 0) {
+ echo $lang['srv_inv_list_choose_left'].'<br>';
+ }
+ session_start();
+ if (is_array($pids) && !empty($pids))
+ {
+ echo '<div style="height:25px;width:100%;"><label><input name="inv_show_list_edit" id="inv_show_list_edit" type="checkbox" value="1" onclick="changeInvRecListEdit();" checked="checked" autocomplete="off">'.$lang['srv_inv_list_edit'].'</label></div>';
+ $respondents = array();
+ $fields = array();
+ $infoBox = null;
+ if ($onlyThisSurvey <= 1)
+ {
+ # če imamo normalne sezname
+ if (is_array($pids) && count($pids) == 1) {
+ $sql_string = "SELECT rp.respondents, fields,rp.name, rp.comment, u.email AS iemail, DATE_FORMAT(rp.insert_time,'%d.%m.%Y, %T') AS fitime, e.email AS eemail, DATE_FORMAT(rp.edit_time,'%d.%m.%Y, %T') AS fetime FROM srv_invitations_recipients_profiles AS rp LEFT JOIN users AS u ON rp.uid = u.id LEFT JOIN users AS e ON rp.uid = e.id WHERE rp.pid IN(".(implode(',',$pids)).")";
+ } else {
+ $sql_string = "SELECT rp.respondents, fields FROM srv_invitations_recipients_profiles AS rp WHERE rp.pid IN(".(implode(',',$pids)).")";
+ }
+
+ $sql_query = sisplet_query($sql_string);
+
+ while ($sql_row = mysqli_fetch_assoc($sql_query))
+ {
+ # info box prikazujemo samo ko imamo izbran 1 seznam
+ if (is_array($pids) && count($pids) == 1)
+ {
+ $infoBox = '<span class="gray" style="display:inline-block; margin:10px;5px;">';
+ $infoBox .= $lang['srv_inv_list_edit_added'];
+ $infoBox .= trim($sql_row['iemail']) != '' ? $sql_row['iemail'] : $lang['srv_inv_list_edit_1kasi'];
+ $infoBox .= $lang['srv_inv_list_edit_date'].$sql_row['fitime'];
+ if ($sql_row['fitime'] != $sql_row['fetime'])
+ {
+ $infoBox .= '<br/>'.$lang['srv_inv_list_edit_changed'];
+ $infoBox .= trim($sql_row['eemail']) != '' ? $sql_row['eemail'] : $lang['srv_inv_list_edit_1kasi'];
+ $infoBox .= $lang['srv_inv_list_edit_date'].$sql_row['fetime'];
+ }
+ $infoBox .= '<br/><label>'.$lang['srv_inv_list_edit_name'].'<input type="text" id="rec_profile_name" value="'.$sql_row['name'].'" tabindex="1" ></label>';
+ $infoBox .= '<br/><label>'.$lang['srv_inv_list_edit_comment'].'<input type="text" id="rec_profile_comment" value="'.$sql_row['comment'].'" tabindex="2"></label>';
+ }
+ #$array_profiles[$sql_row['pid']] = array('name' => $sql_row['name']);
+
+ $respondents_list = str_replace("\n\r", "\n", $sql_row['respondents']);
+ $respondents_list = explode("\n",$respondents_list);
+ $respondents = array_merge($respondents,$respondents_list);
+
+ $_fields = explode(",",$sql_row['fields']);
+ foreach ($_fields as $_field)
+ {
+ if (!in_array($_field,$fields))
+ {
+ $fields[] = $_field;
+ }
+ }
+ }
+ }
+ else
+ {
+ # imamo arhive
+ $fields = array();
+ $_recipients = array();
+ $sql_string = "SELECT email,firstname,lastname,salutation,phone,custom,relation FROM srv_invitations_recipients AS sir WHERE sir.id IN (SELECT siar.rec_id FROM srv_invitations_archive_recipients siar WHERE siar.arch_id IN (".(implode(',',$pids))."))";
+ $sql_query = sisplet_query($sql_string);
+ while ($row = mysqli_fetch_assoc($sql_query) ) {
+ $_recipients[] = $row;
+ foreach ($row AS $key => $value) {
+ if ($value !== null && !in_array($key,$fields)) {
+ $fields[] = $key;
+ }
+ }
+ }
+
+ # pripravimo respondente
+ foreach ($_recipients AS $_recipient) {
+ $recipient = '';
+ $prefix='';
+ foreach ($fields AS $field) {
+ $recipient.=$prefix.$_recipient[$field];
+ $prefix=',';
+ }
+ if ($recipient != '') {
+ $respondents[] = $recipient;
+ }
+ }
+
+ }
+ # pohandlamo polja
+ $field_list = array();
+ $default_fields = array(
+ 'inv_field_email' => count($fields) == 0 ? 1 : 0,
+ 'inv_field_firstname' => 0,
+ 'inv_field_lastname' => 0,
+ 'inv_field_password' => 0,
+ 'inv_field_salutation' => 0,
+ 'inv_field_phone' => 0,
+ 'inv_field_custom' => 0,
+ );
+
+ // Ce imamo modul 360 imamo tudi odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ $default_fields['inv_field_relation'] = 0;
+ }
+
+ # skreiramo nov vrstni red polj
+ if (count($fields) > 0) {
+ foreach ($fields as $field) {
+ $field_list['inv_field_'.$field] = 1;
+ if (isset($default_fields['inv_field_'.$field])) {
+ unset($default_fields['inv_field_'.$field]);
+ }
+ }
+ }
+
+ if (count($default_fields) > 0) {
+ foreach ($default_fields as $key =>$field) {
+ $field_list[$key] = $field;
+ unset($default_fields[$key]);
+ }
+ }
+ $respondents = array_unique($respondents);
+ echo '<div id="inv_field_container">';
+ echo '<ul class="connectedSortable">';
+ $field_lang = array();
+ if (count($field_list ) > 0) {
+ foreach ($field_list AS $field => $checked)
+ {
+ # ali je polje izbrano ( če imamo personalizirano e-vabilo, moramo nujno imeti polje email
+ $is_selected = ($checked == 1 ) ? true : false;
+
+ # če je polje obkljukano
+ $css = $is_selected ? ' class="inv_field_enabled"' : '';
+
+ # ali labela sproži klik checkboxa
+ $label_for = ' for="'.$field.'_chk"';
+ echo '<li id="'.$field.'"'.$css.'>';
+ echo '<input id="'.$field.'_chk" type="checkbox" class="inv_checkbox' . $hidden_checkbox . '"'.($is_selected == true ? ' checked="checked"' : '').'>';
+ echo '<label'.$label_for.'>'.$lang['srv_'.$field].'</label>';
+ echo '</li>';
+ }
+ if ($is_selected == 1) {
+ $field_lang[] = $lang['srv_'.$field];
+ }
+ }
+ echo '</ul>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ echo '<script type="text/javascript">';
+ echo "$('ul.connectedSortable').sortable({update : function () { refreshFieldsList(); }, forcePlaceholderSize: 'true',tolerance: 'pointer',placeholder: 'inv_field_placeholder',});";
+ echo '</script>';
+ echo '<div>';
+ echo '<textarea id="inv_recipients_list" name="inv_recipients_list">';
+ if (is_array($respondents) && count($respondents) > 0 ) {
+ echo str_replace ("|~|", ",", implode("\n",$respondents));
+ }
+ echo '</textarea>';
+ echo '</div>';
+
+ echo $infoBox;
+ echo '<br class="clr" />';
+ echo '<br class="clr" />';
+ if (count($pids) <= 1 ) {
+ echo '<span class="buttonwrapper floatLeft spaceLeft"><a class="ovalbutton ovalbutton_gray" href="#" onclick="inv_list_save_old(\''.implode('',$pids).'\'); return false;"><span>'.$lang['srv_inv_list_save_old'].'</span></a></span>';
+ }
+ echo '<span class="buttonwrapper floatLeft spaceLeft"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_list_get_name(\'true\'); return false;"><span>'.$lang['srv_inv_list_save_new'].'</span></a></span>';
+ echo '<br class="clr" />';
+
+ }
+
+ }
+
+ function invListEdit() {
+ global $lang,$site_url, $global_user_id;
+
+ # polovimo podatke profila
+ $sql_string = "SELECT pid, name, comment, uid FROM srv_invitations_recipients_profiles WHERE pid='".$_POST['pid']."'";
+ $sql_query = sisplet_query($sql_string);
+ list($pid, $name, $comment, $uid) = mysqli_fetch_row($sql_query);
+ echo '<div id="inv_recipients_profile_name" class="access">';
+ echo '<form id="inv_list_edit_form" name="inv_list_edit_form" autocomplete="off">';
+ /*
+ echo '<span id="new_recipients_list_span" >';
+ echo '<label>'.$lang['srv_inv_recipient_list_name'];
+ echo '<input type="text" id="rec_profile_name" name="rec_profile_name" value="'.$name.'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+
+ echo '<br/><br/>';
+ echo $lang['srv_inv_recipient_list_comment'];
+
+ echo '<textarea id="rec_profile_comment" name="rec_profile_comment" tabindex="3" rows="5" >'.$comment.'</textarea>';
+ echo '<br/>';
+ */
+ $this->displayListAccess($pid);
+ # skrita polja za respondente in polja
+ echo '<input id="profile_id" name="profile_id" type="hidden" value="'.($_POST['pid']).'" >';
+ echo '<br class="clr" /><br/>';
+ echo '<span class="buttonwrapper floatRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_list_edit_save(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</form>';
+ echo '</div>'; # id="inv_view_arch_recipients"
+ /* echo '<script type="text/javascript">';
+ echo "$('#rec_profile_name').focus();";
+ echo '</script>';
+ */
+ }
+
+ function listGetName() {
+ global $lang,$site_url, $global_user_id;
+
+ $saveNew = $_POST['saveNew'] == 'true' ? true : false;
+
+ $array_profiles = array();
+ #ne vem če je fino da lahko dodaja kar na vse sezname
+ session_start();
+
+ # polovimo še ostale porfile
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."')";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $array_profiles[$sql_row['pid']] = array('name' => $sql_row['name'], 'comment'=>$sql_row['comment']);
+ }
+
+ echo '<div id="inv_recipients_profile_name">';
+ if ($saveNew == true) {
+ echo '<span id="new_recipients_list_span" >';
+ echo '<label>'.$lang['srv_inv_recipient_list_name'];
+ # zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ $new_name = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q)) {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+
+ echo '<input type="text" id="rec_profile_name" value="'.$new_name.'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+ } else {
+ echo '<span id="new_recipients_list_span" >';
+ echo '<label>'.$lang['srv_inv_recipient_list_name'];
+ echo '<input type="text" id="rec_profile_name" value="'.$array_profiles[$_POST['pid']]['name'].'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+ }
+
+ echo '<br/><br/>';
+ echo $lang['srv_inv_recipient_list_comment'];
+
+ echo '<textarea id="rec_profile_comment" tabindex="3" rows="2" >'.$array_profiles[$_POST['pid']]['comment'].'</textarea>';
+ # skrita polja za respondente in polja
+ $_fields = str_replace('inv_field_','',implode(',',$_POST['fields']));
+ echo '<input id="inv_prof_field_list" type="hidden" value="'.$_fields.'" >';
+ echo '<input id="inv_prof_recipients_list" type="hidden" value="'.$this->getCleanString($_POST['recipients_list']).'" >';
+ echo '<input id="saveNew" type="hidden" value="'.($saveNew == true ? 'true' : 'false').'" >';
+ echo '<input id="profile_id" type="hidden" value="'.($_POST['pid']).'" >';
+ echo '<br class="clr" /><br/>';
+ echo '<span class="buttonwrapper floatLeft spaceRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fade\').fadeOut(\'slow\');$(\'#fullscreen\').fadeOut(\'slow\').html(\'\');return false;" ><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceRight" title="'.$lang['save'].'"><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_list_save(); return false;"><span>'.$lang['save'].'</span></a></span>';
+ echo '<br class="clr" />';
+ echo '</div>'; # id="inv_view_arch_recipients"
+ echo '<script type="text/javascript">';
+ echo "$('#rec_profile_name').focus();";
+ echo '</script>';
+ }
+
+ function invListSaveOld() {
+ global $lang,$site_url, $global_user_id;
+
+ $return = array('error'=>'0');
+ $recipients_list = trim($this->getCleanString($_POST['recipients_list']));
+
+ $field_list = (is_array($_POST['field_list']) && count($_POST['field_list']) > 0) ? implode(',',$_POST['field_list']) : trim($_POST['field_list']);
+ $field_list = str_replace('inv_field_','',$field_list);
+
+ $profile_id = explode(',',$_POST['profile_id']);
+ $profile_id = $profile_id[0];
+
+ $rec_profile_name = $_POST['rec_profile_name'];
+ $rec_profile_comment = $_POST['rec_profile_comment'];
+
+ # dodajamo v obstoječ profil
+ $sql_string_update = "UPDATE srv_invitations_recipients_profiles SET name='$rec_profile_name', comment='$rec_profile_comment', respondents = '$recipients_list', fields='$field_list' WHERE uid in('$global_user_id') AND pid = '$profile_id'";
+ $sqlQuery = sisplet_query($sql_string_update);
+ sisplet_query("COMMIT");
+ $this->removeDuplicates($profile_id);
+
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error, 'pid'=>$profile_id());
+ } else {
+ $return = array('error'=>'0', 'msg'=>'x2', 'pid'=>$profile_id);
+ }
+ #echo json_encode($return);
+
+ $this->showInvitationLists($profile_id);
+ }
+
+
+ function listSave() {
+ global $lang,$site_url, $global_user_id;
+
+ $return = array('error'=>'0');
+ $profile_name = (isset($_POST['profile_name']) && trim($_POST['profile_name']) != '') ? trim($_POST['profile_name']) : $lang['srv_invitation_new_templist'];
+ $profile_comment = (isset($_POST['profile_comment']) && trim($_POST['profile_comment']) != '') ? trim($_POST['profile_comment']) : '';
+ $recipients_list = trim($this->getCleanString($_POST['recipients_list']));
+ $field_list = (isset($_POST['field_list']) && trim($_POST['field_list']) != '') ? trim($_POST['field_list']) : 'email';
+ $profile_id = explode(',',$_POST['profile_id']);
+ $profile_id = $profile_id[0];
+
+
+ $saveNew = $_POST['saveNew'] == 'true' ? true : false;
+ if ($saveNew == true) {
+ # shranjujemo v nov profil
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles (name,uid,fields,respondents,insert_time,comment, from_survey) VALUES ('$profile_name', '$global_user_id', '$field_list', '$recipients_list', NOW(), '$profile_comment', '".$this->sid."' )";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ $new_pid = mysqli_insert_id($GLOBALS['connect_db']);
+ sisplet_query("COMMIT");
+
+ #odstranimo podvojene
+ $this->removeDuplicates($new_pid);
+
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error, 'pid'=>$new_pid);
+ } else {
+ $return = array('error'=>'0', 'msg'=>'x1', 'pid'=>$new_pid);
+ }
+ sisplet_query("COMMIT");
+ } else {
+ # dodajamo v obstoječ profil
+ $sql_string_update = "UPDATE srv_invitations_recipients_profiles SET name='$profile_name', respondents = '$recipients_list', comment='$profile_comment' WHERE uid in('$global_user_id') AND pid = '$profile_id'";
+ $sqlQuery = sisplet_query($sql_string_update);
+ sisplet_query("COMMIT");
+
+ #odstranimo podvojene
+ $this->removeDuplicates($profile_id);
+
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $return = array('error'=>'1', 'msg'=>$error, 'pid'=>$profile_id());
+ } else {
+ $return = array('error'=>'0', 'msg'=>'x2', 'pid'=>$profile_id);
+ }
+ }
+ #echo json_encode($return);
+ $this->showInvitationLists();
+ }
+
+ function invListEditSave() {
+ global $lang,$site_url, $global_user_id;
+ /*
+ * rec_profile_name] => Seznam1 [rec_profile_comment] => Komentar [uid] => Array ( [0] => 1045 [1] => 1049 [2] => 1046 ) [profile_id] => 2 [anketa] => 94 )
+ */
+ $return = array('error'=>'0');
+ $profile_name = (isset($_POST['rec_profile_name']) && trim($_POST['rec_profile_name']) != '') ? trim($_POST['rec_profile_name']) : $lang['srv_invitation_new_templist'];
+ $profile_comment = (isset($_POST['rec_profile_comment']) && trim($_POST['rec_profile_comment']) != '') ? trim($_POST['rec_profile_comment']) : '';
+
+ $uids = $_POST['uid'];
+ $pid = (int)$_POST['profile_id'];
+ # pripravimo insert query (id avtorja ne dodajamo v dostope, ker je tako v uid profila)
+ $insert_string = array();
+ if (count($uids) > 0) {
+ foreach ($uids AS $key => $uid) {
+ $insert_string[] = "('".$pid."','".$uid."')";
+ }
+ }
+ # pobrišemo stare vrednosti dostopov in jih nastavimo na novo
+ $delStr = "DELETE FROM srv_invitations_recipients_profiles_access WHERE pid = '$pid'";
+ $delQuery = sisplet_query($delStr);
+
+ if (count($insert_string)) {
+ # dodamo nove vrednosti dostopov
+ $insStr = "INSERT INTO srv_invitations_recipients_profiles_access VALUES ".implode(',',$insert_string);
+ $insQuery = sisplet_query($insStr);
+ }
+ sisplet_query("COMMIT");
+
+
+
+ # dodajamo v obstoječ profil
+ # $sql_string_update = "UPDATE srv_invitations_recipients_profiles SET name='$profile_name', comment='$profile_comment' WHERE pid = '$pid'";
+ # $sqlQuery = sisplet_query($sql_string_update);
+ # sisplet_query("COMMIT");
+ // if (!$sqlQuery) {
+ # $error = mysqli_error($GLOBALS['connect_db']);
+ # $return = array('error'=>'1', 'msg'=>$error, 'pid'=>$pid);
+ # } else {
+ # $return = array('error'=>'0', 'msg'=>'x2', 'pid'=>$pid);
+ # }
+ #echo json_encode($return);
+ $this->showInvitationLists();
+ }
+
+
+ function deleteRecipientsList() {
+ global $global_user_id;
+ $id = (int)$_POST['id'];
+
+ if ($id > 0 ) {
+ $sql_string = "DELETE FROM srv_invitations_recipients_profiles WHERE pid='".$id."' AND uid='".$global_user_id."'";
+ $sqlQuery = sisplet_query($sql_string);
+ sisplet_query("COMMIT");
+ }
+ $this->showInvitationLists();
+ }
+
+ function deleteRecipientsListMulti() {
+ $return = array('success'=>'0');
+ global $global_user_id;
+
+ $ids = $_POST['ids'];
+
+ if(count($ids) > 0){
+ $sql_string = "DELETE FROM srv_invitations_recipients_profiles WHERE uid='".$global_user_id."' AND pid IN(".implode(',',$ids).")";
+ $sqlQuery = sisplet_query($sql_string);
+ $sqlQuery = sisplet_query("COMMIT");
+ }
+ if (!$sqlQuery) {
+ $errors[] = $lang['srv_inv_recipient_delete_error'];
+ } else {
+ $return['success'] = 2;
+ //$this->showInvitationLists();
+ }
+ }
+
+ function removeDuplicates($pid) {
+ # dodamo tracking
+ if ((int)$pid > 0) {
+ $sql_string = "SELECT respondents FROM srv_invitations_recipients_profiles WHERE pid = '$pid'";
+ $sql_query = sisplet_query($sql_string);
+ $respondents = array();
+ list ($new_recipients) = mysqli_fetch_row($sql_query);
+ $new_recipients = str_replace("\n\r", "\n", $new_recipients);
+ $new_recipients = explode("\n",$new_recipients);
+ $new_recipients = implode("\n",array_unique($new_recipients));
+
+ $sql_string_update = "UPDATE srv_invitations_recipients_profiles SET respondents='".$new_recipients."' WHERE pid = '$pid'";
+ $sqlQuery = sisplet_query($sql_string_update);
+ sisplet_query("COMMIT");
+ }
+ }
+
+ function displayListAccess($pid) {
+ global $lang, $global_user_id, $admin_type;
+
+ # polovimo avtorja profila
+ $uidQuery = sisplet_query("SELECT uid FROM srv_invitations_recipients_profiles WHERE pid ='$pid'");
+ list($uid) = mysqli_fetch_row($uidQuery);
+
+ # polovimo id-je userjev ki imajo dostop do tega profila
+ $accessArray = array();
+ $accessQuery = sisplet_query("SELECT uid FROM srv_invitations_recipients_profiles_access WHERE pid ='$pid'");
+ while (list($uid_) = mysqli_fetch_row($accessQuery)) {
+ $accessArray[] = $uid_;
+ }
+
+ $sqlQuery = null;
+ // tip admina: 0=>admin, 1=>manager, 2=>clan, 3=>user
+ switch ( $admin_type ) {
+ case 0: // admin vidi vse
+ $sqlQuery = sisplet_query("SELECT name, surname, id, email FROM users ORDER BY name ASC");
+ break;
+ case 1: // manager vidi ljudi pod sabo
+ // polovimo vse clane ki spo pod managerjem
+ $sqlQuery = sisplet_query("SELECT DISTINCT name, surname, id, email FROM users WHERE id IN (SELECT DISTINCT user FROM srv_dostop_manage WHERE manager='$global_user_id') OR id = '$global_user_id'");
+
+ break;
+ case 2:
+ case 3:
+ // TODO
+ // clani in userji lahko vidijo samo tiste ki so jim poslali maile in so se registrirali
+ $sqlQuery = sisplet_query("SELECT name FROM users WHERE 1 = 0");
+ break;
+ }
+ echo '<span>'.$lang['srv_inv_list_access'].'</span><br/>';
+ echo '<span class="gray small">'.$lang['srv_inv_list_access_legend'].'</span><br/><br/>';
+ echo '<span id="invListAccessShow1"><a href="#" onClick="inv_listAccess(\'true\'); return false;">'.$lang['srv_dostop_show_all'].'</a></span>';
+ echo '<span id="invListAccessShow2" class="displayNone"><a href="#" onClick="inv_listAccess(\'false\'); return false;">'.$lang['srv_dostop_hide_all'].'</a></span>';
+ echo '<div id="invListAccess">';
+
+ while ($row1 = mysqli_fetch_assoc($sqlQuery)) {
+
+ $checked = ( in_array($row1[id],$accessArray) ||$uid == $row1['id']) ? ' checked="checked"' : '';
+
+ $_css_hidden = ($checked != '' ? '' : ' displayNone');
+ echo '<div id="div_for_uid_' . $row1['id'] . '" name="listAccess" class="floatLeft listAccess_uid'.$_css_hidden.'">';
+ echo '<label nowrap title="' . $row1['email'] . '"'.($uid == $row1['id']?' class="gray"':'').'>';
+ echo '<input type="checkbox" name="uid[]" value="' . $row1['id'] . '" id="uid_' . $row1['id'] . '"' . $checked .($uid == $row1['id'] ? ' disabled="disabled"' : ''). ' autocomplete="off"/>';
+ echo $row1['name'] . ($uid == $row1['id'] ? ' (' . $lang['author'] . ')' : '') . '</label>';
+ echo '</div>';
+ }
+
+ echo '</div>';
+
+ }
+
+ function changeInvRecListEdit() {
+ session_start();
+
+ $_SESSION['inv_edit_rec_profile'][$this->sid] = ($_POST['checked'] == 'true' ? true : false);
+
+ session_commit();
+ }
+
+ function getUrlLists() {
+ global $lang,$site_url;
+
+ $result = array();
+
+ $p = new Prevajanje($this->sid);
+ $lang_array = $p->get_all_translation_langs();
+
+ $link = SurveyInfo::getSurveyLink();
+ $sqll = sisplet_query("SELECT link FROM srv_nice_links WHERE ank_id = '$this->sid' ORDER BY id ASC");
+
+ $default_checked =false;
+ $cnt=0;
+ #lepi linki
+ while ($rowl = mysqli_fetch_assoc($sqll)) {
+
+ $result[$cnt] = array('url'=>$site_url.$rowl['link'], 'name'=>$site_url.$rowl['link'].(count($lang_array) > 0 ? ' - '.$lang['language'].' ' : ''));
+ if ($default_checked == false) {
+ $result[$cnt]['dc'] = true;
+ $default_checked = true;
+ }
+ $cnt++;
+ if (count($lang_array) > 0) {
+ #jezikovni podlinki
+ foreach ($lang_array AS $lang_id => $lang_name) {
+ $result[$cnt] = array('url'=>$site_url.$rowl['link'].'?language='.$lang_id, 'name'=>$site_url.$rowl['link'].'?language='.$lang_id.' - '.$lang_name);
+ $cnt++;
+ }
+ }
+ }
+
+ $link1 = $site_url.'a/'.Common::encryptAnketaID($this->sid);
+ # normalen link
+ $result[$cnt] = array('url'=>$link1, 'name'=>$link1.(count($lang_array) > 0 ? ' - '.$lang['language'] : ''));
+ if ($default_checked == false) {
+ $result[$cnt]['dc'] = true;
+ $default_checked = true;
+ }
+ $cnt++;
+
+ #jezikovni link
+ if (count($lang_array) > 0) {
+ foreach ($lang_array AS $lang_id => $lang_name) {
+ $result[$cnt] = array('url'=>$link1.'?language='.$lang_id, 'name'=>$link1.'?language='.$lang_id.' - '.$lang_name);
+ if ($default_checked == false) {
+ $result[$cnt]['dc'] = true;
+ $default_checked = true;
+ }
+ $cnt++;
+ }
+ }
+
+ return $result;
+ }
+
+ function upload_list() {
+ global $lang, $site_path, $site_url;
+
+ $fields = array();
+ $field_list = array();
+ # odvisno od tipa sporočil prikažemo različna polja
+ # Personalizirano e-poštno vabilo
+
+ $default_fields = array(
+ 'inv_field_email' => 1,
+ 'inv_field_firstname' => 0,
+ 'inv_field_lastname' => 0,
+ 'inv_field_password' => 0,
+ 'inv_field_salutation' => 0,
+ 'inv_field_phone' => 0,
+ 'inv_field_custom' => 0,
+ );
+
+ // Ce imamo modul 360 imamo tudi odnos
+ if(SurveyInfo::getInstance()->checkSurveyModule('360_stopinj')){
+ $default_fields['inv_field_relation'] = 0;
+ }
+
+ # pri personaliziranih aporočilih je e-mail obvezno polje
+ array_push($fields, 'inv_field_email');
+
+ # skreiramo nov vrstni red polj
+ if (count($fields) > 0) {
+ foreach ($fields as $key=>$field) {
+ $field_list[$field] = 1;
+ if (isset($default_fields[$field])) {
+ unset($default_fields[$field]);
+ }
+ }
+ }
+
+ if (count($default_fields) > 0) {
+ foreach ($default_fields as $key =>$field) {
+ $field_list[$key] = $field;
+ unset($default_fields[$key]);
+ }
+ }
+
+
+ echo '<div id="inv_upload_list">';
+
+ echo '<h2>'.$lang['srv_inv_list_upload_header'].'</h2>';
+
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_field_note'].':</span>';
+
+ echo '<div id="inv_field_container">';
+
+ echo '<ul class="connectedSortable">';
+ $field_lang = array();
+ if (count($field_list ) > 0) {
+ foreach ($field_list AS $field => $checked) {
+ # ali je polje izbrano ( če imamo personalizirano e-vabilo, moramo nujno imeti polje email
+ # $is_selected = ($checked == 1 || $field == 'inv_field_email' ) ? true : false;
+ $is_selected = ($checked == 1 ) ? true : false;
+
+ # če je polje obkljukano
+ $css = $is_selected ? ' class="inv_field_enabled"' : '';
+
+ # ali prikazujemo checkbox
+ # $hidden_checkbox = $field == 'inv_field_email' ? ' hidden' : '';
+
+ # ali labela sproži klik checkboxa
+ # $label_for = $field != 'inv_field_email' ? ' for="'.$field.'_chk"' : '';
+ $label_for = ' for="'.$field.'_chk"';
+
+ echo '<li id="'.$field.'"'.$css.'>';
+ echo '<input id="'.$field.'_chk" type="checkbox" class="inv_checkbox' . $hidden_checkbox . '"'.($is_selected == true ? ' checked="checked"' : '').'>';
+ echo '<label'.$label_for.'>'.$lang['srv_'.$field].'</label>';
+ echo '</li>';
+ if ($is_selected == 1) {
+ $field_lang[] = $lang['srv_'.$field];
+ }
+ }
+ }
+ echo '</ul>';
+ echo '</div>';
+ echo '<br class="clr" />';
+ echo '<script type="text/javascript">';
+ echo "$('ul.connectedSortable').sortable({update : function () { refreshFieldsList(); }, forcePlaceholderSize: 'true',tolerance: 'pointer',placeholder: 'inv_field_placeholder',});";
+ echo '</script>';
+
+ echo '<form id="inv_recipients_upload_form" name="resp_uploader" method="post" enctype="multipart/form-data" action="'.$site_url.'admin/survey/index.php?anketa='.$this->sid.'&a='.A_INVITATIONS.'&m=send_upload_list" autocomplete="off">';
+ echo '<input type="hidden" name="fields" id="inv_recipients_upoad_fields" value="'.implode(',',$fields).'" />';
+ echo '<input type="hidden" name="posted" value="1" />';
+ echo '<span class="inv_note">'.$lang['srv_inv_recipiens_file_note_1'].'</span>';
+
+ echo '<br class="clr" />'.$lang['srv_inv_recipiens_fields'].' <span id="inv_field_list" class="inv_type_1">';
+ echo implode(',',$field_lang);
+ echo '</span>';
+ echo '<br class="clr" />';
+ echo $lang['srv_mailing_upload_list'];
+ echo '<input type="file" name="invListFile" id="invListFile" size="42" >';
+ if (count($errors) > 0) {
+ echo '<br class="clr" />';
+ echo '<span class="inv_error_note">';
+ foreach($errors as $error) {
+ echo '* '.$error.'<br />';
+ }
+ echo '</span>';
+ }
+ echo '<br/><br/><label>'.$lang['srv_inv_recipient_import_file_delimiter'].'</label> <input type="radio" name="recipientsDelimiter" id="recipientsDelimiter1" value="," checked><label for="recipientsDelimiter1">'.$lang['srv_inv_recipient_delimiter_comma'].' (,)</label>';
+ echo ' <input type="radio" name="recipientsDelimiter" id="recipientsDelimiter2" value=";"><label for="recipientsDelimiter2">'.$lang['srv_inv_recipient_delimiter_semicolon'].' (;)</label>';
+ echo '</form>';
+
+ echo '<span class="inv_sample" >';
+ echo $lang['srv_inv_recipiens_sample'].'&nbsp;</span><span class="inv_sample">';
+ echo $lang['srv_inv_recipiens_sample1'];
+ echo '</span>';
+
+ echo '<br class="clr" />';
+
+ echo '<div class="buttons_holder">';
+ echo '<span class="buttonwrapper floatRight spaceLeft" ><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#inv_upload_list, #fullscreen, #fade\').hide();return false;"><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight spaceLeft" ><a class="ovalbutton ovalbutton_orange" href="#" onclick="inv_upload_list_check(); return false;"><span>'.$lang['srv_inv_btn_add_recipients_add'].'</span></a></span>';
+ echo '</div>';
+
+ echo '</div>';
+ }
+
+ function send_upload_list() {
+ global $lang, $global_user_id;
+ $errors = array();
+ $allowedExtensions = array("txt","csv","dat");
+ $_fields = trim($_POST['fields']);
+ if ($_fields != null && $_fields != '') {
+ $fields = explode(',',$_fields);
+ } else {
+ $fields = array();
+ }
+
+ $file_name = $_FILES["invListFile"]["name"];
+ $file_type = $_FILES["invListFile"]["type"];
+ $file_size = $_FILES["invListFile"]["size"] > 0 ? $_FILES["invListFile"]["size"] / 1024 : 0;
+ $file_tmp = $_FILES["invListFile"]["tmp_name"];
+
+ $okFileType = ( $file_type == 'text/plain' || $file_type == 'text/csv' || $file_type == 'application/vnd.ms-excel' );
+ $okFileEnd = ( pathinfo($file_name, PATHINFO_EXTENSION) != 'txt'
+ || pathinfo($file_name, PATHINFO_EXTENSION) != 'csv'
+ || pathinfo($file_name, PATHINFO_EXTENSION) != 'dat');
+ # preverimo ali smo uploadali datoteko in če smo izbrali katero polje
+ if ($_POST['posted'] == '1' && count($fields) == 0) {
+ $errors[] = $lang['srv_inv_recipiens_upload_error_no_fields'];
+ }
+ #preverimo ime datoteke
+ if ( trim($file_name) == '' || $file_name == null ) {
+ $errors[] = $lang['srv_respondents_invalid_file'];
+
+ # preverimo tip:
+ } else if ( $okFileType == false ) {
+ $errors[] = $lang['srv_respondents_invalid_file_type'];
+
+ # prevermio še končnico (.txt)
+ } else if ($okFileEnd == false) {
+ $errors[] = $lang['srv_respondents_invalid_file_type'];
+ }
+
+ # preverimo velikost
+ else if ( (float)$file_size == 0 ) {
+ $errors[] = $lang['srv_respondents_invalid_file_size'];
+ }
+
+ # če so napake jih prikažemo če ne obdelamo datoteko
+ if (count($errors) > 0) {
+
+ echo '<br class="clr" />';
+ echo '<span class="inv_message_errors">'.$lang['srv_inv_recipiens_upload_error'].'</span>';
+ echo '<br class="clr" />';
+ echo '<br class="clr" />';
+ echo '<span class="inv_error_note">';
+ foreach($errors as $error) {
+ echo '* '.$error.'<br />';
+ }
+ echo '</span>';
+ #$this->addRecipientsView($fields, $invalid_recipiens_array);
+ } else {
+
+ $fh = @fopen($file_tmp, "rb");
+ if ($fh) {
+ $_recipients = fread($fh, filesize($file_tmp));
+ fclose($fh);
+ }
+ $_recipients = str_replace("\n\r", "\n", $_recipients);
+ $recipients_list = explode("\n",$_recipients);
+ $num_recipients_list = count($recipients_list);
+
+ # pri prejemnikih odrežemo "polja", katerih nismo navedli
+ $fields_cont = (int)count($fields);
+ $fields = str_replace('inv_field_','',$fields);
+
+ $clean_recipients = array();
+ if (count($recipients_list) > 0) {
+
+ if (isset ($_POST['recipientsDelimiter'])) {
+ $delimiter = $_POST['recipientsDelimiter'];
+ }
+ else {
+ $delimiter = "|~|";
+ }
+ foreach ($recipients_list AS $recipient) {
+ #poiščemo n-ti delimiter
+ $clean_recipients[] = trim(substr($recipient, 0, $this->strpos_offset($delimiter, $recipient, $fields_cont)));
+ }
+ }
+ $clean_fields = trim(implode(',', $fields));
+ $clean_recipients = trim(implode("\n", $clean_recipients));
+ if ($fields!=null && $fields != '' && $clean_recipients != null && $clean_recipients != '') {
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles".
+ " (name,uid,fields,respondents,insert_time,comment, from_survey) ".
+ " VALUES ('Uploaded list', '$global_user_id', '$clean_fields', '$clean_recipients', NOW(), 'Uploaded list', '".$this->sid."' )";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ }
+
+ }
+ $this->showInvitationLists();
+
+ }
+ /*
+ function strpos_index($haystack = '',$needle = '',$offset = 0,$limit = 99,$return = null)
+ {
+ $length = strlen($needle);
+ $occurances = array();
+ while((($count = count($occurances)) < $limit) && (false !== ($offset = strpos($haystack,$needle,$offset))))
+ {
+ $occurances[$count]['length'] = $length;
+ $occurances[$count]['start'] = $offset;
+ $occurances[$count]['end'] = $offset = $offset + $length;
+ }
+ return $return === null ? $occurances : $occurances[$return];
+ }
+ */
+ /**
+ * Find position of Nth $occurrence of $needle in $haystack
+ * Starts from the beginning of the string
+ **/
+ function strpos_offset($needle, $haystack, $occurrence) {
+ // explode the haystack
+ $arr = explode($needle, $haystack);
+
+ // check the needle is not out of bounds
+ switch( $occurrence ) {
+ case $occurrence == 0:
+ return false;
+ case $occurrence > max(array_keys($arr)):
+ return strlen($haystack);
+ default:
+ $index = (int)strlen(implode($needle, array_slice($arr, 0, $occurrence)));
+ return $index;
+ }
+ }
+
+ function changePaginationLimit() {
+ session_start();
+ if (isset($_POST['limit']) && (int)$_POST['limit'] > 0) {
+ $_SESSION['rec_on_send_page'] = (int)$_POST['limit'];
+ $this->rec_send_page_limit = (int)$_POST['limit'];
+ }
+ session_commit();
+ $this->displaySendPagination((int)$_POST['cnt']);
+ }
+
+ function displayMessagePreview() {
+ global $lang;
+
+ $sql_string_m = "SELECT id, naslov, subject_text, body_text, reply_to, isdefault, comment, url FROM srv_invitations_messages WHERE ank_id = '$this->sid' AND isdefault='1'";
+
+ $sql_query_m = sisplet_query($sql_string_m);
+ $preview_message = mysqli_fetch_assoc($sql_query_m);
+ # polovimo imena vseh sporocil
+ $sql_string_m = "SELECT id, naslov FROM srv_invitations_messages WHERE ank_id = '$this->sid'";
+
+ echo '<table id="inv_send_mail_preview">';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_name'].':</th>';
+ echo '<td class="inv_bt">';
+ echo '<span>';
+ $sql_query_m = sisplet_query($sql_string_m);
+ if (mysqli_num_rows($sql_query_m) > 0 ) {
+ echo '<select onchange="mailSourceMesageChange(this);">';
+ while ($row = mysqli_fetch_assoc($sql_query_m)) {
+ echo '<option value="'.$row['id'].'"'.($row['id'] ==$preview_message['id']?' selected="selected"':'' ).'>'.$row['naslov'].'</option>';
+ }
+ echo '</select>';
+ }
+ #.$preview_message['naslov'];
+ echo '</span>';
+ echo '</td></tr>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_subject'].':</th>';
+ echo '<td class="inv_bt">';
+ echo '<span>'.$preview_message['subject_text'].'</span>';
+ echo '</td></tr>';
+ echo '<tr><th>'.$lang['srv_inv_message_draft_content_body'].':</th>';
+ echo '<td >';
+ echo '<span class="nl2br">'.($preview_message['body_text']).'</span>';
+ echo '</td></tr>';
+ echo '</table>';
+
+ // Opozorilo ce manjka #URL# v besedilu maila in imamo individualizirano vabilo
+ if(strpos($preview_message['body_text'], '#URL#') == false && $this->surveySettings['usercode_required'] == 0 && $this->surveySettings['individual_invitation'] != 0)
+ echo '<span class="red">'.$lang['srv_inv_message_draft_nourl_warning'].'</span><br />';
+
+ // Opozorilo ce je #URL# v besedilu maila in imamo neindividualizirano vabilo
+ elseif(strpos($preview_message['body_text'], '#URL#') == true && $this->surveySettings['individual_invitation'] == 0)
+ echo '<span class="red">'.$lang['srv_inv_message_draft_url_warning'].'</span><br />';
+
+ // Popravi sporocilo
+ echo '<a href="'.$this->addUrl('view_message').'">'.$lang['srv_invitation_reedit_message'].'</a>';
+ }
+
+ function addSortField($field){
+ $type = 'ASC';
+ session_start();
+ if ($_SESSION['rec_sort_field'] == $field) {
+ if ($_SESSION['rec_sort_type'] == 'DESC') {
+ $type = 'ASC';
+ } else {
+ $type = 'DESC';
+ }
+ } else {
+ $type = 'ASC';
+ }
+ return ' onclick="inv_set_sort_field(\''.$field.'\',\''.$type.'\');" ';
+ }
+ function addSortIcon($field){
+ session_start();
+ if ($_SESSION['rec_sort_field'] == $field) {
+ if ($_SESSION['rec_sort_type'] == 'DESC') {
+ return ' <span class="faicon sort_descending icon-blue"></span>';
+
+ } else {
+ return ' <span class="faicon sort_ascending icon-blue"></span>';
+ }
+ }
+ return;
+ }
+
+ function setSortField() {
+ session_start();
+ if (isset($_POST['field']) && trim($_POST['field']) != '') {
+ $_SESSION['rec_sort_field'] = trim($_POST['field']);
+ } else {
+ $_SESSION['rec_sort_field'] = 'date_inserted';
+ }
+ if (isset($_POST['type']) && trim($_POST['type']) != '') {
+ $_SESSION['rec_sort_type'] = trim($_POST['type']);
+ } else {
+ $_SESSION['rec_sort_type'] = 'ASC';
+ }
+ session_commit();
+ }
+
+
+ function getSortString() {
+ session_start();
+
+ $sort_string = ' ORDER BY i.last_status';
+
+ if (isset($_SESSION['rec_sort_field']) && trim($_SESSION['rec_sort_field']) != '') {
+ $prefix = 'i.';
+ if ($_SESSION['rec_sort_field'] == 'count_inv') {
+ $prefix = '';
+ }
+
+ if ($_SESSION['rec_sort_field'] == 'date(date_expired)') {
+ $sort_string = ' ORDER BY '.$prefix.'date_expired';
+ }
+ else{
+ $sort_string = ' ORDER BY '.$prefix.trim($_SESSION['rec_sort_field']);
+ }
+
+ if ($_SESSION['rec_sort_type'] == 'DESC') {
+ $sort_string .= ' DESC';
+ } else {
+ $sort_string .= ' ASC';
+ }
+ }
+
+ // Vedno dodatno se sortirtamo po mailu
+ $sort_string .= ', i.email';
+
+ return $sort_string;
+ }
+
+ function getAvailableSysVars() {
+ $result = array();
+ $qry = sisplet_query("SELECT s.variable, s.naslov FROM srv_spremenljivka s, srv_grupa g WHERE g.ank_id='".$this->sid."' AND s.gru_id=g.id AND s.tip!='5' AND (s.tip < '10' OR s.tip = '22' OR s.tip = '25' OR s.tip='21') AND s.sistem='1'");
+ while ($row = mysqli_fetch_assoc($qry)) {
+ $result[$row['variable']] = $row['naslov'];
+ }
+ return $result;
+ }
+
+ function getAvailableIndicators() {
+ $result = array();
+ $_indicators = array('email','password','firstname','lastname','salutation','phone','custom','relation');
+ #za vsako spremenljivko preverimo zapise v bazi
+ foreach ($_indicators AS $indicator) {
+ $sql_string = "SELECT count(*) FROM srv_invitations_recipients WHERE ank_id = '".$this->sid."' AND deleted = '0' AND $indicator IS NOT NULL";
+ list($cnt) = mysqli_fetch_row(sisplet_query($sql_string));
+ if ((int)$cnt > 0) {
+ $result[] = $indicator;
+ }
+ }
+ return $result;
+ }
+
+ function createSystemVariablesMapping() {
+ global $lang;
+ # polovimo sistemske variable
+ $sys_db_maps = array('email');
+
+ $strSelect = "SELECT spr_id, field FROM srv_invitations_mapping WHERE sid = '".$this->sid."'";
+ $qrySelect = sisplet_query($strSelect);
+ $mappingArray = array();
+ while (list($spr_id,$field) = mysqli_fetch_row($qrySelect)) {
+ $mappingArray[$spr_id] = $field;
+ }
+ $qryString = "SELECT s.id, s.naslov, s.variable, s.variable_custom, s.coding FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.tip IN (1,3,17,21) AND s.gru_id=g.id AND g.ank_id='".$this->sid."' ORDER BY g.vrstni_red, s.vrstni_red";
+ $sqlSpremenlivka = sisplet_query($qryString);
+
+ if (mysqli_num_rows($sqlSpremenlivka) > 0) {
+ echo '<form id="inv_ValidateSysVarsMappingFrm" name="inv_ValidateSysVarsMappingFrm">';
+ echo $lang['srv_invitation_system_email_choose'];
+ echo '<table>';
+ while ($row = mysqli_fetch_assoc($sqlSpremenlivka)) {
+ $system_variables[$row['id']] = $row;
+ echo '<tr>';
+ echo '<td>';
+ $checked = (isset($mappingArray[$row['id']]) && $mappingArray[$row['id']] == 'email' )?' checked="checked"':'';
+ echo '<input type="radio" name="sysVarMap" id="sysVarMap_'.$row['id'].'" value="'.$row['id'].'"'.$checked.'>';
+ echo '</td>';
+ echo '<td><label for="sysVarMap_'.$row['id'].'"><span style="color: #78a971;">'.$row['variable'].'</span></label></td>';
+ echo '<td><label for="sysVarMap_'.$row['id'].'">'.$row['naslov'].'</label></td>';
+
+ echo '</tr>';
+ }
+ echo '</table>';
+ echo '<form/>';
+ echo '<br/>';
+ echo '<div id="inv_ValidateSysVarsMappingDiv">';
+ echo '<span onclick="inv_ValidateSysVarsMapping();" class="buttonwrapper floatLeft spaceLeft" ><a class="ovalbutton ovalbutton_orange" ><span>'.$lang['srv_invitation_system_validate'].'</span></a></span>';
+ echo '</div>';
+
+ } else {
+ echo '<span>'.$lang['srv_invitation_system_error3'].'</span>';
+ }
+ }
+
+ function validateSysVarsMapping() {
+ global $lang,$global_user_id;
+ # preverimo sistemske spremenljivke
+ $strSistemske = "SELECT count(*) FROM srv_spremenljivka s, srv_grupa g WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".$this->sid."' AND variable IN("."'" . implode("','",$this->inv_variables)."') ORDER BY g.vrstni_red, s.vrstni_red";
+ list($cntSistemske) = mysqli_fetch_row(sisplet_query($strSistemske));
+
+ $emailsToAdd = array();
+ $invalidEmails = array();
+ $errors = array();
+ $emailSpr = (int)$_POST['sysVarMap'];
+ if ((int)$emailSpr > 0) {
+ # preverimo ali lovimo samo ustrezne ali vse userje , preverimo kako imamo nastavljeno pri podatkih
+ global $global_user_id;
+ $_POST['meta_akcija'] = 'data';
+ SurveyStatusProfiles :: Init($this->sid, $global_user_id);
+ $currentProfileId = SurveyStatusProfiles :: getCurentProfileId();
+ $statusProfileCondition = SurveyStatusProfiles :: getStatusAsQueryString($currentProfileId);
+
+ #zloopamo skozi userje in dodamo kateri še niso bili dodani
+ $selectUser = "SELECT id,cookie,pass,last_status,lurker,unsubscribed FROM srv_user where ank_id='".$this->sid."' AND inv_res_id IS NULL AND deleted='0' ".$statusProfileCondition;
+ $queryUser = sisplet_query($selectUser );
+
+ if (mysqli_num_rows($queryUser) ) {
+ #zakeširamo vrednosti za email
+ $this->getUsersDataForSpr($emailSpr);
+
+ while ($row = mysqli_fetch_assoc($queryUser)) {
+ $email = trim($this->cacheArrayVrednost[$emailSpr][$row['id']]);
+
+ if ($this->validEmail($email)) {
+ $emailsToAdd[] = $email;
+ } else {
+ $invalidEmails[] = $email;
+ }
+ }
+ if (count($invalidEmails) > 0) {
+ $errors[] = $lang['srv_invitation_system_error1']."(".count($invalidEmails).')';
+ }
+ } else {
+ $errors[] = $lang['srv_invitation_system_error2'];
+ }
+ } else {
+
+ if ((int)$cntSistemske == 0) {
+ # ni sistemskih spremenljivk
+ $errors[] = $lang['srv_invitation_system_error3'];
+ } else {
+ # ni določena email spremenljivka
+ $errors[] = $lang['srv_invitation_system_error4'];
+ }
+ }
+ echo '<span onclick="inv_ValidateSysVarsMapping();" class="buttonwrapper floatLeft spaceLeft spaceRight" ><a class="ovalbutton ovalbutton_gray" ><span>'.$lang['srv_invitation_system_validate'].'</span></a></span>';
+ if (count($emailsToAdd)) {
+ echo '<span onclick="inv_addSysVarsMapping();" class="buttonwrapper floatLeft spaceLeft spaceRight" ><a class="ovalbutton ovalbutton_orange" ><span>'.$lang['srv_invitation_system_validateAndAdd'].'</span></a></span>';
+ }
+ if (mysqli_num_rows($queryUser) > 0)
+ { # če je kaj novih zapisov v bazi
+
+ # če že imamo prejemnike v bazi ponudimo gumb naprej
+ echo '<span class="buttonwrapper floatLeft spaceLeft" ><a class="ovalbutton ovalbutton_orange" href="'.$this->addUrl('view_recipients').'"><span>'.$lang['srv_invitation_forward'].'</span></a></span>';
+
+ echo '<br class="clr"/>';
+ echo '<br/>';
+ echo '<span class="strong">';
+ printf($lang['srv_invitation_system_found'],mysqli_num_rows($queryUser));
+ echo '</span>';
+ echo '<br/>';
+ echo $lang['srv_invitation_system_from_this'];
+
+ if (count($emailsToAdd)) {
+ echo $lang['srv_invitation_system_from_this_valid'].(int)count($emailsToAdd);
+ if (count($invalidEmails) > 0) {
+ echo '<br/>';
+ echo $lang['srv_invitation_system_and'];
+ }
+ }
+ if (count($invalidEmails) > 0) {
+ echo $lang['srv_invitation_system_from_this_invalid'].(int)count($invalidEmails);
+ }
+ }
+ else
+ {
+ echo '<br class="clr"/>';
+ echo '<br/>';
+ echo $lang['srv_invitation_system_not_found'];
+ }
+ }
+ function addSysVarsMapping() {
+ global $lang,$global_user_id;
+
+ $addedEmails = array();
+ $errorEmails = array();
+ $invalidEmails = array();
+ $errors = array();
+
+ #pobrišemo obstoječe povezave
+ $strDelete = "DELETE FROM srv_invitations_mapping WHERE sid = '".$this->sid."'";
+ $qryDelete = sisplet_query($strDelete);
+
+ $emailSpr = (int)$_POST['sysVarMap'];
+ if ((int)$emailSpr > 0) {
+ $insertString = "INSERT INTO srv_invitations_mapping (sid, spr_id, field) VALUES ('$this->sid','$emailSpr','email')";
+ sisplet_query($insertString);
+ sisplet_query("COMMIT");
+
+ # preverimo ali lovimo samo ustrezne ali vse userje , preverimo kako imamo nastavljeno pri podatkih
+ global $global_user_id;
+ $_POST['meta_akcija'] = 'data';
+ SurveyStatusProfiles :: Init($this->sid, $global_user_id);
+ $currentProfileId = SurveyStatusProfiles :: getCurentProfileId();
+ $statusProfileCondition = SurveyStatusProfiles :: getStatusAsQueryString($currentProfileId);
+
+ #zloopamo skozi userje in dodamo kateri še niso bili dodani
+ $selectUser = "SELECT id,cookie,pass,last_status,lurker,unsubscribed FROM srv_user where ank_id='".$this->sid."' AND inv_res_id IS NULL AND deleted='0' ".$statusProfileCondition;
+ $queryUser = sisplet_query($selectUser );
+ if (mysqli_num_rows($queryUser)) {
+ #zakeširamo vrednosti za email
+ $this->getUsersDataForSpr($emailSpr);
+
+ while ($row = mysqli_fetch_assoc($queryUser)) {
+ $email = trim($this->cacheArrayVrednost[$emailSpr][$row['id']]);
+ if ($this->validEmail($email)) {
+ $pass = (trim($row['pass']) != '') ? trim($row['pass']) : substr($row['cookie'],0,6);
+ #dodamo respondenra in naredimo povezav
+ $sql_insert = "INSERT IGNORE INTO srv_invitations_recipients (ank_id,email,password,cookie,sent,responded,unsubscribed,deleted,date_inserted,inserted_uid,list_id,last_status) VALUES ";
+ $sql_insert .= "('".$this->sid."','$email','$pass','".$row['cookie']."'";
+ $sql_insert .= ",'0','0','".(int)$row['unsubscribed']."','0',NOW(),'".$global_user_id."','".$list_id."','".$row['last_status']."')";
+ $sqlQuery = sisplet_query($sql_insert);
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ $errorEmails[] = $email;
+ } else {
+ $rid = mysqli_insert_id($GLOBALS['connect_db']);
+ if ((int)$rid > 0) {
+ # updejtamo srv user
+ $sqlString2 = "UPDATE srv_user SET inv_res_id='$rid' WHERE id='".$row['id']."'";
+ $updateQuery2 = sisplet_query($sqlString2);
+ $addedEmails[] = $email;
+ } else {
+ $errorEmails[] = $email;
+ }
+ }
+ sisplet_query("COMMIT");
+ } else {
+ if ($email != '') {
+ $invalidEmails[] = $email;
+ } else {
+ $invalidEmails[] = $lang['srv_invitation_system_empty_email'];
+ }
+ }
+ }
+ } else {
+ #V bazi ni respondentov, katere lahko dodam v vabila!
+ $errors[] = $lang['srv_invitation_system_error2'];
+ }
+ } else {
+ # ni določena email spremenljivka
+ $errors[] = $lang['srv_invitation_system_error4'];
+ }
+ echo '<span onclick="inv_ValidateSysVarsMapping();" class="buttonwrapper floatLeft spaceLeft" ><a class="ovalbutton ovalbutton_orange" ><span>'.$lang['srv_invitation_system_validate'].'</span></a></span>';
+ echo '<br class="clr"/>';
+ echo '<br/>';
+ if (count($errors) > 0) {
+ foreach ($errors AS $error) {
+ echo '<br/><span class="strong">'.$error.'</span>';
+ }
+ }
+ if (count($addedEmails) > 0) {
+ echo '<span class="strong">'.$lang['srv_invitation_system_added_users_finish']."(".(int)count($addedEmails)."): </span>";
+ foreach ($addedEmails AS $email) {
+ echo '<br/><span>'.$email.'</span>';
+ }
+ }
+ if (count($errorEmails) > 0) {
+ echo $lang['srv_invitation_system_error6']." (".(int)count($errorEmails)."): ";
+ foreach ($errorEmails AS $email) {
+ echo '<br/><span>'.$email.'</span>';
+ }
+
+ }
+ if (count($invalidEmails) > 0) {
+ echo '<span class="strong gray">'.$lang['srv_invitation_system_error6'].'('.(int)count($invalidEmails).'): </span><br/>';
+ foreach ($invalidEmails AS $email) {
+ echo '<span>'.$email.'</span><br/>';
+ }
+
+ }
+ }
+
+ private $cacheArrayVrednost = array();
+ function getUsersDataForSpr($spr_id = 0) {
+
+ if ((int)$spr_id > 0 ) {
+ if (!isset($this->cacheArrayVrednost[$spr_id])) {
+ list($tip) = mysqli_fetch_row(sisplet_query("SELECT tip FROM srv_spremenljivka WHERE id = '$spr_id'"));
+ switch ($tip) {
+ case 21:
+ $str = "SELECT u.id, sdt.text FROM srv_data_text".$this->db_table." AS sdt LEFT JOIN srv_user AS u ON u.id=sdt.usr_id WHERE sdt.spr_id ='$spr_id' AND ank_id='".$this->sid."' AND inv_res_id IS NULL AND deleted='0'";
+ $sql = sisplet_query($str);
+ while (list($uid,$txt) = mysqli_fetch_row($sql)) {
+ if ((int)$uid > 0 && trim($txt) != '') {
+ $this->cacheArrayVrednost[$spr_id][$uid] = $txt;
+ }
+ }
+ break;
+ return $this->cacheArrayVrednost[$spr_id];
+ }
+ } else {
+ return $this->cacheArrayVrednost[$spr_id];
+ }
+ }
+ }
+
+ function saveRecipientListName() {
+ global $lang,$site_url, $global_user_id;
+
+ $array_profiles = array();
+ #ne vem če je fino da lahko dodaja kar na vse sezname
+ session_start();
+ $_only_this_survey = (isset($_SESSION['inv_rec_only_this_survey']) && (int)$_SESSION['inv_rec_only_this_survey'] == 1) ? '' : " AND from_survey = '".$this->sid. "'" ;
+
+ # polovimo še ostale porfile
+ $sql_string = "SELECT pid, name,comment FROM srv_invitations_recipients_profiles WHERE uid in('".$global_user_id."')".$_only_this_survey;
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $array_profiles[$sql_row['pid']] = array('name' => $sql_row['name'], 'comment'=>$sql_row['comment']);
+ }
+
+ echo '<div style="margin-top:10px; padding:5px; background-color:#f2f2f2; border:1px solid #c2c2c2;">';
+ # echo '<span class="inv_new_list_note">';
+ # echo $lang[''].'Izberite seznam kamor želite dodati prejemnike. Izbirate lahko med:<br/><ul><li>\'Nov seznam\' - prejemniki se dodajo v nov seznam, kateremu določite ime</li><li>\'Začasen seznam\' - seznam obstaja samo v času seje brskalnika</li><li>ali izberete obstoječ seznam, h kateremu se bodo dodali prejemniki</li></ul><br/>';
+ # echo '</span>';
+ echo $lang['srv_invitation_recipients_list_add'].':&nbsp;';
+ echo '<select id="sel_inv_list_type" onchange="inv_new_recipients_list_change(this);" autofocus="autofocus">';
+ echo '<option value="0" class="gray bold"'.((int)$_POST['pid'] > 0 ? '' : ' selected="selected"' ).'>'.$lang['srv_invitation_new_list'].'</option>';
+ echo '<option value="-1" class="gray bold">'.$lang['srv_invitation_new_templist'].'</option>';
+ if (count($array_profiles) > 0){
+ foreach($array_profiles AS $key => $profile) {
+ echo '<option value="'.$key.'" comment="'.$profile['comment'].'"'.($_POST['pid'] == $key ? ' selected="selected"' : '').'>'.$profile['name'].'</option>';
+ }
+ }
+ echo '</select>';
+ echo '<span id="new_recipients_list_span_note" '.((int)$_POST['pid'] < 1 ? ' class="displayNone"' : '' ).'>';
+ echo '<br>';
+ echo '<br>';
+ echo $lang[''].'Uporabniki bodo dodani v seznam: ';
+ echo $array_profiles[$_POST['pid']]['name'];
+ echo '<span id="new_recipients_list_span_note_name"></span>';
+ echo '</span>';
+ echo '<span id="new_recipients_list_span" '.((int)$_POST['pid'] > 0 ? ' class="displayNone"' : '' ).'>';
+
+ echo '<br>';
+ echo '<br>';
+ echo '<label>'.$lang['srv_inv_recipient_list_name'];
+ # zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ $new_name = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q)) {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0) {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names)) {
+ $cnt++;
+ }
+ $new_name = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+
+ echo '<input type="text" id="rec_profile_name" value="'.$new_name.'" tabindex="1" autofocus="autofocus">';
+ echo '</label>';
+ echo '</span>';
+ echo '<br/><br/>';
+ echo $lang['srv_inv_recipient_list_comment'];
+ echo '<textarea id="rec_profile_comment" tabindex="3" rows="2" >';
+ echo $array_profiles[$_POST['pid']]['comment'];
+ echo '</textarea>';
+ echo '</div>';
+
+ }
+
+ function getCleanString($string) {
+ return preg_replace ("/'/", "`", $string);
+ }
+
+ function recipientsAddForward() {
+
+ $doSave = $_POST['doSave'] == 'true' ? true : false;
+ $doAdd = $_POST['doAdd'] == 'true' ? true : false;
+
+ $fields = $_POST['fields'];
+ $recipients_list = $this->getCleanString($_POST['recipients_list']);
+ $delimiter = $_POST['recipientsDelimiter'];
+
+ $profileName = $_POST['profile_name'];
+ $profileComment = $_POST['profile_comment'];
+ $pid = $_POST['profile_id'];
+
+ // Bom kar tule rešil konverzijo iz delimiterja v |~|
+ $recipients_list = str_replace ($delimiter, "|~|", $recipients_list);
+
+ # če shranjujemo respondente
+ if ($doSave == true){
+ $pid = $this->saveAppendRecipientList($pid, $fields, $recipients_list, $profileName, $profileComment);
+ }
+
+ # če dodajamo respondente v bazo
+ if ($doAdd == true){
+ #dodamo polja
+ $result = $this->addMassRecipients($recipients_list, $fields, $pid);
+
+ # prikažemo napake
+ $invalid_recipiens_array = $this->displayRecipentsErrors($result);
+ }
+
+ # če smo dodajali repsondente v bazo, prikažemo tabelo respondentov
+ if ($doAdd == true){
+ $this->viewRecipients();
+ }
+ # če ne prikažemo profile respondentov
+ else {
+ $this->useRecipientsList($pid);
+ }
+
+ // Ce smo dodajali respondente rocno v bazo, to shranimo, ker potem ne smemo povezati mailov s podatki
+ // TEGA NE SMEMO NAREDITI, KER DRUGACE SE VSAKIC OB DODAJANJU NA NOVO UGASNE
+ /*if ($doAdd == true) {
+ $update = sisplet_query("UPDATE srv_anketa SET show_email='0' WHERE id='".$this->sid."'");
+ }*/
+ }
+
+ function saveAppendRecipientList($pid, $fields, $recipients, $profileName, $profileComment) {
+ global $lang,$site_url, $global_user_id;
+
+ # shranjujemo v nov profil
+ $post_fields = str_replace('inv_field_','',implode(',',$fields));
+ $post_recipients = $this->getCleanString($recipients);
+
+ $pid = (int)$pid;
+ # če je pid < 0 shranimo v nov porfil
+ if ($pid <= 0)
+ {
+ # ali shranjujemo v sejo
+ if ($pid == -1)
+ {
+ $this->saveSessionRecipients($post_recipients,$post_fields,$profileComment);
+ }
+ else
+ {
+ # dodelimo ime
+ if ($profileName == NULL || trim($profileName) == '')
+ {
+ #zaporedno številčimo ime seznama1,2.... če slučajno ime že obstaja
+ $profileName = $lang['srv_inv_recipient_list_new'];
+ $names = array();
+ $s = "SELECT name FROM srv_invitations_recipients_profiles WHERE name LIKE '%".$new_name."%' AND uid='$global_user_id'";
+ $q = sisplet_query($s);
+ while ($r = mysqli_fetch_assoc($q))
+ {
+ $names[] = $r['name'];
+ }
+ if (count($names) > 0)
+ {
+ $cnt = 1;
+ while (in_array($lang['srv_inv_recipient_list_new'].$cnt, $names))
+ {
+ $cnt++;
+ }
+ $profileName = $lang['srv_inv_recipient_list_new'].$cnt;
+ }
+ }
+ $sql_insert = "INSERT INTO srv_invitations_recipients_profiles".
+ " (name,uid,fields,respondents,insert_time,comment, from_survey) ".
+ " VALUES ('$profileName', '$global_user_id', '$post_fields', '$post_recipients', NOW(), '$profileComment', '".$this->sid."' )";
+ $sqlQuery = sisplet_query($sql_insert);
+ if (!$sqlQuery)
+ {
+ }
+ else
+ {
+ $pid = mysqli_insert_id($GLOBALS['connect_db']);
+ }
+ }
+ } else {
+ # polovimo obstoječe podatke
+
+ $s = "SELECT fields, respondents FROM srv_invitations_recipients_profiles WHERE pid ='$pid'";
+ $q = sisplet_query($s);
+ list($old_fields, $old_respondents) = mysqli_fetch_row($q);
+
+ # najprej polja
+ $old_fields = explode(',',$old_fields);
+ $post_fields = explode(',',$post_fields);
+ foreach ($post_fields AS $post_field )
+ {
+ #če polje še ni v bazi ga dodamo
+ if (!in_array($post_field, $old_fields))
+ {
+ $old_fields[] = $post_field;
+ }
+ }
+
+ # nato porihtamo podatke
+ $old_recipients_list = explode("\n", $old_respondents);
+ $new_recipients_list = explode("\n", $post_recipients);
+
+ foreach ($new_recipients_list AS $post_recipient )
+ {
+ #če polje še ni v bazi ga dodamo
+ if (!in_array($post_recipient, $old_recipients_list))
+ {
+ $old_recipients_list[] = $post_recipient;
+ }
+ }
+
+ # počistimo prazne
+ foreach ($old_recipients_list AS $k => $post_recipient )
+ {
+ if (is_null($post_recipient) || $post_recipient == '')
+ {
+ unset($old_recipients_list[$k]);
+ }
+ }
+
+ $post_fields = implode(",",$old_fields);;
+ $post_recipients = implode("\n",$old_recipients_list);
+
+ # updejtamo obstoječ profil
+ $sql_update = " UPDATE srv_invitations_recipients_profiles".
+ " SET fields = '$post_fields', respondents ='$post_recipients' WHERE pid = '$pid'";
+
+ $sqlQuery = sisplet_query($sql_update);
+ if (!$sqlQuery)
+ {
+ }
+ else
+ {
+ }
+ }
+ sisplet_query("COMMIT");
+
+ #vrnemo pid seznama (če smo kreirali nov seznam je tako now pid)
+ return $pid;
+ }
+
+
+ function showAdvancedConditions()
+ {
+ global $lang;
+
+ $scp = new SurveyCondition($this->sid);
+ $scp->setChooseAction('invitationSetCondition()');
+ $scp->displayConditions($_POST['cid']);
+
+ }
+
+ function setAdvancedCondition()
+ {
+ global $lang;
+ SurveySession::sessionStart($this->sid);
+ SurveySession::set('invitationAdvancedConditionId', (int)$_POST['cid']);
+ $this->invitationAdvancedConditionId = (int)$_POST['cid'];
+ $this->viewRecipients();
+ }
+
+ function getConditionUserIds($cid = 0){
+ global $global_user_id;
+
+ if ($cid > 0){
+
+ // Poskrbimo za datoteko s podatki
+ $SDF = SurveyDataFile::get_instance();
+ $SDF->init($this->sid);
+ $SDF->prepareFiles();
+
+ $headFileName = $SDF->getHeaderFileName();
+ $dataFileName = $SDF->getDataFileName();
+ $dataFileStatus = $SDF->getStatus();
+
+
+ if ($dataFileStatus >= 0){
+
+ $_HEADERS = unserialize(file_get_contents($headFileName));
+
+ SurveyConditionProfiles :: Init($this->sid, $global_user_id);
+ SurveyConditionProfiles :: setHeader($_HEADERS);
+
+ $_condition_profile_AWK = SurveyConditionProfiles:: getAwkConditionString($cid);
+
+ if (IS_WINDOWS) {
+ $_command = 'gawk -F"'.STR_DLMT.'" "'.$_condition_profile_AWK.' { if ('.USER_ID_FIELD.'!=0) print \"$invUsrId[]=\",'.USER_ID_FIELD.',\";\" }" '.$dataFileName .' >> '. $dataFileName.'.tmp';
+ }
+ else {
+ $_command = 'awk -F"'.STR_DLMT.'" \' '.$_condition_profile_AWK.' { if ('.USER_ID_FIELD.'!=0) print "$invUsrId[]=",'.USER_ID_FIELD.',";" }\' '.$dataFileName .' >> '.$dataFileName.'.tmp';
+ }
+
+ $file_handler = fopen($dataFileName.'.tmp',"w");
+ fwrite($file_handler,"<?php\n");
+ fclose($file_handler);
+ $out = shell_exec($_command);
+
+ $file_handler = fopen($dataFileName.'.tmp',"a");
+ fwrite($file_handler,'?>');
+ fclose($file_handler);
+ include($dataFileName.'.tmp');
+
+ if (file_exists($dataFileName.'.tmp')) {
+ unlink($dataFileName.'.tmp');
+ }
+
+ if (is_array($invUsrId) && count($invUsrId) > 0){
+ return $invUsrId;
+ }
+ }
+ else{
+ echo '!!!OLD DATA FILE!!!';
+ }
+ }
+
+ return array();
+ }
+
+ function advancedCondition()
+ {
+ global $lang;
+ echo '<span id="conditionProfileNote" class="simple">';
+ echo $lang['srv_inv_condition_filter'].' ';
+
+ if ((int)$this->invitationAdvancedConditionId > 0)
+ {
+ $scp = new SurveyCondition($this->sid);
+ echo ' <strong>'.$scp->getConditionName((int)$this->invitationAdvancedConditionId).'</strong> ';
+ $this->user_inv_ids = $this->getConditionUserIds($this->invitationAdvancedConditionId);
+ $note = $scp -> getConditionString($this->invitationAdvancedConditionId );
+ echo $note;
+ if (is_array($this->user_inv_ids) && count($this->user_inv_ids) > 0)
+ {
+ }
+ else
+ {
+ }
+ echo '<span class="as_link spaceLeft" onclick="showInvitationAdvancedConditions(\''.(int)$this->invitationAdvancedConditionId.'\'); return false;">'.$lang['srv_profile_edit'].'</span>';
+ echo '<span class="as_link spaceLeft" onclick="invitationSetCondition(\'0\'); return false;">'.$lang['srv_profile_remove'].'</span>';
+ }
+ else
+ {
+ echo '<strong>'.$lang['srv_inv_condition_no_filter'].'</strong>';
+ echo '<a href="#" class="faicon if_add" onclick="showInvitationAdvancedConditions(); return false;" data-cid="'.(int)$this->invitationAdvancedConditionId.'">&nbsp;</a>';
+ }
+ echo '</span>';
+ }
+
+ function listCondition()
+ {
+ global $lang;
+ # get all lists
+ $lists = $this->getSurveyInvitationLists(true);
+
+ $selected = (int)(isset($_SESSION['inv_filter']['list']) ? (int)$_SESSION['inv_filter']['list'] : -2);
+ echo '&nbsp;';
+ echo '<label>'.$lang['srv_invitation_recipients_filter_list'];
+ echo '<select id="inv_rec_filter_list" onchange="inv_filter_recipients();">';
+ foreach ($lists AS $list_id => $list)
+ {
+ echo '<option value="'.$list_id.'"'.((int)$selected == $list_id ? ' selected="selected"' : '').'>'.$list['name'].'</option>';
+ }
+ echo '</select></label>';
+ }
+
+ function getSurveyInvitationLists($add_all = false)
+ {
+ global $lang;
+ # polovimo sezname
+ $lists = array();
+ if ($add_all)
+ {
+ $lists['-2'] = array('name'=>$lang['srv_invitation_recipients_filter_list_all']);
+ }
+ $lists['-1'] = array('name'=>$lang['srv_invitation_new_templist']);
+ $lists['0'] = array('name'=>$lang['srv_invitation_new_templist_author']);
+ $sql_string_lists = "SELECT * from srv_invitations_recipients_profiles WHERE pid IN(SELECT i.list_id FROM srv_invitations_recipients AS i WHERE i.ank_id = '{$this->sid}' AND i.deleted = '0' GROUP BY i.list_id ORDER BY i.id) ";
+ $sql_query_lists = sisplet_query($sql_string_lists);
+ while ($row_lists = mysqli_fetch_assoc($sql_query_lists)) {
+ $lists[$row_lists['pid']] = array('name'=>$row_lists['name']);
+ }
+
+ return $lists;
+ }
+
+
+ function viewServerSettings(){
+ global $lang;
+ global $site_url;
+ global $site_url;
+ global $site_path;
+ global $admin_type;
+ global $global_user_id;
+ global $mysql_database_name;
+ global $aai_instalacija;
+
+
+ $row = SurveyInfo::getInstance()->getSurveyRow();
+
+ echo '<form name="settingsanketa_' . $row['id'] . '" action="ajax.php?a=editanketasettings&m=inv_server" method="post" autocomplete="off">' . "\n\r";
+ echo ' <input type="hidden" name="anketa" value="' . $this->sid . '" />' . "\n\r";
+ echo ' <input type="hidden" name="location" value="' . $_GET['a'] . '" />' . "\n\r";
+ echo ' <input type="hidden" name="submited" value="1" />' . "\n\r";
+
+ $MA = new MailAdapter($this->sid, $type='invitation');
+
+ // Dostop za posiljanje mailov preko 1ka serverja
+ $enabled1ka = $MA->is1KA() ? true : false;
+
+ // Admini na testu, www in virtualkah imajo 1ka smtp
+ if(($admin_type == 0) && ($mysql_database_name == 'www1kasi' || $mysql_database_name == 'test1kasi' || $mysql_database_name == 'real1kasi'))
+ $enabled1ka = true;
+
+
+ // Squalo
+ $squalo = new SurveyInvitationsSqualo($this->sid);
+ if($squalo->getSqualoEnabled()){
+
+ // Vklop squalo
+ echo '<div class="squalo_switch"><p>';
+
+ echo '<span class="bold">'.$lang['srv_squalo'].':</span>&nbsp;';
+
+ echo '<input type="hidden" name="squalo_mode" value="0">';
+ echo '<label><input type="checkbox" name="squalo_mode" id="squalo_mode" value="1" '.($squalo->getSqualoActive() ? 'checked ="checked" ' : '').' style="vertical-align:-2px;" onclick="squaloSwitch();">';
+ echo $lang['srv_squalo_sending'].' </label>';
+
+ echo '</p></div>';
+
+
+ // Squalo nastavitve...
+ echo '<div class="squalo_settings '.(!$squalo->getSqualoActive() ? ' displayNone' : '').'">';
+
+ echo $lang['srv_squalo_active'];
+
+ echo '</div>';
+ }
+
+
+ // Izbira streznika
+ echo '<div class="mail_mode_switch '.($squalo->getSqualoActive() ? ' displayNone' : '').'">';
+
+ // Opozorilo, ce imamo vklopljena vabila, da gre za iste nastavitve
+ echo '<p class="red bold">'.$lang['srv_email_server_settings_warning'].'</p>';
+
+ // Izbira SMTP streznika
+ echo '<span class="bold">'.$lang['srv_email_setting_select_server'].'</span>&nbsp;';
+
+ // AAI ima Arnesov smtp
+ if($aai_instalacija){
+ echo '<label><input type="radio" name="SMTPMailMode" value="0" '.($MA->is1KA() ? 'checked ="checked" ' : '').' onclick="smtpAAIPopupShow();">';
+ echo $lang['srv_email_setting_adapter0_aai']. ' </label>';
+ }
+ else{
+ echo '<label><input type="radio" name="SMTPMailMode" value="0" '.($MA->is1KA() ? 'checked ="checked" ' : '').' '.($enabled1ka ? '' : ' disabled="disabled"').' onclick="$(\'#send_mail_mode1, #send_mail_mode2\').hide();$(\'#send_mail_mode0\').show();">';
+ echo $lang['srv_email_setting_adapter0']. ' </label>';
+ }
+
+ // Google smtp je viden samo starim, kjer je ze vklopljen
+ if($MA->isGoogle()){
+ echo '<label><input type="radio" name="SMTPMailMode" value="1" '.($MA->isGoogle() ? 'checked ="checked" ' : '').' onclick="$(\'#send_mail_mode0, #send_mail_mode2\').hide(); $(\'#send_mail_mode1\').show();">';
+ echo $lang['srv_email_setting_adapter1'].' </label>';
+ }
+
+ // Lastni smtp
+ echo '<label><input type="radio" name="SMTPMailMode" value="2" '.($MA->isSMTP() ? 'checked ="checked" ' : '').' onclick="$(\'#send_mail_mode0, #send_mail_mode1\').hide(); $(\'#send_mail_mode2\').show();">';
+ echo $lang['srv_email_setting_adapter2'].' </label>';
+
+ echo Help :: display('srv_mail_mode');
+
+ echo '</div>';
+
+
+ #1KA
+ $enkaSettings = $MA->get1KASettings($raziskave=true);
+ echo '<div id="send_mail_mode0" '.(!$MA->is1KA() || $squalo->getSqualoActive() ? ' class="displayNone"' : '').'>';
+ echo '<br /><span class="bold">'.$lang['srv_email_setting_settings'].'</span>';
+ echo '<br />';
+ # from
+ echo '<p><label>'.$lang['srv_email_setting_from'].'<span>'.$enkaSettings['SMTPFrom'].'</span><input type="hidden" name="SMTPFrom0" value="'.$enkaSettings['SMTPFrom'].'"></label>';
+ echo '</p>';
+ # replyTo
+ echo '<p><label>'.$lang['srv_email_setting_reply'].'<input type="text" name="SMTPReplyTo0" value="'.$enkaSettings['SMTPReplyTo'].'" ></label>';
+ echo '</p>';
+ #delay
+ echo '<p><label>'.$lang['srv_email_setting_smtp_delay'].' '.Help::display('srv_inv_delay').': <select name="SMTPDelay0">'
+ /*. '<option value="0" '.($enkaSettings['SMTPDelay']=="0"?'selected="selected"':'') .'>0 </option>'
+ . '<option value="10000" '.($enkaSettings['SMTPDelay']=="10000"?'selected="selected"':'') .'>0.01 sec (max 100 / sec)</option>'
+ . '<option value="20000" '.($enkaSettings['SMTPDelay']=="20000"?'selected="selected"':'') .'>0.02 sec (max 50 / sec)</option>'
+ . '<option value="50000" '.($enkaSettings['SMTPDelay']=="50000"?'selected="selected"':'') .'>0.05 sec (max 20 / sec)</option>'
+ . '<option value="100000" '.($enkaSettings['SMTPDelay']=="100000"?'selected="selected"':'') .'>0.1 sec (max 10 / sec)</option>'
+ . '<option value="200000" '.($enkaSettings['SMTPDelay']=="200000"?'selected="selected"':'') .'>0.2 sec (max 5 / sec)</option>'*/
+ . '<option value="500000" '.($enkaSettings['SMTPDelay']=="500000"?'selected="selected"':'') .'>0.5 sec (max 2 / sec)</option>'
+ . '<option value="1000000" '.($enkaSettings['SMTPDelay']=="1000000"?'selected="selected"':'') .'>1 sec (max 1 / sec)</option>'
+ . '<option value="2000000" '.($enkaSettings['SMTPDelay']=="2000000"?'selected="selected"':'') .'>2 sec (max 30 / min)</option>'
+ . '<option value="4000000" '.($enkaSettings['SMTPDelay']=="4000000"?'selected="selected"':'') .'>4 sec (max 15 / min)</option>'
+ . '<option value="5000000" '.($enkaSettings['SMTPDelay']=="5000000"?'selected="selected"':'') .'>5 sec (max 12 / min)</option>'
+ . '<option value="10000000" '.($enkaSettings['SMTPDelay']=="10000000"?'selected="selected"':'') .'>10 sec (max 6 / min)</option>'
+ . '<option value="20000000" '.($enkaSettings['SMTPDelay']=="20000000"?'selected="selected"':'') .'>20 sec (max 3 / min)</option>'
+ . '<option value="30000000" '.($enkaSettings['SMTPDelay']=="30000000"?'selected="selected"':'') .'>30 sec (max 2 / min)</option>'
+ . '</select></label>';
+ echo '</p>';
+ echo '</div>';
+
+ #GMAIL - Google
+ $enkaSettings = $MA->getGoogleSettings();
+ echo '<div id="send_mail_mode1" '.(!$MA->isGoogle() || $squalo->getSqualoActive() ? ' class="displayNone"' : '').'>';
+ echo '<br /><span class="italic">'.$lang['srv_email_setting_adapter1_note'].'</span><br />';
+ echo '<br /><span class="bold">'.$lang['srv_email_setting_settings'].'</span><br />';
+ # from
+ echo '<p><label>'.$lang['srv_email_setting_from'].'<input type="text" name="SMTPFrom1" value="'.$enkaSettings['SMTPFrom'].'"></label>';
+ echo '</p>';
+ # replyTo
+ echo '<p><label>'.$lang['srv_email_setting_reply'].'<input type="text" name="SMTPReplyTo1" value="'.$enkaSettings['SMTPReplyTo'].'" ></label>';
+ echo '</p>';
+ #Password
+ echo '<p><label>'.$lang['srv_email_setting_password'].'<input type="password" name="SMTPPassword1" placeholder="'.$lang['srv_email_setting_password_placeholder'].'"></label>';
+ echo '</p>';
+ echo '</div>';
+
+ #SMTP
+ $enkaSettings = $MA->getSMTPSettings();
+ echo '<div id="send_mail_mode2" '.(!$MA->isSMTP() || $squalo->getSqualoActive() ? ' class="displayNone"' : '').'>';
+ echo '<br /><span class="italic">'.$lang['srv_email_setting_adapter2_note'].'</span><br />';
+ echo '<br /><span class="bold">'.$lang['srv_email_setting_settings'].'</span><br />';
+ # from - NICE
+ echo '<p><label>'.$lang['srv_email_setting_from_nice'].'<input type="text" name="SMTPFromNice2" value="'.$enkaSettings['SMTPFromNice'].'"></label>';
+ echo '</p>';
+ # from
+ echo '<p><label>'.$lang['srv_email_setting_from'].'<input type="text" name="SMTPFrom2" value="'.$enkaSettings['SMTPFrom'].'"></label>';
+ echo '</p>';
+ # replyTo
+ echo '<p><label>'.$lang['srv_email_setting_reply'].'<input type="text" name="SMTPReplyTo2" value="'.$enkaSettings['SMTPReplyTo'].'" ></label>';
+ echo '</p>';
+ #Username
+ echo '<p><label>'.$lang['srv_email_setting_username'].'<input type="text" name="SMTPUsername2" value="'.$enkaSettings['SMTPUsername'].'" ></label>';
+ echo '</p>';
+ #Password
+ echo '<p><label>'.$lang['srv_email_setting_password'].'<input type="password" name="SMTPPassword2" placeholder="'.$lang['srv_email_setting_password_placeholder'].'"></label>';
+ echo '</p>';
+ #autentikacija
+ echo '<p>';
+ echo $lang['srv_email_setting_autentication'];
+ echo '<label><input type="radio" name="SMTPAuth2" value="0" '.((int)$enkaSettings['SMTPAuth'] != 1 ? 'checked ="checked" ' : '').'>';
+ echo $lang['srv_email_setting_no'].'</label>';
+ echo '<label><input type="radio" name="SMTPAuth2" value="1" '.((int)$enkaSettings['SMTPAuth'] == 1 ? 'checked ="checked" ' : '').'>';
+ echo $lang['srv_email_setting_yes'].'</label>';
+ echo '</p>';
+ #Varnost SMTPSecure
+ echo '<p>';
+ echo $lang['srv_email_setting_encryption'];
+ echo '<label><input type="radio" name="SMTPSecure2" value="0" '.((int)$enkaSettings['SMTPSecure'] == 0 ? 'checked ="checked" ' : '').'>';
+ echo $lang['srv_email_setting_encryption_none'].'</label>';
+ echo '<label><input type="radio" name="SMTPSecure2" value="ssl" '.($enkaSettings['SMTPSecure'] == 'ssl' ? 'checked ="checked" ' : '').'>';
+ echo $lang['srv_email_setting_encryption_ssl'].'</label>';
+ echo '<label><input type="radio" name="SMTPSecure2" value="tls" '.($enkaSettings['SMTPSecure'] == 'tls' ? 'checked ="checked" ' : '').'>';
+ echo $lang['srv_email_setting_encryption_tls'].'</label>';
+ echo '</p>';
+ #port
+ echo '<p><label>'.$lang['srv_email_setting_port'].'<input type="number" min="0" max="65535" name="SMTPPort2" value="'.(int)$enkaSettings['SMTPPort'].'" style="width:80px;"></label>';
+ echo ' '.$lang['srv_email_setting_port_note'];
+ echo '</p>';
+ #host
+ echo '<p><label>'.$lang['srv_email_setting_host'].'<input type="text" name="SMTPHost2" value="'.$enkaSettings['SMTPHost'].'" ></label>';
+ echo '</p>';
+
+ #delay
+ echo '<p><label>'.$lang['srv_email_setting_smtp_delay'].' '.Help::display('srv_inv_delay').': <select name="SMTPDelay2">'
+ /*. '<option value="0" '.($enkaSettings['SMTPDelay']=="0"?'selected="selected"':'') .'>0 </option>'
+ . '<option value="10000" '.($enkaSettings['SMTPDelay']=="10000"?'selected="selected"':'') .'>0.01 sec (max 100 / sec)</option>'
+ . '<option value="20000" '.($enkaSettings['SMTPDelay']=="20000"?'selected="selected"':'') .'>0.02 sec (max 50 / sec)</option>'
+ . '<option value="50000" '.($enkaSettings['SMTPDelay']=="50000"?'selected="selected"':'') .'>0.05 sec (max 20 / sec)</option>'
+ . '<option value="100000" '.($enkaSettings['SMTPDelay']=="100000"?'selected="selected"':'') .'>0.1 sec (max 10 / sec)</option>'
+ . '<option value="200000" '.($enkaSettings['SMTPDelay']=="200000"?'selected="selected"':'') .'>0.2 sec (max 5 / sec)</option>'*/
+ . '<option value="500000" '.($enkaSettings['SMTPDelay']=="500000"?'selected="selected"':'') .'>0.5 sec (max 2 / sec)</option>'
+ . '<option value="1000000" '.($enkaSettings['SMTPDelay']=="1000000"?'selected="selected"':'') .'>1 sec (max 1 / sec)</option>'
+ . '<option value="2000000" '.($enkaSettings['SMTPDelay']=="2000000"?'selected="selected"':'') .'>2 sec (max 30 / min)</option>'
+ . '<option value="4000000" '.($enkaSettings['SMTPDelay']=="4000000"?'selected="selected"':'') .'>4 sec (max 15 / min)</option>'
+ . '<option value="5000000" '.($enkaSettings['SMTPDelay']=="5000000"?'selected="selected"':'') .'>5 sec (max 12 / min)</option>'
+ . '<option value="10000000" '.($enkaSettings['SMTPDelay']=="10000000"?'selected="selected"':'') .'>10 sec (max 6 / min)</option>'
+ . '<option value="20000000" '.($enkaSettings['SMTPDelay']=="20000000"?'selected="selected"':'') .'>20 sec (max 3 / min)</option>'
+ . '<option value="30000000" '.($enkaSettings['SMTPDelay']=="30000000"?'selected="selected"':'') .'>30 sec (max 2 / min)</option>'
+ . '</select></label>';
+ echo '</p>';
+
+ echo '</div>';
+
+ echo '</form>';
+
+ echo '<br class="clr" />';
+
+ // Gumb shrani
+ echo '<span class="floatRight" ><div class="buttonwrapper"><a class="ovalbutton ovalbutton_orange btn_savesettings" href="#" onclick="document.settingsanketa_' . $row['id'] . '.submit(); return false;">';
+ echo $lang['srv_email_setting_btn_save'] . '</a></div></span>';
+
+ // Gumb preveri nastavitve
+ echo '<span id="send_mail_mode_test" class="floatRight spaceRight '.($squalo->getSqualoActive() ? ' displayNone' : '').'"><div class="buttonwrapper"><a class="ovalbutton ovalbutton_green" href="#" onclick="showTestSurveySMTP(); return false;">';
+ echo $lang['srv_email_setting_btn_test'].'</a></div></span>';
+
+
+ if ($_GET['s'] == '1') {
+ echo '<div id="success_save" style="float:left; display:inline; margin: -2px 0 0 0;"></div>';
+ echo '<script type="text/javascript">$(document).ready(function() {show_success_save();});</script>';
+ }
+ }
+
+ // V session nastavimo nastavitev da se posilja z/brez email posiljanja
+ function setNoEmailing(){
+
+ if(isset($_POST['value'])){
+ SurveySession::sessionStart($this->sid);
+ SurveySession::set('inv_noEmailing', (int)$_POST['value']);
+
+ // Ce preklopimo na drugo posiljanje (posta, sms...) moramo tudi preklopiti na rocni vnos kode
+ if($_POST['value'] == '1'){
+ sisplet_query("UPDATE srv_anketa SET usercode_required='1' WHERE id='".$this->sid."'");
+ }
+ }
+ }
+
+ // V session nastavimo tip posiljanja (ce ni email - posta, sms, drugo...)
+ function setNoEmailingType(){
+
+ if(isset($_POST['value'])){
+ SurveySession::sessionStart($this->sid);
+ SurveySession::set('inv_noEmailing_type', (int)$_POST['value']);
+ }
+ }
+
+ // Prikazemo popup za vklop arnes smtp-ja na aai
+ private function showAAISmtpPopup(){
+ global $lang;
+
+ echo '<div class="popup_close"><a href="#" onClick="quick_title_edit_cancel(); return false;">✕</a></div>';
+
+ echo '<h2>'.$lang['srv_email_setting_adapter0_aai_title'].'</h2>';
+
+ echo '<div class="popup_content">';
+ echo $lang['srv_email_setting_adapter0_aai_popup'];
+ echo '<br /><br />';
+ echo '<input type="checkbox" id="aai_smtp_checkbox" name="aai_smtp_checkbox" class="pointer" onClick="smtpAAIAccept();">';
+ echo ' <label for="aai_smtp_checkbox"><b>'.$lang['srv_email_setting_adapter0_aai_popup2'].'</b></label>';
+ echo '</div>';
+
+ echo '<div class="buttons_holder">';
+ echo '<span class="buttonwrapper floatRight spaceLeft" id="aai_smtp_button" style="display:none;" title="'.$lang['srv_save_profile_yes'].'"><a class="ovalbutton ovalbutton_orange" href="#" onClick="smtpAAISet(); return false;"><span>'.$lang['srv_save_profile_yes'].'</span></a></span>';
+ echo '<span class="buttonwrapper floatRight" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="smtpAAIPopupClose(); return false;"><span>'.$lang['srv_cancel'].'</span></a></span>';
+ echo '</div>';
+ }
+}
diff --git a/admin/survey/classes/surveyEmails/class.SurveySimpleMailInvitation.php b/admin/survey/classes/surveyEmails/class.SurveySimpleMailInvitation.php
new file mode 100644
index 0000000..62fef17
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/class.SurveySimpleMailInvitation.php
@@ -0,0 +1,464 @@
+<?php
+/**
+ * @author Gorazd Veselič
+ * @date December 2011
+ *
+ */
+
+define("SIMPLE_MAIL_QUOTA", 20);
+
+class SurveySimpleMailInvitation {
+
+ public $sid; # id ankete
+
+ function __construct($anketa) {
+ $this->sid = $anketa;
+ SurveyInfo::SurveyInit($this->sid);
+ }
+
+ function ajax() {
+
+ switch ($_GET['a']) {
+ case 'showInvitation':
+ $this->showSimpleMailInvitation();
+ break;
+ case 'previewInvitation':
+ $this->previewInvitation();
+ break;
+ case 'sendInvitation':
+ $this->sendInvitation();
+ break;
+
+ default:
+ print_r("<pre>");
+ print_r($_GET);
+ print_r($_POST);
+ print_r("</pre>"); ;
+ break;
+ }
+ }
+
+ function showSimpleMailInvitation() {
+ global $site_url, $lang, $global_user_id;
+ global $admin_type;
+
+
+ $pid = (isset($_POST['pid']) && trim($_POST['pid']) != '') ? trim($_POST['pid']) : 'def1';
+
+ # najprej preverimo prejemnike
+ $emails = explode( "\n",mysql_real_unescape_string($_POST['emails'] ));
+
+ #počistimo emaile
+ $valid_emails = array();
+ foreach ($emails as $email) {
+ $email = trim($email);
+ if ($this->validEmail($email) && !in_array($email,$valid_emails)) {
+ $valid_emails[] = $email;
+ }
+ }
+ if (count($valid_emails) > 0 ) {
+ $css_wide = ' wide';
+ }
+ # izrišemo osnovni div .divPopUp
+ echo '<div id="simpleMailInvitation_div" class="divPopUp'.$css_wide.'">';
+ echo '<div class="divPopUp_top clr">';
+ echo $lang['srv_email_vabila_simple_popup_title'];
+ echo '</div>'; #PM_top
+ echo '<div class="divPopUp_content">';
+
+
+ # če ni admin ali manager preverimo koliko emailov je ta uporabnik že uspešno poslal
+ if ($admin_type > 1) {
+ $r = sisplet_query("SELECT count(email)FROM srv_simple_mail_invitation WHERE ank_id='".$this->sid."' AND state='ok' AND usr_id='".$global_user_id."'");
+ list ($quota) = mysqli_fetch_row($r);
+ if ($quota > SIMPLE_MAIL_QUOTA) {
+ echo '<div class="simpleMailError">';
+ printf ($lang['srv_simple_mail_inv_quota1'], SIMPLE_MAIL_QUOTA);
+ echo '</div>';
+ } else if ( ($quota+count($valid_emails)) > SIMPLE_MAIL_QUOTA) {
+ echo '<div class="simpleMailError">';
+ printf ($lang['srv_simple_mail_inv_quota2'], SIMPLE_MAIL_QUOTA);
+ echo '</div>';
+ }
+ }
+
+
+ # če imamo kaj vlejavnih emailov, potem nadaljujemo
+ if (count($valid_emails) > 0 ) {
+ # preberemo vsa obvestila ankete (2x iz lang fajla in če obstaja še kaj shranjeno)
+ $profiles = $this->getProfiles();
+
+ # izrišemo profile
+ # dodamo cover div
+ echo '<div id="simpleMailInvitationCoverDiv" />';
+ echo '<div id="simpleMailInvitationPreviewDiv" />';
+ echo '<div class="floatLeft">';
+ echo '<div class="profile_holder">';
+ foreach ($profiles as $key => $profile) {
+ echo '<div value="'.$key.'" class="option'.($key == $pid ? ' active': '').'">'.$profile['subject'].'</div>';
+ }
+ echo '</div>';
+ echo '</div>'; #floatLeft
+ echo '<div class="floatLeft spaceLeft">';
+ echo '<div>';
+ echo $lang['srv_invitation_subject'].':';
+ echo '<br/>';
+ echo '<input id="simpleMailSubject" type="text" value="'.$profiles[$pid]['subject'].'">';
+ echo '</div>';
+ echo '<div>';
+ echo $lang['srv_invitation_content'].':';;
+ echo '<br/>';
+ echo '<textarea id="simpleMailBody">';
+ echo $profiles[$pid]['body'];
+ echo '</textarea>';
+ echo '</div>';
+ echo '</div>'; #floatLeft
+
+ echo '<div class="floatLeft spaceLeft">';
+ echo '<div>';
+ echo $lang['srv_invitation_recipients'].':';
+ echo '<br/>';
+ echo '<textarea id="simpleMailRecipients">';
+ echo implode("\n",$valid_emails);
+ echo '</textarea>';
+ echo '</div>';
+ echo '</div>'; #floatLeft
+ $buttonsRight = '<span class="buttonwrapper floatRight spaceRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="sendSimpleMailInvitation(); return false;"><span>'.$lang['srv_invitation_send'].'</span></a></span>';
+ $buttonsRight .= '<span class="buttonwrapper floatRight"><a class="ovalbutton ovalbutton_gray" href="#" onclick="previewMailInvitation(); return false;"><span>'.$lang['srv_invitation_preview'].'</span></a></span>';
+ } else {
+ # nimamo veljavnih emailov, obvestimo in damo gumb zapri
+ echo '<div class="simpleMailError">';
+ echo $lang['srv_simple_mail_inv_no_emails'];
+ echo '</div>';
+ }
+
+ echo '<br class="clr">';
+ echo '</div>'; # class="popUp_content"
+ echo '<div class="divPopUp_btm clr">'; #class="inv_FS_btm"
+ echo '<div class="floatLeft spaceLeft"><div class="buttonwrapper" title="'.$lang['srv_cancel'].'"><a class="ovalbutton ovalbutton_gray" href="#" onclick="$(\'#fullscreen\').hide();$(\'#fade\').fadeOut(\'slow\'); return false;"><span>'.$lang['srv_cancel'].'</span></a></div></div>';
+
+ if (count($valid_emails) > 0 ) {
+ echo $buttonsRight;
+ }
+
+ echo '</div>'; #class="inv_FS_btm"
+ echo '</div>'; #class="divPopUp"
+ }
+
+ function previewInvitation() {
+ global $lang;
+ # polovimo poslano
+
+ # najprej preverimo prejemnike
+ $emails = explode( "\n", mysql_real_unescape_string($_POST['emails']) );
+ #počistimo emaile
+ $valid_emails = array();
+ foreach ($emails as $email) {
+ $email = trim($email);
+ if ($this->validEmail($email) && !in_array($email,$valid_emails)) {
+ $valid_emails[] = $email;
+ }
+ }
+
+ reset($valid_emails);
+ $email = current($valid_emails);
+ #polovimo subject
+ $subject = trim($_POST['subject']);
+ $body = nl2br(trim(mysql_real_unescape_string($_POST['body'])));
+
+ # če mamo SEO
+ $url = SurveyInfo::getSurveyLink();
+
+ $body = str_replace(
+ array('#URL#','#EMAIL#'),
+ array('<a href="' . $url . '">' . $url . '</a>',$email),
+ $body);
+
+ echo '<div><b>'.$subject.'</b></div><br/>';
+ echo '<div>';
+ echo $body;
+ echo '</div>';
+ echo '<br class="clr"/>';
+ echo '<br/>';
+ echo '<span class="buttonwrapper floatRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="$(\'#simpleMailInvitationPreviewDiv\').hide(); $(\'#simpleMailInvitationCoverDiv\').fadeOut(\'slow\'); return false;"><span>'.$lang['srv_zapri'].'</span></a></span>';
+ }
+
+
+ function sendInvitation() {
+ global $lang, $admin_type, $site_path, $global_user_id;
+ # polovimo poslano
+
+ # najprej preverimo prejemnike
+ $emails = explode( "\n", mysql_real_unescape_string($_POST['emails']) );
+ #počistimo emaile
+ $valid_emails = array();
+ foreach ($emails as $email) {
+ $email = trim($email);
+ if ($this->validEmail($email) && !in_array($email,$valid_emails)) {
+ $valid_emails[] = $email;
+ }
+ }
+
+ #polovimo subject
+ $subject = trim(mysql_real_unescape_string($_POST['subject']));
+ $body = nl2br(trim(mysql_real_unescape_string($_POST['body'])));
+
+ # če mamo SEO
+ $url = SurveyInfo::getSurveyLink();
+
+ # zamenjamo sistemske vrednosti
+ $body = str_replace(array('#URL#', '[URL]'),
+ array('<a href="' . $url . '">' . $url . '</a>','<a href="' . $url . '">' . $url . '</a>'),
+ $body);
+
+ $c = 0;
+ # če ni admin ali manager preverimo koliko emailov je ta uporabnik že uspešno poslal
+ if ($admin_type > 1 ) {
+ $r = sisplet_query("SELECT count(email)FROM srv_simple_mail_invitation WHERE ank_id='".$this->sid."' AND state='ok' AND usr_id='".$global_user_id."'");
+ list ($quota) = mysqli_fetch_row($r);
+ $c = (int)$quota;
+ }
+
+
+
+ # izrišemo osnovni div .divPopUp
+ echo '<div id="simpleMailInvitation_div" class="divPopUp'.$css_wide.'">';
+ echo '<div class="divPopUp_top clr">';
+ echo $lang['srv_email_vabila_simple_popup_title'];
+ echo '</div>';
+ echo '<div class="divPopUp_content">';
+
+ if (is_array($valid_emails) && count($valid_emails) > 0) {
+ if ($subject != null && $subject != '') {
+ if ($body != null && $body != '') {
+
+ $send_success = array ();
+ $send_errors = array ();
+ $send_over_quota = array ();
+
+ Common::getInstance()->Init($this->sid);
+
+ foreach ($valid_emails AS $email) {
+ if ( $c < SIMPLE_MAIL_QUOTA ) {
+
+ # povečamo counter za neadmine
+ if ($admin_type > 1) {
+ $c++;
+ }
+ # zamenjamo morebitne meaile
+ $body = str_replace(array('#EMAIL#', '[EMAIL]'),
+ array($email,
+ $email),
+ $body);
+
+ try
+ {
+ $MA = new MailAdapter($this->anketa, $type='invitation');
+ $MA->addRecipients($email);
+ $resultX = $MA->sendMail($body, $subject);
+ }
+ catch (Exception $e)
+ {
+ }
+
+ if ($resultX) {
+ # poslalo ok
+ $send_success[] = $email;
+ } else {
+ # ni poslalo
+ $send_errors[] = $email;
+ }
+
+ } else {
+ # presegli smo kvoto, zabeležimo email.
+ $send_over_quota[] = $email;
+ }
+ }
+ } else {
+ # Polje Vsebina ne sme biti prazno
+ echo '<div class="simpleMailError">';
+ echo $lang['srv_simple_mail_inv_error1'];
+ echo '</div>';
+ $has_error = true;
+ }
+
+ } else {
+ # Polje Naslov - (zadeva) ne sme biti prazna
+ echo '<div class="simpleMailError">';
+ echo $lang['srv_simple_mail_inv_error2'];
+ echo '</div>';
+ $has_error = true;
+ }
+ } else {
+ # ni vnešenih prejemnikov, ali pa emaili niso pravilni
+ echo '<div class="simpleMailError">';
+ echo $lang['srv_simple_mail_inv_error3'];
+ echo '</div>';
+ $has_error = true;
+ }
+
+
+ echo '<div class="floatLeft" style="width:310px; max-height:400px; overflow:auto;">';
+ if (count($send_success) > 0 || count($send_errors) > 0) {
+ if (count($send_success) > 0) {
+ echo $lang['srv_simple_mail_inv_ok_msg'];
+ echo '<br/>';
+ echo implode("<br/>",$send_success);
+ echo '<br/>';
+ }
+ if (count($send_errors) > 0) {
+ echo $lang['srv_simple_mail_inv_error4'];
+ echo '<br/>';
+ echo '<br/>';
+ echo implode("<br/>",$send_errors);
+ }
+ } else {
+ echo $lang['srv_simple_mail_inv_error5'];
+ }
+ echo '</div>'; #floatLeft
+
+ echo '<div class="floatRight spaceLeft" >';
+ echo '<strong>'.$lang['srv_invitation_subject'].':'.'</strong>';
+ echo '<br/>';
+ echo '<div style="background-color: #fefefe; padding:3px; width:500px;">';
+ echo $subject;
+ echo '</div>';
+ echo '<br/>';
+ echo '<strong>'.$lang['srv_invitation_content'].':'.'</strong>';
+ echo '<br/>';
+ echo '<div style="background-color: #fefefe; padding:3px; width:500px;">';
+ echo $body;
+ echo '</div>';
+ echo '</div>'; #floatLeft
+ echo '<br class="clr" />';
+
+ echo '</div>'; # class="popUp_content"
+ echo '<div class="divPopUp_btm clr">'; #class="inv_FS_btm"
+
+ echo '<span class="buttonwrapper floatRight spaceRight"><a class="ovalbutton ovalbutton_orange" href="#" onclick="$(\'#fullscreen\').hide();$(\'#fade\').fadeOut(\'slow\'); return false;"><span>'.$lang['srv_zapri'].'</span></a></span>';
+
+ echo '</div>'; #class="inv_FS_btm"
+ echo '</div>'; #class="divPopUp"
+
+ # poskrbimo za tracking: statusi emailov: ENUM('ok','error','quota_exceeded'),
+ $values = '';
+ $prefix = '';
+ $send_time = date( 'Y-m-d H:i:s');
+ if (is_array($send_success) && count($send_success)>0) {
+ foreach ($send_success AS $email) {
+ $values .= $prefix."('".$this->sid."', '".$email."', '".$send_time."', 'ok', '".$global_user_id."')";
+ $prefix = ', ';
+ }
+ }
+ if (is_array($send_errors) && count($send_errors)>0) {
+ foreach ($send_errors AS $email) {
+ $values .= $prefix."('".$this->sid."', '".$email."', '".$send_time."', 'error', '".$global_user_id."')";
+ $prefix = ', ';
+ }
+ }
+ if (is_array($send_over_quota) && count($send_over_quota)>0) {
+ foreach ($send_over_quota AS $email) {
+ $values .= $prefix."('".$this->sid."', '".$email."', '".$send_time."', 'quota_exceeded', '".$global_user_id."')";
+ $prefix = ', ';
+ }
+ }
+ if ($values != '') {
+ $insert_string = 'INSERT INTO srv_simple_mail_invitation (ank_id, email, send_time, state, usr_id) VALUES '.$values;
+ sisplet_query($insert_string);
+ sisplet_query("COMMIT");
+ }
+ }
+
+ function getProfiles() {
+ global $lang;
+ # preberemo vsa obvestila ankete (2x iz lang fajla in če obstaja še kaj shranjeno)
+ $profiles = array();
+ $profiles['def1'] = array('subject' => $lang['srv_simple_mail_inv_def1_subject'],
+ 'body' => $lang['srv_simple_mail_inv_def1_body']);
+ $profiles['def2'] = array('subject' => $lang['srv_simple_mail_inv_def2_subject'],
+ 'body' => $lang['srv_simple_mail_inv_def2_body']);
+
+ return $profiles;
+ }
+
+ /**
+ Validate an email address.
+ Provide email address (raw input)
+ Returns true if the email address has the email
+ address format and the domain exists.
+ */
+ function validEmail($email = null) {
+ $isValid = true;
+ $atIndex = strrpos($email, "@");
+ if (is_bool($atIndex) && !$atIndex)
+ {
+ $isValid = false;
+ }
+ else
+ {
+ $domain = substr($email, $atIndex+1);
+ $local = substr($email, 0, $atIndex);
+ $localLen = strlen($local);
+ $domainLen = strlen($domain);
+ $domain_parts = explode('.',$domain);
+
+ if ($localLen < 1 || $localLen > 64) {
+ // local part length exceeded
+ $isValid = false;
+ } else if ($domainLen < 1 || $domainLen > 255) {
+ // domain part length exceeded
+ $isValid = false;
+ } else if ($local[0] == '.' || $local[$localLen-1] == '.') {
+ // local part starts or ends with '.'
+ $isValid = false;
+ } else if ($domain[0] == '.' || $domain[$domainLen-1] == '.') {
+ // domain part starts or ends with '.'
+ $isValid = false;
+ } else if (preg_match('/\\.\\./', $local))
+ {
+ // local part has two consecutive dots
+ $isValid = false;
+ } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
+ // character not valid in domain part
+ $isValid = false;
+ } else if (preg_match('/\\.\\./', $domain)) {
+ // domain part has two consecutive dots
+ $isValid = false;
+ } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
+ // character not valid in local part unless
+ // local part is quoted
+ if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
+ $isValid = false;
+ }
+ } else if ( strlen($domain_parts[0]) < 1) {
+ // num chars in
+ $isValid = false;
+ } else if ( strlen($domain_parts[1]) < 1) {
+ $isValid = false;
+ }
+
+ #if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
+ # // domain not found in DNS
+ # $isValid = false;
+ #}
+
+ }
+ return $isValid;
+ }
+
+ function countRecipients() {
+ $r = sisplet_query("SELECT count(email)FROM srv_simple_mail_invitation WHERE ank_id='".$this->sid."' AND state='ok'");
+ list ($quota) = mysqli_fetch_row($r);
+ return (int)$quota;
+ }
+
+ function getRecipients() {
+ $result = array();
+ $sql_string = "SELECT smi.*, u.name, u.surname, u.email AS adminmail FROM srv_simple_mail_invitation AS smi LEFT JOIN users AS u ON smi.usr_id = u.id WHERE smi.ank_id='".$this->sid."' ORDER BY smi.send_time DESC";
+ $sql_query = sisplet_query($sql_string);
+ while ($row = mysqli_fetch_assoc($sql_query)) {
+ $result[] = $row;
+ }
+ return $result;
+ }
+}
diff --git a/admin/survey/classes/surveyEmails/class.SurveyUnsubscribe.php b/admin/survey/classes/surveyEmails/class.SurveyUnsubscribe.php
new file mode 100644
index 0000000..084cb9a
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/class.SurveyUnsubscribe.php
@@ -0,0 +1,268 @@
+<?php
+/**
+ * skrbi za odjavo posameznega uporabnik od prejemanja obvestil ankete
+ *
+ */
+class SurveyUnsubscribe {
+ private static $sid = null;
+ private static $unsubscribed = null;
+
+
+ function __construct($sid) {
+ self::$sid = $sid;
+ SurveyInfo::SurveyInit(self::$sid);
+ }
+
+ static function isUnsubscribedEmail($email) {
+
+ # če še nismo zakeširamo djavljene emaile za anketo
+ if (self::$unsubscribed == null && !is_array(self::$unsubscribed)) {
+ self::getUnsubscribedEmails();
+ }
+ if (is_array(self::$unsubscribed) && count(self::$unsubscribed) > 0 && $email != null && trim($email) != '') {
+ return isset(self::$unsubscribed[$email]);
+ }
+
+ return false;
+ }
+
+ static function getUnsubscribedEmails() {
+ # polovimo vse odjavljene e-maile in jih shranimo v array
+ # preverimo ali je uporabnik že odjavljen
+ $emails = array();
+ $u1s = "SELECT email FROM srv_survey_unsubscribe WHERE ank_id ='".self::$sid."'";
+ $u1q = sisplet_query($u1s);
+ while ($u1r = mysqli_fetch_assoc($u1q)) {
+ if (trim($u1r['email']) != '') {
+ $emails[$u1r['email']] = $u1r['email'];
+ }
+ }
+ # preverimo tabelo srv_invitations_recipients
+ $u2s = "SELECT email FROM srv_invitations_recipients WHERE ank_id ='".self::$sid."' AND unsubscribed = '1'";
+ if (count($emails) > 0 ) {
+ $emails_implode = implode('\', \'', $emails);
+ $u2s .= " AND email NOT IN ('".$emails_implode."')";
+ //$u2s.=" AND email NOT IN ('".implode('\',\'',$emails)."')";
+ }
+ $u2q = sisplet_query($u2s);
+ while ($u2r = mysqli_fetch_assoc($u2q)) {
+ if (trim($u2r['email']) != '') {
+ $emails[$u2r['email']] = $u2r['email'];
+ }
+ }
+
+ # polovimo še vse iz srv_user in users
+ $u3s = "SELECT user_id, email FROM srv_user WHERE ank_id ='".self::$sid."' AND unsubscribed = '1'";
+ $u3q = sisplet_query($u3s);
+ $cms_id = array();
+ while ($u3r = mysqli_fetch_assoc($u3q)) {
+ if (trim($u3r['email']) != '') {
+ $emails[$u3r['email']] = $u3r['email'];
+ } else {
+ #poiščemo še email v tabeli users (če gre za userja iz cms
+ if ((int)$u3r['user_id'] > 0) {
+ $cms_id[] = $u3r['user_id'];
+ }
+ }
+ }
+
+ if (count($cms_id) > 0) {
+ $u4s = "SELECT email FROM users WHERE id IN ('".implode("','",$cms_id)."')";
+ $u4q = sisplet_query($u4s);
+ while ($u4r = mysqli_fetch_assoc($u4q)) {
+ if (trim($u4r['email']) != '') {
+ $emails[$u4r['email']] = $u4r['email'];
+ }
+ }
+ }
+
+ self::$unsubscribed = $emails;
+ }
+
+ function generateCodeForEmail($email) {
+
+ #preverimo ali email že obstaja za to anketo
+ $used_codes = array();
+ $sql_string = "SELECT code FROM srv_survey_unsubscribe_codes WHERE ank_id = '".self::$sid."' AND email='".$email."'";
+ $sql_query = sisplet_query($sql_string);
+ if (mysqli_num_rows($sql_query) > 0) {
+ $sql_row = mysqli_fetch_assoc($sql_query);
+ return $sql_row['code'];
+ }
+
+
+ #polovimo katere kode smo že uporabili za to anketo
+ $used_codes = array();
+ $sql_string = "SELECT code FROM srv_survey_unsubscribe_codes WHERE ank_id = '".self::$sid."'";
+ $sql_query = sisplet_query($sql_string);
+ while ($sql_row = mysqli_fetch_assoc($sql_query)) {
+ $used_codes[$sql_row['code']] = $sql_row['code'];
+ }
+ # zgeneriramo kodo za upoirabika
+ # Izberemo random hash, ki se ni v bazi
+ do {
+ list($code,$cookie) = self::generateCode();
+ } while (in_array($cookie,$used_codes) && !is_numeric($cookie));
+
+ #vstavimo v tabelo srv_survey_unsubscribe_codes
+ $sql_insert = "INSERT INTO srv_survey_unsubscribe_codes (ank_id, email, code) VALUES ( '".self::$sid."', '".$email."', '".$cookie."') ";
+ $sqlQuery = sisplet_query($sql_insert);
+
+ return $cookie;
+ }
+
+ function generateCode() {
+ $cookie = md5(mt_rand(1, mt_getrandmax()) . '@' . $_SERVER['REMOTE_ADDR']);
+
+ return array(substr($cookie,0,6), $cookie);
+ }
+
+ function doUnsubscribe() {
+ global $lang;
+
+ $anketa = self::$sid;
+
+ $db_table = (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) ? '_active' : '';
+
+ $lang_id = (int)$_GET['language'];
+ if ($lang_id != null) $_lang = '_'.$lang_id; else $_lang = '';
+ SurveySetting::getInstance()->init($anketa);
+ $user_bye_textA = SurveySetting::getInstance()->getSurveyMiscSetting('srvlang_user_bye_textA'.$_lang);
+ if ($user_bye_textA == '') $user_bye_textA = $lang['user_bye_textA'];
+
+ if (isset($_GET['uc']) && trim($_GET['uc']) != '' && isset($_GET['em']) && trim($_GET['em']) != '') {
+ # imamo userja iz cms, email smo poslali kodirano
+ #dodamo ga v tabelo: srv_survey_unsubscribe
+ $uc = trim($_GET['uc']);
+ $em = base64_decode($_GET['em']);
+ # preverimo obstoj in pravilnost emaila in kode v bazi
+
+ $s = "SELECT * FROM srv_survey_unsubscribe_codes WHERE ank_id='".self::$sid."' AND email='".$em."' AND code='".$uc."'";
+ $q = sisplet_query($s);
+ if (mysqli_num_rows($q) > 0) {
+ # zapis je v bazi uporabnika lahko odjavimo
+ $si = "INSERT INTO srv_survey_unsubscribe (ank_id, email, unsubscribe_time) VALUES ('".self::$sid."','".$em."',now())";
+ $qi = $s = sisplet_query($si);
+
+ echo $user_bye_textA;
+ }
+ else {
+ # zapisa ni v bazi obvestimo uporabnika o napačni kodi
+ echo 'Koda je napačna! Ne moremo vas odjaviti od prejemanja obvestil!';
+ }
+
+ exit();
+ }
+ else if ( isset($_GET['email']) && trim($_GET['email']) != '' &&
+ isset($_GET['uid']) && (int)trim($_GET['uid']) > 0) {
+
+ $uid = (int)trim($_GET['uid']);
+ $email = trim($_GET['email']);
+ #poiščemo userja
+ #poiščemo id spremenljivke z emailom
+ $ssp = "SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' AND variable = 'email' and sistem ='1'";
+ $qsp = sisplet_query($ssp);
+ $rsp = mysqli_fetch_assoc($qsp);
+ $spid = $rsp['id'];
+
+ #poiščemo email uporabnika
+ if ((int)$spid > 0 && (int) $uid > 0) {
+ $se = "SELECT count(*) from srv_data_text".$db_table." WHERE spr_id = '$spid' AND usr_id = '$uid' AND text ='$email'";
+ $qe = sisplet_query($se);
+ list($count) = mysqli_fetch_row($qe);
+ }
+
+ # če ustreza email in uid, ga odjavimo
+ if ((int)$count > 0) {
+ if ($email != null && trim($email) != '') {
+ $si = "INSERT INTO srv_survey_unsubscribe (ank_id, email, unsubscribe_time) VALUES ('$anketa','$email',now())";
+ $qi = $s = sisplet_query($si);
+ }
+ $s = sisplet_query("UPDATE srv_user SET unsubscribed='1' WHERE id='$uid' AND ank_id='$anketa'");
+ if ($s) {
+ echo $user_bye_textA;
+ } else {
+ //echo mysqli_error($GLOBALS['connect_db']);
+ echo 'error';
+ }
+ } else {
+ echo 'V bazi ni podaanega emaila.';
+ }
+
+ }
+ else {
+ $code = strtolower( $_GET['code'] );
+ $msgOutputed = false;
+ if (trim($code) != '' && trim($anketa) != '' && (int)$anketa > 0) {
+ # id uporabnika v tabeli srv_user
+ $su = "SELECT id FROM srv_user WHERE pass='$code' AND ank_id='$anketa'";
+ $qu = sisplet_query($su);
+ $ru = mysqli_fetch_assoc($qu);
+ $uid = $ru['id'];
+
+ #poiščemo id spremenljivke z emailom
+ $ssp = "SELECT s.id FROM srv_spremenljivka s, srv_grupa g WHERE s.gru_id=g.id AND g.ank_id='$anketa' AND variable = 'email' and sistem ='1'";
+ $qsp = sisplet_query($ssp);
+ $rsp = mysqli_fetch_assoc($qsp);
+ $spid = $rsp['id'];
+
+ #poiščemo email uporabnika
+ if ((int)$spid > 0 && (int) $uid > 0) {
+ $se = "SELECT text as email from srv_data_text".$db_table." WHERE spr_id = '$spid' AND usr_id = '$uid'";
+ $qe = sisplet_query($se);
+ $re = mysqli_fetch_assoc($qe);
+ $email = $re['email'];
+ }
+
+ if ($email != null && trim($email) != '') {
+ $si = "INSERT INTO srv_survey_unsubscribe (ank_id, email, unsubscribe_time) VALUES ('$anketa','$email',now())";
+ $qi = $s = sisplet_query($si);
+ }
+
+ # preverimo ali obstaja koda za nov način pošiljanja sporočil
+ $sqlString = "SELECT id, email FROM srv_invitations_recipients WHERE ank_id='$anketa' AND password ='$code' AND unsubscribed='0'";
+ $sql_query = sisplet_query($sqlString);
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ $row = mysqli_fetch_assoc($sql_query);
+ if (trim($row['email']) != '') {
+ // KAJ TO DELA TUKAJ??
+ //$sqlG = sisplet_query("INSERT INTO srv_glasovanje (ank_id, spr_id) VALUES ('$anketa', '$spr_id')");
+ $si = "INSERT INTO srv_survey_unsubscribe (ank_id, email, unsubscribe_time) VALUES ('$anketa','$row[email]',now())";
+ $qi = $s = sisplet_query($si);
+ }
+ $s = sisplet_query("UPDATE srv_invitations_recipients SET unsubscribed='1', date_unsubscribed=NOW() WHERE password='$code' AND ank_id='$anketa'");
+ sisplet_query("COMMIT");
+ if ($s) {
+ echo $user_bye_textA;
+ $msgOutputed = true;
+ } else {
+ //echo mysqli_error($GLOBALS['connect_db']);
+ echo 'error1';
+ }
+
+ } else {
+ # preverimo ali je že predhodno odjavljen
+ $sqlString = "SELECT id FROM srv_invitations_recipients WHERE ank_id='$anketa' AND password ='$code' AND unsubscribed='1'";
+ $sql_query = sisplet_query($sqlString);
+ if (mysqli_num_rows($sql_query) > 0 ) {
+ echo $lang['user_bye_textC'];
+ $msgOutputed = true;
+ } else {
+ #userja z kodo ni v bazi
+ }
+ }
+
+ $s = sisplet_query("UPDATE srv_user SET unsubscribed='1' WHERE (pass='$code' OR SUBSTRING(cookie,1,6) ='$code') AND ank_id='$anketa'");
+ if ($s) {
+ #tekst je bil poslan že zgoraj!
+ if ($msgOutputed == false) {
+ echo $user_bye_textA;
+ }
+ } else {
+ //echo mysqli_error($GLOBALS['connect_db']);
+ echo 'error';
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyEmails/squalo/api_test.php b/admin/survey/classes/surveyEmails/squalo/api_test.php
new file mode 100644
index 0000000..03ce3e5
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/squalo/api_test.php
@@ -0,0 +1,97 @@
+<?php
+/**
+ *
+ * Skripta za testiranje Squalo API-ja
+ *
+**/
+
+
+ini_set('display_errors', 1);
+ini_set('display_startup_errors', 1);
+error_reporting(E_ALL);
+
+include_once '../../../definition.php';
+include_once '../../../../../function.php';
+include_once '../../../../../vendor/autoload.php';
+
+
+
+//$squalo = new SqualoApi();
+
+//$result = $squalo->createList($list_name='Testni seznam Xyz');
+
+/*$result = $squalo->createNewsletter(
+ $list_id = '11',
+ $subject = 'Testek',
+ $body = 'Testno sporočilo...',
+ $body_alt = 'Testno sporočilo ALT...',
+ $from_email = 'peter.hrvatin@gmail.com',
+ $from_name = 'Peter',
+ $reply_to_email = 'peter.hrvatin@gmail.com',
+ $language = 'sl'
+);*/
+
+//$result = $squalo->addRecipient($email='peter.h1203@gmail.com', $list_id='5');
+
+//$result = $squalo->sendEmails($newsletter_id='24');
+
+//$result = $squalo->deleteRecipient($recipient_id='2');
+
+
+
+
+$squalo = new SurveyInvitationsSqualo($ank_id='10');
+
+
+// Ustvarimo testni seznam z respondenti
+/*$list_name = 'List test 1';
+$recipients = array(
+ array(
+ 'email' => 'peter.hrvatin@gmail.com',
+ 'custom_attributes' => array(
+ 'firstname' => 'Peterx',
+ 'lastname' => 'Hrvax',
+ 'url' => 'www.google.si'
+ )
+ ),
+ array(
+ 'email' => 'peter.h1203@gmail.com',
+ 'custom_attributes' => array(
+ 'firstname' => 'Peter12',
+ 'lastname' => 'Hrva12',
+ 'url' => 'www.najdi.si'
+ )
+ ),
+ array(
+ 'email' => 'peter.hrvatin@siol.net',
+ 'custom_attributes' => array(
+ 'firstname' => 'Petersiol',
+ 'lastname' => 'Hrvaxsiol',
+ 'url' => 'www.1ka.si'
+ )
+ )
+);
+
+$result = $squalo->createList($list_name, $recipients);*/
+
+
+// Ustvarimo mail in posljemo
+/*$list_id = '11';
+
+$subject = 'Testni subject';
+$body = 'Sporočilo v emailu... Še nekaj atributov url: #URL#, ime: #FIRSTNAME#';
+
+$from_email = 'peter.hrvatin@gmail.com';
+$from_name = 'Peter Gmail';
+$reply_to_email = 'peter.hrvatin@gmail.com';
+
+$result = $squalo->sendEmail($subject, $body, $list_id, $from_email, $from_name, $reply_to_email);*/
+
+
+
+
+echo '<pre>'; print_r($result); echo '</pre>';
+
+
+
+ \ No newline at end of file
diff --git a/admin/survey/classes/surveyEmails/squalo/class.SqualoApi.php b/admin/survey/classes/surveyEmails/squalo/class.SqualoApi.php
new file mode 100644
index 0000000..4b01a7f
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/squalo/class.SqualoApi.php
@@ -0,0 +1,298 @@
+<?php
+
+/**
+ *
+ * Class ki vsebuje funkcije Squalo APIJA (dodajanje prejemnikov, posiljanje...)
+ *
+ */
+
+class SqualoApi {
+
+ // Squalo api url
+ var $api_url = 'https://api.squalomail.com/v1/';
+
+
+ public function __construct(){
+
+ }
+
+
+ private function executeCall($action, $method, $data){
+ global $squalo_user;
+ global $squalo_key;
+
+ // Add credentials
+ $data['apiUser'] = $squalo_user;
+ $data['apiKey'] = $squalo_key;
+
+ // GET call - set url params
+ if($method == 'GET'){
+ $response = $this->executeGET($action, $data);
+ }
+ // POST call
+ else{
+ $response = $this->executePOST($action, $data);
+ }
+
+ // Decode json response
+ $response_array = json_decode($response, true);
+
+ // Zalogiramo kaj se je dogajalo
+ $SL = new SurveyLog();
+
+ // Error
+ if($response_array['errorCode'] != '0'){
+ $result['error'] = $response_array["errorMessage"]. ' (code '.$response_array["errorCode"].')';
+ $result['success'] = false;
+
+ $SL->addMessage(SurveyLog::MAILER, "NAPAKA pri SQUALO API klicu ('.$action.')! ".$result['error']);
+ }
+ else{
+ $result = $response_array;
+ $result['success'] = true;
+
+ $SL->addMessage(SurveyLog::MAILER, "USPEŠEN SQUALO API klic ('.$action.').");
+ }
+
+ $SL->write();
+
+ return $result;
+ }
+
+ // Izvedemo post klic
+ private function executePOST($action, $data){
+
+ // Nastavimo url
+ $url = $this->api_url.$action;
+
+
+ // Init curl
+ $ch = curl_init($url);
+
+ // JSON string za POST
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ // for debug only!
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+
+ $headers = array(
+ "Content-Type: application/json",
+ );
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+
+
+ // Izvedemo klic
+ $response = curl_exec($ch);
+ curl_close($ch);
+
+
+ return $response;
+ }
+
+ // Izvedemo get klic
+ private function executeGET($action, $data){
+
+ // GET params
+ $params = '?';
+ foreach($data as $name => $value){
+ $params .= $name.'='.$value.'&';
+ }
+ $params = substr($params, 0, -1);
+
+ // Nastavimo celoten url s parametri
+ $url = $this->api_url.$action.$params;
+
+
+ // Init curl
+ $ch = curl_init($url);
+
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+
+ // Izvedemo klic
+ $response = curl_exec($ch);
+
+ return $response;
+ }
+
+
+ /*
+ Ustvarimo seznam uporabnikov za pošiljanje
+ create-list
+
+ "name":"String content",
+ "description":"String content",
+ "listTag":"String content",
+ "color":"String content",
+ "ordering":2147483647,
+ "published":true
+
+ {subtag:name}
+ {subtag:code}
+ {subtag:url}
+
+ {date:4}
+
+ {unsubscribe}{/unsubscribe}
+ */
+ public function createList($list_name){
+
+ $action = 'create-list';
+ $method = 'POST';
+
+ $data = array(
+ 'name' => $list_name,
+ 'ordering' => $list_number,
+ 'published' => true
+ );
+
+ $response = $this->executeCall($action, $method, $data);
+
+ $list_id = ($response['success']) ? $response['list']['id'] : '0';
+
+ return $list_id;
+ }
+
+ /*
+ Ustvarimo email,ki se bo poslal
+
+ "altBody":"String content",
+ "body":"String content",
+ "fromEmail":"String content",
+ "fromName":"String content",
+ "language":"String content",
+ "listIds":[2147483647],
+ "published":2147483647,
+ "replyToEmail":"String content",
+ "replyToName":"String content",
+ "subject":"String content",
+ "visible":true
+ */
+ public function createNewsletter($list_id, $subject, $body, $body_alt, $from_email, $from_name, $reply_to_email, $language){
+
+ $action = 'create-newsletter';
+ $method = 'POST';
+
+ $data = array(
+ 'listIds' => array($list_id),
+ 'subject' => $subject,
+ 'body' => $body,
+ 'altBody' => $body_alt,
+ 'fromEmail' => $from_email,
+ 'fromName' => $from_name,
+ 'replyToEmail' => $reply_to_email,
+ 'language' => $language,
+ 'visible' => true
+ );
+
+ $response = $this->executeCall($action, $method, $data);
+
+ $newsletter_id = ($response['success']) ? $response['newsletter']['id'] : '0';
+
+ return $newsletter_id;
+ }
+
+ /*
+ Dodamo prejemnika
+
+ "accept": true,
+ "confirmed": true,
+ "customAttributes": [{
+ "name": "firstname",
+ "value": "John"
+ },
+ {
+ "name": "lastname",
+ "value": "Smith"
+ }
+ ],
+ "email": "String content",
+ "enabled": true,
+ "html": true,
+ "listIds": [2147483647],
+ "name": "String content",
+ "surname": "String content",
+ "gender": "null | male | female | other",
+ "gdprCanSend": true,
+ "gdprCanTrack": true
+ */
+ public function addRecipient($email, $list_id, $custom_attributes=array()){
+
+ $action = 'create-recipient';
+ $method = 'POST';
+
+ // Pretvorimo atribute po meri v pravo obliko
+ $custom_attributes_squalo = array();
+ $i = 0;
+ foreach($custom_attributes as $key => $value){
+
+ $custom_attributes_squalo[$i] = array(
+ "name" => $key,
+ "value" => $value
+ );
+
+ $i++;
+ }
+
+ $data = array(
+ 'email' => $email,
+ 'listIds' => array($list_id),
+ 'accept' => true,
+ 'confirmed' => true,
+ 'enabled' => true,
+ 'gdprCanSend' => true,
+ 'gdprCanTrack' => true,
+ 'customAttributes' => $custom_attributes_squalo
+ );
+
+ $response = $this->executeCall($action, $method, $data);
+
+ $recipient_id = ($response['success']) ? $response['recipient']['id'] : '0';
+
+ return $recipient_id;
+ }
+
+ /*
+ Pošljemo emaile
+
+ "newsletterId":2147483647,
+ "sendDate":2147483647
+ */
+ public function sendEmails($newsletter_id){
+
+ $action = 'send-newsletter';
+ $method = 'GET';
+
+ $data = array(
+ 'newsletterId' => $newsletter_id,
+ 'sendDate' => time()+30
+ );
+
+ $response = $this->executeCall($action, $method, $data);
+
+ return $response;
+ }
+
+
+ // Pobrisemo prejemnika
+ public function deleteRecipient($recipient_id){
+
+ $action = 'delete-recipient';
+ $method = 'GET';
+
+ $data = array(
+ 'recipientId' => $recipient_id
+ );
+
+ $response = $this->executeCall($action, $method, $data);
+
+ return $response;
+ }
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/surveyEmails/squalo/class.SurveyInvitationsSqualo.php b/admin/survey/classes/surveyEmails/squalo/class.SurveyInvitationsSqualo.php
new file mode 100644
index 0000000..77e3a2c
--- /dev/null
+++ b/admin/survey/classes/surveyEmails/squalo/class.SurveyInvitationsSqualo.php
@@ -0,0 +1,480 @@
+<?php
+
+/**
+ *
+ * Class ki vsebuje funkcije potrebne za posiljanje vabil preko SQUALO
+ *
+ */
+
+class SurveyInvitationsSqualo {
+
+ private $anketa;
+
+ private $squaloEnabled;
+ private $squaloActive;
+
+
+ public function __construct($anketa){
+
+ $this->anketa = $anketa;
+
+ // Preverimo ce je squalo omogocen na tej instalaciji in anketi
+ $this->squaloEnabled = $this->checkSqualoEnabled() ? true : false;
+
+ // Preverimo ce je squalo vklopljen na anketi
+ $this->squaloActive = $this->checkSqualoActive() ? true : false;
+ }
+
+
+ public function getSqualoEnabled(){
+ return $this->squaloEnabled;
+ }
+
+ public function getSqualoActive(){
+ return $this->squaloActive;
+ }
+
+ // Preverimo ce je squalo omogocen na instalaciji
+ private function checkSqualoEnabled(){
+ global $mysql_database_name;
+ global $admin_type;
+ global $squalo_user;
+ global $squalo_key;
+
+ // Zaenkrat imajo squalo samo admini
+ if($admin_type != 0)
+ return false;
+
+ // Squalo je omogocen samo na testu, www in virtualkah
+ if($mysql_database_name != 'www1kasi' && $mysql_database_name != 'test1kasi' && $mysql_database_name != 'real1kasi')
+ return false;
+
+ // Zaenkrat imajo squalo samo admini
+ if(!isset($squalo_user) || $squalo_user == '' || !isset($squalo_key) || $squalo_key == '')
+ return false;
+
+ return true;
+ }
+
+ // Preverimo ce je squalo vklopljen na anketi
+ private function checkSqualoActive(){
+
+ $vabila_type = SurveyInfo::getSurveyModules('email');
+
+ // Vklopljen squalo
+ if($vabila_type === '2'){
+ return true;
+ }
+
+ return false;
+ }
+
+
+ // Izvedemo squalo pošiljanje (ustvarimo seznam, newsletter, pošljemo maile)
+ public function sendSqualoInvitations($sql_recipients_query, $sending_data){
+ global $global_user_id;
+ global $site_url;
+
+
+ // Preverimo ce je vklopljen modul za volitve
+ $voting = SurveyInfo::getInstance()->checkSurveyModule('voting');
+
+ // Ce mamo SEO
+ $nice_url = SurveyInfo::getSurveyLink();
+
+ // Ali imamo individualizirana vabila s kodo
+ $surveySettings = SurveyInfo::getInstance()->getSurveyRow();
+ $individual = (int)$surveySettings['individual_invitation'];
+
+ # zakeširamo user_id za datapiping
+ $arryDataPiping = array();
+ $qryDataPiping = sisplet_query("SELECT id, inv_res_id FROM srv_user WHERE ank_id='$this->anketa' AND inv_res_id IS NOT NULL");
+ while (list($dpUid, $dpInvResId) = mysqli_fetch_row($qryDataPiping)) {
+
+ if ((int)$dpInvResId > 0 && (int)$dpUid > 0) {
+ $arryDataPiping[$dpInvResId] = (int)$dpUid;
+ }
+ }
+
+ $duplicated = array();
+
+ # array za rezultate
+ $send_ok = array();
+ $send_ok_ids = array();
+ $send_users_data = array();
+ $send_error = array();
+ $send_error_ids = array();
+
+ // Loop po prejemnikih
+ $recipients = array();
+ while ($sql_row = mysqli_fetch_assoc($sql_recipients_query)) {
+
+ $password = $sql_row['password'];
+
+ $email = $sql_row['email'];
+
+ // Preverimo ce je duplikat
+ if ($dont_send_duplicated == true && isset($duplicated[$email])) {
+ $duplicated[$email] ++;
+ continue;
+ }
+
+ $duplicated[$email] = 1;
+
+
+
+ if ( ($individual == 1 && trim($email) != '' && trim($password) != '') || ($individual == 0 && trim($email) != '') ){
+
+ // odvisno ali imamo url za jezik.
+ if ($sending_data['msg_url'] != null && trim($sending_data['msg_url']) != '' ) {
+ $url = $sending_data['msg_url'] . ($individual == 1 ? '?code='.$password : '');
+ }
+ else {
+ $url = $nice_url . ($individual == 1 ? '&code='.$password : '');
+ }
+
+ $url .= '&ai='.(int)$sending_data['arch_id'];
+
+ // odjava
+ $unsubscribe = $site_url . 'admin/survey/unsubscribe.php?anketa=' . $this->anketa . '&code='.$password;
+
+ $custom_attributes = array(
+ 'url' => '<a href="' . $url . '">' . $url . '</a>',
+ 'urllink' => $url,
+ 'firstname' => $sql_row['firstname'],
+ 'lastname' => $sql_row['lastname'],
+ //'email' => $sql_row['email'],
+ 'code' => $sql_row['password'],
+ 'password' => $sql_row['password'],
+ 'phone' => $sql_row['phone'],
+ 'custom' => $sql_row['custom'],
+ 'unsubscribe' => $unsubscribe,
+ );
+
+ $recipients[] = array(
+ 'email' => $sql_row['email'],
+ 'name' => $sql_row['firstname'],
+ 'surname' => $sql_row['lastname'],
+ 'custom_attributes' => $custom_attributes
+ );
+
+ $_user_data = $sql_row;
+ $send_users_data[] = $_user_data;
+
+ $send_emails[] = $email;
+ $send_ids[] = $sql_row['id'];
+ }
+ }
+
+ // Ustvarimo squalo seznam z respondenti
+ $list_name = $global_user_id.'_'.$this->anketa.'_'.$sending_data['arch_id'];
+
+ $list_id = $this->createList($list_name, $recipients);
+
+
+ // Ce so vsi prejemniki ok dodani na seznam, ustvarimo mail in posljemo
+ if($list_id != false)
+ $squalo_sending_result = $this->sendEmail($sending_data['subject_text'], $sending_data['body_text'], $list_id, $sending_data['from_email'], $sending_data['from_name'], $sending_data['reply_to_email']);
+
+
+ // Napaka pri squalo posiljanju oz. dodajanju - zabelezimo kot da ni noben ok poslan
+ if(!$squalo_sending_result || !$list_id){
+
+ $send_error = $send_emails;
+ $send_error_ids = $send_ids;
+
+ foreach($send_users_data as $key => $val){
+ $val['status'] = 2;
+ $send_users_data[$key] = $val;
+ }
+
+ $send_ok = array();
+ $send_ok_ids = array();
+
+ # updejtamo status za errorje
+ if (count($send_error_ids) > 0) {
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET last_status = GREATEST(last_status,2) WHERE id IN (".implode(',',$send_error_ids).") AND last_status IN ('0')");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+
+ $results = array(
+ 'send_ok' => $send_ok,
+ 'send_ok_ids' => $send_ok_ids,
+ 'send_users_data' => $send_users_data,
+ 'send_error' => $send_error,
+ 'send_error_ids' => $send_error_ids,
+ );
+
+ return $results;
+ }
+
+
+ // Ok squalo posiljanje - zabelezimo da so bili vsi ok poslani
+ $send_ok = $send_emails;
+ $send_ok_ids = $send_ids;
+
+ foreach($send_users_data as $key => $val){
+ $val['status'] = 1;
+ $send_users_data[$key] = $val;
+ }
+
+ $send_error = array();
+ $send_error_ids = array();
+
+ // updejtamo userja da mu je bilo poslano - SQUALO je vedno vse ok
+ if (count($send_ok_ids) > 0) {
+
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET sent='1', date_sent='".$sending_data['date_sent']."' WHERE id IN (".implode(',',$send_ok_ids).")");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // statuse popravimo samo če vabilo še ni bilo poslano ali je bila napaka
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients SET last_status='1' WHERE id IN (".implode(',',$send_ok_ids).") AND last_status IN ('0','2')");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+
+ // Pri volitvah za sabo pobrisemo podatke preko katerih bi lahko povezali prejemnike z responsi
+ if($voting){
+ $sqlQuery = sisplet_query("UPDATE srv_invitations_recipients
+ SET cookie='', password=''
+ WHERE id IN (".implode(',',$send_ok_ids).") AND sent='1' AND last_status='1' AND ank_id='".$this->anketa."'
+ ");
+ if (!$sqlQuery) {
+ $error = mysqli_error($GLOBALS['connect_db']);
+ }
+ }
+ }
+
+
+ // če mamo personalizirana email vabila, userje dodamo v bazo
+ if ($individual == 1) {
+
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $db_table = '_active';
+
+ $inv_variables_link = array('email'=>'email','geslo'=>'password','ime'=>'firstname','priimek'=>'lastname','naziv'=>'salutation','telefon'=>'phone','drugo'=>'custom','odnos'=>'relation','last_status'=>'last_status','sent'=>'sent','responded'=>'responded','unsubscribed'=>'unsubscribed');
+
+ $sys_vars = $this->getSystemVars();
+
+ foreach($send_users_data as $_user_data){
+
+ // dodamo še userja v srv_user da je kompatibilno s staro logiko
+ $strInsertDataText = array();
+ $strInsertDataVrednost = array();
+
+ // Pri volitvah zaradi anonimizacije ignoriramo vse identifikatorje
+ if($voting){
+ $_r = sisplet_query("INSERT INTO srv_user
+ (ank_id, cookie, pass, last_status, inv_res_id)
+ VALUES
+ ('".$this->anketa."', '".$_user_data['cookie']."', '".$_user_data['password']."', '".$_user_data['status']."', '-1') ON DUPLICATE KEY UPDATE cookie = '".$_user_data['cookie']."', pass='".$_user_data['password']."'
+ ");
+
+ // Ce ne belezimo parapodatka za cas responsa, anonimno zabelezimo cas zadnjega responsa
+ sisplet_query("UPDATE srv_anketa SET last_response_time=NOW() WHERE id='".$this->anketa."'");
+ }
+ else{
+ $_r = sisplet_query("INSERT INTO srv_user
+ (ank_id, email, cookie, pass, last_status, time_insert, inv_res_id)
+ VALUES
+ ('".$this->anketa."', '".$_user_data['email']."', '".$_user_data['cookie']."', '".$_user_data['password']."', '".$_user_data['status']."', NOW(), '".$_user_data['id']."') ON DUPLICATE KEY UPDATE cookie = '".$_user_data['cookie']."', pass='".$_user_data['password']."'
+ ");
+ }
+ $usr_id = mysqli_insert_id($GLOBALS['connect_db']);
+
+ if ($usr_id) {
+
+ // dodamo še srv_userbase in srv userstatus
+ sisplet_query("INSERT INTO srv_userbase (usr_id, tip, datetime, admin_id) VALUES ('".$usr_id."','0',NOW(),'".$global_user_id."')");
+ sisplet_query("INSERT INTO srv_userstatus (usr_id, tip, status, datetime) VALUES ('".$usr_id."', '0', '0', NOW())");
+
+
+
+ // dodamo še podatke za posameznega userja za sistemske spremenljivke
+ foreach ($sys_vars AS $sid => $spremenljivka) {
+
+ $_user_variable = $inv_variables_link[$spremenljivka['variable']];
+
+ if (trim($_user_data[$_user_variable]) != '' && $_user_data[$_user_variable] != null) {
+ if($spremenljivka['variable'] == 'odnos')
+ $strInsertDataVrednost[] = "('".$sid."','".$spremenljivka['vre_id'][trim($_user_data[$_user_variable])]."','".$usr_id."')";
+ else
+ $strInsertDataText[] = "('".$sid."','".$spremenljivka['vre_id']."','".trim($_user_data[$_user_variable])."','".$usr_id."')";
+ }
+ }
+ }
+
+ // Pri volitvah zaradi anonimizacije ne vsatvimo nicesar v sistemske spremenljivke
+ if(!$voting){
+
+ // vstavimo v srv_data_text
+ if (count($strInsertDataText) > 0) {
+ $strInsert = "INSERT INTO srv_data_text".$db_table." (spr_id, vre_id, text, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataText);
+ sisplet_query($strInsert);
+ }
+ // vstavimo v srv_data_vrednost
+ if (count($strInsertDataVrednost) > 0) {
+ $strInsert = "INSERT INTO srv_data_vrednost".$db_table." (spr_id, vre_id, usr_id) VALUES ";
+ $strInsert .= implode(',',$strInsertDataVrednost);
+ sisplet_query($strInsert);
+ }
+ }
+ }
+ }
+
+
+ $results = array(
+ 'send_ok' => $send_ok,
+ 'send_ok_ids' => $send_ok_ids,
+ 'send_users_data' => $send_users_data,
+ 'send_error' => $send_error,
+ 'send_error_ids' => $send_error_ids,
+ );
+
+ return $results;
+ }
+
+
+ // Ustvarimo nov seznam in nanj dodamo respondente
+ private function createList($list_name, $recipients){
+
+ $squalo_api = new SqualoApi();
+
+ // Ustvarimo prazen seznam
+ $list_id = $squalo_api->createList($list_name);
+
+ // Napaka pri ustvarjanju seznama
+ if($list_id == '0'){
+ echo 'Napaka pri ustvarjanju Squalo seznama.';
+ return false;
+ }
+
+ // Dodamo respondente na ta seznam
+ foreach($recipients as $recipient){
+
+ $email = $recipient['email'];
+
+ $custom_attributes = $recipient['custom_attributes'];
+
+ $recipient_id = $squalo_api->addRecipient($email, $list_id, $custom_attributes);
+
+ // Napaka pri ustvarjanju seznama
+ if($recipient_id == '0'){
+ echo 'Napaka pri dodajanju prejemnika '.$email.' na Squalo seznam.';
+ return false;
+ }
+ }
+
+ return $list_id;
+ }
+
+ // Ustvarimo nov email z vsebino (api klic createNewsletter) in posljemo na vse naslove v seznamu
+ private function sendEmail($subject, $body, $list_id, $from_email, $from_name, $reply_to_email){
+
+ $squalo_api = new SqualoApi();
+
+ // Zamenjamo datapiping npr. #URL# -> {subtag:url}...
+ $subject = self::squaloDatapiping($subject);
+ $body = self::squaloDatapiping($body);
+
+ $language = 'sl';
+
+ // Api klic za ustvarjanje emaila
+ $newsletter_id = $squalo_api->createNewsletter($list_id, $subject, $body, $body, $from_email, $from_name, $reply_to_email, $language='sl');
+
+ // Napaka pri ustvarjanju newsletterja
+ if($newsletter_id == '0'){
+ echo 'Napaka pri ustvarjanju Squalo newsletterja.';
+ return false;
+ }
+
+ // Api klic za posiljanje na naslove
+ $result = $squalo_api->sendEmails($newsletter_id);
+
+ // Napaka pri ustvarjanju newsletterja
+ if(!$result['success']){
+ echo 'Napaka pri pošiljanju emailov za Squalo newsletter '.$newsletter_id.'.';
+ return false;
+ }
+
+ return $result;
+ }
+
+
+ private static function squaloDatapiping($text){
+
+ $text_fixed = str_replace(
+ array(
+ '#URL#',
+ '#URLLINK#',
+ '#UNSUBSCRIBE#',
+ '#FIRSTNAME#',
+ '#LASTNAME#',
+ '#EMAIL#',
+ '#CODE#',
+ '#PASSWORD#',
+ '#PHONE#',
+ '#SALUTATION#',
+ '#CUSTOM#',
+ '#RELATION#',
+ ),
+ array(
+ '{subtag:url}',
+ '{subtag:urllink}',
+ '{subtag:unsubscribe}',
+ '{subtag:firstname}',
+ '{subtag:lastname}',
+ '{subtag:email}',
+ '{subtag:code}',
+ '{subtag:password}',
+ '{subtag:phone}',
+ '{subtag:salutation}',
+ '{subtag:custom}'
+ ),
+ $text
+ );
+
+ return $text_fixed;
+ }
+
+ private function getSystemVars(){
+
+ $inv_variables = array('email','password','ime','priimek','naziv','telefon','drugo','odnos');
+
+ // polovimo sistemske spremenljivke z vrednostmi
+ $qrySistemske = sisplet_query("SELECT s.id, s.naslov, s.variable
+ FROM srv_spremenljivka s, srv_grupa g
+ WHERE s.sistem='1' AND s.gru_id=g.id AND g.ank_id='".$this->anketa."' AND variable IN ("."'" . implode("','",$inv_variables)."')
+ ORDER BY g.vrstni_red, s.vrstni_red
+ ");
+ $sys_vars = array();
+ $sys_vars_ids = array();
+
+ while ($row = mysqli_fetch_assoc($qrySistemske)) {
+ $sys_vars[$row['id']] = array('id'=>$row['id'], 'variable'=>$row['variable'],'naslov'=>$row['naslov']);
+ $sys_vars_ids[] = $row['id'];
+ }
+
+ $sqlVrednost = sisplet_query("SELECT spr_id, id AS vre_id, vrstni_red, variable FROM srv_vrednost WHERE spr_id IN(".implode(',',$sys_vars_ids).") ORDER BY vrstni_red ASC ");
+ while ($row = mysqli_fetch_assoc($sqlVrednost)) {
+
+ // Ce gre za odnos imamo radio
+ if($sys_vars[$row['spr_id']]['variable'] == 'odnos'){
+
+ if(!isset($sys_vars[$row['spr_id']]['vre_id'][$row['vrstni_red']]))
+ $sys_vars[$row['spr_id']]['vre_id'][$row['variable']] = $row['vre_id'];
+ }
+ elseif (!isset($sys_vars[$row['spr_id']]['vre_id'])) {
+ $sys_vars[$row['spr_id']]['vre_id'] = $row['vre_id'];
+ }
+ }
+
+ return $sys_vars;
+ }
+} \ No newline at end of file
diff --git a/admin/survey/classes/tracking/CrossRoad.php b/admin/survey/classes/tracking/CrossRoad.php
new file mode 100644
index 0000000..cd8c2e4
--- /dev/null
+++ b/admin/survey/classes/tracking/CrossRoad.php
@@ -0,0 +1,251 @@
+<?php
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ * Description of CrossRoad
+ *
+ * @author podkrizniku
+ */
+
+class CrossRoad {
+ static function MainNavigation($anketa=null){
+ $status = -1;
+ # ajaxa se poslje skupaj z ajaxom, da ob updatu vemo kaksen 'a' je bil na originalni strani
+ # (drugace se ob updatu z ajaxom informacija o 'a'ju zgubi)
+ $get = $_GET['a'];
+ if (isset ($_GET['ajaxa']))
+ $get = $_GET['ajaxa'];
+ if (trim($get) == '') {
+ $get = A_BRANCHING;
+ }
+
+ //smo vezani na anketo
+ if($anketa != null && $anketa > 0){
+ switch ($get) {
+ # status
+ case A_REPORTI:
+ $first_action = NAVI_STATUS;
+ $second_action = NAVI_STATUS_OSNOVNI;
+ $status = 3;
+ break;
+ case A_NONRESPONSE_GRAPH:
+ case A_USABLE_RESP:
+ case A_KAKOVOST_RESP:
+ case A_SPEEDER_INDEX:
+ case A_TEXT_ANALYSIS:
+ case A_GEOIP_LOCATION:
+ case A_EDITS_ANALYSIS:
+ case A_REMINDER_TRACKING:
+ case A_UL_EVALVATION:
+ case A_PARA_GRAPH:
+ case 'langStatistic':
+ case 'AAPOR':
+ $first_action = NAVI_STATUS;
+ $second_action = NAVI_STATUS_OSNOVNI;
+ $status = 4;
+ break;
+
+ # urejanje
+ case A_BRANCHING:
+ case A_GLASOVANJE:
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_BRANCHING;
+ $status = 0;
+ break;
+
+ case A_TESTIRANJE:
+ $first_action = NAVI_TESTIRANJE;
+ $second_action = M_TESTIRANJE_DIAGNOSTIKA;
+ if ($_GET['m'] == M_TESTIRANJE_VNOSI) {
+ $second_action = NAVI_TESTIRANJE_VNOSI;
+ }
+ if ($_GET['m'] == M_TESTIRANJE_PREDVIDENI) {
+ $second_action = NAVI_TESTIRANJE_PREDVIDENI;
+ }
+ if ($_GET['m'] == M_TESTIRANJE_CAS) {
+ $second_action = NAVI_TESTIRANJE_CAS;
+ }
+ $status = 4;
+ break;
+
+ case A_KOMENTARJI:
+ case A_KOMENTARJI_ANKETA:
+ $first_action = NAVI_TESTIRANJE;
+ $second_action = NAVI_TESTIRANJE_KOMENTARJI;
+ $status = 0;
+ break;
+
+ case A_SETTINGS:
+ case A_OSNOVNI_PODATKI:
+ case A_FORMA:
+
+ case A_COOKIE:
+ case A_TRAJANJE:
+ case A_DOSTOP:
+ case A_MISSING:
+ case A_METADATA:
+ case A_MOBILESETTINGS:
+ case A_JEZIK: # nastavitve jezik
+ case A_UREJANJE: # nastavitve komentarjev
+ case A_PRIKAZ: # nastavitve komentarjev
+ case A_SKUPINE:
+ case A_EXPORTSETTINGS:
+ case A_GDPR:
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_ANKETA;
+ $status = 0;
+ break;
+
+ case A_TEMA: # nastavitve prevajanje
+ case 'theme-editor': # nastavitve prevajanje
+ case 'edit_css': # nastavitve prevajanje
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_TEMA;
+ $status = 0;
+ break;
+
+ case A_HIERARHIJA:
+ $first_action = NAVI_HIERARHIJA;
+ break;
+
+ case A_PREVAJANJE: # nastavitve prevajanje
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_PREVAJANJE;
+ $status = 0;
+ break;
+
+ case A_ALERT:
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_ANKETA;
+ $status = 0;
+ break;
+
+ case A_NAGOVORI:
+ case A_ARHIVI:
+ case A_TRACKING:
+ $first_action = NAVI_UREJANJE;
+ $status = 0;
+ break;
+
+ # objave, vabila
+ case A_VABILA:
+ $first_action = NAVI_OBJAVA;
+ $status = 5;
+ break;
+
+ case A_EMAIL:
+ $first_action = NAVI_OBJAVA;
+ $second_action = NAVI_OBJAVA;
+ $status = 5;
+ break;
+
+ case 'invitations':
+ $first_action = NAVI_OBJAVA;
+ $second_action = 'invitations';
+ $status = 5;
+ break;
+
+ # analize, podatki
+ case A_ANALYSIS:
+ $first_action = NAVI_ANALYSIS;
+
+ $second_action = NAVI_STATISTIC_ANALYSIS;
+ if ($_GET['m'] == M_ANALYSIS_LINKS) {
+ $second_action = NAVI_ANALYSIS_LINKS;
+ }
+ $status = 2;
+ break;
+
+ case A_COLLECT_DATA:
+ $first_action = NAVI_RESULTS;
+ $second_action = NAVI_DATA;
+ $status = 4;
+ break;
+
+ #izvozi
+ case A_COLLECT_DATA_EXPORT:
+ $first_action = NAVI_RESULTS;
+ $second_action = NAVI_DATA_EXPORT;
+ $status = 4;
+ if ($_GET['m'] == A_COLLECT_DATA_EXPORT_ALL) {
+ $first_action = NAVI_RESULTS;
+ $second_action = NAVI_ANALYSIS_LINKS;
+ $status = 2;
+ }
+ break;
+
+ # dodatne nastavitve
+ case A_ADVANCED:
+ case A_UPORABNOST:
+ case A_HIERARHIJA_SUPERADMIN:
+ case A_KVIZ:
+ case A_VOTING:
+ case A_ADVANCED_PARADATA:
+ case A_JSON_SURVEY_EXPORT:
+ case A_VNOS:
+ case A_SOCIAL_NETWORK:
+ case A_CHAT:
+ case A_PANEL:
+ case A_SLIDESHOW:
+ case A_360:
+ case A_360_1KA:
+ case A_MAZA:
+ case A_WPN:
+ case 'evoli':
+ case 'evoli_teammeter':
+ case 'evoli_quality_climate':
+ case 'evoli_teamship_meter':
+ case 'evoli_organizational_employeeship_meter':
+ case 'evoli_employmeter':
+ case 'mfdps':
+ case 'borza':
+ case 'mju':
+ case 'excell_matrix':
+ case 'fieldwork':
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_ANKETA;
+ $status = 0;
+ break;
+
+ case A_TELEPHONE:
+ case A_PHONE:
+ case T_PHONE:
+ $first_action = NAVI_UREJANJE;
+ $second_action = NAVI_UREJANJE_ANKETA;
+ $status = 5;
+ break;
+
+ case A_LANGUAGE_TECHNOLOGY:
+ $first_action = NAVI_TESTIRANJE;
+ $second_action = NAVI_TESTIRANJE_LANGUAGE_TECHNOLOGY;
+ $status = 4;
+ break;
+
+ case A_LANGUAGE_TECHNOLOGY_OLD:
+ $first_action = NAVI_TESTIRANJE;
+ $second_action = NAVI_TESTIRANJE_LANGUAGE_TECHNOLOGY_OLD;
+ $status = 4;
+ break;
+
+ default:
+ break;
+ }
+
+ //shrani tracking
+ TrackingClass::update($anketa, $status);
+ //vrni podatke o navigaciji nazaj v SurveyAdmin
+ return array('first_action' => $first_action, 'second_action' => $second_action);
+ }
+ //nismo vezani na anketo, tracking uporabnika
+ else{
+ TrackingClass::update_user();
+ }
+
+
+ }
+}
diff --git a/admin/survey/classes/tracking/TrackingClass.php b/admin/survey/classes/tracking/TrackingClass.php
new file mode 100644
index 0000000..f635d4f
--- /dev/null
+++ b/admin/survey/classes/tracking/TrackingClass.php
@@ -0,0 +1,420 @@
+<?php
+
+/***************************************
+ * Description:
+ * Autor: Robert Šmalc
+ * Created date: 02.02.2017
+ *****************************************/
+class TrackingClass
+{
+ private $sub;
+ private $anketa;
+ private $status = '';
+
+ private $db_table = "";
+
+ public function __construct($anketa = null)
+ {
+ if ((isset ($_REQUEST['anketa']) && $_REQUEST['anketa'] > 0) || (isset ($anketa) && $anketa > 0)) {
+ $this->anketa = (isset ($_REQUEST['anketa']) && $_REQUEST['anketa'] > 0) ? $_REQUEST['anketa'] : $anketa;
+ } else {
+ return 'Anketa ID ne obstaja';
+ }
+
+ # poiščemo aktivno anketo
+ SurveyInfo :: getInstance()->SurveyInit($this->anketa);
+ if (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1)
+ $this->db_table = '_active';
+
+ if ($_GET['m'] == 'tracking_data')
+ $this->sub = 'data';
+ elseif ($_GET['appendMerge'] == '1')
+ $this->sub = 'append';
+ else
+ $this->sub = 'survey';
+
+ // Filter po statusu
+ if (isset($_GET['status']) && in_array($_GET['status'], array('0', '1', '2', '3', '4', '5', '6')))
+ $this->status = " AND status = '{$_GET[status]}' ";
+
+
+ return $this;
+ }
+
+ private static $_instance;
+
+ /**
+ * V kolikor razred kličemo statično
+ *
+ * @return instance
+ */
+
+ public static function init()
+ {
+ if (!static::$_instance)
+ static::$_instance = new TrackingClass();
+
+ return static::$_instance;
+ }
+
+ /**
+ * Filter po statusih
+ * Filter omogoča, da se prvi parameter ne upošteva statusa, v koliko ni filtra upošteva vse statuse.
+ * Drugi parameter naredi inverzno operacijo - išče samo po tem statusu
+ * 0 => urejanje
+ * 1 => uvoz podatkov
+ * 2 => analiza
+ * 3 => reporti
+ * 4 => podatki
+ * 5 => objava - vabila
+ * 6 => hierarhija
+ * 20 => hierarhija - splošno
+ * 21 => hierarhija - gradnja strukture
+ * 22 => hierarhija - uporabniki
+ *
+ * @param (int or array) $exclude_status
+ * @param (boolean) $invert_status
+ * @return $this
+ */
+ public function filter($exclude_status = null, $invert_status = false)
+ {
+ $opcija = '!';
+ if ($invert_status)
+ $opcija = '';
+
+
+ if (!is_null($exclude_status) && is_int($exclude_status)) {
+ $this->status = " AND status " . $opcija . "= '" . $exclude_status . "' ";
+ } elseif (!is_null($exclude_status) && is_array($exclude_status)) {
+
+ if (!empty($opcija)) {
+ $this->status = " AND status NOT IN (" . implode(',', $exclude_status) . ")";
+ } else {
+ $this->status = " AND status IN (" . implode(',', $exclude_status) . ")";
+ }
+
+
+ }
+
+ return $this;
+ }
+
+
+ /**
+ * @desc prikaze tracking sprememb
+ * status:
+ * -1 => unknown
+ * 0 => urejanje
+ * 1 => uvoz podatkov
+ * 2 => analiza
+ * 3 => reporti
+ * 4 => podatki
+ * 5 => objava - vabila
+ * 20 => hierarhija - splošno
+ * 21 => hierarhija - gradnja strukture
+ * 22 => hierarhija - uporabniki
+ */
+ public function trackingDisplay()
+ {
+ global $lang;
+
+ echo '<fieldset>';
+ echo '<legend>' . $lang['srv_survey_archives_tracking_' . $this->sub] . '</legend>';
+
+ // Izvoz v Excel
+ echo '<p><a href="index.php?anketa=' . $this->anketa . '&a=' . $_GET['a'] . '&d=download">Download Excel</a></p>';
+
+
+ echo '<table id="tracking">';
+
+ // Tabela s podatki o spremembah podatkov
+ if ($this->sub == 'data') {
+
+ // Filter po podatkih
+ $data = ' AND (`get` LIKE \'%edit_data%\'
+ OR (`get` LIKE \'%a: "data", m: "quick_edit"%\' AND `get` LIKE \'%post: "1"%\')
+ OR (`get` LIKE \'%a: "dataCopyRow"%\')
+ OR (`get` LIKE \'%a: "dataDeleteMultipleRow"%\')
+ OR (`get` LIKE \'%a: "dataDeleteRow"%\')
+ OR (`get` LIKE \'%urejanje: "1"%\' AND status=\'4\')
+ )';
+
+ // Prva vrstica
+ echo '<tr>';
+ echo ' <th>' . $lang['date'] . '</th>';
+ echo ' <th>User</th>';
+ echo ' <th class="center">IP</th>';
+ echo ' <th class="center">Recnum</th>';
+ echo ' <th>GET</th>';
+ echo ' <th>POST</th>';
+ echo '</tr>';
+
+ // Vrstice s podatki
+ $sql = sisplet_query("SELECT * FROM srv_tracking".$this->db_table." WHERE ank_id = '$this->anketa' " . $appendMerge . " " . $data . " ORDER BY datetime DESC");
+ while ($row = mysqli_fetch_array($sql)) {
+ echo '<tr>';
+
+ $sqlu = sisplet_query("SELECT name, surname FROM users WHERE id = '$row[user]'");
+ $rowu = mysqli_fetch_array($sqlu);
+
+ // Pri podatkih dobimo posebej podatke o editiranem respondentu
+ $usr_id = '';
+ $cookie = '';
+
+ // Preverimo ce imamo usr_id v GET-u
+ $get_array_temp = explode(', ', $row['get']);
+ foreach ($get_array_temp AS $get_val) {
+ $param = explode(': ', $get_val);
+ $get_array[$param[0]] = $param[1];
+ }
+
+ if (isset($get_array['usr_id']) && $get_array['usr_id'] != '') {
+ $usr_id = trim($get_array['usr_id'], '"');
+ } // Preverimo ce iammo slucajno cookie
+ elseif (isset($get_array['survey-' . $this->anketa]) && $get_array['survey-' . $this->anketa] != '') {
+ $cookie = trim($get_array['survey-' . $this->anketa], '"');
+ } else {
+ // Preverimo ce imamo usr_id v POST-u
+ $post_array_temp = explode(', ', $row['post']);
+ foreach ($post_array_temp AS $post_val) {
+ $param = explode(': ', $post_val);
+ $post_array[$param[0]] = $param[1];
+ }
+
+ if (isset($post_array['usr_id']) && $post_array['usr_id'] != '')
+ $usr_id = trim($post_array['usr_id'], '"');
+ }
+
+ if ($usr_id != '') {
+ $sqlR = sisplet_query("SELECT recnum FROM srv_user WHERE id = '$usr_id'");
+ $rowR = mysqli_fetch_array($sqlR);
+
+ $recnum = $rowR['recnum'];
+ } elseif ($cookie != '') {
+ $sqlR = sisplet_query("SELECT recnum FROM srv_user WHERE cookie = '$cookie'");
+ $rowR = mysqli_fetch_array($sqlR);
+
+ $recnum = $rowR['recnum'];
+ } else
+ $recnum = 0;
+
+ echo ' <td>' . datetime($row['datetime']) . '</td>';
+ echo ' <td>' . $rowu['name'] . ' ' . $rowu['surname'] . '</td>';
+ echo ' <td class="center">' . $row['ip'] . '</td>';
+ echo ' <td class="center">' . $recnum . '</td>';
+ echo ' <td>' . $row['get'] . '</td>';
+ echo ' <td>' . $row['post'] . '</td>';
+
+ echo '</tr>';
+ }
+ } // Tabela s podatki o spremembah - vse oz. merge/append
+ else {
+
+ // Legenda statusov
+ $statuses = array(
+ -1 => $lang['srv_unknown'],
+ 0 => $lang['srv_urejanje'],
+ 1 => $lang['import_data'],
+ 2 => $lang['export_analisys'],
+ 3 => $lang['srv_reporti'],
+ 4 => $lang['srv_podatki'],
+ 5 => $lang['srv_inv_nav_email'],
+ 20 => $lang['srv_hierarchy'], // Splošni podatki o hierarhiji
+ 21 => $lang['srv_hierarchy_structure'], // Grajenje hierarhije
+ 22 => $lang['srv_hierarchy_users'], // Urejanje uporabnikov
+ );
+
+
+ // Filter za uvoze
+ if ($this->sub == 'append')
+ $appendMerge = " AND (`get` LIKE '%appendMerge%' OR status='1') ";
+ else
+ $appendMerge = "";
+
+ // Prva vrstica
+ echo '<tr>';
+ echo ' <th>' . $lang['date'] . '</th>';
+ echo ' <th>User</th>';
+ echo ' <th class="center">IP</th>';
+ echo ' <th class="center">Podstran</th>';
+ echo ' <th>GET</th>';
+ echo ' <th>POST</th>';
+ echo '</tr>';
+
+ // Vrstice s podatki
+ $sql = sisplet_query("SELECT * FROM srv_tracking".$this->db_table." WHERE ank_id = '$this->anketa' " . $this->status . " " . $appendMerge . " " . $data . " ORDER BY datetime DESC");
+ while ($row = mysqli_fetch_array($sql)) {
+ echo '<tr>';
+
+ $sqlu = sisplet_query("SELECT name, surname FROM users WHERE id = '$row[user]'");
+ $rowu = mysqli_fetch_array($sqlu);
+
+ echo ' <td>' . datetime($row['datetime']) . '</td>';
+ echo ' <td>' . $rowu['name'] . ' ' . $rowu['surname'] . '</td>';
+ echo ' <td class="center">' . $row['ip'] . '</td>';
+ echo ' <td class="center">' . $statuses[$row['status']] . '</td>';
+ echo ' <td>' . $row['get'] . '</td>';
+ echo ' <td>' . $row['post'] . '</td>';
+
+ echo '</tr>';
+ }
+ }
+
+ echo '</table>';
+
+ echo '</fieldset>';
+ }
+
+ public function csvExport()
+ {
+ define('delimiter', ';');
+
+
+ $podatki = 'datetime' . delimiter;
+ $podatki .= 'uid' . delimiter;
+ $podatki .= 'ip' . delimiter;
+ $podatki .= 'status' . delimiter;
+ $podatki .= 'parameter' . delimiter;
+ $podatki .= 'value' . delimiter;
+ $podatki .= 'parameter' . delimiter;
+ $podatki .= 'value' . delimiter;
+
+
+ $podatki .= "\n";
+
+ $sql = sisplet_query("SELECT * FROM srv_tracking".$this->db_table." WHERE ank_id = '" . $this->anketa . "' " . $this->status . " ORDER BY datetime DESC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+
+ $sqlu = sisplet_query("SELECT name, surname, id FROM users WHERE id = '$row[user]'");
+ $rowu = mysqli_fetch_array($sqlu);
+
+ $podatki .= '' . datetime($row['datetime']) . delimiter;
+ $podatki .= '' . $rowu['id'] . delimiter;
+ $podatki .= '' . $row['ip'] . delimiter;
+ $podatki .= '' . $row['status'] . delimiter;
+
+ foreach (explode(',', $row['get']) AS $value) {
+ $value = explode(':', $value);
+ $podatki .= trim($value[0]) . delimiter;
+ $podatki .= trim($value[1]) . delimiter;
+ }
+
+ $podatki .= "\n";
+ }
+
+ $ime = str_replace('-', '_', $_GET['a']);
+ return Export::init()->csv('Spremembe_' . $ime, $podatki);
+ }
+
+ /**
+ * Update srv_tracking table
+ * @desc vnese spremembo v srv_tracking za sledenje sprememb
+ *
+ * @param (int) $anketa
+ * @param (int) $status
+ */
+ private static $time_start;
+
+ static function update($anketa, $status = 0)
+ {
+ global $global_user_id;
+
+ # poiščemo aktivno anketo
+ SurveyInfo :: getInstance()->SurveyInit($anketa);
+ $db_table = (SurveyInfo::getInstance()->getSurveyColumn('db_table') == 1) ? '_active' : '';
+
+ $get = '';
+ foreach ($_GET AS $key => $val) {
+ if ($get != '')
+ $get .= ', ';
+ $get .= $key . ': "' . $val . '"';
+ }
+
+ $post = '';
+ foreach ($_POST AS $key => $val) {
+ if ($post != '')
+ $post .= ', ';
+
+// if (is_array($val))
+// $val = implode(',', $val);
+
+ if (is_array($val))
+ $val = self::arrayToString($val);
+
+ $post .= $key . ': "' . $val . '"';
+ }
+
+ // izracunamo trajanje skripte v sekundah
+ if (self::$time_start != null)
+ $time_seconds = microtime(true) - self::$time_start;
+ else
+ $time_seconds = 0;
+
+ // IP uporabnika
+ $ip = GetIP();
+
+ $s = sisplet_query("INSERT INTO srv_tracking".$db_table." (ank_id, datetime, ip, user, `get`, post, status, time_seconds) VALUES ('$anketa', NOW(), '".$ip."', '$global_user_id', '$get', '$post','$status', '$time_seconds')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ static function update_user($status = 0)
+ {
+ global $global_user_id;
+
+ $get = '';
+ foreach ($_GET AS $key => $val) {
+ if ($get != '')
+ $get .= ', ';
+ $get .= $key . ': "' . $val . '"';
+ }
+
+ $post = '';
+ foreach ($_POST AS $key => $val) {
+ if ($post != '')
+ $post .= ', ';
+
+// if (is_array($val))
+// $val = implode(',', $val);
+
+ if (is_array($val))
+ $val = self::arrayToString($val);
+
+ $post .= $key . ': "' . $val . '"';
+ }
+
+ // izracunamo trajanje skripte v sekundah
+ if (self::$time_start != null)
+ $time_seconds = microtime(true) - self::$time_start;
+ else
+ $time_seconds = 0;
+
+ // IP uporabnika
+ $ip = GetIP();
+
+ $s = sisplet_query("INSERT INTO user_tracking (datetime, ip, user, `get`, post, status, time_seconds) VALUES (NOW(), '".$ip."', '$global_user_id', '$get', '$post','$status', '$time_seconds')");
+ if (!$s) echo mysqli_error($GLOBALS['connect_db']);
+ }
+
+ private static function arrayToString($array)
+ {
+ $string = "";
+ if (is_array($array)) {
+ foreach ($array as $key => $value) {
+
+ if (is_array($value)) {
+ $string .= ', '.$key .': [' . self::arrayToString($value) . '] ';
+ } else {
+ if ($key == 0)
+ $string .= $key . ': ' . $value . ' ';
+ }
+
+
+ }
+ }
+
+ return $string;
+ }
+
+
+} \ No newline at end of file
diff --git a/admin/survey/classes/tracking/UserTrackingClass.php b/admin/survey/classes/tracking/UserTrackingClass.php
new file mode 100644
index 0000000..3833003
--- /dev/null
+++ b/admin/survey/classes/tracking/UserTrackingClass.php
@@ -0,0 +1,124 @@
+<?php
+
+/***************************************
+ * Description:
+ * Autor: Uroš Podkrižnik
+ * Created date: 09.04.2020
+ *****************************************/
+class UserTrackingClass
+{
+
+ public function __construct()
+ {
+ return $this;
+ }
+
+ private static $_instance;
+
+ /**
+ * V kolikor razred kličemo statično
+ *
+ * @return instance
+ */
+
+ public static function init()
+ {
+ if (!static::$_instance)
+ static::$_instance = new UserTrackingClass();
+
+ return static::$_instance;
+ }
+
+ /**
+ * @desc prikaze tracking sprememb
+ */
+ public function userTrackingDisplay()
+ {
+ global $lang;
+ global $global_user_id;
+
+ echo '<div id="div_archive_content" class="tracking">';
+
+ echo '<fieldset>';
+ echo '<legend>' . $lang['srv_survey_archives_tracking'] . '</legend>';
+
+ // Izvoz v Excel
+ echo '<p>'.$lang['srv_survey_archives_tracking_last_changes'].'</p>';
+
+
+ echo '<table id="tracking">';
+
+ // Prva vrstica
+ echo '<tr>';
+ echo ' <th>' . $lang['date'] . '</th>';
+ echo ' <th class="center">IP</th>';
+ echo ' <th>GET</th>';
+ echo ' <th>POST</th>';
+ echo '</tr>';
+
+ // Vrstice s podatki
+ $sql = sisplet_query("SELECT * FROM user_tracking WHERE user = '$global_user_id' ORDER BY datetime DESC LIMIT 25");
+
+ while ($row = mysqli_fetch_array($sql)) {
+ echo '<tr>';
+
+ echo ' <td>' . datetime($row['datetime']) . '</td>';
+ echo ' <td class="center">' . $row['ip'] . '</td>';
+ echo ' <td>' . $row['get'] . '</td>';
+ echo ' <td>' . $row['post'] . '</td>';
+
+ echo '</tr>';
+ }
+
+ echo '</table>';
+
+ echo '</fieldset>';
+
+ echo '<br class="clr" />';
+ echo '</div>';
+ }
+
+ public function csvExport()
+ {
+ global $global_user_id;
+
+ define('delimiter', ';');
+
+
+ $podatki = 'datetime' . delimiter;
+ //$podatki .= 'uid' . delimiter;
+ $podatki .= 'ip' . delimiter;
+ //$podatki .= 'status' . delimiter;
+ $podatki .= 'parameter' . delimiter;
+ $podatki .= 'value' . delimiter;
+ $podatki .= 'parameter' . delimiter;
+ $podatki .= 'value' . delimiter;
+
+
+ $podatki .= "\n";
+
+ $sql = sisplet_query("SELECT * FROM user_tracking WHERE user = '$global_user_id' ORDER BY datetime DESC");
+ while ($row = mysqli_fetch_array($sql)) {
+
+
+ $sqlu = sisplet_query("SELECT name, surname, id FROM users WHERE id = '$row[user]'");
+ $rowu = mysqli_fetch_array($sqlu);
+
+ $podatki .= '' . datetime($row['datetime']) . delimiter;
+ //$podatki .= '' . $rowu['id'] . delimiter;
+ $podatki .= '' . $row['ip'] . delimiter;
+ //$podatki .= '' . $row['status'] . delimiter;
+
+ foreach (explode(',', $row['get']) AS $value) {
+ $value = explode(':', $value);
+ $podatki .= trim($value[0]) . delimiter;
+ $podatki .= trim($value[1]) . delimiter;
+ }
+
+ $podatki .= "\n";
+ }
+
+ $ime = str_replace('-', '_', $_GET['a']);
+ return Export::init()->csv('Spremembe_' . $ime, $podatki);
+ }
+} \ No newline at end of file