[Release] wrt-installer_0.1.90
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_widget_config.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /*
17  * @file    task_widget_config.cpp
18  * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version 1.0
20  * @brief   Implementation file for installer task widget config
21  */
22
23 #include <map>
24 #include <sstream>
25 #include <string>
26 #include <sys/stat.h>
27 #include <dirent.h>
28
29 #include <dpl/errno_string.h>
30 #include <dpl/foreach.h>
31 #include <dpl/localization/w3c_file_localization.h>
32 #include <dpl/singleton_impl.h>
33 #include <dpl/utils/mime_type_utils.h>
34 #include <dpl/utils/wrt_global_settings.h>
35 #include <dpl/utils/wrt_utility.h>
36 #include <dpl/wrt-dao-ro/global_config.h>
37 #include <dpl/wrt-dao-ro/config_parser_data.h>
38 #include <dpl/wrt-dao-rw/feature_dao.h>
39
40 #include <libiriwrapper.h>
41 #include <parser_runner.h>
42 #include <root_parser.h>
43
44 #include <widget_install/job_widget_install.h>
45 #include <widget_install/task_widget_config.h>
46 #include <widget_install/widget_install_context.h>
47 #include <widget_install/widget_install_errors.h>
48 #include <widget_parser.h>
49 #include <web_provider_plugin_info.h>
50 #include <web_provider_livebox_info.h>
51 #include <manifest.h>
52
53 namespace { // anonymous
54 const DPL::String BR = DPL::FromUTF8String("<br>");
55 const std::string WIDGET_NOT_COMPATIBLE = "This widget is "
56                                           "not compatible with WRT.<br><br>";
57 const std::string QUESTION = "Do you want to install it anyway?";
58
59 const char *const DEFAULT_LANGUAGE = "default";
60
61 const char *const WRT_WIDGET_CONFIG_FILE_NAME = "config.xml";
62
63 const std::string WINDGET_INSTALL_NETWORK_ACCESS = "network access";
64
65 const char WRT_WIDGETS_XML_SCHEMA[] = "/usr/etc/wrt-installer/widgets.xsd";
66 }
67
68 namespace Jobs {
69 namespace WidgetInstall {
70 void InstallerTaskWidgetPopupData::PopupData::addWidgetInfo(
71     const DPL::String &info)
72 {
73     widgetInfo = info;
74 }
75
76 TaskWidgetConfig::TaskWidgetConfig(InstallerContext& installContext) :
77     DPL::TaskDecl<TaskWidgetConfig>(this),
78     m_installContext(installContext)
79 {
80     AddStep(&TaskWidgetConfig::StepProcessConfigurationFile);
81     AddStep(&TaskWidgetConfig::ReadLocaleFolders);
82     AddStep(&TaskWidgetConfig::ProcessLocalizedStartFiles);
83     AddStep(&TaskWidgetConfig::ProcessBackgroundPageFile);
84     AddStep(&TaskWidgetConfig::ProcessLocalizedIcons);
85     AddStep(&TaskWidgetConfig::ProcessWidgetInstalledPath);
86     AddStep(&TaskWidgetConfig::ProcessAppControlInfo);
87     AddStep(&TaskWidgetConfig::ProcessSecurityModel);
88     AddStep(&TaskWidgetConfig::StepVerifyFeatures);
89     AddStep(&TaskWidgetConfig::StepCheckMinVersionInfo);
90 }
91
92 void TaskWidgetConfig::StepProcessConfigurationFile()
93 {
94     Try
95     {
96         std::string path = m_installContext.locations->getConfigurationDir();
97         LogInfo("path: " << path);
98
99         processFile(path, m_installContext.widgetConfig);
100     }
101     Catch(Exception::ConfigParseFailed)
102     {
103         LogError("Parsing failed.");
104         ReThrow(Exceptions::WidgetConfigFileInvalid);
105     }
106
107     m_installContext.job->UpdateProgress(
108         InstallerContext::INSTALL_WIDGET_CONFIG1,
109         "Parse elements of configuration file and save them");
110 }
111
112 void TaskWidgetConfig::ReadLocaleFolders()
113 {
114     LogDebug("Reading locale");
115     //Adding default locale
116     m_localeFolders.insert(L"");
117
118     std::string localePath =
119         m_installContext.locations->getConfigurationDir() + "/locales";
120     DIR* localeDir = opendir(localePath.c_str());
121     if (!localeDir) {
122         LogDebug("No /locales directory in the widget package.");
123         return;
124     }
125
126     struct stat statStruct;
127     struct dirent dirent;
128     struct dirent *result;
129     int return_code;
130     errno = 0;
131     for (return_code = readdir_r(localeDir, &dirent, &result);
132             result != NULL && return_code == 0;
133             return_code = readdir_r(localeDir, &dirent, &result))
134     {
135         DPL::String dirName = DPL::FromUTF8String(dirent.d_name);
136         std::string absoluteDirName = localePath + "/";
137         absoluteDirName += dirent.d_name;
138
139         if (stat(absoluteDirName.c_str(), &statStruct) != 0) {
140             LogError("stat() failed with " << DPL::GetErrnoString());
141             continue;
142         }
143
144         if (S_ISDIR(statStruct.st_mode)) {
145             //Yes, we ignore current, parent & hidden directories
146             if (dirName[0] != L'.') {
147                 LogDebug("Adding locale directory \"" << dirName << "\"");
148                 m_localeFolders.insert(dirName);
149             }
150         }
151     }
152
153     if (return_code != 0 || errno != 0) {
154         LogError("readdir_r() failed with " << DPL::GetErrnoString());
155     }
156
157     if (-1 == TEMP_FAILURE_RETRY(closedir(localeDir))) {
158         LogError("Failed to close dir: " << localePath << " with error: "
159                                          << DPL::GetErrnoString());
160     }
161 }
162
163 void TaskWidgetConfig::ProcessLocalizedStartFiles()
164 {
165     typedef DPL::String S;
166     ProcessStartFile(
167         m_installContext.widgetConfig.configInfo.startFile,
168         m_installContext.widgetConfig.configInfo.
169             startFileContentType,
170         m_installContext.widgetConfig.configInfo.startFileEncoding,
171         true);
172     ProcessStartFile(S(L"index.htm"), S(L"text/html"));
173     ProcessStartFile(S(L"index.html"), S(L"text/html"));
174     ProcessStartFile(S(L"index.svg"), S(L"image/svg+xml"));
175     ProcessStartFile(S(L"index.xhtml"), S(L"application/xhtml+xml"));
176     ProcessStartFile(S(L"index.xht"), S(L"application/xhtml+xml"));
177     // TODO: we need better check if in current locales widget is valid
178     FOREACH(it, m_installContext.widgetConfig.localizationData.startFiles) {
179         if (it->propertiesForLocales.size() > 0) {
180             return;
181         }
182     }
183     ThrowMsg(Exceptions::WidgetConfigFileInvalid,
184              L"The Widget has no valid start file");
185 }
186
187 void TaskWidgetConfig::ProcessStartFile(const DPL::OptionalString& path,
188                                         const DPL::OptionalString& type,
189                                         const DPL::OptionalString& encoding,
190                                         bool typeForcedInConfig)
191 {
192     using namespace WrtDB;
193
194     if (!!path) {
195         WidgetRegisterInfo::LocalizedStartFile startFileData;
196         startFileData.path = *path;
197
198         FOREACH(i, m_localeFolders) {
199             DPL::String pathPrefix = *i;
200             if (!pathPrefix.empty()) {
201                 pathPrefix = L"locales/" + pathPrefix + L"/";
202             }
203
204             DPL::String relativePath = pathPrefix + *path;
205             DPL::String absolutePath = DPL::FromUTF8String(
206                     m_installContext.locations->getConfigurationDir()) + L"/" +
207                 relativePath;
208
209             // get property data from packaged app
210             if (WrtUtilFileExists(DPL::ToUTF8String(absolutePath))) {
211                 WidgetRegisterInfo::StartFileProperties startFileProperties;
212                 if (!!type) {
213                     startFileProperties.type = *type;
214                 } else {
215                     startFileProperties.type =
216                         MimeTypeUtils::identifyFileMimeType(absolutePath);
217                 }
218
219                 //proceed only if MIME type is supported
220                 if (MimeTypeUtils::isMimeTypeSupportedForStartFile(
221                         startFileProperties.type))
222                 {
223                     if (!!encoding) {
224                         startFileProperties.encoding = *encoding;
225                     } else {
226                         MimeTypeUtils::MimeAttributes attributes =
227                             MimeTypeUtils::getMimeAttributes(
228                                 startFileProperties.type);
229                         if (attributes.count(L"charset") > 0) {
230                             startFileProperties.encoding =
231                                 attributes[L"charset"];
232                         } else {
233                             startFileProperties.encoding = L"UTF-8";
234                         }
235                     }
236
237                     startFileData.propertiesForLocales[*i] =
238                         startFileProperties;
239                 } else {
240                     //9.1.16.5.content.8
241                     //(there seems to be no similar requirement in .6,
242                     //so let's throw only when mime type is
243                     // provided explcitly in config.xml)
244                     if (typeForcedInConfig) {
245                         ThrowMsg(Exceptions::WidgetConfigFileInvalid,
246                                  "Unsupported MIME type for start file.");
247                     }
248                 }
249             } else {
250                 // set property data for hosted start url
251                 // Hosted start url only support TIZEN WebApp
252                 if (m_installContext.widgetConfig.webAppType ==
253                     APP_TYPE_TIZENWEBAPP)
254                 {
255                     std::string startPath = DPL::ToUTF8String(
256                             startFileData.path);
257
258                     if (strstr(startPath.c_str(),
259                                "http") == startPath.c_str())
260                     {
261                         WidgetRegisterInfo::StartFileProperties
262                             startFileProperties;
263                         if (!!type) {
264                             startFileProperties.type = *type;
265                         }
266                         if (!!encoding) {
267                             startFileProperties.encoding = *encoding;
268                         }
269                         startFileData.propertiesForLocales[*i] =
270                             startFileProperties;
271                     }
272                 }
273             }
274         }
275
276         m_installContext.widgetConfig.localizationData.startFiles.push_back(
277             startFileData);
278     }
279 }
280
281 void TaskWidgetConfig::ProcessBackgroundPageFile()
282 {
283     if (!!m_installContext.widgetConfig.configInfo.backgroundPage) {
284         // check whether file exists
285         DPL::String backgroundPagePath = DPL::FromUTF8String(
286                 m_installContext.locations->getConfigurationDir()) + L"/" +
287             *m_installContext.widgetConfig.configInfo.backgroundPage;
288         //if no then cancel installation
289         if (!WrtUtilFileExists(DPL::ToUTF8String(backgroundPagePath))) {
290             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
291                      L"Given background page file not found in archive");
292         }
293     }
294 }
295
296 void TaskWidgetConfig::ProcessLocalizedIcons()
297 {
298     using namespace WrtDB;
299     ProcessIcon(ConfigParserData::Icon(L"icon.svg"));
300     ProcessIcon(ConfigParserData::Icon(L"icon.ico"));
301     ProcessIcon(ConfigParserData::Icon(L"icon.png"));
302     ProcessIcon(ConfigParserData::Icon(L"icon.gif"));
303     ProcessIcon(ConfigParserData::Icon(L"icon.jpg"));
304
305     FOREACH(i, m_installContext.widgetConfig.configInfo.iconsList)
306     {
307         ProcessIcon(*i);
308     }
309 }
310
311 void TaskWidgetConfig::ProcessIcon(const WrtDB::ConfigParserData::Icon& icon)
312 {
313     LogInfo("enter");
314     bool isAnyIconValid = false;
315     //In case a default filename is passed as custom filename in config.xml, we
316     //need to keep a set of already processed filenames to avoid icon
317     // duplication
318     //in database.
319
320     using namespace WrtDB;
321
322     if (m_processedIconSet.count(icon.src) > 0) {
323         return;
324     }
325     m_processedIconSet.insert(icon.src);
326
327     LocaleSet localesAvailableForIcon;
328
329     FOREACH(i, m_localeFolders)
330     {
331         DPL::String pathPrefix = *i;
332         if (!pathPrefix.empty()) {
333             pathPrefix = L"locales/" + pathPrefix + L"/";
334         }
335
336         DPL::String relativePath = pathPrefix + icon.src;
337         DPL::String absolutePath = DPL::FromUTF8String(
338                 m_installContext.locations->getConfigurationDir()) + L"/" +
339             relativePath;
340
341         if (WrtUtilFileExists(DPL::ToUTF8String(absolutePath))) {
342             DPL::String type = MimeTypeUtils::identifyFileMimeType(absolutePath);
343
344             if (MimeTypeUtils::isMimeTypeSupportedForIcon(type)) {
345                 isAnyIconValid = true;
346                 localesAvailableForIcon.insert(*i);
347                 LogInfo("Icon absolutePath :" << absolutePath <<
348                         ", assigned locale :" << *i << ", type: " << type);
349             }
350         }
351     }
352
353     if (isAnyIconValid) {
354         WidgetRegisterInfo::LocalizedIcon localizedIcon(icon,
355                                                         localesAvailableForIcon);
356         m_installContext.widgetConfig.localizationData.icons.push_back(
357             localizedIcon);
358     }
359 }
360
361 void TaskWidgetConfig::ProcessWidgetInstalledPath()
362 {
363     LogDebug("ProcessWidgetInstalledPath");
364     m_installContext.widgetConfig.widgetInstalledPath =
365         DPL::FromUTF8String(
366             m_installContext.locations->getPackageInstallationDir());
367 }
368
369 void TaskWidgetConfig::ProcessAppControlInfo()
370 {
371     LogDebug("ProcessAppControlInfo");
372     using namespace WrtDB;
373
374     WrtDB::ConfigParserData::AppControlInfo::Disposition disposition =
375         WrtDB::ConfigParserData::AppControlInfo::Disposition::WINDOW;
376     FOREACH(it, m_installContext.widgetConfig.configInfo.settingsList) {
377         if (!strcmp(DPL::ToUTF8String(it->m_name).c_str(), "nodisplay") &&
378             !strcmp(DPL::ToUTF8String(it->m_value).c_str(), "true"))
379         {
380             disposition =
381                 WrtDB::ConfigParserData::AppControlInfo::Disposition::INLINE;
382         }
383     }
384
385     std::map<std::string, int> srcMap;
386     int index = 0;
387     // index = 0 is reserved for start file
388     FOREACH(startFileIt, m_installContext.widgetConfig.localizationData.startFiles)
389     {
390         if (!startFileIt->propertiesForLocales.empty()) {
391             std::string src = DPL::ToUTF8String(startFileIt->path);
392              if (srcMap.find(src) == srcMap.end()) {
393                 LogDebug("Insert [" << src << "," << index << "]");
394                 srcMap.insert(std::pair<std::string, int>(src, index++));
395             }
396         }
397     }
398
399     FOREACH(appControlIt, m_installContext.widgetConfig.configInfo.appControlList)
400     {
401         appControlIt->m_disposition = disposition;
402         std::string src = DPL::ToUTF8String(appControlIt->m_src);
403         LogDebug("src = [" << src << "]");
404         std::map<std::string, int>::iterator findIt = srcMap.find(src);
405         if (findIt == srcMap.end()) {
406             LogDebug("Insert [" << src << "," << index << "]");
407             srcMap.insert(std::pair<std::string, int>(src, index));
408             appControlIt->m_index = index++;
409         } else {
410             LogDebug("Exist  [" << src << "," << findIt->second << "]");
411             appControlIt->m_index = findIt->second;
412         }
413     }
414 }
415
416 void TaskWidgetConfig::ProcessSecurityModel()
417 {
418     // 0104.  If the "required_version" specified in the Web Application's
419     // configuration is 2.2 or higher and if the Web Application's
420     // configuration is "CSP-compatible configuration", then the WRT MUST be
421     // set to "CSP-based security mode". Otherwise, the WRT MUST be set to
422     // "WARP-based security mode".
423     // 0105.  A Web Application configuration is "CSP-compatible configuration"
424     // if the configuration includes one or more of
425     // <tizen:content-security-policy> /
426     // <tizen:content-security-policy-report-only> /
427     // <tizen:allow-navigation> elements.
428
429     bool isSecurityModelV1 = false;
430     bool isSecurityModelV2 = false;
431     std::string securityModelV2supportedVersion = "2.2";
432     WrtDB::ConfigParserData &data = m_installContext.widgetConfig.configInfo;
433
434     // Parse required version
435     long majorWidget = 0, minorWidget = 0, microWidget = 0;
436     if (!parseVersionString(DPL::ToUTF8String(*data.tizenMinVersionRequired),
437                             majorWidget,
438                             minorWidget,
439                             microWidget))
440     {
441         ThrowMsg(Exceptions::NotAllowed, "Wrong version string");
442     }
443
444     // Parse since version (CSP & allow-navigation start to support since 2.2)
445     long majorSupported = 0, minorSupported = 0, microSupported = 0;
446     if (!parseVersionString(securityModelV2supportedVersion,
447                             majorSupported,
448                             minorSupported,
449                             microSupported))
450     {
451         ThrowMsg(Exceptions::NotAllowed, "Wrong version string");
452     }
453
454     if (majorWidget < majorSupported ||
455         (majorWidget == majorSupported && minorWidget < minorSupported) ||
456         (majorWidget == majorSupported && minorWidget == minorSupported
457          && microWidget < microSupported))
458     {
459         // Under 2.2, clear v2 data
460         data.cspPolicy = DPL::OptionalString::Null;
461         data.cspPolicyReportOnly = DPL::OptionalString::Null;
462         data.allowNavigationInfoList.clear();
463     } else {
464         // More than 2.2, if v2 is defined, clear v1 data
465         if (!data.cspPolicy.IsNull() ||
466             !data.cspPolicyReportOnly.IsNull() ||
467             !data.allowNavigationInfoList.empty())
468         {
469             data.accessInfoSet.clear();
470         }
471     }
472
473     // WARP is V1
474     if (!data.accessInfoSet.empty()) {
475         isSecurityModelV1 = true;
476     }
477
478     // CSP & allow-navigation is V2
479     if (!data.cspPolicy.IsNull() ||
480         !data.cspPolicyReportOnly.IsNull() ||
481         !data.allowNavigationInfoList.empty())
482     {
483         isSecurityModelV2 = true;
484     }
485
486     if (isSecurityModelV1 && isSecurityModelV2) {
487         LogError("Security model is conflict");
488         ThrowMsg(Exceptions::NotAllowed, "Security model is conflict");
489     } else if (isSecurityModelV1) {
490         data.securityModelVersion =
491             WrtDB::ConfigParserData::SecurityModelVersion::SECURITY_MODEL_V1;
492     } else if (isSecurityModelV2) {
493         data.securityModelVersion =
494             WrtDB::ConfigParserData::SecurityModelVersion::SECURITY_MODEL_V2;
495     } else {
496         data.securityModelVersion =
497             WrtDB::ConfigParserData::SecurityModelVersion::SECURITY_MODEL_V1;
498     }
499
500     m_installContext.job->UpdateProgress(
501         InstallerContext::INSTALL_WIDGET_CONFIG2,
502         "Finished process security model");
503 }
504
505 void TaskWidgetConfig::StepCheckMinVersionInfo()
506 {
507     if (!isMinVersionCompatible(
508             m_installContext.widgetConfig.webAppType.appType,
509             m_installContext.widgetConfig.minVersion))
510     {
511         LogError(
512             "Platform version lower than required -> cancelling installation");
513         ThrowMsg(Exceptions::NotAllowed,
514                  "Platform version does not meet requirements");
515     }
516
517     m_installContext.job->UpdateProgress(
518         InstallerContext::INSTALL_WIDGET_CONFIG2,
519         "Check MinVersion Finished");
520 }
521
522 void TaskWidgetConfig::StepVerifyFeatures()
523 {
524     using namespace WrtDB;
525     ConfigParserData &data = m_installContext.widgetConfig.configInfo;
526     ConfigParserData::FeaturesList list = data.featuresList;
527     ConfigParserData::FeaturesList newList;
528
529     //in case of tests, this variable is unused
530     std::string featureInfo;
531     FOREACH(it, list)
532     {
533         // check feature vender for permission
534         // WAC, TIZEN WebApp cannot use other feature
535
536         if (!isFeatureAllowed(m_installContext.widgetConfig.webAppType.appType,
537                               it->name))
538         {
539             LogInfo("This application type not allowed to use this feature");
540             ThrowMsg(
541                 Exceptions::WidgetConfigFileInvalid,
542                 "This app type [" <<
543                 m_installContext.widgetConfig.webAppType.getApptypeToString()
544                                   <<
545                 "] cannot be allowed to use [" <<
546                 DPL::ToUTF8String(it->name) + "] feature");
547         } else {
548             newList.insert(*it);
549             featureInfo += DPL::ToUTF8String(it->name);
550             featureInfo += DPL::ToUTF8String(BR);
551         }
552     }
553     if (!data.accessInfoSet.empty()) {
554         featureInfo += WINDGET_INSTALL_NETWORK_ACCESS;
555         featureInfo += DPL::ToUTF8String(BR);
556     }
557     data.featuresList = newList;
558     if (!featureInfo.empty()) {
559         m_popupData.addWidgetInfo(DPL::FromUTF8String(featureInfo));
560     }
561
562     m_installContext.job->UpdateProgress(
563         InstallerContext::INSTALL_WIDGET_CONFIG2,
564         "Widget Config step2 Finished");
565 }
566
567 void TaskWidgetConfig::StepVerifyLivebox()
568 {
569     using namespace WrtDB;
570     ConfigParserData &data = m_installContext.widgetConfig.configInfo;
571     ConfigParserData::LiveboxList liveBoxList = data.m_livebox;
572
573     if (liveBoxList.size() <= 0) {
574         return;
575     }
576
577     FOREACH (it, liveBoxList) {
578         std::string boxType;
579
580         if ((**it).m_type.empty()) {
581             boxType = web_provider_livebox_get_default_type();
582         } else {
583             boxType = DPL::ToUTF8String((**it).m_type);
584         }
585
586         LogInfo("livebox type: " << boxType);
587
588         ConfigParserData::LiveboxInfo::BoxSizeList boxSizeList =
589             (**it).m_boxInfo.m_boxSize;
590         char** boxSize = static_cast<char**>(
591             malloc(sizeof(char*)* boxSizeList.size()));
592
593         int boxSizeCnt = 0;
594         FOREACH (m, boxSizeList) {
595             boxSize[boxSizeCnt++] = strdup(DPL::ToUTF8String((*m).m_size).c_str());
596         }
597
598         bool chkSize = web_provider_plugin_check_supported_size(
599             boxType.c_str(), boxSize, boxSizeCnt);
600
601         for(int i = 0; i < boxSizeCnt; i++) {
602             free(boxSize[i]);
603         }
604         free(boxSize);
605
606         if(!chkSize) {
607             LogError("Invalid boxSize");
608             ThrowMsg(Exceptions::WidgetConfigFileInvalid, "Invalid boxSize");
609         }
610     }
611 }
612
613 bool TaskWidgetConfig::isFeatureAllowed(WrtDB::AppType appType,
614                                         DPL::String featureName)
615 {
616     using namespace WrtDB;
617     LogInfo("AppType = [" <<
618             WidgetType(appType).getApptypeToString() << "]");
619     LogInfo("FetureName = [" << featureName << "]");
620
621     AppType featureType = APP_TYPE_UNKNOWN;
622     std::string featureStr = DPL::ToUTF8String(featureName);
623     const char* feature = featureStr.c_str();
624
625     // check prefix of  feature name
626     if (strstr(feature, PluginsPrefix::TIZENPluginsPrefix) == feature) {
627         // Tizen WebApp feature
628         featureType = APP_TYPE_TIZENWEBAPP;
629     } else if (strstr(feature, PluginsPrefix::WACPluginsPrefix) == feature) {
630         // WAC 2.0 feature
631         featureType = APP_TYPE_WAC20;
632     } else if (strstr(feature, PluginsPrefix::W3CPluginsPrefix) == feature) {
633         // W3C standard feature
634         // Both WAC and TIZEN WebApp are possible to use W3C plugins
635         return true;
636     } else {
637         // unknown feature
638         // unknown feature will be checked next step
639         return true;
640     }
641
642     if (appType == featureType) {
643         return true;
644     }
645     return false;
646 }
647
648 bool TaskWidgetConfig::parseVersionString(const std::string &version,
649                                           long &majorVersion,
650                                           long &minorVersion,
651                                           long &microVersion) const
652 {
653     std::istringstream inputString(version);
654     inputString >> majorVersion;
655     if (inputString.bad() || inputString.fail()) {
656         LogWarning("Invalid minVersion format.");
657         return false;
658     }
659     inputString.get(); // skip period
660     inputString >> minorVersion;
661     if (inputString.bad() || inputString.fail()) {
662         LogWarning("Invalid minVersion format");
663         return false;
664     } else {
665         inputString.get(); // skip period
666         if (inputString.bad() || inputString.fail()) {
667             inputString >> microVersion;
668         }
669     }
670     return true;
671 }
672
673 bool TaskWidgetConfig::isMinVersionCompatible(
674     WrtDB::AppType appType,
675     const DPL::OptionalString &
676     widgetVersion) const
677 {
678     if (widgetVersion.IsNull() || (*widgetVersion).empty()) {
679         if (appType == WrtDB::AppType::APP_TYPE_TIZENWEBAPP) {
680             return false;
681         } else {
682             LogWarning("minVersion attribute is empty. WRT assumes platform "
683                     "supports this widget.");
684             return true;
685         }
686     }
687
688     //Parse widget version
689     long majorWidget = 0, minorWidget = 0, microWidget = 0;
690     if (!parseVersionString(DPL::ToUTF8String(*widgetVersion), majorWidget,
691                             minorWidget, microWidget))
692     {
693         LogWarning("Invalid format of widget version string.");
694         return false;
695     }
696
697     //Parse supported version
698     long majorSupported = 0, minorSupported = 0, microSupported = 0;
699     std::string version;
700     if (appType == WrtDB::AppType::APP_TYPE_TIZENWEBAPP) {
701         version = WrtDB::GlobalConfig::GetTizenVersion();
702     } else if (appType == WrtDB::AppType::APP_TYPE_WAC20) {
703         version = WrtDB::GlobalConfig::GetWACVersion();
704     } else {
705         LogWarning("Invaild AppType");
706         return false;
707     }
708
709     if (!parseVersionString(version,
710                             majorSupported, minorSupported, microSupported))
711     {
712         LogWarning("Invalid format of platform version string.");
713         return true;
714     }
715
716     if (majorWidget > majorSupported ||
717         (majorWidget == majorSupported && minorWidget > minorSupported) ||
718         (majorWidget == majorSupported && minorWidget == minorSupported
719          && microWidget > microSupported))
720     {
721         LogInfo("Platform doesn't support this widget.");
722         return false;
723     }
724     return true;
725 }
726
727 bool TaskWidgetConfig::isTizenWebApp() const
728 {
729     bool ret = FALSE;
730     if (m_installContext.widgetConfig.webAppType.appType
731         == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
732     {
733         ret = TRUE;
734     }
735
736     return ret;
737 }
738
739 bool TaskWidgetConfig::parseConfigurationFileBrowser(
740     WrtDB::ConfigParserData& configInfo,
741     const std::string& _currentPath)
742 {
743     ParserRunner parser;
744     Try
745     {
746         parser.Parse(_currentPath, ElementParserPtr(new
747                                                     RootParser<
748                                                         WidgetParser>(
749                                                         configInfo,
750                                                         DPL::FromUTF32String(
751                                                             L"widget"))));
752     }
753     Catch(ElementParser::Exception::Base)
754     {
755         LogError("Invalid widget configuration file!");
756         return false;
757     }
758     return true;
759 }
760
761 bool TaskWidgetConfig::parseConfigurationFileWidget(
762     WrtDB::ConfigParserData& configInfo,
763     const std::string& _currentPath)
764 {
765     std::string configFilePath;
766     WrtUtilJoinPaths(configFilePath, _currentPath, WRT_WIDGET_CONFIG_FILE_NAME);
767     if (!WrtUtilFileExists(configFilePath))
768     {
769         LogError("Archive does not contain configuration file");
770         return false;
771     }
772
773     LogDebug("Configuration file: " << configFilePath);
774
775     Try
776     {
777         ParserRunner parser;
778 #ifdef SCHEMA_VALIDATION_ENABLED
779         if(!parser.Validate(configFilePath, WRT_WIDGETS_XML_SCHEMA))
780         {
781             LogError("Invalid configuration file - schema validation failed");
782             return false;
783         }
784 #endif
785         parser.Parse(configFilePath,
786                      ElementParserPtr(new RootParser<WidgetParser>(
787                                           configInfo,
788                                           DPL::FromUTF32String(L"widget"))));
789         return true;
790     }
791     Catch (ElementParser::Exception::Base)
792     {
793         LogError("Invalid configuration file!");
794         return false;
795     }
796 }
797
798 bool TaskWidgetConfig::locateAndParseConfigurationFile(
799     const std::string& _currentPath,
800     WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
801     const std::string& baseFolder)
802 {
803     using namespace WrtDB;
804
805     ConfigParserData& configInfo = pWidgetConfigInfo.configInfo;
806
807     // check if this installation from browser, or not.
808     size_t pos = _currentPath.rfind("/");
809     std::ostringstream infoPath;
810     infoPath << _currentPath.substr(pos + 1);
811
812     if (infoPath.str() != WRT_WIDGET_CONFIG_FILE_NAME) {
813         if (_currentPath.empty() || baseFolder.empty()) {
814             return false;
815         }
816         // in case of general installation using wgt archive
817         if (!parseConfigurationFileWidget(configInfo, _currentPath))
818         {
819             return false;
820         }
821     } else {
822         // in case of browser installation
823         if (!parseConfigurationFileBrowser(configInfo, _currentPath))
824         {
825             return false;
826         }
827     }
828
829     if (!fillWidgetConfig(pWidgetConfigInfo, configInfo)) {
830         return false;
831     }
832     return true;
833 }
834
835 bool TaskWidgetConfig::fillWidgetConfig(
836     WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
837     WrtDB::ConfigParserData& configInfo)
838 {
839     if (!!configInfo.widget_id) {
840         if (!pWidgetConfigInfo.guid) {
841             pWidgetConfigInfo.guid = configInfo.widget_id;
842         } else {
843             if (pWidgetConfigInfo.guid != configInfo.widget_id) {
844                 LogError("Invalid archive");
845                 return false;
846             }
847         }
848     }
849     if (!!configInfo.tizenAppId) {
850         if (DPL::ToUTF8String(pWidgetConfigInfo.tzAppid).compare(
851                 DPL::ToUTF8String(*configInfo.tizenAppId)) < 0)
852         {
853             LogError("Invalid archive - Tizen App ID not same error");
854             return false;
855         }
856     }
857     if (!!configInfo.tizenPkgId) {
858         if (pWidgetConfigInfo.tzPkgid != *configInfo.tizenPkgId) {
859             LogError("Invalid archive - Tizen Pkg ID not same error");
860             return false;
861         }
862     }
863     if (!!configInfo.version) {
864         if (!pWidgetConfigInfo.version) {
865             pWidgetConfigInfo.version = configInfo.version;
866         } else {
867             if (pWidgetConfigInfo.version != configInfo.version) {
868                 LogError("Invalid archive");
869                 return false;
870             }
871         }
872     }
873     if (!!configInfo.minVersionRequired) {
874         pWidgetConfigInfo.minVersion = configInfo.minVersionRequired;
875     } else if (!!configInfo.tizenMinVersionRequired) {
876         pWidgetConfigInfo.minVersion = configInfo.tizenMinVersionRequired;
877     }
878     return true;
879 }
880
881 void TaskWidgetConfig::processFile(
882     const std::string& path,
883     WrtDB::WidgetRegisterInfo &
884     widgetConfiguration)
885 {
886     if (!locateAndParseConfigurationFile(path, widgetConfiguration,
887                                          DEFAULT_LANGUAGE))
888     {
889         LogWarning("Widget archive: Failed while parsing config file");
890         ThrowMsg(Exception::ConfigParseFailed, path);
891     }
892 }
893 } //namespace WidgetInstall
894 } //namespace Jobs