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